{"record":{"id":"541de83fe43c461c","repo":"amark/gun","slug":"invalid-first-argument-for-type-hex","errorCode":null,"errorMessage":"Invalid first argument for type 'hex'.","messagePattern":"Invalid first argument for type 'hex'\\.","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"sea/buffer.js","lineNumber":29,"sourceCode":"      console.warn('new SafeBuffer() is depreciated, please use SafeBuffer.from()')\n      return SafeBuffer.from(...props)\n    }\n    SafeBuffer.prototype = Object.create(Array.prototype)\n    Object.assign(SafeBuffer, {\n      // (data, enc) where typeof data === 'string' then enc === 'utf8'|'hex'|'base64'\n      from() {\n        if (!Object.keys(arguments).length || arguments[0]==null) {\n          throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n        }\n        const input = arguments[0]\n        let buf\n        if (typeof input === 'string') {\n          const enc = arguments[1] || 'utf8'\n          if (enc === 'hex') {\n            const bytes = input.match(/([\\da-fA-F]{2})/g)\n            .map((byte) => parseInt(byte, 16))\n            if (!bytes || !bytes.length) {\n              throw new TypeError('Invalid first argument for type \\'hex\\'.')\n            }\n            buf = SeaArray.from(bytes)\n          } else if (enc === 'utf8' || 'binary' === enc) { // EDIT BY MARK: I think this is safe, tested it against a couple \"binary\" strings. This lets SafeBuffer match NodeJS Buffer behavior more where it safely btoas regular strings.\n            const length = input.length\n            const words = new Uint16Array(length)\n            Array.from({ length: length }, (_, i) => words[i] = input.charCodeAt(i))\n            buf = SeaArray.from(words)\n          } else if (enc === 'base64') {\n            const dec = atob(input)\n            const length = dec.length\n            const bytes = new Uint8Array(length)\n            Array.from({ length: length }, (_, i) => bytes[i] = dec.charCodeAt(i))\n            buf = SeaArray.from(bytes)\n          } else if (enc === 'binary') { // deprecated by above comment\n            buf = SeaArray.from(input) // some btoas were mishandled.\n          } else {\n            console.info('SafeBuffer.from unknown encoding: '+enc)\n          }","sourceCodeStart":11,"sourceCodeEnd":47,"githubUrl":"https://github.com/amark/gun/blob/552227599d47ba0493824b7fcf8a00c8cd6404ba/sea/buffer.js#L11-L47","documentation":"SafeBuffer.from with encoding 'hex' decodes the input string by matching pairs of hex digits. It throws a TypeError when the string contains no valid hex character pairs, i.e. nothing matched the /([\\da-fA-F]{2})/g pattern, so no bytes could be produced.","triggerScenarios":"Calling SafeBuffer.from(str, 'hex') where str is empty (''), contains no hex-pair characters (e.g. 'zzzz', 'xyz'), or is plain prose — note match() returns null for no matches, and the check `!bytes || !bytes.length` catches both. Strings with odd-length hex or partial junk will NOT throw (match silently skips invalid chars), so this fires mainly for fully non-hex input.","commonSituations":"Loading a hex-encoded key/secret from env or config that was never set or is placeholder text; decoding user input that was expected to be hex but was pasted as base64 or raw text; schema changes where a field switched from hex to utf8 encoding.","solutions":["Validate the string is non-empty hex before calling: /^[0-9a-fA-F]+$/ and even length","Confirm the correct encoding — the data may actually be base64 or utf8, not hex","Check the config/env/source actually contains the expected hex payload","Trim whitespace and any '0x' prefix, which are not matched as valid hex pairs"],"exampleFix":"// before\nconst bytes = SafeBuffer.from(raw, 'hex'); // throws when raw isn't hex\n// after\nif (!/^[0-9a-fA-F]+$/.test(raw || '') || raw.length % 2 !== 0) {\n  throw new Error('expected even-length hex string');\n}\nconst bytes = SafeBuffer.from(raw, 'hex');","handlingStrategy":"validation","validationCode":"function isHex(s) {\n  return typeof s === 'string' && s.length > 0 && s.length % 2 === 0 && /^[0-9a-fA-F]+$/.test(s);\n}\nif (!isHex(raw)) throw new Error('expected even-length hex string');","typeGuard":"const isHexString = (v) => typeof v === 'string' && /^[0-9a-fA-F]*$/.test(v);","tryCatchPattern":"try {\n  const bytes = SafeBuffer.from(raw, 'hex');\n} catch (e) {\n  console.error('not valid hex:', raw);\n  throw e;\n}","preventionTips":["Validate hex format (regex + even length) before decoding","Confirm the actual encoding of your data (hex vs base64 vs utf8)","Trim whitespace and strip '0x' prefixes","Check env/config sources are populated with real hex payloads"],"tags":["buffer","hex","typeerror","encoding","sea"],"backgroundTag":"invalid-hex-input","analyzedSha":"552227599d47ba0493824b7fcf8a00c8cd6404ba","analyzedAt":"2026-09-02T18:40:58.370Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-09T21:17:11.164Z"}