import assert from 'node:assert/strict'; import { test } from 'node:test'; import { extractJsonObjectAfterKey } from '../src/platforms/scan.ts'; test('a plain payload is read straight out', () => { const source = `window.x = {"a":1,"shortcode_media":{"id":"7","is_video":false},"b":2};`; assert.deepEqual(extractJsonObjectAfterKey(source, 'shortcode_media'), { id: '7', is_video: false }); }); test('braces inside strings do not end the object', () => { const source = `{"shortcode_media":{"caption":"a } b { c","id":"7"}}`; assert.deepEqual(extractJsonObjectAfterKey(source, 'shortcode_media'), { caption: 'a } b { c', id: '7' }); }); test('an escaped quote inside a string does not end the string', () => { const source = String.raw`{"shortcode_media":{"caption":"she said \"hi\" }","id":"7"}}`; const found = extractJsonObjectAfterKey<{ caption: string }>(source, 'shortcode_media'); assert.equal(found?.caption, 'she said "hi" }'); }); test('a null value is skipped in favour of a later real one', () => { const source = `{"shortcode_media":null,"other":1,"wrap":{"shortcode_media":{"id":"7"}}}`; assert.deepEqual(extractJsonObjectAfterKey(source, 'shortcode_media'), { id: '7' }); }); test('a payload escaped inside a JS string is unescaped and decoded', () => { // This is the real shape: Instagram nests the post JSON inside a bootstrap // call, so the quotes and slashes arrive escaped a level deeper. const source = String.raw`requireLazy(["ServerJS"],function(s){s.handle({"gql_data":{\"shortcode_media\":{\"id\":\"7\",\"display_url\":\"https:\\\/\\\/cdn\\\/a.jpg\",\"caption\":\"line one\\nline two\"}}})})`; const found = extractJsonObjectAfterKey<{ id: string; display_url: string; caption: string }>( source, 'shortcode_media', ); assert.equal(found?.id, '7'); // Both the slash escaping and the newline have to survive intact. assert.equal(found?.display_url, 'https://cdn/a.jpg'); assert.equal(found?.caption, 'line one\nline two'); }); test('a missing key is undefined rather than a throw', () => { assert.equal(extractJsonObjectAfterKey('{"a":1}', 'shortcode_media'), undefined); assert.equal(extractJsonObjectAfterKey('', 'shortcode_media'), undefined); assert.equal(extractJsonObjectAfterKey('{"shortcode_media":{"a":', 'shortcode_media'), undefined); });