toon-format/toon · error · Error

Unexpected endArray event

Error message

Unexpected endArray event

What it means

applyEvent received an endArray event while the stack is empty — no open array exists to close, so the stream is unbalanced.

Source

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

          if (parent.currentKey === undefined) {
            throw new Error('Array startArray event without preceding key')
          }
          setOwnProperty(parent.obj, parent.currentKey, arr)
          parent.currentKey = undefined
        }
        else if (parent.type === 'array') {
          parent.arr.push(arr)
        }

        stack.push({ type: 'array', arr })
      }

      break
    }

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

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

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

      break
    }

    case 'key': {
      if (stack.length === 0) {
        throw new Error('Key event outside of object context')
      }

View on GitHub (pinned to 604eac266e)

Solutions

  1. Balance each endArray with a startArray
  2. Fix the producer emitting surplus endArray events
  3. Pre-validate start/end counts

Example fix

// before
[{type:'endArray'}] // unbalanced
// after
[{type:'startArray'},{type:'endArray'}]
Defensive patterns

Strategy: validation

Validate before calling

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

Try / catch

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

Prevention

When it happens

Trigger: A stream with more endArray events than startArray events, or a leading endArray.

Common situations: Corrupted/truncated streams; double-emission of endArray by custom producers.

Related errors


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