@figma/code-connect 1.4.1 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +4 -4
  2. package/dist/commands/connect.d.ts +6 -4
  3. package/dist/commands/connect.d.ts.map +1 -1
  4. package/dist/commands/connect.js +80 -107
  5. package/dist/commands/connect.js.map +1 -1
  6. package/dist/commands/filter_project_info.d.ts +7 -0
  7. package/dist/commands/filter_project_info.d.ts.map +1 -0
  8. package/dist/commands/filter_project_info.js +32 -0
  9. package/dist/commands/filter_project_info.js.map +1 -0
  10. package/dist/connect/helpers.d.ts +6 -0
  11. package/dist/connect/helpers.d.ts.map +1 -1
  12. package/dist/connect/helpers.js +18 -0
  13. package/dist/connect/helpers.js.map +1 -1
  14. package/dist/connect/intrinsics.d.ts +3 -3
  15. package/dist/connect/intrinsics.d.ts.map +1 -1
  16. package/dist/connect/intrinsics.js +21 -10
  17. package/dist/connect/intrinsics.js.map +1 -1
  18. package/dist/connect/migration_helpers.d.ts +15 -1
  19. package/dist/connect/migration_helpers.d.ts.map +1 -1
  20. package/dist/connect/migration_helpers.js +187 -73
  21. package/dist/connect/migration_helpers.js.map +1 -1
  22. package/dist/connect/parser_common.d.ts +3 -2
  23. package/dist/connect/parser_common.d.ts.map +1 -1
  24. package/dist/connect/parser_common.js +2 -2
  25. package/dist/connect/parser_common.js.map +1 -1
  26. package/dist/connect/project.d.ts +8 -3
  27. package/dist/connect/project.d.ts.map +1 -1
  28. package/dist/connect/project.js +25 -11
  29. package/dist/connect/project.js.map +1 -1
  30. package/dist/connect/raw_templates.d.ts +11 -0
  31. package/dist/connect/raw_templates.d.ts.map +1 -0
  32. package/dist/connect/raw_templates.js +149 -0
  33. package/dist/connect/raw_templates.js.map +1 -0
  34. package/dist/connect/upload.d.ts.map +1 -1
  35. package/dist/connect/upload.js +27 -6
  36. package/dist/connect/upload.js.map +1 -1
  37. package/dist/html/parser.d.ts +2 -2
  38. package/dist/html/parser.d.ts.map +1 -1
  39. package/dist/html/parser.js +9 -9
  40. package/dist/html/parser.js.map +1 -1
  41. package/dist/react/parser.d.ts +3 -3
  42. package/dist/react/parser.d.ts.map +1 -1
  43. package/dist/react/parser.js +14 -12
  44. package/dist/react/parser.js.map +1 -1
  45. package/dist/storybook/convert.d.ts +7 -1
  46. package/dist/storybook/convert.d.ts.map +1 -1
  47. package/dist/storybook/convert.js +12 -5
  48. package/dist/storybook/convert.js.map +1 -1
  49. package/figma-types.d.ts +214 -0
  50. package/package.json +7 -3
@@ -42,6 +42,7 @@ const parser_template_helpers_1 = require("./parser_template_helpers");
42
42
  const jsdom_1 = require("jsdom");
43
43
  const parse5_1 = require("parse5");
44
44
  const parser_common_1 = require("../connect/parser_common");
45
+ const helpers_1 = require("../connect/helpers");
45
46
  const project_1 = require("../connect/project");
46
47
  const label_language_mapping_1 = require("../connect/label_language_mapping");
47
48
  const prettier_1 = require("prettier");
@@ -196,7 +197,7 @@ function escapeTemplateString(code) {
196
197
  *
197
198
  * @returns The code of the render function and a list of imports
198
199
  */
199
- function parseExampleTemplate(exp, parserContext, propMappings, skipTemplateHelpers) {
200
+ function parseExampleTemplate(exp, parserContext, propMappings, isForMigration) {
200
201
  const { sourceFile } = parserContext;
201
202
  if (exp.parameters.length > 1) {
202
203
  throw new parser_common_1.ParserError(`Expected a single props parameter for the render function, got ${exp.parameters.length} parameters`, { sourceFile, node: exp });
@@ -217,7 +218,7 @@ function parseExampleTemplate(exp, parserContext, propMappings, skipTemplateHelp
217
218
  }
218
219
  let exampleCode = printer.printNode(typescript_1.default.EmitHint.Unspecified, exp.body, sourceFile);
219
220
  let templateCode = '';
220
- if (!skipTemplateHelpers) {
221
+ if (!isForMigration) {
221
222
  templateCode = (0, parser_template_helpers_1.getParsedTemplateHelpersString)() + '\n\n';
222
223
  }
223
224
  templateCode += `const figma = require('figma')\n\n`;
@@ -225,6 +226,7 @@ function parseExampleTemplate(exp, parserContext, propMappings, skipTemplateHelp
225
226
  propMappings,
226
227
  exp,
227
228
  sourceFile,
229
+ isForMigration,
228
230
  });
229
231
  exampleCode = exampleCode.replace(/`/g, '\\`');
230
232
  // Body is a string literal, so there aren't any placeholders
@@ -364,7 +366,7 @@ function parseExampleTemplate(exp, parserContext, propMappings, skipTemplateHelp
364
366
  throw new parser_common_1.ParserError(`Expected a template expression as the body of the render function, got ${typescript_1.SyntaxKind[templateNode.template.kind]}`, { sourceFile, node: templateNode.template });
365
367
  }
366
368
  let templateCode = '';
367
- if (!skipTemplateHelpers) {
369
+ if (!isForMigration) {
368
370
  templateCode = (0, parser_template_helpers_1.getParsedTemplateHelpersString)() + '\n\n';
369
371
  }
370
372
  templateCode += `const figma = require('figma')\n\n`;
@@ -372,6 +374,7 @@ function parseExampleTemplate(exp, parserContext, propMappings, skipTemplateHelp
372
374
  propMappings,
373
375
  exp,
374
376
  sourceFile,
377
+ isForMigration,
375
378
  });
376
379
  templateCode += `export default figma.html\`${exampleCode}\`\n`;
377
380
  return {
@@ -478,7 +481,7 @@ function parseConfigObjectArg(configArg, parserContext) {
478
481
  importsArg,
479
482
  };
480
483
  }
481
- async function parseHtmlDoc(node, parserContext, { skipTemplateHelpers }) {
484
+ async function parseHtmlDoc(node, parserContext, { isForMigration }) {
482
485
  const { checker, sourceFile, config } = parserContext;
483
486
  // Parse the arguments to the `figma.connect()` call
484
487
  const { figmaNodeUrlArg, configObjArg } = parseFigmaConnectArgs(node, parserContext);
@@ -486,15 +489,12 @@ async function parseHtmlDoc(node, parserContext, { skipTemplateHelpers }) {
486
489
  let figmaNode = (0, compiler_1.stripQuotesFromNode)(figmaNodeUrlArg);
487
490
  // TODO This logic is duplicated in connect.ts transformDocFromParser due to some type issues
488
491
  if (config.documentUrlSubstitutions) {
489
- Object.entries(config.documentUrlSubstitutions).forEach(([from, to]) => {
490
- // @ts-expect-error
491
- figmaNode = figmaNode.replace(from, to);
492
- });
492
+ figmaNode = (0, helpers_1.applyDocumentUrlSubstitutions)(figmaNode, config.documentUrlSubstitutions);
493
493
  }
494
494
  const metadata = undefined;
495
495
  const props = propsArg ? (0, intrinsics_1.parsePropsObject)(propsArg, parserContext) : undefined;
496
496
  const render = exampleArg
497
- ? parseExampleTemplate(exampleArg, parserContext, props, skipTemplateHelpers)
497
+ ? parseExampleTemplate(exampleArg, parserContext, props, isForMigration)
498
498
  : undefined;
499
499
  const variant = variantArg ? (0, parser_common_1.parseVariant)(variantArg, sourceFile, checker) : undefined;
500
500
  const links = linksArg ? (0, parser_common_1.parseLinks)(linksArg, parserContext) : undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"parser.js","sourceRoot":"","sources":["../../src/html/parser.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyMA,oDAiPC;AAiID,oCAmEC;AA9nBD,yDAAoF;AACpF,qDAI+B;AAC/B,sDAA0F;AAE1F,uEAA0E;AAC1E,iCAA6B;AAC7B,mCAA8B;AAC9B,4DAUiC;AACjC,gDAAgF;AAChF,8EAA2E;AAC3E,uCAAiC;AAEjC,SAAS,yBAAyB,CAAC,IAAa;IAC9C,IAAI,oBAAE,CAAC,0BAA0B,CAAC,IAAI,CAAC,EAAE,CAAC;QACxC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAA;QACpB,IAAI,oBAAE,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAChD,OAAO,IAAI,CAAA;QACb,CAAC;IACH,CAAC;SAAM,IACL,oBAAE,CAAC,OAAO,CAAC,IAAI,CAAC;QAChB,IAAI,CAAC,UAAU,CAAC,MAAM,KAAK,CAAC;QAC5B,oBAAE,CAAC,iBAAiB,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QACxC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU;QAC7B,oBAAE,CAAC,0BAA0B,CAAC,IAAI,CAAC,UAAU,CAA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AAC,SAAS,CAAA;IAExE,IAAI,OAAO,GAAG,UAAU,CAAC,CAAC,CAAC,IAAA,4BAAY,EAAC,UAAU,EAAE,aAAa,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;IAE9E,IAAI,QAAQ,CAAA;IACZ,IAAI,MAAM,EAAE,IAAI,EAAE,CAAC;QACjB,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAA;IACxB,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,2BAAW,CAAC,GAAG,+BAAkB,iCAAiC,EAAE;YAC5E,UAAU;YACV,IAAI;SACL,CAAC,CAAA;IACJ,CAAC;IAED,OAAO;QACL,SAAS;QACT,KAAK,EAAE,kCAAwB,CAAC,IAAK;QACrC,QAAQ,EAAE,gDAAuB,CAAC,IAAI;QACtC,SAAS,EAAE,QAAQ,EAAE,SAAS;QAC9B,MAAM,EAAE,EAAE;QACV,cAAc,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE;QAC5B,OAAO;QACP,QAAQ;QACR,YAAY,EAAE;YACZ,qEAAqE;YACrE,uDAAuD;YACvD,KAAK;YACL,OAAO;YACP,wEAAwE;YACxE,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI;SAC1C;QACD,KAAK;QACL,QAAQ,EAAE;YACR,UAAU,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO;SAClD;KACF,CAAA;AACH,CAAC","sourcesContent":["import ts, { isReturnStatement, isTemplateExpression, SyntaxKind } from 'typescript'\nimport {\n stripQuotesFromNode,\n parsePropertyOfType,\n parseFunctionArgument,\n} from '../typescript/compiler'\nimport { FIGMA_CONNECT_CALL, PropMappings, parsePropsObject } from '../connect/intrinsics'\nimport { CodeConnectJSON } from '../connect/figma_connect'\nimport { getParsedTemplateHelpersString } from './parser_template_helpers'\nimport { JSDOM } from 'jsdom'\nimport { parse } from 'parse5'\nimport {\n makeCreatePropPlaceholder,\n ParserContext,\n visitPropReferencingNode,\n getReferencedPropsForTemplate,\n ParserError,\n parseLinks,\n parseVariant,\n parseImports,\n ParseOptions,\n} from '../connect/parser_common'\nimport { CodeConnectParser, DEFAULT_LABEL_PER_PARSER } from '../connect/project'\nimport { SyntaxHighlightLanguage } from '../connect/label_language_mapping'\nimport { format } from 'prettier'\n\nfunction getHtmlTaggedTemplateNode(node: ts.Node): ts.TaggedTemplateExpression | undefined {\n if (ts.isTaggedTemplateExpression(node)) {\n const tag = node.tag\n if (ts.isIdentifier(tag) && tag.text === 'html') {\n return node\n }\n } else if (\n ts.isBlock(node) &&\n node.statements.length === 1 &&\n ts.isReturnStatement(node.statements[0]) &&\n node.statements[0].expression &&\n ts.isTaggedTemplateExpression(node.statements[0].expression) &&\n ts.isIdentifier(node.statements[0].expression.tag) &&\n node.statements[0].expression.tag.text === 'html'\n ) {\n return node.statements[0].expression\n }\n\n return undefined\n}\n\n/**\n * This function converts the HTML template literal into a DOM (using JSDOM) to\n * extract information which is used in generating the template:\n * 1. A dictionary of template placeholders which correspond to HTML attribute\n * values. The key is the placeholder index, and the value is the attribute\n * name. The attribute name is unused (it used to be used in the output, but\n * we need to preserve case to support Angular, which JSDOM can't do unless\n * you use XHTML mode, and that doesn't support attributes without a value).\n * 2. Whether the template is \"nestable\" or not. A template is considered\n * nestable if it has only one top level element.\n *\n * For finding the attribute placeholders, the algorithm is as follows:\n * 1. Build up a full string from the template literal, replacing any value\n * ${placeholders} with `__FIGMA_PLACEHOLDER_0`, where 0 is the placeholder\n * index. This results in a valid HTML string, with placeholders we can later\n * detect.\n * 2. Use JSDOM to turn this into a DOM.\n * 3. Iterate over every node in the DOM, and if the node has any attributes\n * starting `__FIGMA_PLACEHOLDER`, store the info of these attributes. This\n * allows us to know which template literal placeholders correspond to HTML\n * attributes when we construct the template.\n */\nfunction getInfoFromDom(\n templateExp: ts.TemplateExpression | ts.TaggedTemplateExpression,\n parserContext: ParserContext,\n): {\n attributePlaceholders: Record<number, string>\n nestable: boolean\n} {\n let htmlString: string\n\n if (ts.isTemplateExpression(templateExp)) {\n // If this is a template expression, build up the HTML string with\n // identifiable placeholders as described above\n htmlString = templateExp.head.text\n templateExp.templateSpans.forEach((part, index) => {\n htmlString += `__FIGMA_PLACEHOLDER_${index}` + part.literal.text\n })\n } else if (templateExp.template.kind === ts.SyntaxKind.FirstTemplateToken) {\n // This is just a template literal with no placeholders\n htmlString = templateExp.template.text\n } else {\n // This should never happen as we check the type in the calling function\n throw new Error(`Unsupported template type: ${SyntaxKind[templateExp.template.kind]}`)\n }\n\n // First, check for HTML which we cannot handle. JSDOM is quite forgiving,\n // like a browser, but we need to be stricter\n //\n // Duplicate attribute names are handled gracefully by JSDOM (it just keeps\n // one of the attributes), but this breaks our algorithm because some of the\n // placeholders are no longer in the DOM. JSDOM has no way to detect this, but\n // parse5 (which is a library JSDOM uses under the hood) can detect this. We\n // just thrown an error in this case as there's no use case for doing this.\n parse(htmlString, {\n onParseError: (error) => {\n if (error.code === 'duplicate-attribute') {\n throw new ParserError(`Duplicate attribute name in example HTML`, {\n node: templateExp,\n sourceFile: parserContext.sourceFile,\n })\n }\n },\n })\n\n // Try to format the HTML with prettier, to catch any errors due to invalid\n // HTML which would otherwise result in broken formatting in the UI as\n // prettier is less forgiving\n try {\n // pluginSearchDirs: false is needed as otherwise prettier picks up other\n // prettier plugins in our monorepo and fails on CI\n format(htmlString, { parser: 'html', pluginSearchDirs: false })\n } catch (e) {\n throw new ParserError(`Error parsing example HTML. Check the HTML is valid.`, {\n node: templateExp,\n sourceFile: parserContext.sourceFile,\n })\n }\n\n // Create a DOM with JSDOM.\n //\n // JSDOM doesn't work properly in all cases if we parse a DOM without a full\n // document, e.g. Vue templates - when traversing with NodeIterator, it\n // doesn't find all elements. We create a Fragment then append it to a full\n // DOM to work around this. The extra wrapping elements don't matter, as we're\n // only interested in the attributes.\n const fragment = JSDOM.fragment(htmlString)\n const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>')\n dom.window.document.body.appendChild(fragment)\n\n const document = dom.window.document\n const NodeFilter = dom.window.NodeFilter\n\n const attributePlaceholders: Record<number, string> = {}\n\n function iterateNodeIterator(nodeIterator: NodeIterator) {\n let currentNode: Node | null\n\n while ((currentNode = nodeIterator.nextNode())) {\n // I couldn't work out how to do this in a way which satisfies TypeScript,\n // so using a check and a cast\n if (currentNode.nodeType === dom.window.Node.ELEMENT_NODE) {\n // Check for any attributes which correspond to placeholders in the\n // template literal, and store their index and name\n for (let attr of (currentNode as Element).attributes) {\n if (attr.value.startsWith('__FIGMA_PLACEHOLDER_')) {\n attributePlaceholders[parseInt(attr.value.split('__FIGMA_PLACEHOLDER_')[1])] = attr.name\n }\n }\n }\n\n // <TEMPLATE> nodes are not iterated over by default, as they are a way to\n // store a fragment which is not rendered immediately. These are used in\n // e.g. Vue templates, so we need to iterate over them explicitly.\n if (currentNode.nodeName === 'TEMPLATE') {\n const templateContent = (currentNode as HTMLTemplateElement).content\n const templateNodeIterator = document.createNodeIterator(\n templateContent,\n NodeFilter.SHOW_ELEMENT,\n null,\n )\n iterateNodeIterator(templateNodeIterator)\n }\n }\n }\n\n // Iterate over all the nodes in the DOM\n const nodeIterator = document.createNodeIterator(document.body, NodeFilter.SHOW_ELEMENT, null)\n iterateNodeIterator(nodeIterator)\n\n // We check if there is more than one top level child, as we use this as a\n // signal that the template is not \"nestable\" (and so we render an instance\n // pill rather than render the child's code inline in the UI)\n const topLevelChildrenCount = document.body.children.length\n\n return {\n attributePlaceholders,\n nestable: topLevelChildrenCount === 1,\n }\n}\n\nfunction escapeTemplateString(code: string) {\n return code.replace(/`/g, '\\\\`').replace(/\\$\\{/g, '\\\\${')\n}\n\n/**\n * Parses the example template string passed to `figma.connect()`.\n *\n * @param exp A function or arrow function expression\n * @param parserContext Parser context\n * @param propMappings Prop mappings object as returned by parseProps\n *\n * @returns The code of the render function and a list of imports\n */\nexport function parseExampleTemplate(\n exp: ts.ArrowFunction,\n parserContext: ParserContext,\n propMappings?: PropMappings,\n skipTemplateHelpers?: boolean,\n) {\n const { sourceFile } = parserContext\n\n if (exp.parameters.length > 1) {\n throw new ParserError(\n `Expected a single props parameter for the render function, got ${exp.parameters.length} parameters`,\n { sourceFile, node: exp },\n )\n }\n\n const propsParameter = exp.parameters[0]\n\n if (!exp.body) {\n throw new ParserError(`Expected a body for the render function`, { sourceFile, node: exp })\n }\n\n // If the body is a string literal, we generate a `figma.value` statement instead, which just\n // renders the string as-is in code examples\n if (ts.isStringLiteral(exp.body)) {\n const printer = ts.createPrinter()\n if (!exp.body) {\n throw new ParserError('Expected a function body', {\n sourceFile: parserContext.sourceFile,\n node: exp,\n })\n }\n let exampleCode = printer.printNode(ts.EmitHint.Unspecified, exp.body, sourceFile)\n\n let templateCode = ''\n if (!skipTemplateHelpers) {\n templateCode = getParsedTemplateHelpersString() + '\\n\\n'\n }\n\n templateCode += `const figma = require('figma')\\n\\n`\n\n templateCode += getReferencedPropsForTemplate({\n propMappings,\n exp,\n sourceFile,\n })\n\n exampleCode = exampleCode.replace(/`/g, '\\\\`')\n\n // Body is a string literal, so there aren't any placeholders\n templateCode += `export default figma.value(${exampleCode})\\n`\n\n return {\n code: templateCode,\n nestable: true,\n }\n }\n\n const templateNode = getHtmlTaggedTemplateNode(exp.body)\n\n if (!templateNode) {\n throw new ParserError(\n `Expected only a tagged template literal as the body of the render function`,\n { sourceFile, node: templateNode },\n )\n }\n\n // Keep track of any props which are referenced in the example so that we can\n // insert the appropriate `figma.properties` call in the JS template\n const referencedProps = new Set<string>()\n let exampleCode = ''\n let nestable = true\n\n if (isTemplateExpression(templateNode.template)) {\n // This is a template expression with placeholders\n\n const createPropPlaceholder = makeCreatePropPlaceholder({\n propMappings,\n referencedProps,\n sourceFile,\n })\n\n // Transform the template to replace any props references with placeholder\n // function calls, normalising the different types of props references\n const transformedTemplate = ts.transform(templateNode.template, [\n (context) => (rootNode) => {\n function visit(node: ts.Node): ts.Node {\n if (ts.isTemplateSpan(node)) {\n const visitResult = visitPropReferencingNode({\n propsParameter,\n node: node.expression,\n createPropPlaceholder,\n useJsx: false,\n })\n\n if (visitResult) {\n return ts.factory.createTemplateSpan(visitResult, node.literal)\n }\n }\n\n return ts.visitEachChild(node, visit, context)\n }\n return ts.visitNode(rootNode, visit) as typeof templateNode.template\n },\n ]).transformed[0] as typeof templateNode.template\n\n // Iterate over the template string spans (i.e. the interleaved strings and\n // placeholders) to build up our example code.\n //\n // Each time we encounter a placeholder (which by this point has been\n // normalised to a __PROP__ placeholder function call), we check if it\n // corresponds to a HTML attribute based on our previous DOM analysis (see\n // getInfoFromDom).\n //\n // If it does, we replace it with a call to\n // `_fcc_renderHtmlAttribute(\"attributeName\", propVariableName), otherwise\n // we replace it with a call to `_fcc_renderHtmlValue(propVariableName)`.\n //\n // We have some additional logic to handle cases where the user accidentally\n // writes `attribute=\"${props.prop}\"` rather than `attribute=${props.prop}`\n // (which is what we show in the docs), as it's easy to make this mistake\n // when copy/pasting.\n\n // Keep track of whether we're inside an attribute value that is wrapped in quotes,\n // so that we can strip the trailing quote if we are\n let insideAttributeWithQuotes = false\n\n const infoFromDom = getInfoFromDom(transformedTemplate, parserContext)\n const { attributePlaceholders } = infoFromDom\n nestable = infoFromDom.nestable\n\n // Handle a chunk of HTML, i.e. a text section of the template string. If\n // the next placeholder is an attribute and this chunk ends with a HTML\n // attribute (i.e. matches a regex like ` text=` or ` text=\"`), we remove the\n // attribute name so that it's not present in the low level template before the\n // call to _fcc_renderHtmlAttribute.\n function handleHtmlChunk(html: string, nextPlaceholderIsAttribute: boolean) {\n // If we were previously inside an attribute value placeholder with quotes\n // surrounding it, remove the leading quote. We do it like this rather\n // than always removing the leading quote to avoid situations where we\n // mistakenly remove a quote that is part of the actual content.\n if (insideAttributeWithQuotes) {\n html = html.replace(/^\"/g, '')\n }\n\n // If the next placeholder is an attribute, then match the start of the\n // attribute (`attribute=`) at the end of this chunk, so that we can\n // remove it from the example code and store the attribute name\n const attributeMatches = html.match(/(.*\\s)([^\\s]+)=\"?$/s)\n if (nextPlaceholderIsAttribute && attributeMatches) {\n // attributeMatches should always have matched here, but we check it\n // anyway so we can fail gracefully if not\n\n // Add the code up to the attribute, not including the ` attribute=`\n // part, as _fcc_renderHtmlAttribute is responsible for (maybe)\n // rendering that\n exampleCode += escapeTemplateString(attributeMatches[1])\n\n // If we are in this block, we know that we've matched an attribute, so\n // store whether it ends with a quote\n insideAttributeWithQuotes = html.endsWith('\"')\n\n // Return the attribute name so we can use it to construct the attribute\n // in the output. We do this rather than extract it from the HTML with\n // JSDOM because we want to preserve case, but do not want to parse the\n // doc as XHTML, so there's no way to do it otherwise.\n return attributeMatches[2]\n } else {\n // No attribute to remove, just add the code\n exampleCode += escapeTemplateString(html)\n insideAttributeWithQuotes = false\n }\n }\n\n // Process the first chunk, which is a special case as it is not in templateSpans\n let maybeAttributeName = handleHtmlChunk(\n transformedTemplate.head.text,\n attributePlaceholders[0] !== undefined,\n )\n\n // For each section of the template string, check that the expression is a\n // prop placeholder, then add the appropriate template function call\n transformedTemplate.templateSpans.forEach((part, index) => {\n if (!ts.isCallExpression(part.expression)) {\n throw new ParserError(\n `Expected a call expression as a placeholder in the template, got ${SyntaxKind[part.expression.kind]}`,\n { sourceFile, node: part.expression },\n )\n }\n\n const propNameArg = part.expression.arguments[0]\n if (!ts.isStringLiteral(propNameArg)) {\n throw new ParserError(\n `Expected a string literal as the argument to the placeholder call, got ${SyntaxKind[propNameArg.kind]}`,\n { sourceFile, node: propNameArg },\n )\n }\n\n const propVariableName = propNameArg.text\n\n if (attributePlaceholders[index]) {\n exampleCode += `\\${_fcc_renderHtmlAttribute('${maybeAttributeName}', ${propVariableName})}`\n } else {\n exampleCode += `\\${_fcc_renderHtmlValue(${propVariableName})}`\n }\n\n // Process the next chunk\n maybeAttributeName = handleHtmlChunk(\n part.literal.text,\n attributePlaceholders[index + 1] !== undefined,\n )\n })\n } else if (templateNode.template.kind === ts.SyntaxKind.FirstTemplateToken) {\n // Template string with no placeholders\n nestable = getInfoFromDom(templateNode, parserContext).nestable\n exampleCode = escapeTemplateString(templateNode.template.text)\n } else {\n throw new ParserError(\n `Expected a template expression as the body of the render function, got ${SyntaxKind[(templateNode.template as any).kind]}`,\n { sourceFile, node: templateNode.template },\n )\n }\n\n let templateCode = ''\n if (!skipTemplateHelpers) {\n templateCode = getParsedTemplateHelpersString() + '\\n\\n'\n }\n\n templateCode += `const figma = require('figma')\\n\\n`\n\n templateCode += getReferencedPropsForTemplate({\n propMappings,\n exp,\n sourceFile,\n })\n\n templateCode += `export default figma.html\\`${exampleCode}\\`\\n`\n\n return {\n code: templateCode,\n nestable,\n }\n}\n\nfunction parseFigmaConnectArgs(node: ts.CallExpression, parserContext: ParserContext) {\n const required = true\n\n const figmaNodeUrlArg = parseFunctionArgument(\n node,\n parserContext,\n 0,\n ts.isStringLiteral,\n required,\n `\\`${FIGMA_CONNECT_CALL}\\` must be called with a Figma Component URL as the first argument. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n example: () => html\\`<button />\\`\n})\\``,\n )!\n\n const configObjArg = parseFunctionArgument(\n node,\n parserContext,\n 1,\n ts.isObjectLiteralExpression,\n true,\n `The second argument to ${FIGMA_CONNECT_CALL}() must be an object literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n example: () => html\\`<button />\\`\n})\\``,\n )\n\n return {\n figmaNodeUrlArg,\n configObjArg,\n }\n}\n\nfunction parseConfigObjectArg(\n configArg: ts.ObjectLiteralExpression | undefined,\n parserContext: ParserContext,\n) {\n if (!configArg) {\n return {\n propsArg: undefined,\n exampleArg: undefined,\n variantArg: undefined,\n importsArg: undefined,\n linksArg: undefined,\n }\n }\n\n const propsArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'props',\n predicate: ts.isObjectLiteralExpression,\n parserContext,\n required: false,\n errorMessage: `The 'props' property must be an object literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n props: {\n disabled: figma.boolean('Disabled'),\n text: figma.string('TextContent'),\n },\n example: (props) => html\\`<my-button disabled=\\${props.disabled} label=\\${props.text} />\\`\n})\\``,\n })\n\n const exampleArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'example',\n predicate: ts.isArrowFunction,\n parserContext,\n required: true,\n errorMessage: `The 'example' property must be an arrow function which returns a html tagged template string. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n example: (props) => html\\`<my-button />\\`\n})\\``,\n })\n\n const variantArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'variant',\n predicate: ts.isObjectLiteralExpression,\n parserContext,\n required: false,\n errorMessage: `The 'variant' property must be an object literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n variant: {\n \"Has Icon\": true\n },\n example: (props) => html\\`<my-button />\\`\n})\\``,\n })\n\n const linksArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'links',\n predicate: ts.isArrayLiteralExpression,\n parserContext,\n required: false,\n errorMessage: `The 'links' property must be an array literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n links: [\n { name: 'Storybook', url: 'https://storybook.com' }\n ],\n example: (props) => html\\`<my-button />\\`\n})\\``,\n })\n\n const importsArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'imports',\n predicate: ts.isArrayLiteralExpression,\n parserContext,\n required: false,\n errorMessage: `The 'imports' property must be an array literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n imports: ['import { Button } from \"./Button\"']\n example: (props) => html\\`<my-button />\\`,\n})\\``,\n })\n\n return {\n propsArg,\n exampleArg,\n variantArg,\n linksArg,\n importsArg,\n }\n}\n\nexport async function parseHtmlDoc(\n node: ts.CallExpression,\n parserContext: ParserContext,\n { skipTemplateHelpers }: ParseOptions,\n): Promise<CodeConnectJSON> {\n const { checker, sourceFile, config } = parserContext\n\n // Parse the arguments to the `figma.connect()` call\n const { figmaNodeUrlArg, configObjArg } = parseFigmaConnectArgs(node, parserContext)\n\n const { propsArg, exampleArg, variantArg, linksArg, importsArg } = parseConfigObjectArg(\n configObjArg,\n parserContext,\n )\n\n let figmaNode = stripQuotesFromNode(figmaNodeUrlArg)\n // TODO This logic is duplicated in connect.ts transformDocFromParser due to some type issues\n if (config.documentUrlSubstitutions) {\n Object.entries(config.documentUrlSubstitutions).forEach(([from, to]) => {\n // @ts-expect-error\n figmaNode = figmaNode.replace(from, to)\n })\n }\n\n const metadata: any = undefined\n\n const props = propsArg ? parsePropsObject(propsArg, parserContext) : undefined\n const render = exampleArg\n ? parseExampleTemplate(exampleArg, parserContext, props, skipTemplateHelpers)\n : undefined\n const variant = variantArg ? parseVariant(variantArg, sourceFile, checker) : undefined\n const links = linksArg ? parseLinks(linksArg, parserContext) : undefined\n\n let imports = importsArg ? parseImports(importsArg, parserContext) : undefined\n\n let template\n if (render?.code) {\n template = render.code\n } else {\n throw new ParserError(`${FIGMA_CONNECT_CALL}() requires an example function`, {\n sourceFile,\n node,\n })\n }\n\n return {\n figmaNode,\n label: DEFAULT_LABEL_PER_PARSER.html!,\n language: SyntaxHighlightLanguage.HTML,\n component: metadata?.component,\n source: '',\n sourceLocation: { line: -1 },\n variant,\n template,\n templateData: {\n // TODO: `props` here is currently only used for validation purposes,\n // we should eventually remove it from the JSON payload\n props,\n imports,\n // If there's no render function, the default example is always nestable\n nestable: render ? render.nestable : true,\n },\n links,\n metadata: {\n cliVersion: require('../../package.json').version,\n },\n }\n}\n"]}
1
+ {"version":3,"file":"parser.js","sourceRoot":"","sources":["../../src/html/parser.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0MA,oDAmPC;AAiID,oCAgEC;AA9nBD,yDAAoF;AACpF,qDAI+B;AAC/B,sDAA0F;A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KAAK;YACL,OAAO;YACP,wEAAwE;YACxE,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI;SAC1C;QACD,KAAK;QACL,QAAQ,EAAE;YACR,UAAU,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO;SAClD;KACF,CAAA;AACH,CAAC","sourcesContent":["import ts, { isReturnStatement, isTemplateExpression, SyntaxKind } from 'typescript'\nimport {\n stripQuotesFromNode,\n parsePropertyOfType,\n parseFunctionArgument,\n} from '../typescript/compiler'\nimport { FIGMA_CONNECT_CALL, PropMappings, parsePropsObject } from '../connect/intrinsics'\nimport { CodeConnectJSON } from '../connect/figma_connect'\nimport { getParsedTemplateHelpersString } from './parser_template_helpers'\nimport { JSDOM } from 'jsdom'\nimport { parse } from 'parse5'\nimport {\n makeCreatePropPlaceholder,\n ParserContext,\n visitPropReferencingNode,\n getReferencedPropsForTemplate,\n ParserError,\n parseLinks,\n parseVariant,\n parseImports,\n ParseOptions,\n} from '../connect/parser_common'\nimport { applyDocumentUrlSubstitutions } from '../connect/helpers'\nimport { CodeConnectParser, DEFAULT_LABEL_PER_PARSER } from '../connect/project'\nimport { SyntaxHighlightLanguage } from '../connect/label_language_mapping'\nimport { format } from 'prettier'\n\nfunction getHtmlTaggedTemplateNode(node: ts.Node): ts.TaggedTemplateExpression | undefined {\n if (ts.isTaggedTemplateExpression(node)) {\n const tag = node.tag\n if (ts.isIdentifier(tag) && tag.text === 'html') {\n return node\n }\n } else if (\n ts.isBlock(node) &&\n node.statements.length === 1 &&\n ts.isReturnStatement(node.statements[0]) &&\n node.statements[0].expression &&\n ts.isTaggedTemplateExpression(node.statements[0].expression) &&\n ts.isIdentifier(node.statements[0].expression.tag) &&\n node.statements[0].expression.tag.text === 'html'\n ) {\n return node.statements[0].expression\n }\n\n return undefined\n}\n\n/**\n * This function converts the HTML template literal into a DOM (using JSDOM) to\n * extract information which is used in generating the template:\n * 1. A dictionary of template placeholders which correspond to HTML attribute\n * values. The key is the placeholder index, and the value is the attribute\n * name. The attribute name is unused (it used to be used in the output, but\n * we need to preserve case to support Angular, which JSDOM can't do unless\n * you use XHTML mode, and that doesn't support attributes without a value).\n * 2. Whether the template is \"nestable\" or not. A template is considered\n * nestable if it has only one top level element.\n *\n * For finding the attribute placeholders, the algorithm is as follows:\n * 1. Build up a full string from the template literal, replacing any value\n * ${placeholders} with `__FIGMA_PLACEHOLDER_0`, where 0 is the placeholder\n * index. This results in a valid HTML string, with placeholders we can later\n * detect.\n * 2. Use JSDOM to turn this into a DOM.\n * 3. Iterate over every node in the DOM, and if the node has any attributes\n * starting `__FIGMA_PLACEHOLDER`, store the info of these attributes. This\n * allows us to know which template literal placeholders correspond to HTML\n * attributes when we construct the template.\n */\nfunction getInfoFromDom(\n templateExp: ts.TemplateExpression | ts.TaggedTemplateExpression,\n parserContext: ParserContext,\n): {\n attributePlaceholders: Record<number, string>\n nestable: boolean\n} {\n let htmlString: string\n\n if (ts.isTemplateExpression(templateExp)) {\n // If this is a template expression, build up the HTML string with\n // identifiable placeholders as described above\n htmlString = templateExp.head.text\n templateExp.templateSpans.forEach((part, index) => {\n htmlString += `__FIGMA_PLACEHOLDER_${index}` + part.literal.text\n })\n } else if (templateExp.template.kind === ts.SyntaxKind.FirstTemplateToken) {\n // This is just a template literal with no placeholders\n htmlString = templateExp.template.text\n } else {\n // This should never happen as we check the type in the calling function\n throw new Error(`Unsupported template type: ${SyntaxKind[templateExp.template.kind]}`)\n }\n\n // First, check for HTML which we cannot handle. JSDOM is quite forgiving,\n // like a browser, but we need to be stricter\n //\n // Duplicate attribute names are handled gracefully by JSDOM (it just keeps\n // one of the attributes), but this breaks our algorithm because some of the\n // placeholders are no longer in the DOM. JSDOM has no way to detect this, but\n // parse5 (which is a library JSDOM uses under the hood) can detect this. We\n // just thrown an error in this case as there's no use case for doing this.\n parse(htmlString, {\n onParseError: (error) => {\n if (error.code === 'duplicate-attribute') {\n throw new ParserError(`Duplicate attribute name in example HTML`, {\n node: templateExp,\n sourceFile: parserContext.sourceFile,\n })\n }\n },\n })\n\n // Try to format the HTML with prettier, to catch any errors due to invalid\n // HTML which would otherwise result in broken formatting in the UI as\n // prettier is less forgiving\n try {\n // pluginSearchDirs: false is needed as otherwise prettier picks up other\n // prettier plugins in our monorepo and fails on CI\n format(htmlString, { parser: 'html', pluginSearchDirs: false })\n } catch (e) {\n throw new ParserError(`Error parsing example HTML. Check the HTML is valid.`, {\n node: templateExp,\n sourceFile: parserContext.sourceFile,\n })\n }\n\n // Create a DOM with JSDOM.\n //\n // JSDOM doesn't work properly in all cases if we parse a DOM without a full\n // document, e.g. Vue templates - when traversing with NodeIterator, it\n // doesn't find all elements. We create a Fragment then append it to a full\n // DOM to work around this. The extra wrapping elements don't matter, as we're\n // only interested in the attributes.\n const fragment = JSDOM.fragment(htmlString)\n const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>')\n dom.window.document.body.appendChild(fragment)\n\n const document = dom.window.document\n const NodeFilter = dom.window.NodeFilter\n\n const attributePlaceholders: Record<number, string> = {}\n\n function iterateNodeIterator(nodeIterator: NodeIterator) {\n let currentNode: Node | null\n\n while ((currentNode = nodeIterator.nextNode())) {\n // I couldn't work out how to do this in a way which satisfies TypeScript,\n // so using a check and a cast\n if (currentNode.nodeType === dom.window.Node.ELEMENT_NODE) {\n // Check for any attributes which correspond to placeholders in the\n // template literal, and store their index and name\n for (let attr of (currentNode as Element).attributes) {\n if (attr.value.startsWith('__FIGMA_PLACEHOLDER_')) {\n attributePlaceholders[parseInt(attr.value.split('__FIGMA_PLACEHOLDER_')[1])] = attr.name\n }\n }\n }\n\n // <TEMPLATE> nodes are not iterated over by default, as they are a way to\n // store a fragment which is not rendered immediately. These are used in\n // e.g. Vue templates, so we need to iterate over them explicitly.\n if (currentNode.nodeName === 'TEMPLATE') {\n const templateContent = (currentNode as HTMLTemplateElement).content\n const templateNodeIterator = document.createNodeIterator(\n templateContent,\n NodeFilter.SHOW_ELEMENT,\n null,\n )\n iterateNodeIterator(templateNodeIterator)\n }\n }\n }\n\n // Iterate over all the nodes in the DOM\n const nodeIterator = document.createNodeIterator(document.body, NodeFilter.SHOW_ELEMENT, null)\n iterateNodeIterator(nodeIterator)\n\n // We check if there is more than one top level child, as we use this as a\n // signal that the template is not \"nestable\" (and so we render an instance\n // pill rather than render the child's code inline in the UI)\n const topLevelChildrenCount = document.body.children.length\n\n return {\n attributePlaceholders,\n nestable: topLevelChildrenCount === 1,\n }\n}\n\nfunction escapeTemplateString(code: string) {\n return code.replace(/`/g, '\\\\`').replace(/\\$\\{/g, '\\\\${')\n}\n\n/**\n * Parses the example template string passed to `figma.connect()`.\n *\n * @param exp A function or arrow function expression\n * @param parserContext Parser context\n * @param propMappings Prop mappings object as returned by parseProps\n *\n * @returns The code of the render function and a list of imports\n */\nexport function parseExampleTemplate(\n exp: ts.ArrowFunction,\n parserContext: ParserContext,\n propMappings?: PropMappings,\n isForMigration?: boolean,\n) {\n const { sourceFile } = parserContext\n\n if (exp.parameters.length > 1) {\n throw new ParserError(\n `Expected a single props parameter for the render function, got ${exp.parameters.length} parameters`,\n { sourceFile, node: exp },\n )\n }\n\n const propsParameter = exp.parameters[0]\n\n if (!exp.body) {\n throw new ParserError(`Expected a body for the render function`, { sourceFile, node: exp })\n }\n\n // If the body is a string literal, we generate a `figma.value` statement instead, which just\n // renders the string as-is in code examples\n if (ts.isStringLiteral(exp.body)) {\n const printer = ts.createPrinter()\n if (!exp.body) {\n throw new ParserError('Expected a function body', {\n sourceFile: parserContext.sourceFile,\n node: exp,\n })\n }\n let exampleCode = printer.printNode(ts.EmitHint.Unspecified, exp.body, sourceFile)\n\n let templateCode = ''\n if (!isForMigration) {\n templateCode = getParsedTemplateHelpersString() + '\\n\\n'\n }\n\n templateCode += `const figma = require('figma')\\n\\n`\n\n templateCode += getReferencedPropsForTemplate({\n propMappings,\n exp,\n sourceFile,\n isForMigration,\n })\n\n exampleCode = exampleCode.replace(/`/g, '\\\\`')\n\n // Body is a string literal, so there aren't any placeholders\n templateCode += `export default figma.value(${exampleCode})\\n`\n\n return {\n code: templateCode,\n nestable: true,\n }\n }\n\n const templateNode = getHtmlTaggedTemplateNode(exp.body)\n\n if (!templateNode) {\n throw new ParserError(\n `Expected only a tagged template literal as the body of the render function`,\n { sourceFile, node: templateNode },\n )\n }\n\n // Keep track of any props which are referenced in the example so that we can\n // insert the appropriate `figma.properties` call in the JS template\n const referencedProps = new Set<string>()\n let exampleCode = ''\n let nestable = true\n\n if (isTemplateExpression(templateNode.template)) {\n // This is a template expression with placeholders\n\n const createPropPlaceholder = makeCreatePropPlaceholder({\n propMappings,\n referencedProps,\n sourceFile,\n })\n\n // Transform the template to replace any props references with placeholder\n // function calls, normalising the different types of props references\n const transformedTemplate = ts.transform(templateNode.template, [\n (context) => (rootNode) => {\n function visit(node: ts.Node): ts.Node {\n if (ts.isTemplateSpan(node)) {\n const visitResult = visitPropReferencingNode({\n propsParameter,\n node: node.expression,\n createPropPlaceholder,\n useJsx: false,\n })\n\n if (visitResult) {\n return ts.factory.createTemplateSpan(visitResult, node.literal)\n }\n }\n\n return ts.visitEachChild(node, visit, context)\n }\n return ts.visitNode(rootNode, visit) as typeof templateNode.template\n },\n ]).transformed[0] as typeof templateNode.template\n\n // Iterate over the template string spans (i.e. the interleaved strings and\n // placeholders) to build up our example code.\n //\n // Each time we encounter a placeholder (which by this point has been\n // normalised to a __PROP__ placeholder function call), we check if it\n // corresponds to a HTML attribute based on our previous DOM analysis (see\n // getInfoFromDom).\n //\n // If it does, we replace it with a call to\n // `_fcc_renderHtmlAttribute(\"attributeName\", propVariableName), otherwise\n // we replace it with a call to `_fcc_renderHtmlValue(propVariableName)`.\n //\n // We have some additional logic to handle cases where the user accidentally\n // writes `attribute=\"${props.prop}\"` rather than `attribute=${props.prop}`\n // (which is what we show in the docs), as it's easy to make this mistake\n // when copy/pasting.\n\n // Keep track of whether we're inside an attribute value that is wrapped in quotes,\n // so that we can strip the trailing quote if we are\n let insideAttributeWithQuotes = false\n\n const infoFromDom = getInfoFromDom(transformedTemplate, parserContext)\n const { attributePlaceholders } = infoFromDom\n nestable = infoFromDom.nestable\n\n // Handle a chunk of HTML, i.e. a text section of the template string. If\n // the next placeholder is an attribute and this chunk ends with a HTML\n // attribute (i.e. matches a regex like ` text=` or ` text=\"`), we remove the\n // attribute name so that it's not present in the low level template before the\n // call to _fcc_renderHtmlAttribute.\n function handleHtmlChunk(html: string, nextPlaceholderIsAttribute: boolean) {\n // If we were previously inside an attribute value placeholder with quotes\n // surrounding it, remove the leading quote. We do it like this rather\n // than always removing the leading quote to avoid situations where we\n // mistakenly remove a quote that is part of the actual content.\n if (insideAttributeWithQuotes) {\n html = html.replace(/^\"/g, '')\n }\n\n // If the next placeholder is an attribute, then match the start of the\n // attribute (`attribute=`) at the end of this chunk, so that we can\n // remove it from the example code and store the attribute name\n const attributeMatches = html.match(/(.*\\s)([^\\s]+)=\"?$/s)\n if (nextPlaceholderIsAttribute && attributeMatches) {\n // attributeMatches should always have matched here, but we check it\n // anyway so we can fail gracefully if not\n\n // Add the code up to the attribute, not including the ` attribute=`\n // part, as _fcc_renderHtmlAttribute is responsible for (maybe)\n // rendering that\n exampleCode += escapeTemplateString(attributeMatches[1])\n\n // If we are in this block, we know that we've matched an attribute, so\n // store whether it ends with a quote\n insideAttributeWithQuotes = html.endsWith('\"')\n\n // Return the attribute name so we can use it to construct the attribute\n // in the output. We do this rather than extract it from the HTML with\n // JSDOM because we want to preserve case, but do not want to parse the\n // doc as XHTML, so there's no way to do it otherwise.\n return attributeMatches[2]\n } else {\n // No attribute to remove, just add the code\n exampleCode += escapeTemplateString(html)\n insideAttributeWithQuotes = false\n }\n }\n\n // Process the first chunk, which is a special case as it is not in templateSpans\n let maybeAttributeName = handleHtmlChunk(\n transformedTemplate.head.text,\n attributePlaceholders[0] !== undefined,\n )\n\n // For each section of the template string, check that the expression is a\n // prop placeholder, then add the appropriate template function call\n transformedTemplate.templateSpans.forEach((part, index) => {\n if (!ts.isCallExpression(part.expression)) {\n throw new ParserError(\n `Expected a call expression as a placeholder in the template, got ${SyntaxKind[part.expression.kind]}`,\n { sourceFile, node: part.expression },\n )\n }\n\n const propNameArg = part.expression.arguments[0]\n if (!ts.isStringLiteral(propNameArg)) {\n throw new ParserError(\n `Expected a string literal as the argument to the placeholder call, got ${SyntaxKind[propNameArg.kind]}`,\n { sourceFile, node: propNameArg },\n )\n }\n\n const propVariableName = propNameArg.text\n\n if (attributePlaceholders[index]) {\n exampleCode += `\\${_fcc_renderHtmlAttribute('${maybeAttributeName}', ${propVariableName})}`\n } else {\n exampleCode += `\\${_fcc_renderHtmlValue(${propVariableName})}`\n }\n\n // Process the next chunk\n maybeAttributeName = handleHtmlChunk(\n part.literal.text,\n attributePlaceholders[index + 1] !== undefined,\n )\n })\n } else if (templateNode.template.kind === ts.SyntaxKind.FirstTemplateToken) {\n // Template string with no placeholders\n nestable = getInfoFromDom(templateNode, parserContext).nestable\n exampleCode = escapeTemplateString(templateNode.template.text)\n } else {\n throw new ParserError(\n `Expected a template expression as the body of the render function, got ${SyntaxKind[(templateNode.template as any).kind]}`,\n { sourceFile, node: templateNode.template },\n )\n }\n\n let templateCode = ''\n if (!isForMigration) {\n templateCode = getParsedTemplateHelpersString() + '\\n\\n'\n }\n\n templateCode += `const figma = require('figma')\\n\\n`\n\n templateCode += getReferencedPropsForTemplate({\n propMappings,\n exp,\n sourceFile,\n isForMigration,\n })\n\n templateCode += `export default figma.html\\`${exampleCode}\\`\\n`\n\n return {\n code: templateCode,\n nestable,\n }\n}\n\nfunction parseFigmaConnectArgs(node: ts.CallExpression, parserContext: ParserContext) {\n const required = true\n\n const figmaNodeUrlArg = parseFunctionArgument(\n node,\n parserContext,\n 0,\n ts.isStringLiteral,\n required,\n `\\`${FIGMA_CONNECT_CALL}\\` must be called with a Figma Component URL as the first argument. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n example: () => html\\`<button />\\`\n})\\``,\n )!\n\n const configObjArg = parseFunctionArgument(\n node,\n parserContext,\n 1,\n ts.isObjectLiteralExpression,\n true,\n `The second argument to ${FIGMA_CONNECT_CALL}() must be an object literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n example: () => html\\`<button />\\`\n})\\``,\n )\n\n return {\n figmaNodeUrlArg,\n configObjArg,\n }\n}\n\nfunction parseConfigObjectArg(\n configArg: ts.ObjectLiteralExpression | undefined,\n parserContext: ParserContext,\n) {\n if (!configArg) {\n return {\n propsArg: undefined,\n exampleArg: undefined,\n variantArg: undefined,\n importsArg: undefined,\n linksArg: undefined,\n }\n }\n\n const propsArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'props',\n predicate: ts.isObjectLiteralExpression,\n parserContext,\n required: false,\n errorMessage: `The 'props' property must be an object literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n props: {\n disabled: figma.boolean('Disabled'),\n text: figma.string('TextContent'),\n },\n example: (props) => html\\`<my-button disabled=\\${props.disabled} label=\\${props.text} />\\`\n})\\``,\n })\n\n const exampleArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'example',\n predicate: ts.isArrowFunction,\n parserContext,\n required: true,\n errorMessage: `The 'example' property must be an arrow function which returns a html tagged template string. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n example: (props) => html\\`<my-button />\\`\n})\\``,\n })\n\n const variantArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'variant',\n predicate: ts.isObjectLiteralExpression,\n parserContext,\n required: false,\n errorMessage: `The 'variant' property must be an object literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n variant: {\n \"Has Icon\": true\n },\n example: (props) => html\\`<my-button />\\`\n})\\``,\n })\n\n const linksArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'links',\n predicate: ts.isArrayLiteralExpression,\n parserContext,\n required: false,\n errorMessage: `The 'links' property must be an array literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n links: [\n { name: 'Storybook', url: 'https://storybook.com' }\n ],\n example: (props) => html\\`<my-button />\\`\n})\\``,\n })\n\n const importsArg = parsePropertyOfType({\n objectLiteralNode: configArg,\n propertyName: 'imports',\n predicate: ts.isArrayLiteralExpression,\n parserContext,\n required: false,\n errorMessage: `The 'imports' property must be an array literal. Example usage:\n\\`${FIGMA_CONNECT_CALL}('https://www.figma.com/file/123?node-id=1-1', {\n imports: ['import { Button } from \"./Button\"']\n example: (props) => html\\`<my-button />\\`,\n})\\``,\n })\n\n return {\n propsArg,\n exampleArg,\n variantArg,\n linksArg,\n importsArg,\n }\n}\n\nexport async function parseHtmlDoc(\n node: ts.CallExpression,\n parserContext: ParserContext,\n { isForMigration }: ParseOptions,\n): Promise<CodeConnectJSON> {\n const { checker, sourceFile, config } = parserContext\n\n // Parse the arguments to the `figma.connect()` call\n const { figmaNodeUrlArg, configObjArg } = parseFigmaConnectArgs(node, parserContext)\n\n const { propsArg, exampleArg, variantArg, linksArg, importsArg } = parseConfigObjectArg(\n configObjArg,\n parserContext,\n )\n\n let figmaNode = stripQuotesFromNode(figmaNodeUrlArg)\n // TODO This logic is duplicated in connect.ts transformDocFromParser due to some type issues\n if (config.documentUrlSubstitutions) {\n figmaNode = applyDocumentUrlSubstitutions(figmaNode as string, config.documentUrlSubstitutions)\n }\n\n const metadata: any = undefined\n\n const props = propsArg ? parsePropsObject(propsArg, parserContext) : undefined\n const render = exampleArg\n ? parseExampleTemplate(exampleArg, parserContext, props, isForMigration)\n : undefined\n const variant = variantArg ? parseVariant(variantArg, sourceFile, checker) : undefined\n const links = linksArg ? parseLinks(linksArg, parserContext) : undefined\n\n let imports = importsArg ? parseImports(importsArg, parserContext) : undefined\n\n let template\n if (render?.code) {\n template = render.code\n } else {\n throw new ParserError(`${FIGMA_CONNECT_CALL}() requires an example function`, {\n sourceFile,\n node,\n })\n }\n\n return {\n figmaNode,\n label: DEFAULT_LABEL_PER_PARSER.html!,\n language: SyntaxHighlightLanguage.HTML,\n component: metadata?.component,\n source: '',\n sourceLocation: { line: -1 },\n variant,\n template,\n templateData: {\n // TODO: `props` here is currently only used for validation purposes,\n // we should eventually remove it from the JSON payload\n props,\n imports,\n // If there's no render function, the default example is always nestable\n nestable: render ? render.nestable : true,\n },\n links,\n metadata: {\n cliVersion: require('../../package.json').version,\n },\n }\n}\n"]}
@@ -55,7 +55,7 @@ export declare function parseRenderFunctionExpression(exp: ts.ArrowFunction | ts
55
55
  *
56
56
  * @returns The code of the render function and a list of imports
57
57
  */
58
- export declare function parseJSXRenderFunction(exp: ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration, parserContext: ParserContext, propMappings?: PropMappings, skipTemplateHelpers?: boolean): {
58
+ export declare function parseJSXRenderFunction(exp: ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration, parserContext: ParserContext, propMappings?: PropMappings, isForMigration?: boolean): {
59
59
  code: string;
60
60
  imports: {
61
61
  statement: string;
@@ -68,7 +68,7 @@ export declare function parseJSXRenderFunction(exp: ts.ArrowFunction | ts.Functi
68
68
  * Parses the render function for a value (i.e. example which returns a string or React
69
69
  * component reference, not JSX) passed to `figma.connect()`
70
70
  */
71
- export declare function parseValueRenderFunction(exp: ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration, parserContext: ParserContext, propMappings?: PropMappings, skipTemplateHelpers?: boolean): {
71
+ export declare function parseValueRenderFunction(exp: ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration, parserContext: ParserContext, propMappings?: PropMappings, isForMigration?: boolean): {
72
72
  code: string;
73
73
  imports: {
74
74
  statement: string;
@@ -79,5 +79,5 @@ export declare function parseValueRenderFunction(exp: ts.ArrowFunction | ts.Func
79
79
  };
80
80
  export declare function replacePropPlaceholders(exampleCode: string): string;
81
81
  export declare function getDefaultTemplate(componentMetadata: Awaited<ReturnType<typeof parseComponentMetadata>>): string;
82
- export declare function parseReactDoc(node: ts.CallExpression, parserContext: ParserContext, { repoUrl, silent, skipTemplateHelpers }: ParseOptions): Promise<CodeConnectJSON>;
82
+ export declare function parseReactDoc(node: ts.CallExpression, parserContext: ParserContext, { repoUrl, silent, isForMigration }: ParseOptions): Promise<CodeConnectJSON>;
83
83
  //# sourceMappingURL=parser.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../../src/react/parser.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,YAAY,CAAA;AAkB3B,OAAO,EAAsB,YAAY,EAAoB,MAAM,uBAAuB,CAAA;AAC1F,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAE1D,OAAO,EAIL,aAAa,EAQb,YAAY,EACb,MAAM,0BAA0B,CAAA;AAEjC;;;;GAIG;AACH,wBAAgB,cAAc,CAC5B,IAAI,EAAE,EAAE,CAAC,IAAI,GACZ,EAAE,CAAC,UAAU,GAAG,EAAE,CAAC,qBAAqB,GAAG,EAAE,CAAC,WAAW,GAAG,SAAS,CAMvE;AAiED,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,EAAE,UAAU,EAAE,EAAE,CAAC,UAAU,0BAanF;AA0ED,MAAM,MAAM,sBAAsB,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAE3D;;;;;;;;;GASG;AACH,wBAAsB,sBAAsB,CAC1C,IAAI,EAAE,EAAE,CAAC,wBAAwB,GAAG,EAAE,CAAC,UAAU,GAAG,EAAE,CAAC,UAAU,EACjE,aAAa,EAAE,aAAa,EAC5B,MAAM,CAAC,EAAE,OAAO;;;;GA4GjB;AAED;;;;;;;;;GASG;AACH,wBAAgB,6BAA6B,CAC3C,GAAG,EAAE,EAAE,CAAC,aAAa,GAAG,EAAE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mBAAmB,EACtE,aAAa,EAAE,aAAa,EAC5B,YAAY,CAAC,EAAE,YAAY,EAC3B,cAAc,CAAC,EAAE,OAAO;;;mBAqCX,MAAM;cACX,MAAM;yBACK,MAAM;;;EAyB1B;AAED,wBAAgB,uBAAuB,CAAC,WAAW,EAAE,MAAM,UA+B1D;AA+LD,wBAAgB,kBAAkB,CAChC,iBAAiB,EAAE,OAAO,CAAC,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC,UAItE;AAED,wBAAsB,aAAa,CACjC,IAAI,EAAE,EAAE,CAAC,cAAc,EACvB,aAAa,EAAE,aAAa,EAC5B,EAAE,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,EAAE,YAAY,GAChD,OAAO,CAAC,eAAe,CAAC,CA6H1B"}
@@ -17,6 +17,7 @@ const project_1 = require("../connect/project");
17
17
  const label_language_mapping_1 = require("../connect/label_language_mapping");
18
18
  const logging_1 = require("../common/logging");
19
19
  const compiler_1 = require("../typescript/compiler");
20
+ const helpers_1 = require("../connect/helpers");
20
21
  const intrinsics_1 = require("../connect/intrinsics");
21
22
  const parser_template_helpers_1 = require("./parser_template_helpers");
22
23
  const parser_common_1 = require("../connect/parser_common");
@@ -395,13 +396,13 @@ function parseRenderFunctionExpression(exp, parserContext, propMappings) {
395
396
  *
396
397
  * @returns The code of the render function and a list of imports
397
398
  */
398
- function parseJSXRenderFunction(exp, parserContext, propMappings, skipTemplateHelpers) {
399
+ function parseJSXRenderFunction(exp, parserContext, propMappings, isForMigration) {
399
400
  const { sourceFile } = parserContext;
400
401
  const { code, imports, nestable, referencedProps } = parseRenderFunctionExpression(exp, parserContext, propMappings);
401
402
  let templateCode = '';
402
403
  // Generate the template code
403
404
  // Inject React-specific template helper functions
404
- if (!skipTemplateHelpers) {
405
+ if (!isForMigration) {
405
406
  templateCode = (0, parser_template_helpers_1.getParsedTemplateHelpersString)() + '\n\n';
406
407
  }
407
408
  // Require the template API
@@ -412,6 +413,7 @@ function parseJSXRenderFunction(exp, parserContext, propMappings, skipTemplateHe
412
413
  propMappings,
413
414
  exp,
414
415
  sourceFile,
416
+ isForMigration,
415
417
  });
416
418
  const includeMetadata = propMappings && Object.keys(propMappings).length > 0;
417
419
  // Finally, output the example code
@@ -428,7 +430,7 @@ function parseJSXRenderFunction(exp, parserContext, propMappings, skipTemplateHe
428
430
  * Parses the render function for a value (i.e. example which returns a string or React
429
431
  * component reference, not JSX) passed to `figma.connect()`
430
432
  */
431
- function parseValueRenderFunction(exp, parserContext, propMappings, skipTemplateHelpers) {
433
+ function parseValueRenderFunction(exp, parserContext, propMappings, isForMigration) {
432
434
  const { sourceFile } = parserContext;
433
435
  const printer = typescript_1.default.createPrinter();
434
436
  if (!exp.body) {
@@ -442,7 +444,7 @@ function parseValueRenderFunction(exp, parserContext, propMappings, skipTemplate
442
444
  let templateCode = '';
443
445
  // Generate the template code
444
446
  // Inject React-specific template helper functions
445
- if (!skipTemplateHelpers) {
447
+ if (!isForMigration) {
446
448
  templateCode = (0, parser_template_helpers_1.getParsedTemplateHelpersString)() + '\n\n';
447
449
  }
448
450
  // Require the template API
@@ -453,6 +455,7 @@ function parseValueRenderFunction(exp, parserContext, propMappings, skipTemplate
453
455
  propMappings,
454
456
  exp,
455
457
  sourceFile,
458
+ isForMigration,
456
459
  });
457
460
  // Escape backticks from the example code
458
461
  exampleCode = exampleCode.replace(/`/g, '\\`');
@@ -645,7 +648,7 @@ function getDefaultTemplate(componentMetadata) {
645
648
  const example = `<${componentMetadata.component} />`;
646
649
  return `const figma = require("figma")\n\nexport default figma.tsx\`${example}\``;
647
650
  }
648
- async function parseReactDoc(node, parserContext, { repoUrl, silent, skipTemplateHelpers }) {
651
+ async function parseReactDoc(node, parserContext, { repoUrl, silent, isForMigration }) {
649
652
  const { checker, sourceFile, config } = parserContext;
650
653
  // Parse the arguments to the `figma.connect()` call
651
654
  const { componentArg, figmaNodeUrlArg, configObjArg } = parseFigmaConnectArgs(node, parserContext);
@@ -653,10 +656,7 @@ async function parseReactDoc(node, parserContext, { repoUrl, silent, skipTemplat
653
656
  let figmaNode = (0, compiler_1.stripQuotesFromNode)(figmaNodeUrlArg);
654
657
  // TODO This logic is duplicated in connect.ts transformDocFromParser due to some type issues
655
658
  if (config.documentUrlSubstitutions) {
656
- Object.entries(config.documentUrlSubstitutions).forEach(([from, to]) => {
657
- // @ts-expect-error
658
- figmaNode = figmaNode.replace(from, to);
659
- });
659
+ figmaNode = (0, helpers_1.applyDocumentUrlSubstitutions)(figmaNode, config.documentUrlSubstitutions);
660
660
  }
661
661
  const metadata = componentArg
662
662
  ? await parseComponentMetadata(componentArg, parserContext, silent)
@@ -664,8 +664,8 @@ async function parseReactDoc(node, parserContext, { repoUrl, silent, skipTemplat
664
664
  const props = propsArg ? (0, intrinsics_1.parsePropsObject)(propsArg, parserContext) : undefined;
665
665
  const render = exampleArg
666
666
  ? findJSXElement(exampleArg)
667
- ? parseJSXRenderFunction(exampleArg, parserContext, props, skipTemplateHelpers)
668
- : parseValueRenderFunction(exampleArg, parserContext, props, skipTemplateHelpers)
667
+ ? parseJSXRenderFunction(exampleArg, parserContext, props, isForMigration)
668
+ : parseValueRenderFunction(exampleArg, parserContext, props, isForMigration)
669
669
  : undefined;
670
670
  const variant = variantArg ? (0, parser_common_1.parseVariant)(variantArg, sourceFile, checker) : undefined;
671
671
  const links = linksArg ? (0, parser_common_1.parseLinks)(linksArg, parserContext) : undefined;
@@ -734,7 +734,9 @@ async function parseReactDoc(node, parserContext, { repoUrl, silent, skipTemplat
734
734
  label: project_1.DEFAULT_LABEL_PER_PARSER.react,
735
735
  language: label_language_mapping_1.SyntaxHighlightLanguage.TypeScript,
736
736
  component: metadata?.component,
737
- source: metadata?.source ? (0, project_1.getRemoteFileUrl)(metadata.source, repoUrl) : '',
737
+ source: metadata?.source
738
+ ? (0, project_1.getRemoteFileUrl)(metadata.source, repoUrl, parserContext.config?.defaultBranch)
739
+ : '',
738
740
  sourceLocation: metadata?.line !== undefined ? { line: metadata.line } : { line: -1 },
739
741
  variant,
740
742
  template,