{"record":{"id":"79bfd30e4d3bfbba","repo":"jackwener/OpenCLI","slug":"returned-malformed-post-row","errorCode":null,"errorMessage":" returned malformed post row","messagePattern":" returned malformed post row","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"clis/instagram/comment.js","lineNumber":43,"sourceCode":"  if (!Number.isInteger(idx) || idx < 0) throw new Error('index must be a positive integer');\n  const headers = { 'X-IG-App-ID': '936619743392459' };\n  const opts = { credentials: 'include', headers };\n  async function readInstagramJson(response, label) {\n    try {\n      return await response.json();\n    } catch {\n      throw new Error(label + ' returned invalid JSON');\n    }\n  }\n  function getPostFromFeed(feed, label) {\n    if (!feed || typeof feed !== 'object' || !Array.isArray(feed.items)) {\n      throw new Error(label + ' returned malformed items payload');\n    }\n    if (idx >= feed.items.length) throw new Error('Post index ' + (idx + 1) + ' not found');\n    const post = feed.items[idx];\n    const pkRaw = post?.pk ?? post?.id;\n    const pk = typeof pkRaw === 'number' ? String(pkRaw) : (typeof pkRaw === 'string' ? pkRaw.trim() : '');\n    if (!/^\\\\d+$/.test(pk)) throw new Error(label + ' returned malformed post row');\n    return { pk };\n  }\n  function assertOkStatus(payload, label) {\n    if (!payload || typeof payload !== 'object' || payload.status !== 'ok') {\n      throw new Error(label + ' returned no success evidence');\n    }\n  }\n\n  // web_profile_info answers HTTP 400 for business accounts; feed-by-username needs no user id. See #2234.\n  const r1 = await fetch('https://www.instagram.com/api/v1/feed/user/' + encodeURIComponent(username) + '/username/?count=' + (idx + 1), opts);\n  if (!r1.ok) throw new Error(r1.status === 404 ? 'User not found: ' + username : 'HTTP ' + r1.status + ' - make sure you are logged in to Instagram');\n  const { pk } = getPostFromFeed(await readInstagramJson(r1, 'Instagram feed-by-username'), 'Instagram feed-by-username');\n\n  const csrf = document.cookie.match(/csrftoken=([^;]+)/)?.[1] || '';\n  const r2 = await fetch('https://www.instagram.com/api/v1/web/comments/' + pk + '/add/', {\n    method: 'POST', credentials: 'include',\n    headers: { ...headers, 'X-CSRFToken': csrf, 'Content-Type': 'application/x-www-form-urlencoded' },\n    body: 'comment_text=' + encodeURIComponent(commentText),","sourceCodeStart":25,"sourceCodeEnd":61,"githubUrl":"https://github.com/jackwener/OpenCLI/blob/49907e53dc3ade5c223ff0c4c2c2785687cec4e6/clis/instagram/comment.js#L25-L61","documentation":"After locating the feed item, the CLI extracts the post id (post.pk ?? post.id), normalizes it to a numeric string, and requires it to be all digits. A non-matching pk means the feed row is not a normal media post (e.g. an ad, story bundle, or reshaped item), so it throws '${label} returned malformed post row'.","triggerScenarios":"The selected feed item is an ad, IGTV/clip wrapper, carousel metadata, or otherwise lacks a numeric pk/id; Instagram schema changes move pk into a nested field.","commonSituations":"Commenting on accounts whose feeds include promoted posts at the chosen index; new media types (e.g. trial reels) that carry string-with-suffix ids; partial API migrations returning nested objects.","solutions":["Skip that index and pick a different post, or filter non-media items (ads, announcements) from items first","Log the offending item and update pk extraction to read the new nesting (e.g. post.media.pk)","Retry with a fresh session if the item shape differs due to experiment buckets","Post-process pk by stripping non-digit characters only if the id is a known formatted variant"],"exampleFix":"// before\nconst pkRaw = post?.pk ?? post?.id;\nconst pk = typeof pkRaw === 'number' ? String(pkRaw) : (typeof pkRaw === 'string' ? pkRaw.trim() : '');\n// after\nconst pkRaw = post?.pk ?? post?.id ?? post?.media?.pk;\nconst pk = String(pkRaw ?? '').replace(/\\D/g, '');\nif (!pk) throw new Error(label + ' returned malformed post row: ' + JSON.stringify(post).slice(0, 200));","handlingStrategy":"type-guard","validationCode":"const post = feed.items[idx];\nconst pkRaw = post?.pk ?? post?.id ?? post?.media?.pk;\nconst pk = String(pkRaw ?? '').replace(/\\D/g, '');\nif (!/^\\d+$/.test(pk)) console.warn('Non-media item at index, skip');","typeGuard":"function hasNumericPk(post) {\n  const raw = post?.pk ?? post?.id;\n  return typeof raw === 'number' || (typeof raw === 'string' && /^\\d+$/.test(raw.trim()));\n}","tryCatchPattern":"try {\n  await runCommentPipeline(args);\n} catch (e) {\n  if (/malformed post row/.test(e.message)) {\n    console.warn('Feed item is not a normal media post (ad/wrapper) - try another index');\n  } else throw e;\n}","preventionTips":["Filter ads/promoted items from feed items","Prefer indexes on recent organic posts","Log the offending item to track schema changes","Normalize pk/id defensively before use"],"tags":["instagram","schema-mismatch","data-validation"],"backgroundTag":"unexpected-api-response-schema","analyzedSha":"49907e53dc3ade5c223ff0c4c2c2785687cec4e6","analyzedAt":"2026-08-29T08:14:47.543Z","schemaVersion":2},"datasetVersion":"2026-08-29T12:17:43.993Z"}