{"record":{"id":"ceb0fc74ab6ad0e2","repo":"linshenkx/prompt-optimizer","slug":"variables-importer-errors-invalidvariablename","errorCode":null,"errorMessage":"variables.importer.errors.invalidVariableName","messagePattern":"variables\\.importer\\.errors\\.invalidVariableName","errorType":"validation","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/ui/src/components/variable/VariableImporter.vue","lineNumber":273,"sourceCode":"  const headers = lines[0].split(',').map(h => h.trim().replace(/\"/g, ''))\n  const nameIndex = headers.findIndex(h => ['name', 'key', 'variable'].includes(h.toLowerCase()))\n  const valueIndex = headers.findIndex(h => ['value', 'val'].includes(h.toLowerCase()))\n  \n  if (nameIndex === -1 || valueIndex === -1) {\n    throw new Error(t('variables.importer.errors.csvRequiredColumns'))\n  }\n  \n  const variables: Record<string, string> = {}\n  \n  for (let i = 1; i < lines.length; i++) {\n    const cells = lines[i].split(',').map(c => c.trim().replace(/\"/g, ''))\n    if (cells.length > Math.max(nameIndex, valueIndex)) {\n      const name = cells[nameIndex]\n      const value = cells[valueIndex]\n      if (name && value !== undefined) {\n        // 验证变量名格式\n        if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {\n          throw new Error(t('variables.importer.errors.invalidVariableName', { name }))\n        }\n        variables[name] = value\n      }\n    }\n  }\n  \n  return variables\n}\n\nconst parseTxtVariables = (content: string): Record<string, string> => {\n  const variables: Record<string, string> = {}\n  const lines = content.trim().split('\\n')\n  \n  for (const line of lines) {\n    const trimmedLine = line.trim()\n    if (!trimmedLine || trimmedLine.startsWith('#')) continue\n    \n    const separatorIndex = Math.max(","sourceCodeStart":255,"sourceCodeEnd":291,"githubUrl":"https://github.com/linshenkx/prompt-optimizer/blob/3e677b1d9f7e0493c142c175560531e7ae786dce/packages/ui/src/components/variable/VariableImporter.vue#L255-L291","documentation":"While iterating CSV data rows, each variable name must match /^[a-zA-Z_][a-zA-Z0-9_]*$/ — it must start with a letter or underscore and contain only letters, digits, and underscores. A row whose name cell violates this (e.g. contains a dot, dash, space, or starts with a digit) aborts the entire import with this error, echoing the offending name.","triggerScenarios":"A CSV row like 'my-var,value', '1key,value', 'user name,value', or a name cell with invisible characters/BOM. Note only rows where the name cell is truthy are validated, so empty name cells are silently skipped.","commonSituations":"Names imported from systems that allow dashes or dots (env-file exporters, spreadsheet users typing 'First Name'), localized keyboards inserting non-ASCII characters, or trailing whitespace inside quotes.","solutions":["Fix the offending variable name in the CSV to match ^[a-zA-Z_][a-zA-Z0-9_]*$ (use underscore instead of dash/space).","Sanitize names during import instead of throwing: name = name.replace(/[^a-zA-Z0-9_]/g, '_') with a warning, if business rules allow.","Collect all invalid names first and report them together rather than failing on the first one."],"exampleFix":"// before\nif (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {\n  throw new Error(t('variables.importer.errors.invalidVariableName', { name }))\n}\n// after (sanitize or skip)\nif (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {\n  invalidNames.push(name)\n  continue\n}","handlingStrategy":"validation","validationCode":"const VALID_NAME = /^[a-zA-Z_][a-zA-Z0-9_]*$/\nconst rows = parseRows(content)\nconst invalid = rows.filter(r => r.name && !VALID_NAME.test(r.name))\nif (invalid.length) {\n  showError(`Invalid variable names: ${invalid.map(r => r.name).join(', ')}`)\n  return\n}","typeGuard":"const isValidVariableName = (name: string): boolean =>\n  /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)","tryCatchPattern":"try { parseCsvVariables(content) } catch (e) { if (e instanceof Error && e.message.includes('invalidVariableName')) { /* extract name, offer to auto-replace invalid chars with '_' */ } else throw e }","preventionTips":["Validate names in the editor/spreadsheet before export.","Offer an auto-sanitize option (replace invalid chars with underscore).","Pre-scan the whole file and report all bad names at once instead of failing on the first."],"tags":["csv","variable-names","validation","regex","file-import"],"backgroundTag":"invalid-identifier-validation","analyzedSha":"3e677b1d9f7e0493c142c175560531e7ae786dce","analyzedAt":"2026-08-27T21:29:16.709Z","schemaVersion":2},"datasetVersion":"2026-08-28T00:17:15.603Z"}