@figma/code-connect 1.4.3 → 1.4.5

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 (52) hide show
  1. package/dist/commands/connect.d.ts.map +1 -1
  2. package/dist/commands/connect.js +61 -10
  3. package/dist/commands/connect.js.map +1 -1
  4. package/dist/commands/connect_template.d.ts +36 -0
  5. package/dist/commands/connect_template.d.ts.map +1 -0
  6. package/dist/commands/connect_template.js +324 -0
  7. package/dist/commands/connect_template.js.map +1 -0
  8. package/dist/commands/preview_utils.d.ts +49 -0
  9. package/dist/commands/preview_utils.d.ts.map +1 -0
  10. package/dist/commands/preview_utils.js +451 -0
  11. package/dist/commands/preview_utils.js.map +1 -0
  12. package/dist/connect/batch_templates.d.ts +11 -0
  13. package/dist/connect/batch_templates.d.ts.map +1 -0
  14. package/dist/connect/batch_templates.js +70 -0
  15. package/dist/connect/batch_templates.js.map +1 -0
  16. package/dist/connect/create.d.ts.map +1 -1
  17. package/dist/connect/create.js +13 -0
  18. package/dist/connect/create.js.map +1 -1
  19. package/dist/connect/create_template.d.ts +22 -0
  20. package/dist/connect/create_template.d.ts.map +1 -0
  21. package/dist/connect/create_template.js +195 -0
  22. package/dist/connect/create_template.js.map +1 -0
  23. package/dist/connect/delete_docs.d.ts +2 -1
  24. package/dist/connect/delete_docs.d.ts.map +1 -1
  25. package/dist/connect/delete_docs.js +2 -2
  26. package/dist/connect/delete_docs.js.map +1 -1
  27. package/dist/connect/figma_rest_api.d.ts +1 -5
  28. package/dist/connect/figma_rest_api.d.ts.map +1 -1
  29. package/dist/connect/figma_rest_api.js +9 -3
  30. package/dist/connect/figma_rest_api.js.map +1 -1
  31. package/dist/connect/project.d.ts +9 -7
  32. package/dist/connect/project.d.ts.map +1 -1
  33. package/dist/connect/project.js +39 -25
  34. package/dist/connect/project.js.map +1 -1
  35. package/dist/connect/raw_templates.d.ts +8 -1
  36. package/dist/connect/raw_templates.d.ts.map +1 -1
  37. package/dist/connect/raw_templates.js +20 -7
  38. package/dist/connect/raw_templates.js.map +1 -1
  39. package/dist/connect/upload.d.ts +3 -1
  40. package/dist/connect/upload.d.ts.map +1 -1
  41. package/dist/connect/upload.js +23 -8
  42. package/dist/connect/upload.js.map +1 -1
  43. package/dist/connect/validation.d.ts +2 -2
  44. package/dist/connect/validation.d.ts.map +1 -1
  45. package/dist/connect/validation.js +4 -4
  46. package/dist/connect/validation.js.map +1 -1
  47. package/dist/connect/wizard/helpers.js.map +1 -1
  48. package/dist/storybook/convert.d.ts.map +1 -1
  49. package/dist/storybook/convert.js +1 -1
  50. package/dist/storybook/convert.js.map +1 -1
  51. package/figma-types.d.ts +3 -0
  52. package/package.json +8 -4
@@ -48,7 +48,11 @@ exports.DEFAULT_LABEL_PER_PARSER = {
48
48
  react: label_language_mapping_1.CodeConnectLabel.React,
49
49
  html: label_language_mapping_1.CodeConnectLabel.WebComponents,
50
50
  };
51
- function determineConfigFromProject(dir, exitOnError = true) {
51
+ function determineConfigFromProject(dir, exitOnError = true, isTemplatesOnlyCLI = false) {
52
+ if (isTemplatesOnlyCLI) {
53
+ const label = determineLabelFromProject(dir);
54
+ return { codeConnect: label ? { label } : {} };
55
+ }
52
56
  const parser = determineParserFromProject(dir);
53
57
  if (parser) {
54
58
  const label = determineLabelFromProject(dir);
@@ -215,12 +219,12 @@ Please raise an issue at https://github.com/figma/code-connect/issues if you hav
215
219
  }
216
220
  return config;
217
221
  }
218
- async function parseConfig(configFilePath, dir) {
222
+ async function parseConfig(configFilePath, dir, isTemplatesOnlyCLI = false) {
219
223
  try {
220
224
  const rawData = fs_1.default.readFileSync(configFilePath, 'utf-8');
221
225
  const rawConfig = JSON.parse(rawData);
222
226
  const config = await checkForLegacyConfig(rawConfig, configFilePath);
223
- if (!config.codeConnect?.parser) {
227
+ if (!isTemplatesOnlyCLI && !config.codeConnect?.parser) {
224
228
  const parser = determineParserFromProject(dir);
225
229
  if (!parser) {
226
230
  logging_1.logger.error(`Code Connect was not able to determine your project type, and no \`parser\` was specified. Please ensure you are running Code Connect from your project root. You may need to add a \`parser\` key to your config file, specifying which parser to use. See https://github.com/figma/code-connect/ for instructions.`);
@@ -235,7 +239,7 @@ async function parseConfig(configFilePath, dir) {
235
239
  if (!config.codeConnect?.label) {
236
240
  const label = determineLabelFromProject(dir);
237
241
  if (label) {
238
- config.codeConnect.label = label;
242
+ config.codeConnect = { ...config.codeConnect, label };
239
243
  }
240
244
  }
241
245
  return config;
@@ -410,7 +414,7 @@ function getDefaultConfigPath(dir) {
410
414
  function getEnvPath(dir) {
411
415
  return path_1.default.resolve(path_1.default.join(dir, ENV_FILE_NAME));
412
416
  }
413
- async function parseOrDetermineConfig(dir, configPath) {
417
+ async function parseOrDetermineConfig(dir, configPath, isTemplatesOnlyCLI = false) {
414
418
  const configFilePath = configPath ? path_1.default.resolve(configPath) : getDefaultConfigPath(dir);
415
419
  const hasConfigFile = fs_1.default.existsSync(configFilePath);
416
420
  if (!hasConfigFile) {
@@ -422,8 +426,8 @@ async function parseOrDetermineConfig(dir, configPath) {
422
426
  }
423
427
  }
424
428
  const globalConfig = hasConfigFile
425
- ? await parseConfig(configFilePath, dir)
426
- : determineConfigFromProject(dir);
429
+ ? await parseConfig(configFilePath, dir, isTemplatesOnlyCLI)
430
+ : determineConfigFromProject(dir, true, isTemplatesOnlyCLI);
427
431
  if (!globalConfig) {
428
432
  throw new Error(`Error parsing config file: ${configFilePath}`);
429
433
  }
@@ -481,23 +485,33 @@ async function checkForEnvAndToken(dir) {
481
485
  * @param config Code Connect config
482
486
  * @returns Object containing information about the project
483
487
  */
484
- async function getProjectInfoFromConfig(dir, config) {
488
+ async function getProjectInfoFromConfig(dir, config, isTemplatesOnlyCLI = false) {
485
489
  const absPath = path_1.default.resolve(dir);
486
490
  const remoteUrl = getGitRemoteURL(absPath);
487
- const defaultIncludeGlobs = config.parser
488
- ? exports.DEFAULT_INCLUDE_GLOBS_BY_PARSER[config.parser]
489
- : undefined;
490
- // always ignore any `node_modules` folders in react projects
491
- const defaultExcludeGlobs = config.parser
492
- ? ({
493
- react: ['node_modules/**'],
494
- html: ['node_modules/**'],
495
- swift: ['**/__test__/**'],
496
- compose: [],
497
- custom: [],
498
- __unit_test__: [],
499
- }[config.parser] ?? [])
500
- : [];
491
+ const defaultIncludeGlobs = isTemplatesOnlyCLI
492
+ ? [
493
+ '**/*.figma.ts',
494
+ '**/*.figma.js',
495
+ '**/*.figma.template.ts',
496
+ '**/*.figma.template.js',
497
+ '**/*.figma.batch.json',
498
+ ]
499
+ : config.parser
500
+ ? exports.DEFAULT_INCLUDE_GLOBS_BY_PARSER[config.parser]
501
+ : undefined;
502
+ // always ignore node_modules; for parsers, apply parser-specific exclusions
503
+ const defaultExcludeGlobs = isTemplatesOnlyCLI
504
+ ? ['node_modules/**']
505
+ : config.parser
506
+ ? ({
507
+ react: ['node_modules/**'],
508
+ html: ['node_modules/**'],
509
+ swift: ['**/__test__/**'],
510
+ compose: [],
511
+ custom: [],
512
+ __unit_test__: [],
513
+ }[config.parser] ?? [])
514
+ : [];
501
515
  const includeGlobs = config.include || defaultIncludeGlobs;
502
516
  const excludeGlobs = config.exclude
503
517
  ? [...config.exclude, ...defaultExcludeGlobs]
@@ -546,11 +560,11 @@ function validateLanguage(language) {
546
560
  * @param configPath Optional path to Code Connect config file
547
561
  * @returns Object containing information about the project
548
562
  */
549
- async function getProjectInfo(dir, configPath) {
550
- const { config } = await parseOrDetermineConfig(dir, configPath);
563
+ async function getProjectInfo(dir, configPath, isTemplatesOnlyCLI = false) {
564
+ const { config } = await parseOrDetermineConfig(dir, configPath, isTemplatesOnlyCLI);
551
565
  // Validate language field if present
552
566
  validateLanguage(config.language);
553
- return getProjectInfoFromConfig(dir, config);
567
+ return getProjectInfoFromConfig(dir, config, isTemplatesOnlyCLI);
554
568
  }
555
569
  function getReactProjectInfo(projectInfo) {
556
570
  const tsProgram = getTsProgram(projectInfo);
@@ -1 +1 @@
1
- {"version":3,"file":"project.js","sourceRoot":"","s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AC,oBAAoB,EAAE,MAAM,CAAC,CAAC,gCAAgC;aACtE,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,CAAA,CAAC,6BAA6B;QACvD,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,IAAI,YAAY,GAAG,CAAC,CAAA;QAC7C,MAAM,KAAK,GAAG,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;QAEpC,IAAI,KAAK,EAAE,CAAC;YACV,+CAA+C;YAC/C,IAAI,MAAM,GAAG,WAAW,CAAA;YACxB,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,SAAS,EAAE,CAAC;gBAC3B,MAAM,GAAG,WAAW,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;YAC7C,CAAC;YACD,OAAO,MAAM,CAAA;QACf,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC","sourcesContent":["import { spawnSync } from 'child_process'\nimport { globSync } from 'glob'\nimport path from 'path'\nimport fs from 'fs'\nimport ts from 'typescript'\nimport { exitWithError, logger } from '../common/logging'\nimport chalk from 'chalk'\nimport readline from 'readline'\n// We use an old version of this dep as I couldn't get ES modules working\nimport findUp from 'find-up'\nimport { exitWithFeedbackMessage } from './helpers'\nimport { CodeConnectLabel, SyntaxHighlightLanguage } from './label_language_mapping'\n\nconst DEFAULT_CONFIG_FILE_NAME = 'figma.config.json'\nconst ENV_FILE_NAME = '.env'\n\nexport const DEFAULT_INCLUDE_GLOBS_BY_PARSER = {\n react: [`**/*.{tsx,jsx}`],\n html: [`**/*.{ts,js}`],\n swift: ['**/*.swift'],\n compose: ['**/*.kt'],\n // include globs should be included in configs for custom parsers\n custom: undefined,\n __unit_test__: [''],\n}\n\nexport const DEFAULT_LABEL_PER_PARSER: Partial<Record<CodeConnectParser, string>> = {\n react: CodeConnectLabel.React,\n html: CodeConnectLabel.WebComponents,\n}\n\n// First party parsers which call into parser executables\nexport type CodeConnectExecutableParser = 'swift' | 'compose' | 'custom' | '__unit_test__'\n\n// React is a special case for now as we call it directly from the CLI rather\n// than via an executable for legacy reasons. We will migrate it to the\n// parser executable model.\nexport type CodeConnectParser = 'react' | 'html' | CodeConnectExecutableParser\n\nexport type BaseCodeConnectConfig = {\n /**\n * Specify glob patterns for files (relative to the project root) to be\n * included when looking for source files. If not specified, all files\n * (except any specified in `exclude`) will be included.\n */\n include?: string[]\n /**\n * Specify glob patterns for files (relative to the project root) to be\n * excluded when looking for source files. If not specified, only\n * `node_modules` will be excluded.\n */\n exclude?: string[]\n /**\n * Optional object of substitutions applied to document URLs (in the format {\n * fromString, toString }) for testing (e.g. remapping a production URL to a\n * staging URL). Not publicly documented.\n */\n documentUrlSubstitutions?: Record<string, string>\n /**\n * The parser name, if using an internal parser.\n */\n parser: CodeConnectParser\n\n /**\n * Label to use for the uploaded code examples\n */\n label?: string\n\n /**\n * Language to use for syntax highlighting in the uploaded code examples.\n * If not specified, language is inferred from the label or parser type.\n */\n language?: SyntaxHighlightLanguage\n\n /**\n * The URL of the Figma file to use during the interactive setup wizard for connecting code components to Figma components.\n */\n interactiveSetupFigmaFileUrl?: string\n\n /**\n * Custom Figma API URL to use instead of https://api.figma.com/v1\n */\n apiUrl?: string\n\n /**\n * The default branch name for your repository. Code Connect uses this when generating source code\n * links in Figma. If not specified, Code Connect will attempt to determine this automatically.\n */\n defaultBranch?: string\n}\n\nexport type CodeConnectExecutableParserConfig = BaseCodeConnectConfig & {\n parser: CodeConnectExecutableParser\n}\n\nexport type CodeConnectCustomExecutableParserConfig = BaseCodeConnectConfig & {\n parser: 'custom'\n parserCommand: string\n}\n\n/**\n * React specific configuration\n */\nexport type CodeConnectReactConfig = BaseCodeConnectConfig & {\n parser: 'react'\n /**\n * Maps imports from their path on disk to the specified path.\n * This will rewrite the imports in generated code examples, so it works with\n * relative imports such as `import { Button } from \"./\"`.\n *\n * Example: { \"src/components/*\": \"@ui/components\" }\n * Would rewrite imports for components located in `src/components` to `@ui/components` in\n * generated code examples.\n * `import { Button } from \"./\"` -> `import { Button } from \"@ui/components/Button\"`\n */\n importPaths?: Record<string, string>\n /**\n * For import resolution - this is a temporary solution to support projects that use\n * pnpm workspaces, as the compiler doesn't seem to be able to resolve imports when\n * the package in node_modules is a symlink. Need to look into this more and find a\n * better solution.\n */\n paths?: Record<string, string[]>\n /**\n * Storybook specific configuration\n */\n storybook?: {\n /**\n * The URL of the Storybook instance for the project\n */\n url: string\n }\n}\n\nexport type CodeConnectHtmlConfig = BaseCodeConnectConfig & {}\n\nexport type CodeConnectParserlessConfig = Omit<BaseCodeConnectConfig, 'parser'>\n\nexport type CodeConnectConfig =\n | CodeConnectReactConfig\n | CodeConnectExecutableParserConfig\n | CodeConnectCustomExecutableParserConfig\n | CodeConnectHtmlConfig\n | BaseCodeConnectConfig\n\ninterface FigmaConfig {\n codeConnect?: CodeConnectConfig\n}\n\nexport function determineConfigFromProject(\n dir: string,\n exitOnError = true,\n): FigmaConfig | undefined {\n const parser = determineParserFromProject(dir)\n if (parser) {\n const label = determineLabelFromProject(dir)\n if (label) {\n return { codeConnect: { parser, label } }\n }\n\n return { codeConnect: { parser } }\n }\n\n if (exitOnError) {\n exitWithError(\n `Code Connect was not able to determine your project type, and no config file was found. Please ensure you are running Code Connect from your project root. You may need to create a config file specifying which parser to use. See https://github.com/figma/code-connect/ for instructions.`,\n )\n }\n}\n\nfunction showParserMessage(message: string) {\n logger.info(\n message +\n '. If this is incorrect, please check you are running Code Connect from your project root, or add a `parser` key to your config file. See https://github.com/figma/code-connect for more information.',\n )\n}\n\nfunction packageJsonContains(packageJson: any, dependency: string) {\n return (\n (packageJson.dependencies && packageJson.dependencies[dependency]) ||\n (packageJson.peerDependencies && packageJson.peerDependencies[dependency]) ||\n (packageJson.devDependencies && packageJson.devDependencies[dependency])\n )\n}\n\n// Walk up from the given directory looking for the first directory which\n// matches heuristics for the platforms we support. This means that e.g. if you\n// have a Swift project inside a React project, we'll detect Swift. This enables\n// users to run commands from anywhere inside their project, rather than having\n// to run from the root (the same way npm works).\nfunction determineParserFromProject(dir: string): CodeConnectParser | undefined {\n let parser: CodeConnectParser | undefined\n\n findUp.sync(\n (currentDir) => {\n const packageJsonPath = path.join(currentDir, 'package.json')\n\n if (fs.existsSync(packageJsonPath)) {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))\n if (packageJsonContains(packageJson, 'react')) {\n showParserMessage(\n `Using \"react\" parser as package.json containing a \"react\" ${\n packageJson.dependencies && packageJson.dependencies['react']\n ? 'dependency'\n : 'peer dependency'\n } was found in ${currentDir}`,\n )\n parser = 'react'\n return findUp.stop\n } else {\n showParserMessage(\n `Using \"html\" parser as package.json containing no other supported web frameworks was found in ${currentDir}`,\n )\n parser = 'html'\n return findUp.stop\n }\n } else {\n if (globSync([`${currentDir}/*.xcodeproj`, `${currentDir}/Package.swift`]).length > 0) {\n showParserMessage(\n `Using \"swift\" parser as a file matching *.xcodeproj or Package.swift was found in ${currentDir}`,\n )\n parser = 'swift'\n return findUp.stop\n } else if (globSync([`${currentDir}/build.gradle.kts`]).length > 0) {\n showParserMessage(\n `Using \"compose\" parser as a file matching build.gradle.kts was found in ${currentDir}`,\n )\n parser = 'compose'\n return findUp.stop\n } else if (globSync([`${currentDir}/build.gradle`]).length > 0) {\n showParserMessage(\n `Using \"compose\" parser as a file matching build.gradle was found in ${currentDir}`,\n )\n parser = 'compose'\n return findUp.stop\n }\n }\n },\n { cwd: dir },\n )\n\n return parser\n}\n\n// Similarly to determineParserFromProject, this walks up looking for a\n// package.json containing a library which we support and we set a specific\n// label for. An example is Angular, which is detected as 'html' parser, but we\n// set a different label for it.\nexport function determineLabelFromProject(dir: string): string | undefined {\n function showMessage(\n libraryName: string,\n moduleName: string,\n packageJson: any,\n currentDir: string,\n ) {\n showParserMessage(\n `Using \"${libraryName}\" label as package.json containing a \"${moduleName}\" ${\n packageJson.dependencies && packageJson.dependencies[moduleName]\n ? 'dependency'\n : 'peer dependency'\n } was found in ${currentDir}`,\n )\n }\n\n let label: string | undefined\n\n findUp.sync(\n (currentDir) => {\n const packageJsonPath = path.join(currentDir, 'package.json')\n\n if (fs.existsSync(packageJsonPath)) {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))\n if (packageJsonContains(packageJson, 'angular')) {\n showMessage('Angular', 'angular', packageJson, currentDir)\n label = CodeConnectLabel.Angular\n return findUp.stop\n } else if (packageJsonContains(packageJson, 'vue')) {\n showMessage('Vue', 'vue', packageJson, currentDir)\n label = CodeConnectLabel.Vue\n return findUp.stop\n }\n }\n },\n { cwd: dir },\n )\n\n return label\n}\n\nasync function checkForLegacyConfig(\n config: FigmaConfig & { codeConnect: { swift?: any; react?: any } },\n configFilePath: string,\n): Promise<FigmaConfig> | never {\n const { codeConnect } = config\n\n const newConfigBase = {\n ...(codeConnect.include ? { include: codeConnect.include } : {}),\n ...(codeConnect.exclude ? { exclude: codeConnect.exclude } : {}),\n ...(codeConnect.documentUrlSubstitutions\n ? { documentUrlSubstitutions: codeConnect.documentUrlSubstitutions }\n : {}),\n }\n const maybeNewReactConfig = {\n codeConnect: { parser: 'react', ...codeConnect.react, ...newConfigBase },\n }\n const maybeNewSwiftConfig = {\n codeConnect: { parser: 'swift', ...codeConnect.swift, ...newConfigBase },\n }\n\n if (codeConnect.react && codeConnect.swift) {\n logger.error(`${chalk.bold('⚠️ Your Code Connect configuration needs to be updated\\n')}`)\n\n logger.infoForce(`Code Connect is migrating from a single configuration file for all supported languages, to individual configuration files for each language.\n\nAs part of this change, your Code Connect configuration file needs to be split into two configuration files, one for React and one for Swift.\n\nThe React ${chalk.bold(\n 'figma.config.json',\n )} should be located in your React project root and contain:\n\n${JSON.stringify(maybeNewReactConfig, null, 2)}\n\nThe Swift ${chalk.bold(\n 'figma.config.json',\n )} should be located in your Swift project root and contain:\n\n${JSON.stringify(maybeNewSwiftConfig, null, 2)}\n\nYou will need to check any include/exclude paths are correct relative to the new locations.`)\n exitWithFeedbackMessage(1)\n }\n\n if (codeConnect.react || codeConnect.swift) {\n const platform = codeConnect.react ? 'React' : 'Swift'\n const newConfig = codeConnect.react ? maybeNewReactConfig : maybeNewSwiftConfig\n\n logger.infoForce(\n `${chalk.bold('⚠️ Your Code Connect configuration needs to be updated')}\n\nCode Connect is migrating from a single configuration file for all supported languages, to individual configuration files for each language.\n\nAs part of this change, your Code Connect configuration file needs to be updated to remove the ${chalk.bold(\n platform.toLowerCase(),\n )} key and add ${chalk.bold(`{ parser: \"${platform.toLowerCase()}\" }`)}:\n\n${JSON.stringify(newConfig, null, 2)}\n\nCode Connect can make this change for you automatically, or you can do it manually.\n\nPlease also ensure your configuration file is located in your ${platform} project root. If you move the configuration file, you will need to check any include/exclude paths are correct relative to the new location.\n\nPlease raise an issue at https://github.com/figma/code-connect/issues if you have any problems.\n\n---\n`,\n )\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stderr,\n })\n\n const updateConfig = await new Promise<string>((resolve) => {\n rl.question(\n 'Would you like Code Connect to update your configuration file for you? (y/n) ',\n (answer) => {\n resolve(answer)\n },\n )\n })\n rl.close()\n\n if (updateConfig.toLowerCase() === 'y') {\n fs.writeFileSync(configFilePath, JSON.stringify(newConfig, null, 2))\n logger.infoForce(`\\nConfiguration file updated`)\n return newConfig\n } else {\n exitWithError(`\\nPlease update your configuration file manually`)\n }\n }\n\n return config\n}\n\nasync function parseConfig(configFilePath: string, dir: string): Promise<FigmaConfig | undefined> {\n try {\n const rawData = fs.readFileSync(configFilePath, 'utf-8')\n const rawConfig = JSON.parse(rawData)\n const config = await checkForLegacyConfig(rawConfig, configFilePath)\n\n if (!config.codeConnect?.parser) {\n const parser = determineParserFromProject(dir)\n\n if (!parser) {\n logger.error(\n `Code Connect was not able to determine your project type, and no \\`parser\\` was specified. Please ensure you are running Code Connect from your project root. You may need to add a \\`parser\\` key to your config file, specifying which parser to use. See https://github.com/figma/code-connect/ for instructions.`,\n )\n exitWithFeedbackMessage(1)\n }\n\n if (!config.codeConnect) {\n config.codeConnect = { parser }\n }\n // TS errors if this is in an else\n config.codeConnect.parser = parser\n }\n\n if (!config.codeConnect?.label) {\n const label = determineLabelFromProject(dir)\n if (label) {\n config.codeConnect.label = label\n }\n }\n\n return config\n } catch (error) {\n console.error('Error parsing config file:', error)\n return undefined\n }\n}\n\nexport function getGitRemoteURL(repoPath: string) {\n try {\n const spawn = spawnSync('git', ['config', '--get', 'remote.origin.url'], {\n cwd: repoPath,\n })\n const output = spawn.stdout\n return (output || '').toString().trim()\n } catch (error) {\n console.error('Error getting git remote URL:', error)\n return ''\n }\n}\n\n/**\n * Uses `git rev-parse` to find absolute path to the root of the git repository\n */\nexport function getGitRepoAbsolutePath(filePath: string) {\n try {\n const dirPath = fs.statSync(filePath).isDirectory() ? filePath : path.dirname(filePath)\n const spawn = spawnSync('git', ['rev-parse', '--show-toplevel'], {\n cwd: dirPath,\n })\n const output = spawn.stdout\n return (\n (output || '')\n .toString()\n // git always uses /, but other Node API use \\ on Windows\n .replaceAll('/', path.sep)\n .trim()\n )\n } catch (error: any) {\n console.error('Error running `git rev-parse`:', error.toString().split('\\n')[0])\n return ''\n }\n}\n\n/**\n * Find the default branch name for the git repository\n */\nexport function getGitRepoDefaultBranchName(repoPath: string, configDefaultBranch?: string) {\n const DEFAULT_BRANCH_NAME = 'master'\n\n if (configDefaultBranch) {\n return configDefaultBranch\n }\n\n try {\n const symbolicRefResult = spawnSync('git', ['symbolic-ref', 'refs/remotes/origin/HEAD'], {\n cwd: repoPath,\n })\n\n if (symbolicRefResult.status === 0 && symbolicRefResult.stdout) {\n const ref = symbolicRefResult.stdout.toString().trim()\n // Output format: \"refs/remotes/origin/<branch>\" – take the last segment\n const branch = ref.split('/').pop()\n if (branch) {\n return branch\n }\n }\n\n // Fall back to scanning remote branches for known default branch names\n const gitBranchResult = spawnSync('git', ['branch', '-r'], {\n cwd: repoPath,\n })\n\n if (!gitBranchResult.stdout) {\n return DEFAULT_BRANCH_NAME\n }\n\n const branches = gitBranchResult.stdout\n .toString()\n .trim()\n .split('\\n')\n .map((s) => s.trim())\n\n // Check if origin/main exists, otherwise assume master\n if (branches.includes('origin/main')) {\n return 'main'\n } else {\n return DEFAULT_BRANCH_NAME\n }\n } catch (error: any) {\n console.error('Error getting git default branch name:', error.toString().split('\\n')[0])\n return DEFAULT_BRANCH_NAME\n }\n}\n\n/**\n * Finds the URL of a remote file\n * @param filePath absolute file path on disk\n * @param repoURL remote URL, can be a GitHub, GitLab, Bitbucket, etc. URL.\n * @returns\n */\nexport function getRemoteFileUrl(filePath: string, repoURL?: string, defaultBranch?: string) {\n if (!repoURL) {\n return ''\n }\n\n filePath = filePath.replaceAll(path.sep, '/')\n\n let url = repoURL.trim()\n if (url.startsWith('git@')) {\n url = url.replace(':', '/')\n url = url.replace('git@', 'https://')\n }\n url = url.replace(/\\.git$/, '')\n\n // the folder of the git repo on disk could be named differently,\n // so we need to find the relative path of the file to the root of the repo\n // and append that to the remote URL\n const repoAbsPath = getGitRepoAbsolutePath(filePath)\n // Windows uses \\ as the path separator, so replace with /\n .replaceAll(path.sep, '/')\n\n const resolvedDefaultBranch = getGitRepoDefaultBranchName(repoAbsPath, defaultBranch)\n const index = filePath.indexOf(repoAbsPath)\n if (index === -1) {\n return ''\n }\n\n const relativeFilePath = filePath.substring(index + repoAbsPath.length)\n\n if (url.includes('github.com')) {\n return `${url}/blob/${resolvedDefaultBranch}${relativeFilePath}`\n } else if (url.includes('gitlab.com')) {\n return `${url}/-/blob/${resolvedDefaultBranch}${relativeFilePath}`\n } else if (url.includes('bitbucket.org')) {\n return `${url}/src/${resolvedDefaultBranch}${relativeFilePath}`\n } else if (url.includes('dev.azure.com')) {\n // `git config --get remote.origin.url` for azure repos will return different strings depending on if it was\n // cloned with https or ssh. We need to convert this to a valid URL like \"https://dev.azure.com/org/repo/_git/repo?path=/\"\n if (repoURL.startsWith('git@')) {\n // ssh: \"git@ssh.dev.azure.com:v3/org/repo/repo\"\n const [org, project1, project2] = repoURL.split('/').slice(-3)\n return `https://dev.azure.com/${org}/${project1}/_git/${project2}?path=${relativeFilePath}&branch=${resolvedDefaultBranch}`\n } else {\n // https: \"https://org@dev.azure.com/org/repo/_git/repo\"\n const [_, url] = repoURL.split('@')\n return `https://${url}?path=${relativeFilePath}&branch=${resolvedDefaultBranch}`\n }\n } else {\n logger.debug('Unknown remote URL - assuming GitHub Enterprise', url)\n return `${url}/blob/${resolvedDefaultBranch}${relativeFilePath}`\n }\n}\n\nexport function getStorybookUrl(filePath: string, storybookUrl: string) {\n // the folder of the git repo on disk could be named differently,\n // so we need to find the relative path of the file to the root of the repo\n // and append that to the remote URL\n const repoAbsPath = getGitRepoAbsolutePath(filePath).replaceAll(path.sep, '/')\n const index = filePath.indexOf(repoAbsPath)\n if (index === -1) {\n return ''\n }\n\n const relativeFilePath = filePath.substring(index + repoAbsPath.length + 1) // +1 to remove the leading slash\n const storybookComponentPath = relativeFilePath\n .trim()\n .replace(/[\\s|_]/g, '-')\n .replace(/\\.[jt]sx?$/, '')\n .replaceAll('\\\\', '/')\n .split('/')\n .join('-')\n\n return `${storybookUrl}/?path=/docs/${storybookComponentPath}`\n}\n\nexport type ProjectInfo<ConfigT = CodeConnectConfig> = {\n /**\n * Absolute path of the project directory\n */\n absPath: string\n /**\n * An array of all tsx files in the project\n */\n files: string[]\n /**\n * The git remote URL of the project\n */\n remoteUrl: string\n /**\n * The parsed Code Connect config file\n */\n config: ConfigT\n}\n\nexport type ReactProjectInfo = ProjectInfo<CodeConnectReactConfig> & {\n /**\n * TS program containing all tsx files in the project\n */\n tsProgram: ts.Program\n}\n\nfunction mapToAbsolutePaths(globPaths: string[], absPath: string) {\n // glob doesn't like Windows paths so convert to *nix format\n return globPaths.map((globPath) => `${absPath.replaceAll(path.sep, '/')}/${globPath}`)\n}\n\nexport function getDefaultConfigPath(dir: string) {\n return path.resolve(path.join(dir, DEFAULT_CONFIG_FILE_NAME))\n}\n\nexport function getEnvPath(dir: string) {\n return path.resolve(path.join(dir, ENV_FILE_NAME))\n}\n\nexport async function parseOrDetermineConfig(dir: string, configPath: string) {\n const configFilePath = configPath ? path.resolve(configPath) : getDefaultConfigPath(dir)\n\n const hasConfigFile = fs.existsSync(configFilePath)\n\n if (!hasConfigFile) {\n if (configPath) {\n logger.warn(`${configPath} does not exist, proceeding with default options`)\n } else {\n logger.info(`No config file found in ${dir}, proceeding with default options`)\n }\n }\n\n const globalConfig = hasConfigFile\n ? await parseConfig(configFilePath, dir)\n : determineConfigFromProject(dir)\n\n if (!globalConfig) {\n throw new Error(`Error parsing config file: ${configFilePath}`)\n }\n\n if (!globalConfig.codeConnect) {\n throw new Error(`No options specified under 'codeConnect' in config file: ${configFilePath}`)\n }\n\n const config = globalConfig.codeConnect\n\n if (hasConfigFile) {\n if (!config) {\n logger.info(`Config file found, but no options specified under 'codeConnect'. Parsing ${dir}`)\n } else if (config && !config.include) {\n logger.info(`Config file found, but no include globs specified. Parsing ${dir}`)\n } else {\n logger.info(`Config file found, parsing ${dir} using specified include globs`)\n }\n }\n\n return {\n config,\n hasConfigFile,\n }\n}\n\n/**\n * Check if a .env file exists in the provided directory and if it contains a FIGMA_ACCESS_TOKEN.\n */\nexport async function checkForEnvAndToken(dir: string) {\n // Scan the provided directory for a .env file\n const envPath = await findUp('.env', { cwd: dir })\n\n if (!envPath) {\n // No .env file found\n return {\n hasEnvFile: false,\n envHasFigmaToken: false,\n }\n }\n\n // Read the contents of the .env file\n const envContents = fs.readFileSync(envPath, 'utf-8')\n\n // Determine if the .env file contains a FIGMA_ACCESS_TOKEN\n const envVars = envContents.split('\\n').reduce(\n (\n acc: {\n [key: string]: string\n },\n line,\n ) => {\n const [key, value] = line.split('=')\n acc[key] = value\n return acc\n },\n {},\n )\n\n const figmaAccessToken = envVars['FIGMA_ACCESS_TOKEN']\n\n return {\n hasEnvFile: true,\n envHasFigmaToken: !!figmaAccessToken,\n }\n}\n\n/**\n * Gets information about a project from config.\n *\n * @param dir Directory containing the project\n * @param config Code Connect config\n * @returns Object containing information about the project\n */\nexport async function getProjectInfoFromConfig(\n dir: string,\n config: CodeConnectConfig,\n): Promise<ProjectInfo> {\n const absPath = path.resolve(dir)\n const remoteUrl = getGitRemoteURL(absPath)\n\n const defaultIncludeGlobs = config.parser\n ? DEFAULT_INCLUDE_GLOBS_BY_PARSER[config.parser]\n : undefined\n\n // always ignore any `node_modules` folders in react projects\n const defaultExcludeGlobs = config.parser\n ? ({\n react: ['node_modules/**'],\n html: ['node_modules/**'],\n swift: ['**/__test__/**'],\n compose: [],\n custom: [],\n __unit_test__: [],\n }[config.parser] ?? [])\n : []\n\n const includeGlobs = config.include || defaultIncludeGlobs\n const excludeGlobs = config.exclude\n ? [...config.exclude, ...defaultExcludeGlobs]\n : defaultExcludeGlobs\n\n if (config.parser === 'custom' && (!includeGlobs || includeGlobs.length === 0)) {\n exitWithError('Include globs must specified in config file for custom parsers')\n }\n\n if (!includeGlobs) {\n exitWithError('No include globs specified in config file')\n }\n\n const files = globSync(mapToAbsolutePaths(includeGlobs, absPath), {\n nodir: true,\n ignore: mapToAbsolutePaths(excludeGlobs, absPath),\n // Otherwise this is true on *nix and false on Windows\n absolute: true,\n })\n\n if (files.length > 10000) {\n logger.warn(\n `Matching number of files was excessively large (${files.length}) - consider using more specific include/exclude globs in your config file.`,\n )\n }\n\n return {\n absPath,\n remoteUrl,\n config,\n files,\n }\n}\n\n/**\n * Validates the language field in the config.\n * Throws an error if the language is invalid.\n *\n * @param language The language string to validate\n */\nfunction validateLanguage(language: SyntaxHighlightLanguage | undefined): void {\n if (!language) return\n\n const validLanguages = Object.values(SyntaxHighlightLanguage)\n if (!validLanguages.includes(language)) {\n throw new Error(\n `Invalid language \"${language}\" in figma.config.json. ` +\n `Valid values are: ${validLanguages.join(', ')}`,\n )\n }\n}\n\n/**\n * Gets information about a project from a directory.\n *\n * @param dir Directory containing the project\n * @param configPath Optional path to Code Connect config file\n * @returns Object containing information about the project\n */\nexport async function getProjectInfo(dir: string, configPath: string): Promise<ProjectInfo> {\n const { config } = await parseOrDetermineConfig(dir, configPath)\n\n // Validate language field if present\n validateLanguage(config.language)\n\n return getProjectInfoFromConfig(dir, config)\n}\n\nexport function getReactProjectInfo(\n projectInfo: ProjectInfo<CodeConnectReactConfig>,\n): ReactProjectInfo {\n const tsProgram = getTsProgram(projectInfo)\n\n return {\n ...projectInfo,\n tsProgram,\n }\n}\n\nexport function getTsProgram(projectInfo: ProjectInfo<CodeConnectConfig>): ts.Program {\n const compilerOptions: ts.CompilerOptions = {\n // This ensures the compiler can resolve imports such as \"ui/button\" when a\n // baseUrl is configured in the tsconfig of the project. We probably want a more\n // sophisticated way to parse the users tsconfig and pass it to the compiler eventually.\n baseUrl: projectInfo.absPath,\n // TODO: not sure why Node10 is needed her, but otherwise module resolution for\n // pnpm workspaces won't work\n moduleResolution: ts.ModuleResolutionKind.Node10,\n paths: 'paths' in projectInfo.config ? (projectInfo.config.paths ?? {}) : {},\n allowJs: true,\n }\n\n return ts.createProgram(projectInfo.files, compilerOptions)\n}\n\n/**\n * Change an imported path for a component like `./button` to e.g `@ui/button`, based on the config file.\n * Note that `filePath` here is the path to the source file on disk, not the module specifier.\n *\n * @param filePath\n * @param config\n * @returns\n */\nexport function mapImportPath(filePath: string, config: CodeConnectReactConfig): string | null {\n // Takes the reversed path and pattern parts and check if they match\n function isMatch(patternParts: string[], pathParts: string[]) {\n if (patternParts[0] === '*') {\n // if the path is just a wildcard and nothing else, match any import\n if (patternParts.length === 1) {\n return true\n }\n\n // if the _next_ part in the pattern does not exist in the path, it's not\n // a match.\n const index = pathParts.indexOf(patternParts[1])\n if (index === -1) {\n return false\n }\n\n // Skip to the matching part in the path and match the rest of\n // the pattern. E.g if the pattern is `*/ui/src` (reversed) and the path is\n // `button.tsx/components/ui/src`, we skip to `ui` and match the rest of the\n // pattern.\n patternParts = patternParts.slice(1)\n pathParts = pathParts.slice(index)\n }\n\n for (let i = 0; i < patternParts.length; i++) {\n if (patternParts[i] !== pathParts[i]) {\n return false\n }\n }\n return true\n }\n\n for (const [key, value] of Object.entries(config.importPaths || {})) {\n // Do a partial match from the end of the path\n const patternParts = key.split('/').reverse()\n const pathParts = filePath.split('/').reverse()\n if (pathParts.length < patternParts.length) {\n continue\n }\n\n // If the mapped path ends with a wildcard we want to keep the filename in\n // the final path\n if (isMatch(patternParts, pathParts)) {\n if (value.endsWith('*')) {\n const filename = pathParts[0].split('.')[0]\n return `${value.slice(0, -1)}${filename}`\n }\n return value\n }\n }\n\n return null\n}\n\n/**\n * Transform an import specifier (the path in the import statement) using importPaths config.\n * This works directly on the module specifier from the source code, preserving the user's intent.\n *\n * E.g., '@/AlertTitle' with config { \"@/*\": \"@acme/package/*\" } → '@acme/package/AlertTitle'\n *\n * @param specifier The original import specifier from the source file (e.g., '@/AlertTitle', './Button')\n * @param config The Code Connect config containing importPaths\n * @returns The transformed import path, or null if no mapping matched\n */\nexport function mapImportSpecifier(\n specifier: string,\n config: CodeConnectReactConfig,\n): string | null {\n for (const [pattern, replacement] of Object.entries(config.importPaths || {})) {\n // Convert glob pattern to regex: @/* → ^@/(.*)$\n // First escape special regex chars, then convert * to capture group\n const regexPattern = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&') // Escape special chars except *\n .replace(/\\*/g, '(.*)') // Convert * to capture group\n const regex = new RegExp(`^${regexPattern}$`)\n const match = specifier.match(regex)\n\n if (match) {\n // Replace * in replacement with captured group\n let result = replacement\n if (match[1] !== undefined) {\n result = replacement.replace('*', match[1])\n }\n return result\n }\n }\n return null\n}\n"]}
1
+ {"version":3,"file":"project.js","sourceRoot":"","sources":["../../src/connect/project.ts"],"names":[],"mappings":";;;;;;AAwJA,gEAyBC;AAgFD,8DAuCC;AA0ID,0CAWC;AAKD,wDAkBC;AAKD,kEA8CC;AAQD,4CAmDC;AAED,0CAoBC;AAiCD,oDAEC;AAED,gCAEC;AAED,wDA6CC;AAKD,kDAoCC;AASD,4DAkEC;AA2BD,wCAWC;AAED,kDASC;AAED,oCAcC;AAUD,sCAoDC;A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,GAAG,QAAQ,EAAE,CAAA;YAC3C,CAAC;YACD,OAAO,KAAK,CAAA;QACd,CAAC;IACH,CAAC;IAED,OAAO,IAAI,CAAA;AACb,CAAC;AAED;;;;;;;;;GASG;AACH,SAAgB,kBAAkB,CAChC,SAAiB,EACjB,MAA8B;IAE9B,KAAK,MAAM,CAAC,OAAO,EAAE,WAAW,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,WAAW,IAAI,EAAE,CAAC,EAAE,CAAC;QAC9E,gDAAgD;QAChD,oEAAoE;QACpE,MAAM,YAAY,GAAG,OAAO;aACzB,OAAO,CAAC,oBAAoB,EAAE,MAAM,CAAC,CAAC,gCAAgC;aACtE,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,CAAA,CAAC,6BAA6B;QACvD,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,IAAI,YAAY,GAAG,CAAC,CAAA;QAC7C,MAAM,KAAK,GAAG,SAAS,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;QAEpC,IAAI,KAAK,EAAE,CAAC;YACV,+CAA+C;YAC/C,IAAI,MAAM,GAAG,WAAW,CAAA;YACxB,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,SAAS,EAAE,CAAC;gBAC3B,MAAM,GAAG,WAAW,CAAC,OAAO,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;YAC7C,CAAC;YACD,OAAO,MAAM,CAAA;QACf,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAA;AACb,CAAC","sourcesContent":["import { spawnSync } from 'child_process'\nimport { globSync } from 'glob'\nimport path from 'path'\nimport fs from 'fs'\nimport ts from 'typescript'\nimport { exitWithError, logger } from '../common/logging'\nimport chalk from 'chalk'\nimport readline from 'readline'\n// We use an old version of this dep as I couldn't get ES modules working\nimport findUp from 'find-up'\nimport { exitWithFeedbackMessage } from './helpers'\nimport { CodeConnectLabel, SyntaxHighlightLanguage } from './label_language_mapping'\n\nconst DEFAULT_CONFIG_FILE_NAME = 'figma.config.json'\nconst ENV_FILE_NAME = '.env'\n\nexport const DEFAULT_INCLUDE_GLOBS_BY_PARSER = {\n react: [`**/*.{tsx,jsx}`],\n html: [`**/*.{ts,js}`],\n swift: ['**/*.swift'],\n compose: ['**/*.kt'],\n // include globs should be included in configs for custom parsers\n custom: undefined,\n __unit_test__: [''],\n}\n\nexport const DEFAULT_LABEL_PER_PARSER: Partial<Record<CodeConnectParser, string>> = {\n react: CodeConnectLabel.React,\n html: CodeConnectLabel.WebComponents,\n}\n\n// First party parsers which call into parser executables\nexport type CodeConnectExecutableParser = 'swift' | 'compose' | 'custom' | '__unit_test__'\n\n// React is a special case for now as we call it directly from the CLI rather\n// than via an executable for legacy reasons. We will migrate it to the\n// parser executable model.\nexport type CodeConnectParser = 'react' | 'html' | CodeConnectExecutableParser\n\nexport type BaseCodeConnectConfig = {\n /**\n * Specify glob patterns for files (relative to the project root) to be\n * included when looking for source files. If not specified, all files\n * (except any specified in `exclude`) will be included.\n */\n include?: string[]\n /**\n * Specify glob patterns for files (relative to the project root) to be\n * excluded when looking for source files. If not specified, only\n * `node_modules` will be excluded.\n */\n exclude?: string[]\n /**\n * Optional object of substitutions applied to document URLs (in the format {\n * fromString, toString }) for testing (e.g. remapping a production URL to a\n * staging URL). Not publicly documented.\n */\n documentUrlSubstitutions?: Record<string, string>\n /**\n * The parser name, if using an internal parser.\n */\n parser?: CodeConnectParser\n\n /**\n * Label to use for the uploaded code examples\n */\n label?: string\n\n /**\n * Language to use for syntax highlighting in the uploaded code examples.\n * If not specified, language is inferred from the label or parser type.\n */\n language?: SyntaxHighlightLanguage\n\n /**\n * The URL of the Figma file to use during the interactive setup wizard for connecting code components to Figma components.\n */\n interactiveSetupFigmaFileUrl?: string\n\n /**\n * Custom Figma API URL to use instead of https://api.figma.com/v1\n */\n apiUrl?: string\n\n /**\n * The default branch name for your repository. Code Connect uses this when generating source code\n * links in Figma. If not specified, Code Connect will attempt to determine this automatically.\n */\n defaultBranch?: string\n}\n\nexport type CodeConnectExecutableParserConfig = BaseCodeConnectConfig & {\n parser: CodeConnectExecutableParser\n}\n\nexport type CodeConnectCustomExecutableParserConfig = BaseCodeConnectConfig & {\n parser: 'custom'\n parserCommand: string\n}\n\n/**\n * React specific configuration\n */\nexport type CodeConnectReactConfig = BaseCodeConnectConfig & {\n parser: 'react'\n /**\n * Maps imports from their path on disk to the specified path.\n * This will rewrite the imports in generated code examples, so it works with\n * relative imports such as `import { Button } from \"./\"`.\n *\n * Example: { \"src/components/*\": \"@ui/components\" }\n * Would rewrite imports for components located in `src/components` to `@ui/components` in\n * generated code examples.\n * `import { Button } from \"./\"` -> `import { Button } from \"@ui/components/Button\"`\n */\n importPaths?: Record<string, string>\n /**\n * For import resolution - this is a temporary solution to support projects that use\n * pnpm workspaces, as the compiler doesn't seem to be able to resolve imports when\n * the package in node_modules is a symlink. Need to look into this more and find a\n * better solution.\n */\n paths?: Record<string, string[]>\n /**\n * Storybook specific configuration\n */\n storybook?: {\n /**\n * The URL of the Storybook instance for the project\n */\n url: string\n }\n}\n\nexport type CodeConnectHtmlConfig = BaseCodeConnectConfig & {}\n\nexport type CodeConnectParserlessConfig = BaseCodeConnectConfig & {\n parser: undefined\n}\n\nexport type CodeConnectConfig =\n | CodeConnectReactConfig\n | CodeConnectExecutableParserConfig\n | CodeConnectCustomExecutableParserConfig\n | CodeConnectHtmlConfig\n | BaseCodeConnectConfig\n | CodeConnectParserlessConfig\n\ninterface FigmaConfig {\n codeConnect?: CodeConnectConfig\n}\n\nexport function determineConfigFromProject(\n dir: string,\n exitOnError = true,\n isTemplatesOnlyCLI = false,\n): FigmaConfig | undefined {\n if (isTemplatesOnlyCLI) {\n const label = determineLabelFromProject(dir)\n return { codeConnect: label ? { label } : {} }\n }\n\n const parser = determineParserFromProject(dir)\n if (parser) {\n const label = determineLabelFromProject(dir)\n if (label) {\n return { codeConnect: { parser, label } }\n }\n\n return { codeConnect: { parser } }\n }\n\n if (exitOnError) {\n exitWithError(\n `Code Connect was not able to determine your project type, and no config file was found. Please ensure you are running Code Connect from your project root. You may need to create a config file specifying which parser to use. See https://github.com/figma/code-connect/ for instructions.`,\n )\n }\n}\n\nfunction showParserMessage(message: string) {\n logger.info(\n message +\n '. If this is incorrect, please check you are running Code Connect from your project root, or add a `parser` key to your config file. See https://github.com/figma/code-connect for more information.',\n )\n}\n\nfunction packageJsonContains(packageJson: any, dependency: string) {\n return (\n (packageJson.dependencies && packageJson.dependencies[dependency]) ||\n (packageJson.peerDependencies && packageJson.peerDependencies[dependency]) ||\n (packageJson.devDependencies && packageJson.devDependencies[dependency])\n )\n}\n\n// Walk up from the given directory looking for the first directory which\n// matches heuristics for the platforms we support. This means that e.g. if you\n// have a Swift project inside a React project, we'll detect Swift. This enables\n// users to run commands from anywhere inside their project, rather than having\n// to run from the root (the same way npm works).\nfunction determineParserFromProject(dir: string): CodeConnectParser | undefined {\n let parser: CodeConnectParser | undefined\n\n findUp.sync(\n (currentDir) => {\n const packageJsonPath = path.join(currentDir, 'package.json')\n\n if (fs.existsSync(packageJsonPath)) {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))\n if (packageJsonContains(packageJson, 'react')) {\n showParserMessage(\n `Using \"react\" parser as package.json containing a \"react\" ${\n packageJson.dependencies && packageJson.dependencies['react']\n ? 'dependency'\n : 'peer dependency'\n } was found in ${currentDir}`,\n )\n parser = 'react'\n return findUp.stop\n } else {\n showParserMessage(\n `Using \"html\" parser as package.json containing no other supported web frameworks was found in ${currentDir}`,\n )\n parser = 'html'\n return findUp.stop\n }\n } else {\n if (globSync([`${currentDir}/*.xcodeproj`, `${currentDir}/Package.swift`]).length > 0) {\n showParserMessage(\n `Using \"swift\" parser as a file matching *.xcodeproj or Package.swift was found in ${currentDir}`,\n )\n parser = 'swift'\n return findUp.stop\n } else if (globSync([`${currentDir}/build.gradle.kts`]).length > 0) {\n showParserMessage(\n `Using \"compose\" parser as a file matching build.gradle.kts was found in ${currentDir}`,\n )\n parser = 'compose'\n return findUp.stop\n } else if (globSync([`${currentDir}/build.gradle`]).length > 0) {\n showParserMessage(\n `Using \"compose\" parser as a file matching build.gradle was found in ${currentDir}`,\n )\n parser = 'compose'\n return findUp.stop\n }\n }\n },\n { cwd: dir },\n )\n\n return parser\n}\n\n// Similarly to determineParserFromProject, this walks up looking for a\n// package.json containing a library which we support and we set a specific\n// label for. An example is Angular, which is detected as 'html' parser, but we\n// set a different label for it.\nexport function determineLabelFromProject(dir: string): string | undefined {\n function showMessage(\n libraryName: string,\n moduleName: string,\n packageJson: any,\n currentDir: string,\n ) {\n showParserMessage(\n `Using \"${libraryName}\" label as package.json containing a \"${moduleName}\" ${\n packageJson.dependencies && packageJson.dependencies[moduleName]\n ? 'dependency'\n : 'peer dependency'\n } was found in ${currentDir}`,\n )\n }\n\n let label: string | undefined\n\n findUp.sync(\n (currentDir) => {\n const packageJsonPath = path.join(currentDir, 'package.json')\n\n if (fs.existsSync(packageJsonPath)) {\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))\n if (packageJsonContains(packageJson, 'angular')) {\n showMessage('Angular', 'angular', packageJson, currentDir)\n label = CodeConnectLabel.Angular\n return findUp.stop\n } else if (packageJsonContains(packageJson, 'vue')) {\n showMessage('Vue', 'vue', packageJson, currentDir)\n label = CodeConnectLabel.Vue\n return findUp.stop\n }\n }\n },\n { cwd: dir },\n )\n\n return label\n}\n\nasync function checkForLegacyConfig(\n config: FigmaConfig & { codeConnect: { swift?: any; react?: any } },\n configFilePath: string,\n): Promise<FigmaConfig> | never {\n const { codeConnect } = config\n\n const newConfigBase = {\n ...(codeConnect.include ? { include: codeConnect.include } : {}),\n ...(codeConnect.exclude ? { exclude: codeConnect.exclude } : {}),\n ...(codeConnect.documentUrlSubstitutions\n ? { documentUrlSubstitutions: codeConnect.documentUrlSubstitutions }\n : {}),\n }\n const maybeNewReactConfig = {\n codeConnect: { parser: 'react', ...codeConnect.react, ...newConfigBase },\n }\n const maybeNewSwiftConfig = {\n codeConnect: { parser: 'swift', ...codeConnect.swift, ...newConfigBase },\n }\n\n if (codeConnect.react && codeConnect.swift) {\n logger.error(`${chalk.bold('⚠️ Your Code Connect configuration needs to be updated\\n')}`)\n\n logger.infoForce(`Code Connect is migrating from a single configuration file for all supported languages, to individual configuration files for each language.\n\nAs part of this change, your Code Connect configuration file needs to be split into two configuration files, one for React and one for Swift.\n\nThe React ${chalk.bold(\n 'figma.config.json',\n )} should be located in your React project root and contain:\n\n${JSON.stringify(maybeNewReactConfig, null, 2)}\n\nThe Swift ${chalk.bold(\n 'figma.config.json',\n )} should be located in your Swift project root and contain:\n\n${JSON.stringify(maybeNewSwiftConfig, null, 2)}\n\nYou will need to check any include/exclude paths are correct relative to the new locations.`)\n exitWithFeedbackMessage(1)\n }\n\n if (codeConnect.react || codeConnect.swift) {\n const platform = codeConnect.react ? 'React' : 'Swift'\n const newConfig = codeConnect.react ? maybeNewReactConfig : maybeNewSwiftConfig\n\n logger.infoForce(\n `${chalk.bold('⚠️ Your Code Connect configuration needs to be updated')}\n\nCode Connect is migrating from a single configuration file for all supported languages, to individual configuration files for each language.\n\nAs part of this change, your Code Connect configuration file needs to be updated to remove the ${chalk.bold(\n platform.toLowerCase(),\n )} key and add ${chalk.bold(`{ parser: \"${platform.toLowerCase()}\" }`)}:\n\n${JSON.stringify(newConfig, null, 2)}\n\nCode Connect can make this change for you automatically, or you can do it manually.\n\nPlease also ensure your configuration file is located in your ${platform} project root. If you move the configuration file, you will need to check any include/exclude paths are correct relative to the new location.\n\nPlease raise an issue at https://github.com/figma/code-connect/issues if you have any problems.\n\n---\n`,\n )\n\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stderr,\n })\n\n const updateConfig = await new Promise<string>((resolve) => {\n rl.question(\n 'Would you like Code Connect to update your configuration file for you? (y/n) ',\n (answer) => {\n resolve(answer)\n },\n )\n })\n rl.close()\n\n if (updateConfig.toLowerCase() === 'y') {\n fs.writeFileSync(configFilePath, JSON.stringify(newConfig, null, 2))\n logger.infoForce(`\\nConfiguration file updated`)\n return newConfig\n } else {\n exitWithError(`\\nPlease update your configuration file manually`)\n }\n }\n\n return config\n}\n\nasync function parseConfig(\n configFilePath: string,\n dir: string,\n isTemplatesOnlyCLI = false,\n): Promise<FigmaConfig | undefined> {\n try {\n const rawData = fs.readFileSync(configFilePath, 'utf-8')\n const rawConfig = JSON.parse(rawData)\n const config = await checkForLegacyConfig(rawConfig, configFilePath)\n\n if (!isTemplatesOnlyCLI && !config.codeConnect?.parser) {\n const parser = determineParserFromProject(dir)\n\n if (!parser) {\n logger.error(\n `Code Connect was not able to determine your project type, and no \\`parser\\` was specified. Please ensure you are running Code Connect from your project root. You may need to add a \\`parser\\` key to your config file, specifying which parser to use. See https://github.com/figma/code-connect/ for instructions.`,\n )\n exitWithFeedbackMessage(1)\n }\n\n if (!config.codeConnect) {\n config.codeConnect = { parser }\n }\n // TS errors if this is in an else\n config.codeConnect.parser = parser\n }\n\n if (!config.codeConnect?.label) {\n const label = determineLabelFromProject(dir)\n if (label) {\n config.codeConnect = { ...config.codeConnect, label }\n }\n }\n\n return config\n } catch (error) {\n console.error('Error parsing config file:', error)\n return undefined\n }\n}\n\nexport function getGitRemoteURL(repoPath: string) {\n try {\n const spawn = spawnSync('git', ['config', '--get', 'remote.origin.url'], {\n cwd: repoPath,\n })\n const output = spawn.stdout\n return (output || '').toString().trim()\n } catch (error) {\n console.error('Error getting git remote URL:', error)\n return ''\n }\n}\n\n/**\n * Uses `git rev-parse` to find absolute path to the root of the git repository\n */\nexport function getGitRepoAbsolutePath(filePath: string) {\n try {\n const dirPath = fs.statSync(filePath).isDirectory() ? filePath : path.dirname(filePath)\n const spawn = spawnSync('git', ['rev-parse', '--show-toplevel'], {\n cwd: dirPath,\n })\n const output = spawn.stdout\n return (\n (output || '')\n .toString()\n // git always uses /, but other Node API use \\ on Windows\n .replaceAll('/', path.sep)\n .trim()\n )\n } catch (error: any) {\n console.error('Error running `git rev-parse`:', error.toString().split('\\n')[0])\n return ''\n }\n}\n\n/**\n * Find the default branch name for the git repository\n */\nexport function getGitRepoDefaultBranchName(repoPath: string, configDefaultBranch?: string) {\n const DEFAULT_BRANCH_NAME = 'master'\n\n if (configDefaultBranch) {\n return configDefaultBranch\n }\n\n try {\n const symbolicRefResult = spawnSync('git', ['symbolic-ref', 'refs/remotes/origin/HEAD'], {\n cwd: repoPath,\n })\n\n if (symbolicRefResult.status === 0 && symbolicRefResult.stdout) {\n const ref = symbolicRefResult.stdout.toString().trim()\n // Output format: \"refs/remotes/origin/<branch>\" – take the last segment\n const branch = ref.split('/').pop()\n if (branch) {\n return branch\n }\n }\n\n // Fall back to scanning remote branches for known default branch names\n const gitBranchResult = spawnSync('git', ['branch', '-r'], {\n cwd: repoPath,\n })\n\n if (!gitBranchResult.stdout) {\n return DEFAULT_BRANCH_NAME\n }\n\n const branches = gitBranchResult.stdout\n .toString()\n .trim()\n .split('\\n')\n .map((s) => s.trim())\n\n // Check if origin/main exists, otherwise assume master\n if (branches.includes('origin/main')) {\n return 'main'\n } else {\n return DEFAULT_BRANCH_NAME\n }\n } catch (error: any) {\n console.error('Error getting git default branch name:', error.toString().split('\\n')[0])\n return DEFAULT_BRANCH_NAME\n }\n}\n\n/**\n * Finds the URL of a remote file\n * @param filePath absolute file path on disk\n * @param repoURL remote URL, can be a GitHub, GitLab, Bitbucket, etc. URL.\n * @returns\n */\nexport function getRemoteFileUrl(filePath: string, repoURL?: string, defaultBranch?: string) {\n if (!repoURL) {\n return ''\n }\n\n filePath = filePath.replaceAll(path.sep, '/')\n\n let url = repoURL.trim()\n if (url.startsWith('git@')) {\n url = url.replace(':', '/')\n url = url.replace('git@', 'https://')\n }\n url = url.replace(/\\.git$/, '')\n\n // the folder of the git repo on disk could be named differently,\n // so we need to find the relative path of the file to the root of the repo\n // and append that to the remote URL\n const repoAbsPath = getGitRepoAbsolutePath(filePath)\n // Windows uses \\ as the path separator, so replace with /\n .replaceAll(path.sep, '/')\n\n const resolvedDefaultBranch = getGitRepoDefaultBranchName(repoAbsPath, defaultBranch)\n const index = filePath.indexOf(repoAbsPath)\n if (index === -1) {\n return ''\n }\n\n const relativeFilePath = filePath.substring(index + repoAbsPath.length)\n\n if (url.includes('github.com')) {\n return `${url}/blob/${resolvedDefaultBranch}${relativeFilePath}`\n } else if (url.includes('gitlab.com')) {\n return `${url}/-/blob/${resolvedDefaultBranch}${relativeFilePath}`\n } else if (url.includes('bitbucket.org')) {\n return `${url}/src/${resolvedDefaultBranch}${relativeFilePath}`\n } else if (url.includes('dev.azure.com')) {\n // `git config --get remote.origin.url` for azure repos will return different strings depending on if it was\n // cloned with https or ssh. We need to convert this to a valid URL like \"https://dev.azure.com/org/repo/_git/repo?path=/\"\n if (repoURL.startsWith('git@')) {\n // ssh: \"git@ssh.dev.azure.com:v3/org/repo/repo\"\n const [org, project1, project2] = repoURL.split('/').slice(-3)\n return `https://dev.azure.com/${org}/${project1}/_git/${project2}?path=${relativeFilePath}&branch=${resolvedDefaultBranch}`\n } else {\n // https: \"https://org@dev.azure.com/org/repo/_git/repo\"\n const [_, url] = repoURL.split('@')\n return `https://${url}?path=${relativeFilePath}&branch=${resolvedDefaultBranch}`\n }\n } else {\n logger.debug('Unknown remote URL - assuming GitHub Enterprise', url)\n return `${url}/blob/${resolvedDefaultBranch}${relativeFilePath}`\n }\n}\n\nexport function getStorybookUrl(filePath: string, storybookUrl: string) {\n // the folder of the git repo on disk could be named differently,\n // so we need to find the relative path of the file to the root of the repo\n // and append that to the remote URL\n const repoAbsPath = getGitRepoAbsolutePath(filePath).replaceAll(path.sep, '/')\n const index = filePath.indexOf(repoAbsPath)\n if (index === -1) {\n return ''\n }\n\n const relativeFilePath = filePath.substring(index + repoAbsPath.length + 1) // +1 to remove the leading slash\n const storybookComponentPath = relativeFilePath\n .trim()\n .replace(/[\\s|_]/g, '-')\n .replace(/\\.[jt]sx?$/, '')\n .replaceAll('\\\\', '/')\n .split('/')\n .join('-')\n\n return `${storybookUrl}/?path=/docs/${storybookComponentPath}`\n}\n\nexport type ProjectInfo<ConfigT = CodeConnectConfig> = {\n /**\n * Absolute path of the project directory\n */\n absPath: string\n /**\n * An array of all tsx files in the project\n */\n files: string[]\n /**\n * The git remote URL of the project\n */\n remoteUrl: string\n /**\n * The parsed Code Connect config file\n */\n config: ConfigT\n}\n\nexport type ReactProjectInfo = ProjectInfo<CodeConnectReactConfig> & {\n /**\n * TS program containing all tsx files in the project\n */\n tsProgram: ts.Program\n}\n\nfunction mapToAbsolutePaths(globPaths: string[], absPath: string) {\n // glob doesn't like Windows paths so convert to *nix format\n return globPaths.map((globPath) => `${absPath.replaceAll(path.sep, '/')}/${globPath}`)\n}\n\nexport function getDefaultConfigPath(dir: string) {\n return path.resolve(path.join(dir, DEFAULT_CONFIG_FILE_NAME))\n}\n\nexport function getEnvPath(dir: string) {\n return path.resolve(path.join(dir, ENV_FILE_NAME))\n}\n\nexport async function parseOrDetermineConfig(\n dir: string,\n configPath: string,\n isTemplatesOnlyCLI = false,\n) {\n const configFilePath = configPath ? path.resolve(configPath) : getDefaultConfigPath(dir)\n\n const hasConfigFile = fs.existsSync(configFilePath)\n\n if (!hasConfigFile) {\n if (configPath) {\n logger.warn(`${configPath} does not exist, proceeding with default options`)\n } else {\n logger.info(`No config file found in ${dir}, proceeding with default options`)\n }\n }\n\n const globalConfig = hasConfigFile\n ? await parseConfig(configFilePath, dir, isTemplatesOnlyCLI)\n : determineConfigFromProject(dir, true, isTemplatesOnlyCLI)\n\n if (!globalConfig) {\n throw new Error(`Error parsing config file: ${configFilePath}`)\n }\n\n if (!globalConfig.codeConnect) {\n throw new Error(`No options specified under 'codeConnect' in config file: ${configFilePath}`)\n }\n\n const config = globalConfig.codeConnect\n\n if (hasConfigFile) {\n if (!config) {\n logger.info(`Config file found, but no options specified under 'codeConnect'. Parsing ${dir}`)\n } else if (config && !config.include) {\n logger.info(`Config file found, but no include globs specified. Parsing ${dir}`)\n } else {\n logger.info(`Config file found, parsing ${dir} using specified include globs`)\n }\n }\n\n return {\n config,\n hasConfigFile,\n }\n}\n\n/**\n * Check if a .env file exists in the provided directory and if it contains a FIGMA_ACCESS_TOKEN.\n */\nexport async function checkForEnvAndToken(dir: string) {\n // Scan the provided directory for a .env file\n const envPath = await findUp('.env', { cwd: dir })\n\n if (!envPath) {\n // No .env file found\n return {\n hasEnvFile: false,\n envHasFigmaToken: false,\n }\n }\n\n // Read the contents of the .env file\n const envContents = fs.readFileSync(envPath, 'utf-8')\n\n // Determine if the .env file contains a FIGMA_ACCESS_TOKEN\n const envVars = envContents.split('\\n').reduce(\n (\n acc: {\n [key: string]: string\n },\n line,\n ) => {\n const [key, value] = line.split('=')\n acc[key] = value\n return acc\n },\n {},\n )\n\n const figmaAccessToken = envVars['FIGMA_ACCESS_TOKEN']\n\n return {\n hasEnvFile: true,\n envHasFigmaToken: !!figmaAccessToken,\n }\n}\n\n/**\n * Gets information about a project from config.\n *\n * @param dir Directory containing the project\n * @param config Code Connect config\n * @returns Object containing information about the project\n */\nexport async function getProjectInfoFromConfig(\n dir: string,\n config: CodeConnectConfig,\n isTemplatesOnlyCLI = false,\n): Promise<ProjectInfo> {\n const absPath = path.resolve(dir)\n const remoteUrl = getGitRemoteURL(absPath)\n\n const defaultIncludeGlobs = isTemplatesOnlyCLI\n ? [\n '**/*.figma.ts',\n '**/*.figma.js',\n '**/*.figma.template.ts',\n '**/*.figma.template.js',\n '**/*.figma.batch.json',\n ]\n : config.parser\n ? DEFAULT_INCLUDE_GLOBS_BY_PARSER[config.parser]\n : undefined\n\n // always ignore node_modules; for parsers, apply parser-specific exclusions\n const defaultExcludeGlobs = isTemplatesOnlyCLI\n ? ['node_modules/**']\n : config.parser\n ? ({\n react: ['node_modules/**'],\n html: ['node_modules/**'],\n swift: ['**/__test__/**'],\n compose: [],\n custom: [],\n __unit_test__: [],\n }[config.parser] ?? [])\n : []\n\n const includeGlobs = config.include || defaultIncludeGlobs\n const excludeGlobs = config.exclude\n ? [...config.exclude, ...defaultExcludeGlobs]\n : defaultExcludeGlobs\n\n if (config.parser === 'custom' && (!includeGlobs || includeGlobs.length === 0)) {\n exitWithError('Include globs must specified in config file for custom parsers')\n }\n\n if (!includeGlobs) {\n exitWithError('No include globs specified in config file')\n }\n\n const files = globSync(mapToAbsolutePaths(includeGlobs, absPath), {\n nodir: true,\n ignore: mapToAbsolutePaths(excludeGlobs, absPath),\n // Otherwise this is true on *nix and false on Windows\n absolute: true,\n })\n\n if (files.length > 10000) {\n logger.warn(\n `Matching number of files was excessively large (${files.length}) - consider using more specific include/exclude globs in your config file.`,\n )\n }\n\n return {\n absPath,\n remoteUrl,\n config,\n files,\n }\n}\n\n/**\n * Validates the language field in the config.\n * Throws an error if the language is invalid.\n *\n * @param language The language string to validate\n */\nfunction validateLanguage(language: SyntaxHighlightLanguage | undefined): void {\n if (!language) return\n\n const validLanguages = Object.values(SyntaxHighlightLanguage)\n if (!validLanguages.includes(language)) {\n throw new Error(\n `Invalid language \"${language}\" in figma.config.json. ` +\n `Valid values are: ${validLanguages.join(', ')}`,\n )\n }\n}\n\n/**\n * Gets information about a project from a directory.\n *\n * @param dir Directory containing the project\n * @param configPath Optional path to Code Connect config file\n * @returns Object containing information about the project\n */\nexport async function getProjectInfo(\n dir: string,\n configPath: string,\n isTemplatesOnlyCLI = false,\n): Promise<ProjectInfo> {\n const { config } = await parseOrDetermineConfig(dir, configPath, isTemplatesOnlyCLI)\n\n // Validate language field if present\n validateLanguage(config.language)\n\n return getProjectInfoFromConfig(dir, config, isTemplatesOnlyCLI)\n}\n\nexport function getReactProjectInfo(\n projectInfo: ProjectInfo<CodeConnectReactConfig>,\n): ReactProjectInfo {\n const tsProgram = getTsProgram(projectInfo)\n\n return {\n ...projectInfo,\n tsProgram,\n }\n}\n\nexport function getTsProgram(projectInfo: ProjectInfo<CodeConnectConfig>): ts.Program {\n const compilerOptions: ts.CompilerOptions = {\n // This ensures the compiler can resolve imports such as \"ui/button\" when a\n // baseUrl is configured in the tsconfig of the project. We probably want a more\n // sophisticated way to parse the users tsconfig and pass it to the compiler eventually.\n baseUrl: projectInfo.absPath,\n // TODO: not sure why Node10 is needed her, but otherwise module resolution for\n // pnpm workspaces won't work\n moduleResolution: ts.ModuleResolutionKind.Node10,\n paths: 'paths' in projectInfo.config ? (projectInfo.config.paths ?? {}) : {},\n allowJs: true,\n }\n\n return ts.createProgram(projectInfo.files, compilerOptions)\n}\n\n/**\n * Change an imported path for a component like `./button` to e.g `@ui/button`, based on the config file.\n * Note that `filePath` here is the path to the source file on disk, not the module specifier.\n *\n * @param filePath\n * @param config\n * @returns\n */\nexport function mapImportPath(filePath: string, config: CodeConnectReactConfig): string | null {\n // Takes the reversed path and pattern parts and check if they match\n function isMatch(patternParts: string[], pathParts: string[]) {\n if (patternParts[0] === '*') {\n // if the path is just a wildcard and nothing else, match any import\n if (patternParts.length === 1) {\n return true\n }\n\n // if the _next_ part in the pattern does not exist in the path, it's not\n // a match.\n const index = pathParts.indexOf(patternParts[1])\n if (index === -1) {\n return false\n }\n\n // Skip to the matching part in the path and match the rest of\n // the pattern. E.g if the pattern is `*/ui/src` (reversed) and the path is\n // `button.tsx/components/ui/src`, we skip to `ui` and match the rest of the\n // pattern.\n patternParts = patternParts.slice(1)\n pathParts = pathParts.slice(index)\n }\n\n for (let i = 0; i < patternParts.length; i++) {\n if (patternParts[i] !== pathParts[i]) {\n return false\n }\n }\n return true\n }\n\n for (const [key, value] of Object.entries(config.importPaths || {})) {\n // Do a partial match from the end of the path\n const patternParts = key.split('/').reverse()\n const pathParts = filePath.split('/').reverse()\n if (pathParts.length < patternParts.length) {\n continue\n }\n\n // If the mapped path ends with a wildcard we want to keep the filename in\n // the final path\n if (isMatch(patternParts, pathParts)) {\n if (value.endsWith('*')) {\n const filename = pathParts[0].split('.')[0]\n return `${value.slice(0, -1)}${filename}`\n }\n return value\n }\n }\n\n return null\n}\n\n/**\n * Transform an import specifier (the path in the import statement) using importPaths config.\n * This works directly on the module specifier from the source code, preserving the user's intent.\n *\n * E.g., '@/AlertTitle' with config { \"@/*\": \"@acme/package/*\" } → '@acme/package/AlertTitle'\n *\n * @param specifier The original import specifier from the source file (e.g., '@/AlertTitle', './Button')\n * @param config The Code Connect config containing importPaths\n * @returns The transformed import path, or null if no mapping matched\n */\nexport function mapImportSpecifier(\n specifier: string,\n config: CodeConnectReactConfig,\n): string | null {\n for (const [pattern, replacement] of Object.entries(config.importPaths || {})) {\n // Convert glob pattern to regex: @/* → ^@/(.*)$\n // First escape special regex chars, then convert * to capture group\n const regexPattern = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&') // Escape special chars except *\n .replace(/\\*/g, '(.*)') // Convert * to capture group\n const regex = new RegExp(`^${regexPattern}$`)\n const match = specifier.match(regex)\n\n if (match) {\n // Replace * in replacement with captured group\n let result = replacement\n if (match[1] !== undefined) {\n result = replacement.replace('*', match[1])\n }\n return result\n }\n }\n return null\n}\n"]}
@@ -7,5 +7,12 @@ import { CodeConnectConfig } from './project';
7
7
  * Code Connect files that share the same extension.
8
8
  */
9
9
  export declare function isRawTemplate(content: string): boolean;
10
- export declare function parseRawFile(filePath: string, label: string | undefined, config?: CodeConnectConfig, dir?: string): CodeConnectJSON;
10
+ export interface BatchOverrides {
11
+ url: string;
12
+ source?: string;
13
+ component?: string;
14
+ batchData: Record<string, any>;
15
+ batchFilePath: string;
16
+ }
17
+ export declare function parseRawFile(filePath: string, label: string | undefined, config?: CodeConnectConfig, dir?: string, batchOverrides?: BatchOverrides): CodeConnectJSON;
11
18
  //# sourceMappingURL=raw_templates.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"raw_templates.d.ts","sourceRoot":"","sources":["../../src/connect/raw_templates.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAA;AAI7C;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAatD;AA+ED,wBAAgB,YAAY,CAC1B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,MAAM,CAAC,EAAE,iBAAiB,EAC1B,GAAG,CAAC,EAAE,MAAM,GACX,eAAe,CA+DjB"}
1
+ {"version":3,"file":"raw_templates.d.ts","sourceRoot":"","sources":["../../src/connect/raw_templates.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AACjD,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAA;AAI7C;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAatD;AA+ED,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,MAAM,CAAA;IACX,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC9B,aAAa,EAAE,MAAM,CAAA;CACtB;AAED,wBAAgB,YAAY,CAC1B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,MAAM,CAAC,EAAE,iBAAiB,EAC1B,GAAG,CAAC,EAAE,MAAM,EACZ,cAAc,CAAC,EAAE,cAAc,GAC9B,eAAe,CA8EjB"}
@@ -94,7 +94,7 @@ function extractMetadataFields(fileContent) {
94
94
  }
95
95
  return { fields, templateStartLine };
96
96
  }
97
- function parseRawFile(filePath, label, config, dir) {
97
+ function parseRawFile(filePath, label, config, dir, batchOverrides) {
98
98
  let fileContent = fs_1.default.readFileSync(filePath, 'utf-8');
99
99
  // Extract metadata fields BEFORE transpilation to avoid losing comments
100
100
  // that appear before type-only imports (which TypeScript erases)
@@ -102,10 +102,16 @@ function parseRawFile(filePath, label, config, dir) {
102
102
  if (filePath.endsWith('.ts')) {
103
103
  fileContent = transpileTypeScriptTemplate(filePath, fileContent);
104
104
  }
105
- if (!fields.url) {
106
- throw new Error(`Missing required url field in ${filePath}. Please add a // url=... comment to the top of the file.`);
105
+ // For batch templates, metadata comes from the batch entry instead of comments
106
+ const component = batchOverrides?.component || fields.component;
107
+ const source = batchOverrides?.source || fields.source || '';
108
+ const figmaUrl = batchOverrides?.url || fields.url;
109
+ if (!figmaUrl) {
110
+ throw new Error(batchOverrides
111
+ ? `Missing required "url" field in ${batchOverrides.batchFilePath}. Please add "url" to each entry in your .figma.batch.json file.`
112
+ : `Missing required url field in ${filePath}. Please add a // url=... comment to the top of the file.`);
107
113
  }
108
- let figmaNodeUrl = fields.url;
114
+ let figmaNodeUrl = figmaUrl;
109
115
  // Extract template from the transpiled content, starting at the line
110
116
  // where the metadata comments ended in the original source
111
117
  const transpiledLines = fileContent.split('\n');
@@ -121,7 +127,14 @@ function parseRawFile(filePath, label, config, dir) {
121
127
  templateStartIndex = i;
122
128
  break;
123
129
  }
124
- const template = transpiledLines.slice(templateStartIndex).join('\n');
130
+ let template = transpiledLines.slice(templateStartIndex).join('\n');
131
+ // For batch templates, set globalThis['__FIGMA_BATCH'] so the runtime exposes it as
132
+ // figma.batch. Using globalThis rather than a const so it's accessible from
133
+ // __FIGMA_CODE_CONNECT_REQUIRE's closure regardless of where require('figma') is called.
134
+ // (globalThis works in both browser and Node.js, unlike window.)
135
+ if (batchOverrides) {
136
+ template = `globalThis['__FIGMA_BATCH'] = ${JSON.stringify(batchOverrides.batchData)}\n${template}`;
137
+ }
125
138
  // Apply documentUrlSubstitutions if provided
126
139
  if (config?.documentUrlSubstitutions) {
127
140
  figmaNodeUrl = (0, helpers_1.applyDocumentUrlSubstitutions)(figmaNodeUrl, config.documentUrlSubstitutions);
@@ -131,7 +144,7 @@ function parseRawFile(filePath, label, config, dir) {
131
144
  const language = config?.language || (0, label_language_mapping_1.getInferredLanguageForRaw)(effectiveLabel);
132
145
  return {
133
146
  figmaNode: figmaNodeUrl,
134
- component: fields.component,
147
+ component,
135
148
  template,
136
149
  // nestable by default unless user specifies in template
137
150
  // (templateData.nestable AND template.metadata.nestable need to
@@ -139,7 +152,7 @@ function parseRawFile(filePath, label, config, dir) {
139
152
  templateData: { nestable: true, isParserless: true },
140
153
  language,
141
154
  label: effectiveLabel,
142
- source: fields.source || '',
155
+ source,
143
156
  sourceLocation: { line: -1 },
144
157
  metadata: {
145
158
  cliVersion: require('../../package.json').version,
@@ -1 +1 @@
1
- {"version":3,"file":"raw_templates.js","sourceRoot":"","sources":["../../src/connect/raw_templates.ts"],"names":[],"mappings":";;;;;AAaA,sCAaC;AA+ED,oCAoEC;AA7KD,4CAAmB;AACnB,4DAA2B;AAG3B,qEAAsF;AACtF,uCAAyD;AAEzD;;;;;GAKG;AACH,SAAgB,aAAa,CAAC,OAAe;IAC3C,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;QACvC,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,CAAA;QAC3B,IAAI,OAAO,KAAK,EAAE,IAAI,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;YAC/C,IAAI,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;gBACpD,OAAO,IAAI,CAAA;YACb,CAAC;YACD,SAAQ;QACV,CAAC;QACD,mGAAmG;QACnG,MAAK;IACP,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC;AAED,SAAS,2BAA2B,CAAC,QAAgB,EAAE,WAAmB;IACxE,kDAAkD;IAClD,sCAAsC;IACtC,MAAM,gBAAgB,GAAG,kDAAkD,CAAA;IAC3E,IAAI,gBAAgB,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC;QACvC,WAAW,GAAG,WAAW,CAAC,OAAO,CAAC,gBAAgB,EAAE,gCAAgC,CAAC,CAAA;IACvF,CAAC;IAED,qFAAqF;IACrF,gFAAgF;IAChF,mFAAmF;IACnF,mBAAmB;IACnB,MA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AE,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO;SAClD;KACF,CAAA;AACH,CAAC","sourcesContent":["import fs from 'fs'\nimport ts from 'typescript'\nimport { CodeConnectJSON } from './figma_connect'\nimport { CodeConnectConfig } from './project'\nimport { CodeConnectLabel, getInferredLanguageForRaw } from './label_language_mapping'\nimport { applyDocumentUrlSubstitutions } from './helpers'\n\n/**\n * Returns true if the file content looks like a raw template file, i.e. its\n * leading comment block contains a `// url=`, `// component=`, or `// source=`\n * directive. Used to distinguish raw `.figma.ts` templates from React/HTML\n * Code Connect files that share the same extension.\n */\nexport function isRawTemplate(content: string): boolean {\n for (const line of content.split('\\n')) {\n const trimmed = line.trim()\n if (trimmed === '' || trimmed.startsWith('//')) {\n if (/^\\/\\/\\s*(url|component|source)=/.test(trimmed)) {\n return true\n }\n continue\n }\n // First non-comment, non-blank line reached without finding a known directive — not a raw template\n break\n }\n return false\n}\n\nfunction transpileTypeScriptTemplate(filePath: string, fileContent: string): string {\n // Convert ESM import of 'figma' to require syntax\n // Supports: import figma from 'figma'\n const figmaImportRegex = /^import\\s+figma\\s+from\\s+['\"]figma['\"]\\s*;?\\s*$/m\n if (figmaImportRegex.test(fileContent)) {\n fileContent = fileContent.replace(figmaImportRegex, \"const figma = require('figma')\")\n }\n\n // Detect any remaining non-type import statements. Type-only imports (`import type`)\n // are erased by the TS compiler and are fine. Regular imports (except the figma\n // import we just converted) are not supported in Phase 1 (no bundling), so we show\n // a helpful error.\n const importRegex = /^import\\s+(?!type\\s)/m\n if (importRegex.test(fileContent)) {\n const match = fileContent.match(/^(import\\s+.+)$/m)\n const importLine = match ? match[1] : 'import ...'\n throw new Error(\n `TypeScript template files only support importing from 'figma'.\\n` +\n `Found in ${filePath}:\\n` +\n ` ${importLine}\\n\\n` +\n `Use \"const figma = require('figma')\" or \"import figma from 'figma'\" to access the Figma API.\\n` +\n `Other module imports will be supported in a future version.`,\n )\n }\n\n const result = ts.transpileModule(fileContent, {\n compilerOptions: {\n module: ts.ModuleKind.ESNext,\n target: ts.ScriptTarget.ES2021,\n removeComments: false,\n },\n })\n\n return result.outputText\n}\n\n/**\n * Extracts metadata fields (url, component, source) from the leading comments\n * of a raw template file. This must be done before transpilation because\n * TypeScript can remove comments that appear before type-only imports.\n */\nfunction extractMetadataFields(fileContent: string): {\n fields: { url?: string; component?: string; source?: string }\n templateStartLine: number\n} {\n const lines = fileContent.split('\\n')\n const fields: { url?: string; component?: string; source?: string } = {}\n let templateStartLine = 0\n\n // Parse consecutive comment lines at the start of the file\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim()\n // Match pattern: // fieldName=value\n const match = line.match(/^\\/\\/\\s*(\\w+)=(.+)$/)\n if (match) {\n const [, fieldName, fieldValue] = match\n const normalizedFieldName = fieldName.toLowerCase()\n if (\n normalizedFieldName === 'url' ||\n normalizedFieldName === 'component' ||\n normalizedFieldName === 'source'\n ) {\n fields[normalizedFieldName] = fieldValue.trim()\n }\n templateStartLine = i + 1\n } else if (line === '' || line.startsWith('//')) {\n // Allow blank lines or other comments, but don't increment template start\n continue\n } else {\n // First non-comment line found\n break\n }\n }\n\n return { fields, templateStartLine }\n}\n\nexport function parseRawFile(\n filePath: string,\n label: string | undefined,\n config?: CodeConnectConfig,\n dir?: string,\n): CodeConnectJSON {\n let fileContent = fs.readFileSync(filePath, 'utf-8')\n\n // Extract metadata fields BEFORE transpilation to avoid losing comments\n // that appear before type-only imports (which TypeScript erases)\n const { fields, templateStartLine } = extractMetadataFields(fileContent)\n\n if (filePath.endsWith('.ts')) {\n fileContent = transpileTypeScriptTemplate(filePath, fileContent)\n }\n\n if (!fields.url) {\n throw new Error(\n `Missing required url field in ${filePath}. Please add a // url=... comment to the top of the file.`,\n )\n }\n let figmaNodeUrl = fields.url\n\n // Extract template from the transpiled content, starting at the line\n // where the metadata comments ended in the original source\n const transpiledLines = fileContent.split('\\n')\n let templateStartIndex = 0\n\n // Skip lines until we've passed the original metadata comment section\n for (let i = 0; i < transpiledLines.length; i++) {\n const line = transpiledLines[i].trim()\n // Skip blank lines and comments at the start\n if (line === '' || line.startsWith('//')) {\n continue\n }\n // First non-comment line in transpiled output\n templateStartIndex = i\n break\n }\n\n const template = transpiledLines.slice(templateStartIndex).join('\\n')\n\n // Apply documentUrlSubstitutions if provided\n if (config?.documentUrlSubstitutions) {\n figmaNodeUrl = applyDocumentUrlSubstitutions(figmaNodeUrl, config.documentUrlSubstitutions)\n }\n\n // Determine effective label from parameter, config, or default\n const effectiveLabel = label || config?.label || CodeConnectLabel.Code\n\n const language = config?.language || getInferredLanguageForRaw(effectiveLabel)\n\n return {\n figmaNode: figmaNodeUrl,\n component: fields.component,\n template,\n // nestable by default unless user specifies in template\n // (templateData.nestable AND template.metadata.nestable need to\n // be true for instance to be nested)\n templateData: { nestable: true, isParserless: true },\n language,\n label: effectiveLabel,\n source: fields.source || '',\n sourceLocation: { line: -1 },\n metadata: {\n cliVersion: require('../../package.json').version,\n },\n }\n}\n"]}
1
+ {"version":3,"file":"raw_templates.js","sourceRoot":"","sources":["../../src/connect/raw_templates.ts"],"names":[],"mappings":";;;;;AAaA,sCAaC;AAuFD,oCAoFC;AArMD,4CAAmB;AACnB,4DAA2B;AAG3B,qEAAsF;AACtF,uCAAyD;AAEzD;;;;;GAKG;AACH,SAAgB,aAAa,CAAC,OAAe;IAC3C,KAAK,MAAM,IAAI,IAAI,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;QACvC,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,CAAA;QAC3B,IAAI,OAAO,KAAK,EAAE,IAAI,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;YAC/C,IAAI,iCAAiC,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC;gBACpD,OAAO,IAAI,CAAA;YACb,CAAC;YACD,SAAQ;QACV,CAAC;QACD,mGAAmG;QACnG,MAAK;IACP,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC;AA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c,EAAE,CAAC;QACnB,QAAQ,GAAG,iCAAiC,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC,SAAS,CAAC,KAAK,QAAQ,EAAE,CAAA;IACrG,CAAC;IAED,6CAA6C;IAC7C,IAAI,MAAM,EAAE,wBAAwB,EAAE,CAAC;QACrC,YAAY,GAAG,IAAA,uCAA6B,EAAC,YAAY,EAAE,MAAM,CAAC,wBAAwB,CAAC,CAAA;IAC7F,CAAC;IAED,+DAA+D;IAC/D,MAAM,cAAc,GAAG,KAAK,IAAI,MAAM,EAAE,KAAK,IAAI,yCAAgB,CAAC,IAAI,CAAA;IAEtE,MAAM,QAAQ,GAAG,MAAM,EAAE,QAAQ,IAAI,IAAA,kDAAyB,EAAC,cAAc,CAAC,CAAA;IAE9E,OAAO;QACL,SAAS,EAAE,YAAY;QACvB,SAAS;QACT,QAAQ;QACR,wDAAwD;QACxD,gEAAgE;QAChE,qCAAqC;QACrC,YAAY,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE;QACpD,QAAQ;QACR,KAAK,EAAE,cAAc;QACrB,MAAM;QACN,cAAc,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE;QAC5B,QAAQ,EAAE;YACR,UAAU,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO;SAClD;KACF,CAAA;AACH,CAAC","sourcesContent":["import fs from 'fs'\nimport ts from 'typescript'\nimport { CodeConnectJSON } from './figma_connect'\nimport { CodeConnectConfig } from './project'\nimport { CodeConnectLabel, getInferredLanguageForRaw } from './label_language_mapping'\nimport { applyDocumentUrlSubstitutions } from './helpers'\n\n/**\n * Returns true if the file content looks like a raw template file, i.e. its\n * leading comment block contains a `// url=`, `// component=`, or `// source=`\n * directive. Used to distinguish raw `.figma.ts` templates from React/HTML\n * Code Connect files that share the same extension.\n */\nexport function isRawTemplate(content: string): boolean {\n for (const line of content.split('\\n')) {\n const trimmed = line.trim()\n if (trimmed === '' || trimmed.startsWith('//')) {\n if (/^\\/\\/\\s*(url|component|source)=/.test(trimmed)) {\n return true\n }\n continue\n }\n // First non-comment, non-blank line reached without finding a known directive — not a raw template\n break\n }\n return false\n}\n\nfunction transpileTypeScriptTemplate(filePath: string, fileContent: string): string {\n // Convert ESM import of 'figma' to require syntax\n // Supports: import figma from 'figma'\n const figmaImportRegex = /^import\\s+figma\\s+from\\s+['\"]figma['\"]\\s*;?\\s*$/m\n if (figmaImportRegex.test(fileContent)) {\n fileContent = fileContent.replace(figmaImportRegex, \"const figma = require('figma')\")\n }\n\n // Detect any remaining non-type import statements. Type-only imports (`import type`)\n // are erased by the TS compiler and are fine. Regular imports (except the figma\n // import we just converted) are not supported in Phase 1 (no bundling), so we show\n // a helpful error.\n const importRegex = /^import\\s+(?!type\\s)/m\n if (importRegex.test(fileContent)) {\n const match = fileContent.match(/^(import\\s+.+)$/m)\n const importLine = match ? match[1] : 'import ...'\n throw new Error(\n `TypeScript template files only support importing from 'figma'.\\n` +\n `Found in ${filePath}:\\n` +\n ` ${importLine}\\n\\n` +\n `Use \"const figma = require('figma')\" or \"import figma from 'figma'\" to access the Figma API.\\n` +\n `Other module imports will be supported in a future version.`,\n )\n }\n\n const result = ts.transpileModule(fileContent, {\n compilerOptions: {\n module: ts.ModuleKind.ESNext,\n target: ts.ScriptTarget.ES2021,\n removeComments: false,\n },\n })\n\n return result.outputText\n}\n\n/**\n * Extracts metadata fields (url, component, source) from the leading comments\n * of a raw template file. This must be done before transpilation because\n * TypeScript can remove comments that appear before type-only imports.\n */\nfunction extractMetadataFields(fileContent: string): {\n fields: { url?: string; component?: string; source?: string }\n templateStartLine: number\n} {\n const lines = fileContent.split('\\n')\n const fields: { url?: string; component?: string; source?: string } = {}\n let templateStartLine = 0\n\n // Parse consecutive comment lines at the start of the file\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim()\n // Match pattern: // fieldName=value\n const match = line.match(/^\\/\\/\\s*(\\w+)=(.+)$/)\n if (match) {\n const [, fieldName, fieldValue] = match\n const normalizedFieldName = fieldName.toLowerCase()\n if (\n normalizedFieldName === 'url' ||\n normalizedFieldName === 'component' ||\n normalizedFieldName === 'source'\n ) {\n fields[normalizedFieldName] = fieldValue.trim()\n }\n templateStartLine = i + 1\n } else if (line === '' || line.startsWith('//')) {\n // Allow blank lines or other comments, but don't increment template start\n continue\n } else {\n // First non-comment line found\n break\n }\n }\n\n return { fields, templateStartLine }\n}\n\nexport interface BatchOverrides {\n url: string\n source?: string\n component?: string\n batchData: Record<string, any>\n batchFilePath: string\n}\n\nexport function parseRawFile(\n filePath: string,\n label: string | undefined,\n config?: CodeConnectConfig,\n dir?: string,\n batchOverrides?: BatchOverrides,\n): CodeConnectJSON {\n let fileContent = fs.readFileSync(filePath, 'utf-8')\n\n // Extract metadata fields BEFORE transpilation to avoid losing comments\n // that appear before type-only imports (which TypeScript erases)\n const { fields, templateStartLine } = extractMetadataFields(fileContent)\n\n if (filePath.endsWith('.ts')) {\n fileContent = transpileTypeScriptTemplate(filePath, fileContent)\n }\n\n // For batch templates, metadata comes from the batch entry instead of comments\n const component = batchOverrides?.component || fields.component\n const source = batchOverrides?.source || fields.source || ''\n\n const figmaUrl = batchOverrides?.url || fields.url\n if (!figmaUrl) {\n throw new Error(\n batchOverrides\n ? `Missing required \"url\" field in ${batchOverrides.batchFilePath}. Please add \"url\" to each entry in your .figma.batch.json file.`\n : `Missing required url field in ${filePath}. Please add a // url=... comment to the top of the file.`,\n )\n }\n let figmaNodeUrl = figmaUrl\n\n // Extract template from the transpiled content, starting at the line\n // where the metadata comments ended in the original source\n const transpiledLines = fileContent.split('\\n')\n let templateStartIndex = 0\n\n // Skip lines until we've passed the original metadata comment section\n for (let i = 0; i < transpiledLines.length; i++) {\n const line = transpiledLines[i].trim()\n // Skip blank lines and comments at the start\n if (line === '' || line.startsWith('//')) {\n continue\n }\n // First non-comment line in transpiled output\n templateStartIndex = i\n break\n }\n\n let template = transpiledLines.slice(templateStartIndex).join('\\n')\n\n // For batch templates, set globalThis['__FIGMA_BATCH'] so the runtime exposes it as\n // figma.batch. Using globalThis rather than a const so it's accessible from\n // __FIGMA_CODE_CONNECT_REQUIRE's closure regardless of where require('figma') is called.\n // (globalThis works in both browser and Node.js, unlike window.)\n if (batchOverrides) {\n template = `globalThis['__FIGMA_BATCH'] = ${JSON.stringify(batchOverrides.batchData)}\\n${template}`\n }\n\n // Apply documentUrlSubstitutions if provided\n if (config?.documentUrlSubstitutions) {\n figmaNodeUrl = applyDocumentUrlSubstitutions(figmaNodeUrl, config.documentUrlSubstitutions)\n }\n\n // Determine effective label from parameter, config, or default\n const effectiveLabel = label || config?.label || CodeConnectLabel.Code\n\n const language = config?.language || getInferredLanguageForRaw(effectiveLabel)\n\n return {\n figmaNode: figmaNodeUrl,\n component,\n template,\n // nestable by default unless user specifies in template\n // (templateData.nestable AND template.metadata.nestable need to\n // be true for instance to be nested)\n templateData: { nestable: true, isParserless: true },\n language,\n label: effectiveLabel,\n source,\n sourceLocation: { line: -1 },\n metadata: {\n cliVersion: require('../../package.json').version,\n },\n }\n}\n"]}
@@ -1,15 +1,17 @@
1
1
  import { CodeConnectJSON } from '../connect/figma_connect';
2
2
  interface Args {
3
3
  accessToken: string;
4
+ useOAuth?: boolean;
4
5
  docs: CodeConnectJSON[];
5
6
  batchSize?: number;
6
7
  verbose: boolean;
7
8
  apiUrl?: string;
9
+ force?: boolean;
8
10
  }
9
11
  /**
10
12
  * Creates a map from fileKey-nodeId to original docs for easy lookup
11
13
  */
12
14
  export declare function createDocsMap(docs: CodeConnectJSON[], verbose: boolean): Map<string, CodeConnectJSON[]>;
13
- export declare function upload({ accessToken, docs, batchSize, verbose, apiUrl: apiUrlOverride, }: Args): Promise<void>;
15
+ export declare function upload({ accessToken, useOAuth, docs, batchSize, verbose, apiUrl: apiUrlOverride, force, }: Args): Promise<void>;
14
16
  export {};
15
17
  //# sourceMappingURL=upload.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../../src/connect/upload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAsC1D,UAAU,IAAI;IACZ,WAAW,EAAE,MAAM,CAAA;IACnB,IAAI,EAAE,eAAe,EAAE,CAAA;IACvB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,OAAO,EAAE,OAAO,CAAA;IAChB,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AA0CD;;GAEG;AACH,wBAAgB,aAAa,CAC3B,IAAI,EAAE,eAAe,EAAE,EACvB,OAAO,EAAE,OAAO,GACf,GAAG,CAAC,MAAM,EAAE,eAAe,EAAE,CAAC,CAkBhC;AAED,wBAAsB,MAAM,CAAC,EAC3B,WAAW,EACX,IAAI,EACJ,SAAS,EACT,OAAO,EACP,MAAM,EAAE,cAAc,GACvB,EAAE,IAAI,iBAoLN"}
1
+ {"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../../src/connect/upload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAyC1D,UAAU,IAAI;IACZ,WAAW,EAAE,MAAM,CAAA;IACnB,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,IAAI,EAAE,eAAe,EAAE,CAAA;IACvB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,OAAO,EAAE,OAAO,CAAA;IAChB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,KAAK,CAAC,EAAE,OAAO,CAAA;CAChB;AA0CD;;GAEG;AACH,wBAAgB,aAAa,CAC3B,IAAI,EAAE,eAAe,EAAE,EACvB,OAAO,EAAE,OAAO,GACf,GAAG,CAAC,MAAM,EAAE,eAAe,EAAE,CAAC,CAkBhC;AAED,wBAAsB,MAAM,CAAC,EAC3B,WAAW,EACX,QAAgB,EAChB,IAAI,EACJ,SAAS,EACT,OAAO,EACP,MAAM,EAAE,cAAc,EACtB,KAAK,GACN,EAAE,IAAI,iBAuNN"}
@@ -7,11 +7,12 @@ const figma_rest_api_1 = require("./figma_rest_api");
7
7
  const helpers_1 = require("./helpers");
8
8
  const validation_1 = require("./validation");
9
9
  const fetch_1 = require("../common/fetch");
10
+ const COMPONENT_BROWSER_CONFLICT_REASON = 'Code Connect UI mapping already exists';
10
11
  const RETRY_DELAYS_MS = [5_000, 15_000, 30_000];
11
- async function postWithRetry(apiUrl, batch, accessToken) {
12
+ async function postWithRetry(apiUrl, batch, accessToken, useOAuth = false) {
12
13
  for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt++) {
13
14
  try {
14
- return await fetch_1.request.post(apiUrl, batch, { headers: (0, figma_rest_api_1.getHeaders)(accessToken) });
15
+ return await fetch_1.request.post(apiUrl, batch, { headers: (0, figma_rest_api_1.getHeaders)(accessToken, useOAuth) });
15
16
  }
16
17
  catch (err) {
17
18
  if ((0, fetch_1.isFetchError)(err) && (err.response.status === 429 || err.response.status >= 500)) {
@@ -73,8 +74,10 @@ function createDocsMap(docs, verbose) {
73
74
  }
74
75
  return docsMap;
75
76
  }
76
- async function upload({ accessToken, docs, batchSize, verbose, apiUrl: apiUrlOverride, }) {
77
- const apiUrl = (0, figma_rest_api_1.getApiUrl)(docs?.[0]?.figmaNode ?? '', apiUrlOverride) + '/code_connect';
77
+ async function upload({ accessToken, useOAuth = false, docs, batchSize, verbose, apiUrl: apiUrlOverride, force, }) {
78
+ const apiUrl = (0, figma_rest_api_1.getApiUrl)(docs?.[0]?.figmaNode ?? '', apiUrlOverride) +
79
+ '/code_connect' +
80
+ (force ? '?force=true' : '');
78
81
  // Strip internal fields before uploading to Figma
79
82
  const cleanedDocs = docs.map((doc) => {
80
83
  const { _codeConnectFilePath, ...cleanDoc } = doc;
@@ -129,7 +132,7 @@ async function upload({ accessToken, docs, batchSize, verbose, apiUrl: apiUrlOve
129
132
  (0, helpers_1.exitWithFeedbackMessage)(1);
130
133
  }
131
134
  logging_1.logger.debug(`Uploading ${size.toFixed(2)}mb to Figma`);
132
- const response = await postWithRetry(apiUrl, batch, accessToken);
135
+ const response = await postWithRetry(apiUrl, batch, accessToken, useOAuth);
133
136
  const data = response.data;
134
137
  if (data.meta?.published_nodes) {
135
138
  data.meta.published_nodes.forEach((node) => allUploadedNodes.add(getKeyFromFigmaNode(node.figmaNode)));
@@ -150,8 +153,8 @@ async function upload({ accessToken, docs, batchSize, verbose, apiUrl: apiUrlOve
150
153
  (0, helpers_1.exitWithFeedbackMessage)(1);
151
154
  }
152
155
  logging_1.logger.debug(`Uploading ${size.toFixed(2)}mb to Figma`);
153
- logging_1.logger.info(`uploading to ${apiUrl}`);
154
- const response = await postWithRetry(apiUrl, cleanedDocs, accessToken);
156
+ logging_1.logger.info(`Uploading to ${apiUrl}`);
157
+ const response = await postWithRetry(apiUrl, cleanedDocs, accessToken, useOAuth);
155
158
  const data = response.data;
156
159
  if (data.meta?.published_nodes) {
157
160
  data.meta.published_nodes.forEach((node) => allUploadedNodes.add(getKeyFromFigmaNode(node.figmaNode)));
@@ -187,8 +190,20 @@ async function upload({ accessToken, docs, batchSize, verbose, apiUrl: apiUrlOve
187
190
  logging_1.logger.info(`Successfully uploaded to Figma, for ${label}:\n${docs.map((doc) => `-> ${codeConnectStr(doc)}`).join('\n')}`);
188
191
  }
189
192
  if (Object.keys(failedDocsByLabel).length > 0) {
193
+ let hasComponentBrowserConflicts = false;
190
194
  for (const [label, failedItems] of Object.entries(failedDocsByLabel)) {
191
- logging_1.logger.error(`Failed to upload to Figma, for ${label}:\n${failedItems.map((item) => `-> ${codeConnectStr(item.doc)} (${item.reason})`).join('\n')}`);
195
+ const conflicts = failedItems.filter((item) => item.reason.includes(COMPONENT_BROWSER_CONFLICT_REASON));
196
+ const otherFailures = failedItems.filter((item) => !item.reason.includes(COMPONENT_BROWSER_CONFLICT_REASON));
197
+ if (conflicts.length > 0) {
198
+ hasComponentBrowserConflicts = true;
199
+ logging_1.logger.warn((0, logging_1.warn)(`Warning: ${conflicts.length} node(s) already have UI-created Code Connect mappings in Figma for label "${label}":\n${conflicts.map((item) => `-> ${codeConnectStr(item.doc)}`).join('\n')}`));
200
+ }
201
+ if (otherFailures.length > 0) {
202
+ logging_1.logger.error(`Failed to upload to Figma, for ${label}:\n${otherFailures.map((item) => `-> ${codeConnectStr(item.doc)} (${item.reason})`).join('\n')}`);
203
+ }
204
+ }
205
+ if (hasComponentBrowserConflicts && !force) {
206
+ logging_1.logger.warn((0, logging_1.warn)(`Re-run with --force to overwrite the existing UI-created mappings with your Code Connect files.`));
192
207
  }
193
208
  }
194
209
  }