toon-format/toon · error · Error

Unexpected endObject event

Error message

Unexpected endObject event

What it means

applyEvent received an endObject event while the nesting stack is empty — there is no open object to close, so the event stream is unbalanced.

Source

Thrown at packages/toon/src/decode/event-builder.ts:79

            throw new Error('Object startObject event without preceding key')
          }

          setOwnProperty(parent.obj, parent.currentKey, obj)
          parent.currentKey = undefined
        }
        else if (parent.type === 'array') {
          parent.arr.push(obj)
        }

        stack.push({ type: 'object', obj })
      }

      break
    }

    case 'endObject': {
      if (stack.length === 0) {
        throw new Error('Unexpected endObject event')
      }

      const context = stack.pop()!
      if (context.type !== 'object') {
        throw new Error('Mismatched endObject event')
      }

      if (stack.length === 0) {
        state.root = context.obj
      }

      break
    }

    case 'startArray': {
      const arr: JsonValue[] = []

      if (stack.length === 0) {

View on GitHub (pinned to 604eac266e)

Solutions

  1. Balance each endObject with a corresponding startObject
  2. Fix the emitter that drops startObject or emits extra endObject events
  3. Pre-validate start/end balance before building

Example fix

// before
[{type:'endObject'}] // unbalanced
// after
[{type:'startObject'},{type:'endObject'}]
Defensive patterns

Strategy: validation

Validate before calling

function hasNoExtraEndObject(events) {
  let depth = 0
  for (const ev of events) {
    if (ev.type === 'startObject') depth++
    if (ev.type === 'endObject') { depth--; if (depth < 0) return false }
  }
  return depth === 0
}

Try / catch

try {
  const value = buildValueFromEvents(events)
} catch (e) {
  if (e.message === 'Unexpected endObject event') {
    throw new Error('Unbalanced event stream: endObject without startObject')
  }
  throw e
}

Prevention

When it happens

Trigger: A stream with more endObject events than startObject events, or endObject as the first event.

Common situations: Truncated or corrupted event streams; off-by-one bugs in custom event producers.

Related errors


AI-assisted analysis of toon-format/toon@604eac266e (2026-08-31). Data as JSON: /api/errors/6b79511f9181d975. Report an issue: GitHub.