@sjawhar/claude-envoy 5.10.1 → 5.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -47645,13 +47645,1129 @@ var DELIMITERS = {
47645
47645
  pipe: "|"
47646
47646
  };
47647
47647
  var DEFAULT_DELIMITER = DELIMITERS.comma;
47648
+ function trimSpaces(value) {
47649
+ let start = 0;
47650
+ let end = value.length;
47651
+ while (start < end && value[start] === " ")
47652
+ start++;
47653
+ while (end > start && value[end - 1] === " ")
47654
+ end--;
47655
+ return start === 0 && end === value.length ? value : value.slice(start, end);
47656
+ }
47648
47657
  function escapeString(value) {
47649
47658
  return value.replace(/\\/g, `\\\\`).replace(/"/g, `\\"`).replace(/\n/g, `\\n`).replace(/\r/g, `\\r`).replace(/\t/g, `\\t`).replace(/[\u0000-\u001F]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
47650
47659
  }
47660
+ function unescapeString(value) {
47661
+ let unescaped = "";
47662
+ let i = 0;
47663
+ while (i < value.length) {
47664
+ if (value[i] === "\\") {
47665
+ if (i + 1 >= value.length)
47666
+ throw new SyntaxError("Invalid escape sequence: backslash at end of string");
47667
+ const next = value[i + 1];
47668
+ if (next === "n") {
47669
+ unescaped += `
47670
+ `;
47671
+ i += 2;
47672
+ continue;
47673
+ }
47674
+ if (next === "t") {
47675
+ unescaped += "\t";
47676
+ i += 2;
47677
+ continue;
47678
+ }
47679
+ if (next === "r") {
47680
+ unescaped += "\r";
47681
+ i += 2;
47682
+ continue;
47683
+ }
47684
+ if (next === "\\") {
47685
+ unescaped += "\\";
47686
+ i += 2;
47687
+ continue;
47688
+ }
47689
+ if (next === '"') {
47690
+ unescaped += '"';
47691
+ i += 2;
47692
+ continue;
47693
+ }
47694
+ if (next === "u") {
47695
+ if (i + 6 > value.length)
47696
+ throw new SyntaxError(`Invalid escape sequence: truncated \\u escape at "${value.slice(i, i + 6)}"`);
47697
+ const hex = value.slice(i + 2, i + 6);
47698
+ if (!/^[0-9a-f]{4}$/i.test(hex))
47699
+ throw new SyntaxError(`Invalid escape sequence: \\u must be followed by 4 hex digits, got "${hex}"`);
47700
+ const codeUnit = Number.parseInt(hex, 16);
47701
+ if (codeUnit >= 55296 && codeUnit <= 57343)
47702
+ throw new SyntaxError(`Invalid escape sequence: \\u${hex} is a lone surrogate. Supplementary code points MUST appear as literal UTF-8`);
47703
+ unescaped += String.fromCodePoint(codeUnit);
47704
+ i += 6;
47705
+ continue;
47706
+ }
47707
+ throw new SyntaxError(`Invalid escape sequence: \\${next}`);
47708
+ }
47709
+ unescaped += value[i];
47710
+ i++;
47711
+ }
47712
+ return unescaped;
47713
+ }
47714
+ function findClosingQuote(content, start) {
47715
+ let i = start + 1;
47716
+ while (i < content.length) {
47717
+ if (content[i] === "\\" && i + 1 < content.length) {
47718
+ i += 2;
47719
+ continue;
47720
+ }
47721
+ if (content[i] === '"')
47722
+ return i;
47723
+ i++;
47724
+ }
47725
+ return -1;
47726
+ }
47727
+ function findUnquotedChar(content, char, start = 0) {
47728
+ let inQuotes = false;
47729
+ let i = start;
47730
+ while (i < content.length) {
47731
+ if (content[i] === "\\" && i + 1 < content.length && inQuotes) {
47732
+ i += 2;
47733
+ continue;
47734
+ }
47735
+ if (content[i] === '"') {
47736
+ inQuotes = !inQuotes;
47737
+ i++;
47738
+ continue;
47739
+ }
47740
+ if (content[i] === char && !inQuotes)
47741
+ return i;
47742
+ i++;
47743
+ }
47744
+ return -1;
47745
+ }
47746
+ var ToonDecodeError = class extends SyntaxError {
47747
+ constructor(message, context) {
47748
+ const prefix = context?.line !== undefined ? `Line ${context.line}: ` : "";
47749
+ super(prefix + message, context?.cause !== undefined ? { cause: context.cause } : undefined);
47750
+ this.name = "ToonDecodeError";
47751
+ this.line = context?.line;
47752
+ this.source = context?.source;
47753
+ }
47754
+ };
47755
+ function withLine(line, fn) {
47756
+ try {
47757
+ return fn();
47758
+ } catch (error) {
47759
+ if (error instanceof ToonDecodeError)
47760
+ throw error;
47761
+ if (error instanceof Error)
47762
+ throw new ToonDecodeError(error.message, {
47763
+ line: line.lineNumber,
47764
+ source: line.raw,
47765
+ cause: error
47766
+ });
47767
+ throw error;
47768
+ }
47769
+ }
47770
+ var LEADING_WHITESPACE_PATTERN = /^[ \t]*/;
47771
+ function createScanState() {
47772
+ return {
47773
+ lineNumber: 0,
47774
+ blankLines: []
47775
+ };
47776
+ }
47777
+ function parseLineIncremental(raw, state, indentSize, strict) {
47778
+ state.lineNumber++;
47779
+ const lineNumber = state.lineNumber;
47780
+ if (lineNumber === 1 && raw[0] === "\uFEFF")
47781
+ raw = raw.slice(1);
47782
+ if (raw[raw.length - 1] === "\r")
47783
+ raw = raw.slice(0, -1);
47784
+ const leadingWhitespace = LEADING_WHITESPACE_PATTERN.exec(raw)[0];
47785
+ const firstTabIndex = leadingWhitespace.indexOf("\t");
47786
+ const indent = strict && firstTabIndex !== -1 ? firstTabIndex : leadingWhitespace.length;
47787
+ const tabIndent = strict || firstTabIndex === -1 ? 0 : leadingWhitespace.split("\t").length - 1;
47788
+ const content = trimTrailingSpaces(raw.slice(indent));
47789
+ if (firstTabIndex === -1 && content[0] === "#")
47790
+ return;
47791
+ const depth = computeDepthFromIndent(indent - tabIndent, indentSize) + tabIndent;
47792
+ if (!content) {
47793
+ state.blankLines.push({
47794
+ lineNumber,
47795
+ indent,
47796
+ depth
47797
+ });
47798
+ return;
47799
+ }
47800
+ if (strict) {
47801
+ if (firstTabIndex !== -1)
47802
+ throw new ToonDecodeError("Tabs are not allowed in indentation in strict mode", {
47803
+ line: lineNumber,
47804
+ source: raw
47805
+ });
47806
+ if (indent > 0 && indent % indentSize !== 0)
47807
+ throw new ToonDecodeError(`Indentation must be exact multiple of ${indentSize}, but found ${indent} spaces`, {
47808
+ line: lineNumber,
47809
+ source: raw
47810
+ });
47811
+ }
47812
+ return {
47813
+ raw,
47814
+ indent,
47815
+ content,
47816
+ depth,
47817
+ lineNumber
47818
+ };
47819
+ }
47820
+ function computeDepthFromIndent(indentSpaces, indentSize) {
47821
+ return Math.floor(indentSpaces / indentSize);
47822
+ }
47823
+ function trimTrailingSpaces(value) {
47824
+ let end = value.length;
47825
+ while (end > 0 && value[end - 1] === " ")
47826
+ end--;
47827
+ return end === value.length ? value : value.slice(0, end);
47828
+ }
47651
47829
  var FETCH_LINE = Symbol("fetch-line");
47830
+ function createLineReader(context) {
47831
+ return {
47832
+ buffer: [],
47833
+ done: false,
47834
+ lastLine: undefined,
47835
+ scanState: createScanState(),
47836
+ indentSize: context.indentSize,
47837
+ strict: context.strict
47838
+ };
47839
+ }
47840
+ function* fillBuffer(reader) {
47841
+ while (reader.buffer.length === 0 && !reader.done) {
47842
+ const raw = yield FETCH_LINE;
47843
+ if (raw === undefined) {
47844
+ reader.done = true;
47845
+ return;
47846
+ }
47847
+ const parsedLine = parseLineIncremental(raw, reader.scanState, reader.indentSize, reader.strict);
47848
+ if (parsedLine !== undefined)
47849
+ reader.buffer.push(parsedLine);
47850
+ }
47851
+ }
47852
+ function* peekLine(reader) {
47853
+ yield* fillBuffer(reader);
47854
+ return reader.buffer[0];
47855
+ }
47856
+ function* readLine(reader) {
47857
+ yield* fillBuffer(reader);
47858
+ const line = reader.buffer[0];
47859
+ if (line !== undefined) {
47860
+ reader.buffer.shift();
47861
+ reader.lastLine = line;
47862
+ }
47863
+ return line;
47864
+ }
47865
+ function* driveSync(rawSource, rule) {
47866
+ const iterator = rawSource[Symbol.iterator]();
47867
+ let step = rule.next();
47868
+ while (!step.done)
47869
+ if (step.value === FETCH_LINE) {
47870
+ const result = iterator.next();
47871
+ step = rule.next(result.done ? undefined : result.value);
47872
+ } else {
47873
+ yield step.value;
47874
+ step = rule.next();
47875
+ }
47876
+ }
47877
+ var NUMERIC_LITERAL_PATTERN = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:e[+-]?\d+)?$/i;
47652
47878
  function isBooleanOrNullLiteral(token) {
47653
47879
  return token === "true" || token === "false" || token === "null";
47654
47880
  }
47881
+ function isNumericLiteral(token) {
47882
+ if (!token)
47883
+ return false;
47884
+ if (!NUMERIC_LITERAL_PATTERN.test(token))
47885
+ return false;
47886
+ const numericValue = Number(token);
47887
+ return !Number.isNaN(numericValue) && Number.isFinite(numericValue);
47888
+ }
47889
+ function parseArrayHeaderLine(content, defaultDelimiter) {
47890
+ const trimmedToken = content.trimStart();
47891
+ let bracketStart = -1;
47892
+ if (trimmedToken.startsWith('"')) {
47893
+ const closingQuoteIndex = findClosingQuote(trimmedToken, 0);
47894
+ if (closingQuoteIndex === -1)
47895
+ return { kind: "notHeader" };
47896
+ if (!trimmedToken.slice(closingQuoteIndex + 1).startsWith("["))
47897
+ return { kind: "notHeader" };
47898
+ const keyEndIndex = content.length - trimmedToken.length + closingQuoteIndex + 1;
47899
+ bracketStart = content.indexOf("[", keyEndIndex);
47900
+ } else
47901
+ bracketStart = findUnquotedChar(content, "[");
47902
+ if (bracketStart === -1)
47903
+ return { kind: "notHeader" };
47904
+ const firstColonIndex = findUnquotedChar(content, ":");
47905
+ if (firstColonIndex !== -1 && firstColonIndex < bracketStart)
47906
+ return { kind: "notHeader" };
47907
+ const bracketEnd = findUnquotedChar(content, "]", bracketStart);
47908
+ if (bracketEnd === -1)
47909
+ return { kind: "notHeader" };
47910
+ let colonIndex = bracketEnd + 1;
47911
+ let braceEnd = colonIndex;
47912
+ const braceStart = findUnquotedChar(content, "{", bracketEnd);
47913
+ if (braceStart !== -1 && braceStart < findUnquotedChar(content, ":", bracketEnd)) {
47914
+ const gapBeforeBrace = content.slice(bracketEnd + 1, braceStart);
47915
+ if (gapBeforeBrace !== "") {
47916
+ const trimmedGap = gapBeforeBrace.trim();
47917
+ return {
47918
+ kind: "invalid",
47919
+ reason: trimmedGap === "" ? `Unexpected whitespace between bracket segment and field list` : `Unexpected content "${trimmedGap}" between bracket segment and field list`
47920
+ };
47921
+ }
47922
+ const foundBraceEnd = findMatchingBrace(content, braceStart);
47923
+ if (foundBraceEnd !== -1)
47924
+ braceEnd = foundBraceEnd + 1;
47925
+ }
47926
+ colonIndex = findUnquotedChar(content, ":", Math.max(bracketEnd, braceEnd));
47927
+ if (colonIndex === -1)
47928
+ return { kind: "notHeader" };
47929
+ const gapStart = Math.max(bracketEnd + 1, braceEnd);
47930
+ const gapBeforeColon = content.slice(gapStart, colonIndex);
47931
+ if (gapBeforeColon !== "") {
47932
+ const trimmedGap = gapBeforeColon.trim();
47933
+ return {
47934
+ kind: "invalid",
47935
+ reason: trimmedGap === "" ? `Unexpected whitespace between bracket segment and colon` : `Unexpected content "${trimmedGap}" between bracket segment and colon`
47936
+ };
47937
+ }
47938
+ let key;
47939
+ if (bracketStart > 0) {
47940
+ const rawKey = content.slice(0, bracketStart);
47941
+ if (rawKey !== rawKey.trimEnd())
47942
+ return {
47943
+ kind: "invalid",
47944
+ reason: "Unexpected whitespace between key and bracket segment"
47945
+ };
47946
+ key = rawKey.startsWith('"') ? parseStringLiteral(rawKey) : rawKey;
47947
+ }
47948
+ const afterColon = trimSpaces(content.slice(colonIndex + 1));
47949
+ const bracketContent = content.slice(bracketStart + 1, bracketEnd);
47950
+ let parsedBracket;
47951
+ try {
47952
+ parsedBracket = parseBracketSegment(bracketContent, defaultDelimiter);
47953
+ } catch (error) {
47954
+ return {
47955
+ kind: "invalid",
47956
+ reason: error.message
47957
+ };
47958
+ }
47959
+ const { length, delimiter, keyed } = parsedBracket;
47960
+ let fields;
47961
+ if (braceStart !== -1 && braceStart < colonIndex) {
47962
+ const foundBraceEnd = findMatchingBrace(content, braceStart);
47963
+ if (foundBraceEnd !== -1 && foundBraceEnd < colonIndex) {
47964
+ const fieldsContent = content.slice(braceStart + 1, foundBraceEnd);
47965
+ const mismatchedDelimiter = findUnquotedMismatchedDelimiter(fieldsContent, delimiter);
47966
+ if (mismatchedDelimiter !== undefined)
47967
+ return {
47968
+ kind: "invalid",
47969
+ reason: `Header delimiter mismatch: bracket declares "${formatDelimiter(delimiter)}" but field list contains unquoted "${formatDelimiter(mismatchedDelimiter)}"`
47970
+ };
47971
+ try {
47972
+ fields = parseFieldEntries(fieldsContent, delimiter);
47973
+ } catch (error) {
47974
+ return {
47975
+ kind: "invalid",
47976
+ reason: error.message
47977
+ };
47978
+ }
47979
+ }
47980
+ }
47981
+ const duplicateFieldName = fields ? findDuplicateFieldName(fields) : undefined;
47982
+ const duplicateReason = duplicateFieldName ? `Duplicate field name "${duplicateFieldName}" in field list` : undefined;
47983
+ if (keyed && !fields)
47984
+ return {
47985
+ kind: "invalid",
47986
+ reason: "Keyed header requires a field list"
47987
+ };
47988
+ if (fields && afterColon)
47989
+ return {
47990
+ kind: "invalid",
47991
+ reason: duplicateReason ?? "Unexpected content after fields-bearing header colon"
47992
+ };
47993
+ return {
47994
+ kind: "header",
47995
+ header: {
47996
+ key,
47997
+ length,
47998
+ delimiter,
47999
+ fields,
48000
+ keyed
48001
+ },
48002
+ inlineValues: afterColon || undefined,
48003
+ strictError: duplicateReason
48004
+ };
48005
+ }
48006
+ var BRACKET_LENGTH_PATTERN = /^(?:0|[1-9]\d*)$/;
48007
+ function parseBracketSegment(seg, defaultDelimiter) {
48008
+ let content = seg;
48009
+ let delimiter = defaultDelimiter;
48010
+ if (content.endsWith("\t")) {
48011
+ delimiter = DELIMITERS.tab;
48012
+ content = content.slice(0, -1);
48013
+ } else if (content.endsWith("|")) {
48014
+ delimiter = DELIMITERS.pipe;
48015
+ content = content.slice(0, -1);
48016
+ }
48017
+ let keyed = false;
48018
+ if (content.endsWith(":")) {
48019
+ keyed = true;
48020
+ content = content.slice(0, -1);
48021
+ }
48022
+ if (!BRACKET_LENGTH_PATTERN.test(content))
48023
+ throw new SyntaxError(`Invalid array length: "${seg}" (expected non-negative integer with no leading zeros)`);
48024
+ return {
48025
+ length: Number.parseInt(content, 10),
48026
+ delimiter,
48027
+ keyed
48028
+ };
48029
+ }
48030
+ function parseFieldEntries(fieldsContent, delimiter) {
48031
+ return splitFieldEntries(fieldsContent, delimiter).map((entry) => {
48032
+ const trimmedEntry = trimSpaces(entry);
48033
+ if (!trimmedEntry)
48034
+ throw new SyntaxError("Empty field name in field list");
48035
+ const groupStart = findUnquotedChar(trimmedEntry, "{");
48036
+ if (groupStart === -1)
48037
+ return { name: parseStringLiteral(trimmedEntry) };
48038
+ const namePart = trimSpaces(trimmedEntry.slice(0, groupStart));
48039
+ if (!namePart)
48040
+ throw new SyntaxError("Missing field name before nested field group");
48041
+ const groupEnd = findMatchingBrace(trimmedEntry, groupStart);
48042
+ if (groupEnd === -1)
48043
+ throw new SyntaxError("Unmatched brace in field list");
48044
+ if (groupEnd !== trimmedEntry.length - 1)
48045
+ throw new SyntaxError("Unexpected content after nested field group");
48046
+ const children = parseFieldEntries(trimmedEntry.slice(groupStart + 1, groupEnd), delimiter);
48047
+ return {
48048
+ name: parseStringLiteral(namePart),
48049
+ children
48050
+ };
48051
+ });
48052
+ }
48053
+ function splitFieldEntries(content, delimiter) {
48054
+ const entries = [];
48055
+ let entryBuffer = "";
48056
+ let inQuotes = false;
48057
+ let braceDepth = 0;
48058
+ let i = 0;
48059
+ while (i < content.length) {
48060
+ const char = content[i];
48061
+ if (char === "\\" && i + 1 < content.length && inQuotes) {
48062
+ entryBuffer += char + content[i + 1];
48063
+ i += 2;
48064
+ continue;
48065
+ }
48066
+ if (char === '"') {
48067
+ inQuotes = !inQuotes;
48068
+ entryBuffer += char;
48069
+ i++;
48070
+ continue;
48071
+ }
48072
+ if (!inQuotes) {
48073
+ if (char === "{")
48074
+ braceDepth++;
48075
+ else if (char === "}")
48076
+ braceDepth--;
48077
+ else if (char === delimiter && braceDepth === 0) {
48078
+ entries.push(entryBuffer);
48079
+ entryBuffer = "";
48080
+ i++;
48081
+ continue;
48082
+ }
48083
+ }
48084
+ entryBuffer += char;
48085
+ i++;
48086
+ }
48087
+ entries.push(entryBuffer);
48088
+ return entries;
48089
+ }
48090
+ function findMatchingBrace(content, braceStart) {
48091
+ let inQuotes = false;
48092
+ let braceDepth = 0;
48093
+ let i = braceStart;
48094
+ while (i < content.length) {
48095
+ const char = content[i];
48096
+ if (char === "\\" && i + 1 < content.length && inQuotes) {
48097
+ i += 2;
48098
+ continue;
48099
+ }
48100
+ if (char === '"') {
48101
+ inQuotes = !inQuotes;
48102
+ i++;
48103
+ continue;
48104
+ }
48105
+ if (!inQuotes) {
48106
+ if (char === "{")
48107
+ braceDepth++;
48108
+ else if (char === "}") {
48109
+ braceDepth--;
48110
+ if (braceDepth === 0)
48111
+ return i;
48112
+ }
48113
+ }
48114
+ i++;
48115
+ }
48116
+ return -1;
48117
+ }
48118
+ function findDuplicateFieldName(fields) {
48119
+ const seenNames = /* @__PURE__ */ new Set;
48120
+ for (const field of fields) {
48121
+ if (seenNames.has(field.name))
48122
+ return field.name;
48123
+ seenNames.add(field.name);
48124
+ if (field.children) {
48125
+ const nestedDuplicate = findDuplicateFieldName(field.children);
48126
+ if (nestedDuplicate !== undefined)
48127
+ return nestedDuplicate;
48128
+ }
48129
+ }
48130
+ }
48131
+ function countLeafFields(fields) {
48132
+ let leafCount = 0;
48133
+ for (const field of fields)
48134
+ leafCount += field.children ? countLeafFields(field.children) : 1;
48135
+ return leafCount;
48136
+ }
48137
+ var DELIMITER_CANDIDATES = [
48138
+ ",",
48139
+ "\t",
48140
+ "|"
48141
+ ];
48142
+ function findUnquotedMismatchedDelimiter(content, activeDelimiter) {
48143
+ for (const candidate of DELIMITER_CANDIDATES) {
48144
+ if (candidate === activeDelimiter)
48145
+ continue;
48146
+ if (findUnquotedChar(content, candidate) !== -1)
48147
+ return candidate;
48148
+ }
48149
+ }
48150
+ function formatDelimiter(delimiter) {
48151
+ if (delimiter === "\t")
48152
+ return "\\t";
48153
+ return delimiter;
48154
+ }
48155
+ function parseDelimitedValues(input, delimiter) {
48156
+ const values = [];
48157
+ let valueBuffer = "";
48158
+ let inQuotes = false;
48159
+ let i = 0;
48160
+ while (i < input.length) {
48161
+ const char = input[i];
48162
+ if (char === "\\" && i + 1 < input.length && inQuotes) {
48163
+ valueBuffer += char + input[i + 1];
48164
+ i += 2;
48165
+ continue;
48166
+ }
48167
+ if (char === '"') {
48168
+ inQuotes = !inQuotes;
48169
+ valueBuffer += char;
48170
+ i++;
48171
+ continue;
48172
+ }
48173
+ if (char === delimiter && !inQuotes) {
48174
+ values.push(trimSpaces(valueBuffer));
48175
+ valueBuffer = "";
48176
+ i++;
48177
+ continue;
48178
+ }
48179
+ valueBuffer += char;
48180
+ i++;
48181
+ }
48182
+ if (valueBuffer || values.length > 0)
48183
+ values.push(trimSpaces(valueBuffer));
48184
+ return values;
48185
+ }
48186
+ function mapRowValuesToPrimitives(values) {
48187
+ return values.map((v) => parsePrimitiveToken(v));
48188
+ }
48189
+ function parsePrimitiveToken(token) {
48190
+ const trimmedToken = trimSpaces(token);
48191
+ if (!trimmedToken)
48192
+ return "";
48193
+ if (trimmedToken.startsWith('"'))
48194
+ return parseStringLiteral(trimmedToken);
48195
+ if (isBooleanOrNullLiteral(trimmedToken)) {
48196
+ if (trimmedToken === "true")
48197
+ return true;
48198
+ if (trimmedToken === "false")
48199
+ return false;
48200
+ if (trimmedToken === "null")
48201
+ return null;
48202
+ }
48203
+ if (isNumericLiteral(trimmedToken)) {
48204
+ const parsedNumber = Number.parseFloat(trimmedToken);
48205
+ return Object.is(parsedNumber, -0) ? 0 : parsedNumber;
48206
+ }
48207
+ return trimmedToken;
48208
+ }
48209
+ function parseStringLiteral(token) {
48210
+ const trimmedToken = trimSpaces(token);
48211
+ if (trimmedToken.startsWith('"')) {
48212
+ const closingQuoteIndex = findClosingQuote(trimmedToken, 0);
48213
+ if (closingQuoteIndex === -1)
48214
+ throw new SyntaxError("Unterminated string: missing closing quote");
48215
+ if (closingQuoteIndex !== trimmedToken.length - 1)
48216
+ throw new SyntaxError("Unexpected characters after closing quote");
48217
+ return unescapeString(trimmedToken.slice(1, closingQuoteIndex));
48218
+ }
48219
+ return trimmedToken;
48220
+ }
48221
+ function parseUnquotedKey(content, start) {
48222
+ const colonIndex = findUnquotedChar(content, ":", start);
48223
+ if (colonIndex === -1)
48224
+ throw new SyntaxError("Missing colon after key");
48225
+ return {
48226
+ key: trimSpaces(content.slice(start, colonIndex)),
48227
+ end: colonIndex + 1
48228
+ };
48229
+ }
48230
+ function parseQuotedKey(content, start) {
48231
+ const closingQuoteIndex = findClosingQuote(content, start);
48232
+ if (closingQuoteIndex === -1)
48233
+ throw new SyntaxError("Unterminated quoted key");
48234
+ const key = unescapeString(content.slice(start + 1, closingQuoteIndex));
48235
+ let parsePosition = closingQuoteIndex + 1;
48236
+ if (parsePosition >= content.length || content[parsePosition] !== ":")
48237
+ throw new SyntaxError("Missing colon after key");
48238
+ parsePosition++;
48239
+ return {
48240
+ key,
48241
+ end: parsePosition
48242
+ };
48243
+ }
48244
+ function parseKeyToken(content, start) {
48245
+ return content[start] === '"' ? parseQuotedKey(content, start) : parseUnquotedKey(content, start);
48246
+ }
48247
+ function isArrayHeaderContent(content) {
48248
+ return content.trim().startsWith("[") && findUnquotedChar(content, ":") !== -1;
48249
+ }
48250
+ function isKeyValueContent(content) {
48251
+ return findUnquotedChar(content, ":") !== -1;
48252
+ }
48253
+ function assertExpectedCount(actual, expected, itemType, options, line) {
48254
+ if (options.strict && actual !== expected)
48255
+ throw new ToonDecodeError(`Expected ${expected} ${itemType}, but got ${actual}`, {
48256
+ line: line.lineNumber,
48257
+ source: line.raw
48258
+ });
48259
+ }
48260
+ function validateNoExtraListItems(nextLine, itemDepth, expectedCount) {
48261
+ if (nextLine?.depth === itemDepth && nextLine.content.startsWith("- "))
48262
+ throw new ToonDecodeError(`Expected ${expectedCount} list-form items, but found more`, {
48263
+ line: nextLine.lineNumber,
48264
+ source: nextLine.raw
48265
+ });
48266
+ }
48267
+ function validateNoExtraTabularRows(nextLine, rowDepth, header) {
48268
+ if (nextLine?.depth === rowDepth && !nextLine.content.startsWith("- ") && isDataRow(nextLine.content, header.delimiter))
48269
+ throw new ToonDecodeError(`Expected ${header.length} tabular rows, but found more`, {
48270
+ line: nextLine.lineNumber,
48271
+ source: nextLine.raw
48272
+ });
48273
+ }
48274
+ function validateNoBlankLinesInRange(startLine, endLine, blankLines, strict, context) {
48275
+ if (!strict)
48276
+ return;
48277
+ const firstBlank = blankLines.find((blank) => blank.lineNumber > startLine && blank.lineNumber < endLine);
48278
+ if (firstBlank)
48279
+ throw new ToonDecodeError(`Blank lines inside ${context} are not allowed in strict mode`, { line: firstBlank.lineNumber });
48280
+ }
48281
+ function isDataRow(content, delimiter) {
48282
+ const colonPos = findUnquotedChar(content, ":");
48283
+ const delimiterPos = findUnquotedChar(content, delimiter);
48284
+ if (colonPos === -1)
48285
+ return true;
48286
+ if (delimiterPos !== -1 && delimiterPos < colonPos)
48287
+ return true;
48288
+ return false;
48289
+ }
48290
+ function resolveContext(options) {
48291
+ return {
48292
+ indentSize: options?.indentSize ?? options?.indent ?? 2,
48293
+ strict: options?.strict ?? true
48294
+ };
48295
+ }
48296
+ function decodeStreamSync$1(source, options) {
48297
+ const resolvedOptions = resolveContext(options);
48298
+ return driveSync(source, decodeDocument(createLineReader(resolvedOptions), resolvedOptions));
48299
+ }
48300
+ function* decodeDocument(reader, options) {
48301
+ const first = yield* peekLine(reader);
48302
+ if (!first) {
48303
+ yield { type: "startObject" };
48304
+ yield { type: "endObject" };
48305
+ return;
48306
+ }
48307
+ if (trimSpaces(first.content) === "[]") {
48308
+ yield* readLine(reader);
48309
+ yield {
48310
+ type: "startArray",
48311
+ length: 0
48312
+ };
48313
+ yield { type: "endArray" };
48314
+ yield* assertFullyConsumed(reader, options.strict);
48315
+ return;
48316
+ }
48317
+ if (isArrayHeaderContent(first.content)) {
48318
+ const headerInfo = withLine(first, () => resolveArrayHeader(parseArrayHeaderLine(first.content, DEFAULT_DELIMITER), options.strict));
48319
+ if (headerInfo) {
48320
+ yield* readLine(reader);
48321
+ yield* decodeArrayFromHeader(headerInfo.header, headerInfo.inlineValues, reader, 0, options, first);
48322
+ yield* assertFullyConsumed(reader, options.strict);
48323
+ return;
48324
+ }
48325
+ }
48326
+ yield* readLine(reader);
48327
+ const following = yield* peekLine(reader);
48328
+ if (!(following !== undefined) && !isKeyValueLine(first)) {
48329
+ yield {
48330
+ type: "primitive",
48331
+ value: withLine(first, () => parsePrimitiveToken(first.content))
48332
+ };
48333
+ return;
48334
+ }
48335
+ if (!isKeyValueLine(first) && following?.depth === 0)
48336
+ throw new ToonDecodeError("Top-level document must start with a key-value or array-header line", {
48337
+ line: first.lineNumber,
48338
+ source: first.raw
48339
+ });
48340
+ const rootSeenKeys = options.strict ? /* @__PURE__ */ new Set : undefined;
48341
+ yield { type: "startObject" };
48342
+ yield* decodeKeyValue(first, reader, 0, options, rootSeenKeys);
48343
+ while (true) {
48344
+ const line = yield* peekLine(reader);
48345
+ if (!line)
48346
+ break;
48347
+ if (line.depth !== 0) {
48348
+ if (options.strict)
48349
+ throw overIndentedLineError(line, 0);
48350
+ assertNotScalarLine(line);
48351
+ yield* readLine(reader);
48352
+ continue;
48353
+ }
48354
+ yield* readLine(reader);
48355
+ yield* decodeKeyValue(line, reader, 0, options, rootSeenKeys);
48356
+ }
48357
+ yield { type: "endObject" };
48358
+ }
48359
+ function assertNoDepthJump(firstNestedLine, parentDepth, strict) {
48360
+ if (strict && firstNestedLine.depth > parentDepth + 1)
48361
+ throw new ToonDecodeError(`Indentation depth jump: expected depth ${parentDepth + 1}, but found ${firstNestedLine.depth}`, {
48362
+ line: firstNestedLine.lineNumber,
48363
+ source: firstNestedLine.raw
48364
+ });
48365
+ }
48366
+ function overIndentedLineError(line, expectedDepth) {
48367
+ return new ToonDecodeError(`Over-indented line: expected depth ${expectedDepth}, but found ${line.depth}`, {
48368
+ line: line.lineNumber,
48369
+ source: line.raw
48370
+ });
48371
+ }
48372
+ function assertNotScalarLine(line) {
48373
+ if (line.content.startsWith("- ") || line.content === "-" || findUnquotedChar(line.content, ":") !== -1)
48374
+ return;
48375
+ throw new ToonDecodeError("Unexpected bare token line outside root primitive position", {
48376
+ line: line.lineNumber,
48377
+ source: line.raw
48378
+ });
48379
+ }
48380
+ function keylessKeyedError(line) {
48381
+ return new ToonDecodeError("Keyless keyed header is only valid at the document root", {
48382
+ line: line.lineNumber,
48383
+ source: line.raw
48384
+ });
48385
+ }
48386
+ function keylessHeaderError(line) {
48387
+ return new ToonDecodeError("Keyless array header is only valid at the document root or as a list item", {
48388
+ line: line.lineNumber,
48389
+ source: line.raw
48390
+ });
48391
+ }
48392
+ function keylessFieldsHeaderError(line) {
48393
+ return new ToonDecodeError("Keyless header with a field list is only valid at the document root", {
48394
+ line: line.lineNumber,
48395
+ source: line.raw
48396
+ });
48397
+ }
48398
+ function* assertFullyConsumed(reader, strict) {
48399
+ if (!strict)
48400
+ return;
48401
+ const line = yield* peekLine(reader);
48402
+ if (line)
48403
+ throw new ToonDecodeError("Unexpected content after the document root", {
48404
+ line: line.lineNumber,
48405
+ source: line.raw
48406
+ });
48407
+ }
48408
+ function assertNoDuplicateKey(key, line, seenKeys) {
48409
+ if (!seenKeys)
48410
+ return;
48411
+ if (seenKeys.has(key))
48412
+ throw new ToonDecodeError(`Duplicate sibling key "${key}"`, {
48413
+ line: line.lineNumber,
48414
+ source: line.raw
48415
+ });
48416
+ seenKeys.add(key);
48417
+ }
48418
+ function* decodeKeyValue(line, reader, baseDepth, options, seenKeys) {
48419
+ const content = line.content;
48420
+ const arrayHeader = withLine(line, () => resolveArrayHeader(parseArrayHeaderLine(content, DEFAULT_DELIMITER), options.strict));
48421
+ if (arrayHeader && arrayHeader.header.key !== undefined) {
48422
+ assertNoDuplicateKey(arrayHeader.header.key, line, seenKeys);
48423
+ yield {
48424
+ type: "key",
48425
+ key: arrayHeader.header.key
48426
+ };
48427
+ yield* decodeArrayFromHeader(arrayHeader.header, arrayHeader.inlineValues, reader, baseDepth, options, line);
48428
+ return;
48429
+ }
48430
+ if (arrayHeader && arrayHeader.header.key === undefined && options.strict)
48431
+ throw arrayHeader.header.keyed ? keylessKeyedError(line) : keylessHeaderError(line);
48432
+ const { key, end } = withLine(line, () => parseKeyToken(content, 0));
48433
+ const rest = trimSpaces(content.slice(end));
48434
+ assertNoDuplicateKey(key, line, seenKeys);
48435
+ yield {
48436
+ type: "key",
48437
+ key
48438
+ };
48439
+ if (!rest) {
48440
+ const nextLine = yield* peekLine(reader);
48441
+ if (nextLine && nextLine.depth > baseDepth) {
48442
+ assertNoDepthJump(nextLine, baseDepth, options.strict);
48443
+ yield { type: "startObject" };
48444
+ yield* decodeObjectFields(reader, baseDepth + 1, options);
48445
+ yield { type: "endObject" };
48446
+ return;
48447
+ }
48448
+ yield { type: "startObject" };
48449
+ yield { type: "endObject" };
48450
+ return;
48451
+ }
48452
+ if (rest === "[]") {
48453
+ yield {
48454
+ type: "startArray",
48455
+ length: 0
48456
+ };
48457
+ yield { type: "endArray" };
48458
+ return;
48459
+ }
48460
+ yield {
48461
+ type: "primitive",
48462
+ value: withLine(line, () => parsePrimitiveToken(rest))
48463
+ };
48464
+ }
48465
+ function* decodeObjectFields(reader, baseDepth, options) {
48466
+ let computedDepth;
48467
+ const seenKeys = options.strict ? /* @__PURE__ */ new Set : undefined;
48468
+ while (true) {
48469
+ const line = yield* peekLine(reader);
48470
+ if (!line || line.depth < baseDepth)
48471
+ break;
48472
+ if (computedDepth === undefined && line.depth >= baseDepth)
48473
+ computedDepth = line.depth;
48474
+ if (line.depth === computedDepth) {
48475
+ yield* readLine(reader);
48476
+ yield* decodeKeyValue(line, reader, computedDepth, options, seenKeys);
48477
+ } else if (computedDepth !== undefined && line.depth > computedDepth) {
48478
+ if (options.strict)
48479
+ throw overIndentedLineError(line, computedDepth);
48480
+ assertNotScalarLine(line);
48481
+ yield* readLine(reader);
48482
+ } else
48483
+ break;
48484
+ }
48485
+ }
48486
+ function* decodeArrayFromHeader(header, inlineValues, reader, baseDepth, options, headerLine) {
48487
+ if (header.keyed) {
48488
+ yield* decodeKeyedObject(header, reader, baseDepth, options, headerLine);
48489
+ return;
48490
+ }
48491
+ yield {
48492
+ type: "startArray",
48493
+ length: header.length
48494
+ };
48495
+ if (inlineValues) {
48496
+ yield* decodeInlinePrimitiveArray(header, inlineValues, options, headerLine);
48497
+ yield { type: "endArray" };
48498
+ return;
48499
+ }
48500
+ if (header.fields && header.fields.length > 0) {
48501
+ yield* decodeTabularArray(header, reader, baseDepth, options, headerLine);
48502
+ yield { type: "endArray" };
48503
+ return;
48504
+ }
48505
+ yield* decodeListArray(header, reader, baseDepth, options, headerLine);
48506
+ yield { type: "endArray" };
48507
+ }
48508
+ function* decodeInlinePrimitiveArray(header, inlineValues, options, headerLine) {
48509
+ if (!trimSpaces(inlineValues)) {
48510
+ assertExpectedCount(0, header.length, "inline-form values", options, headerLine);
48511
+ return;
48512
+ }
48513
+ const values = withLine(headerLine, () => parseDelimitedValues(inlineValues, header.delimiter));
48514
+ const primitives = withLine(headerLine, () => mapRowValuesToPrimitives(values));
48515
+ assertExpectedCount(primitives.length, header.length, "inline-form values", options, headerLine);
48516
+ for (const primitive of primitives)
48517
+ yield {
48518
+ type: "primitive",
48519
+ value: primitive
48520
+ };
48521
+ }
48522
+ function* decodeKeyedObject(header, reader, baseDepth, options, headerLine) {
48523
+ const entryDepth = baseDepth + 1;
48524
+ const leafFieldCount = countLeafFields(header.fields);
48525
+ const seenEntryKeys = options.strict ? /* @__PURE__ */ new Set : undefined;
48526
+ let entryCount = 0;
48527
+ let startLine;
48528
+ let endLine;
48529
+ let lastEntryLine = headerLine;
48530
+ yield { type: "startObject" };
48531
+ while (true) {
48532
+ const line = yield* peekLine(reader);
48533
+ if (!line || line.depth <= baseDepth)
48534
+ break;
48535
+ if (line.depth > entryDepth) {
48536
+ if (options.strict)
48537
+ throw new ToonDecodeError("Unexpected indentation inside keyed tabular object", {
48538
+ line: line.lineNumber,
48539
+ source: line.raw
48540
+ });
48541
+ yield* readLine(reader);
48542
+ continue;
48543
+ }
48544
+ if (findUnquotedChar(line.content, ":") === -1) {
48545
+ if (options.strict)
48546
+ throw new ToonDecodeError("Expected entry row inside keyed tabular object", {
48547
+ line: line.lineNumber,
48548
+ source: line.raw
48549
+ });
48550
+ yield* readLine(reader);
48551
+ continue;
48552
+ }
48553
+ yield* readLine(reader);
48554
+ if (startLine === undefined)
48555
+ startLine = line.lineNumber;
48556
+ endLine = line.lineNumber;
48557
+ lastEntryLine = line;
48558
+ const { key, end } = withLine(line, () => parseKeyToken(line.content, 0));
48559
+ assertNoDuplicateKey(key, line, seenEntryKeys);
48560
+ yield {
48561
+ type: "key",
48562
+ key
48563
+ };
48564
+ const cellsContent = trimSpaces(line.content.slice(end));
48565
+ const values = cellsContent === "" ? [] : withLine(line, () => parseDelimitedValues(cellsContent, header.delimiter));
48566
+ assertExpectedCount(values.length, leafFieldCount, "keyed entry cells", options, line);
48567
+ const primitives = withLine(line, () => mapRowValuesToPrimitives(values));
48568
+ yield* yieldObjectFromFields(header.fields, primitives);
48569
+ entryCount++;
48570
+ }
48571
+ assertExpectedCount(entryCount, header.length, "keyed entries", options, lastEntryLine);
48572
+ if (options.strict && startLine !== undefined && endLine !== undefined)
48573
+ validateNoBlankLinesInRange(startLine, endLine, reader.scanState.blankLines, options.strict, "keyed tabular object");
48574
+ yield { type: "endObject" };
48575
+ }
48576
+ function* decodeTabularArray(header, reader, baseDepth, options, headerLine) {
48577
+ const rowDepth = baseDepth + 1;
48578
+ let rowCount = 0;
48579
+ let startLine;
48580
+ let endLine;
48581
+ let lastRowLine = headerLine;
48582
+ while (!options.strict || rowCount < header.length) {
48583
+ const line = yield* peekLine(reader);
48584
+ if (!line || line.depth < rowDepth)
48585
+ break;
48586
+ if (line.depth === rowDepth) {
48587
+ if (!isDataRow(line.content, header.delimiter))
48588
+ break;
48589
+ if (startLine === undefined)
48590
+ startLine = line.lineNumber;
48591
+ endLine = line.lineNumber;
48592
+ lastRowLine = line;
48593
+ yield* readLine(reader);
48594
+ const values = withLine(line, () => parseDelimitedValues(line.content, header.delimiter));
48595
+ assertExpectedCount(values.length, countLeafFields(header.fields), "tabular row values", options, line);
48596
+ const primitives = withLine(line, () => mapRowValuesToPrimitives(values));
48597
+ yield* yieldObjectFromFields(header.fields, primitives);
48598
+ rowCount++;
48599
+ } else
48600
+ break;
48601
+ }
48602
+ assertExpectedCount(rowCount, header.length, "tabular rows", options, lastRowLine);
48603
+ if (options.strict && startLine !== undefined && endLine !== undefined)
48604
+ validateNoBlankLinesInRange(startLine, endLine, reader.scanState.blankLines, options.strict, "tabular array");
48605
+ if (options.strict)
48606
+ validateNoExtraTabularRows(yield* peekLine(reader), rowDepth, header);
48607
+ }
48608
+ function* decodeListArray(header, reader, baseDepth, options, headerLine) {
48609
+ const itemDepth = baseDepth + 1;
48610
+ let itemCount = 0;
48611
+ let startLine;
48612
+ let endLine;
48613
+ let lastItemLine = headerLine;
48614
+ while (!options.strict || itemCount < header.length) {
48615
+ const line = yield* peekLine(reader);
48616
+ if (!line || line.depth < itemDepth)
48617
+ break;
48618
+ const isListItem = line.content.startsWith("- ") || line.content === "-";
48619
+ if (line.depth === itemDepth && isListItem) {
48620
+ if (startLine === undefined)
48621
+ startLine = line.lineNumber;
48622
+ endLine = line.lineNumber;
48623
+ lastItemLine = line;
48624
+ yield* decodeListItem(reader, itemDepth, options);
48625
+ const lastConsumedLine = reader.lastLine;
48626
+ if (lastConsumedLine) {
48627
+ endLine = lastConsumedLine.lineNumber;
48628
+ lastItemLine = lastConsumedLine;
48629
+ }
48630
+ itemCount++;
48631
+ } else
48632
+ break;
48633
+ }
48634
+ assertExpectedCount(itemCount, header.length, "list-form items", options, lastItemLine);
48635
+ if (options.strict && startLine !== undefined && endLine !== undefined)
48636
+ validateNoBlankLinesInRange(startLine, endLine, reader.scanState.blankLines, options.strict, "list-form array");
48637
+ if (options.strict)
48638
+ validateNoExtraListItems(yield* peekLine(reader), itemDepth, header.length);
48639
+ }
48640
+ function* decodeListItem(reader, baseDepth, options) {
48641
+ const line = yield* readLine(reader);
48642
+ if (!line)
48643
+ throw new ReferenceError("Expected list item");
48644
+ let afterHyphen;
48645
+ if (line.content === "-") {
48646
+ yield { type: "startObject" };
48647
+ yield { type: "endObject" };
48648
+ return;
48649
+ } else if (line.content.startsWith("- "))
48650
+ afterHyphen = line.content.slice(2);
48651
+ else
48652
+ throw new ToonDecodeError(`Expected list item to start with "- "`, {
48653
+ line: line.lineNumber,
48654
+ source: line.raw
48655
+ });
48656
+ if (!trimSpaces(afterHyphen)) {
48657
+ yield { type: "startObject" };
48658
+ yield { type: "endObject" };
48659
+ return;
48660
+ }
48661
+ if (trimSpaces(afterHyphen) === "[]") {
48662
+ yield {
48663
+ type: "startArray",
48664
+ length: 0
48665
+ };
48666
+ yield { type: "endArray" };
48667
+ return;
48668
+ }
48669
+ const itemLine = {
48670
+ ...line,
48671
+ content: afterHyphen
48672
+ };
48673
+ if (isArrayHeaderContent(afterHyphen)) {
48674
+ const arrayHeader = withLine(itemLine, () => resolveArrayHeader(parseArrayHeaderLine(afterHyphen, DEFAULT_DELIMITER), options.strict));
48675
+ if (arrayHeader)
48676
+ if (arrayHeader.header.keyed || arrayHeader.header.fields !== undefined) {
48677
+ if (options.strict)
48678
+ throw arrayHeader.header.keyed ? keylessKeyedError(itemLine) : keylessFieldsHeaderError(itemLine);
48679
+ } else {
48680
+ yield* decodeArrayFromHeader(arrayHeader.header, arrayHeader.inlineValues, reader, baseDepth, options, itemLine);
48681
+ return;
48682
+ }
48683
+ }
48684
+ const headerInfo = withLine(itemLine, () => resolveArrayHeader(parseArrayHeaderLine(afterHyphen, DEFAULT_DELIMITER), options.strict));
48685
+ if (headerInfo && headerInfo.header.key !== undefined && headerInfo.header.fields !== undefined) {
48686
+ const header = headerInfo.header;
48687
+ const seenKeys = options.strict ? /* @__PURE__ */ new Set([header.key]) : undefined;
48688
+ yield { type: "startObject" };
48689
+ yield {
48690
+ type: "key",
48691
+ key: header.key
48692
+ };
48693
+ yield* decodeArrayFromHeader(header, headerInfo.inlineValues, reader, baseDepth + 1, options, itemLine);
48694
+ yield* followSiblingFields(reader, baseDepth + 1, options, seenKeys);
48695
+ yield { type: "endObject" };
48696
+ return;
48697
+ }
48698
+ if (isKeyValueContent(afterHyphen)) {
48699
+ const seenKeys = options.strict ? /* @__PURE__ */ new Set : undefined;
48700
+ yield { type: "startObject" };
48701
+ yield* decodeKeyValue(itemLine, reader, baseDepth + 1, options, seenKeys);
48702
+ yield* followSiblingFields(reader, baseDepth + 1, options, seenKeys);
48703
+ yield { type: "endObject" };
48704
+ return;
48705
+ }
48706
+ yield {
48707
+ type: "primitive",
48708
+ value: withLine(itemLine, () => parsePrimitiveToken(afterHyphen))
48709
+ };
48710
+ }
48711
+ function* followSiblingFields(reader, followDepth, options, seenKeys) {
48712
+ while (true) {
48713
+ const nextLine = yield* peekLine(reader);
48714
+ if (!nextLine || nextLine.depth < followDepth)
48715
+ break;
48716
+ if (nextLine.depth === followDepth && !nextLine.content.startsWith("- ")) {
48717
+ yield* readLine(reader);
48718
+ yield* decodeKeyValue(nextLine, reader, followDepth, options, seenKeys);
48719
+ } else
48720
+ break;
48721
+ }
48722
+ }
48723
+ function isKeyValueLine(line) {
48724
+ const content = line.content;
48725
+ if (content.startsWith('"')) {
48726
+ const closingQuoteIndex = findClosingQuote(content, 0);
48727
+ if (closingQuoteIndex === -1)
48728
+ return false;
48729
+ return content.slice(closingQuoteIndex + 1).includes(":");
48730
+ } else
48731
+ return content.includes(":");
48732
+ }
48733
+ function resolveArrayHeader(result, strict) {
48734
+ if (result.kind === "notHeader")
48735
+ return;
48736
+ if (result.kind === "invalid") {
48737
+ if (strict)
48738
+ throw new SyntaxError(result.reason);
48739
+ return;
48740
+ }
48741
+ if (strict && result.strictError !== undefined)
48742
+ throw new SyntaxError(result.strictError);
48743
+ return {
48744
+ header: result.header,
48745
+ inlineValues: result.inlineValues
48746
+ };
48747
+ }
48748
+ function* yieldObjectFromFields(fields, primitives) {
48749
+ let cellIndex = 0;
48750
+ function* walkFieldGroup(nodes) {
48751
+ yield { type: "startObject" };
48752
+ for (const node of nodes) {
48753
+ if (!node.children && cellIndex >= primitives.length)
48754
+ continue;
48755
+ yield {
48756
+ type: "key",
48757
+ key: node.name
48758
+ };
48759
+ if (node.children)
48760
+ yield* walkFieldGroup(node.children);
48761
+ else
48762
+ yield {
48763
+ type: "primitive",
48764
+ value: primitives[cellIndex++]
48765
+ };
48766
+ }
48767
+ yield { type: "endObject" };
48768
+ }
48769
+ yield* walkFieldGroup(fields);
48770
+ }
47655
48771
  function setOwnProperty(target, key, value) {
47656
48772
  if (key === "__proto__") {
47657
48773
  Object.defineProperty(target, key, {
@@ -47664,6 +48780,116 @@ function setOwnProperty(target, key, value) {
47664
48780
  }
47665
48781
  target[key] = value;
47666
48782
  }
48783
+ function buildValueFromEvents(events) {
48784
+ const state = {
48785
+ stack: [],
48786
+ root: undefined
48787
+ };
48788
+ for (const event of events)
48789
+ applyEvent(state, event);
48790
+ return finalizeState(state);
48791
+ }
48792
+ function applyEvent(state, event) {
48793
+ const { stack } = state;
48794
+ switch (event.type) {
48795
+ case "startObject": {
48796
+ const obj = {};
48797
+ if (stack.length === 0)
48798
+ stack.push({
48799
+ type: "object",
48800
+ obj
48801
+ });
48802
+ else {
48803
+ const parent = stack[stack.length - 1];
48804
+ if (parent.type === "object") {
48805
+ if (parent.currentKey === undefined)
48806
+ throw new Error("Object startObject event without preceding key");
48807
+ setOwnProperty(parent.obj, parent.currentKey, obj);
48808
+ parent.currentKey = undefined;
48809
+ } else if (parent.type === "array")
48810
+ parent.arr.push(obj);
48811
+ stack.push({
48812
+ type: "object",
48813
+ obj
48814
+ });
48815
+ }
48816
+ break;
48817
+ }
48818
+ case "endObject": {
48819
+ if (stack.length === 0)
48820
+ throw new Error("Unexpected endObject event");
48821
+ const context = stack.pop();
48822
+ if (context.type !== "object")
48823
+ throw new Error("Mismatched endObject event");
48824
+ if (stack.length === 0)
48825
+ state.root = context.obj;
48826
+ break;
48827
+ }
48828
+ case "startArray": {
48829
+ const arr = [];
48830
+ if (stack.length === 0)
48831
+ stack.push({
48832
+ type: "array",
48833
+ arr
48834
+ });
48835
+ else {
48836
+ const parent = stack[stack.length - 1];
48837
+ if (parent.type === "object") {
48838
+ if (parent.currentKey === undefined)
48839
+ throw new Error("Array startArray event without preceding key");
48840
+ setOwnProperty(parent.obj, parent.currentKey, arr);
48841
+ parent.currentKey = undefined;
48842
+ } else if (parent.type === "array")
48843
+ parent.arr.push(arr);
48844
+ stack.push({
48845
+ type: "array",
48846
+ arr
48847
+ });
48848
+ }
48849
+ break;
48850
+ }
48851
+ case "endArray": {
48852
+ if (stack.length === 0)
48853
+ throw new Error("Unexpected endArray event");
48854
+ const context = stack.pop();
48855
+ if (context.type !== "array")
48856
+ throw new Error("Mismatched endArray event");
48857
+ if (stack.length === 0)
48858
+ state.root = context.arr;
48859
+ break;
48860
+ }
48861
+ case "key": {
48862
+ if (stack.length === 0)
48863
+ throw new Error("Key event outside of object context");
48864
+ const parent = stack[stack.length - 1];
48865
+ if (parent.type !== "object")
48866
+ throw new Error("Key event outside of object context");
48867
+ parent.currentKey = event.key;
48868
+ break;
48869
+ }
48870
+ case "primitive":
48871
+ if (stack.length === 0)
48872
+ state.root = event.value;
48873
+ else {
48874
+ const parent = stack[stack.length - 1];
48875
+ if (parent.type === "object") {
48876
+ if (parent.currentKey === undefined)
48877
+ throw new Error("Primitive event without preceding key in object");
48878
+ setOwnProperty(parent.obj, parent.currentKey, event.value);
48879
+ parent.currentKey = undefined;
48880
+ } else if (parent.type === "array")
48881
+ parent.arr.push(event.value);
48882
+ }
48883
+ break;
48884
+ }
48885
+ }
48886
+ function finalizeState(state) {
48887
+ if (state.stack.length !== 0)
48888
+ throw new Error("Incomplete event stream: unclosed objects or arrays");
48889
+ if (state.root === undefined)
48890
+ throw new Error("No root value built from events");
48891
+ return state.root;
48892
+ }
47667
48893
  var COMMENT_LINE_PATTERN = new RegExp(`(?:^\uFEFF?|\\n) *#`);
47668
48894
  var RawString = class {
47669
48895
  constructor(value) {
@@ -48145,11 +49371,18 @@ function encode5(input, options) {
48145
49371
  return Array.from(encodeLines(input, options)).join(`
48146
49372
  `);
48147
49373
  }
49374
+ function decode4(input, options) {
49375
+ return decodeFromLines(input.split(`
49376
+ `), options);
49377
+ }
48148
49378
  function encodeLines(input, options) {
48149
49379
  const normalizedValue = normalizeValue(input);
48150
49380
  const resolvedOptions = resolveOptions(options);
48151
49381
  return encodeJsonValue(resolvedOptions.replacer ? applyReplacer(normalizedValue, resolvedOptions.replacer) : normalizedValue, resolvedOptions, 0);
48152
49382
  }
49383
+ function decodeFromLines(lines, options) {
49384
+ return buildValueFromEvents(decodeStreamSync$1(lines, resolveDecodeOptions(options)));
49385
+ }
48153
49386
  function resolveOptions(options) {
48154
49387
  const delimiter = options?.delimiter ?? DEFAULT_DELIMITER;
48155
49388
  assertValidDelimiter(delimiter);
@@ -48159,6 +49392,12 @@ function resolveOptions(options) {
48159
49392
  replacer: options?.replacer
48160
49393
  };
48161
49394
  }
49395
+ function resolveDecodeOptions(options) {
49396
+ return {
49397
+ indentSize: options?.indentSize ?? options?.indent ?? 2,
49398
+ strict: options?.strict ?? true
49399
+ };
49400
+ }
48162
49401
 
48163
49402
  // ../envoy-client/src/dispatch-pictures.ts
48164
49403
  var PICTURE_UPLOAD_MAX_BYTES = 25 * 1024 * 1024;
@@ -60890,7 +62129,7 @@ var import_nats5 = __toESM(require_mod4(), 1);
60890
62129
 
60891
62130
  // package.json
60892
62131
  var name2 = "@sjawhar/claude-envoy";
60893
- var version2 = "5.10.1";
62132
+ var version2 = "5.10.2";
60894
62133
  var legion = {
60895
62134
  daemonApiVersion: 217
60896
62135
  };
@@ -60943,7 +62182,60 @@ var package_default = {
60943
62182
  }
60944
62183
  };
60945
62184
 
62185
+ // ../envoy-client/src/inbound-card.ts
62186
+ var CARD_HEAD = "envoy:";
62187
+ var TOON_INDENT = " ";
62188
+ function fieldOf(value, key) {
62189
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? Reflect.get(value, key) : undefined;
62190
+ }
62191
+ function readInboundCard(text) {
62192
+ const lines = text.split(`
62193
+ `);
62194
+ if (lines[0] !== CARD_HEAD)
62195
+ return;
62196
+ let end = 1;
62197
+ while (end < lines.length && lines[end]?.startsWith(TOON_INDENT) === true)
62198
+ end += 1;
62199
+ let decoded;
62200
+ try {
62201
+ decoded = decode4(lines.slice(0, end).join(`
62202
+ `));
62203
+ } catch {
62204
+ return;
62205
+ }
62206
+ const envoy = fieldOf(decoded, "envoy");
62207
+ const from = fieldOf(envoy, "from");
62208
+ const dispatch = fieldOf(envoy, "dispatch");
62209
+ const wordsAt = (depth, key, value) => {
62210
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
62211
+ return;
62212
+ }
62213
+ if (value === "")
62214
+ return;
62215
+ const line = lines.indexOf(`${TOON_INDENT.repeat(depth)}${encode5({ [key]: value })}`, 1);
62216
+ return line < 1 || line >= end ? undefined : { text: String(value), line };
62217
+ };
62218
+ let words;
62219
+ if (dispatch !== undefined) {
62220
+ const type = fieldOf(dispatch, "type");
62221
+ words = typeof type === "string" && type.startsWith("message.") ? wordsAt(3, "body", fieldOf(fieldOf(dispatch, "payload"), "body")) : undefined;
62222
+ } else {
62223
+ const message = fieldOf(envoy, "message");
62224
+ words = message === undefined ? wordsAt(1, "summary", fieldOf(envoy, "summary")) : wordsAt(1, "message", message);
62225
+ }
62226
+ const note = fieldOf(envoy, "note");
62227
+ const bodyNote = fieldOf(envoy, "body_note");
62228
+ return {
62229
+ bodyNote: typeof bodyNote === "string" ? bodyNote : undefined,
62230
+ dispatch: dispatch !== undefined,
62231
+ from: typeof from === "string" ? from : undefined,
62232
+ note: typeof note === "string" ? note : undefined,
62233
+ words
62234
+ };
62235
+ }
62236
+
60946
62237
  // ../pi-shared/src/agent-stream.ts
62238
+ var ENVOY_CARD = "envoy-message";
60947
62239
  var encoder4 = new TextEncoder;
60948
62240
  var REPLAY_ARRAY_BYTES = 2;
60949
62241
  function jsonBytes(value) {
@@ -60978,12 +62270,31 @@ function readMessage(raw) {
60978
62270
  tag: typeof message.tag === "string" ? message.tag : undefined
60979
62271
  };
60980
62272
  }
60981
- function keyFor(message) {
62273
+ function stringField(value, field) {
62274
+ if (typeof value !== "object" || value === null)
62275
+ return;
62276
+ const found = Reflect.get(value, field);
62277
+ return typeof found === "string" && found !== "" ? found : undefined;
62278
+ }
62279
+ function streamedCard(host) {
62280
+ if (host.customType !== ENVOY_CARD || host.display !== true)
62281
+ return false;
62282
+ const delivered = "dispatchMessageId";
62283
+ return stringField(host.details, delivered) === undefined;
62284
+ }
62285
+ function keyFor(message, untagged) {
60982
62286
  if (message.role === "toolResult") {
60983
62287
  return message.toolCallId === undefined ? null : `t:${message.toolCallId}`;
60984
62288
  }
60985
62289
  if (message.role === "assistant")
60986
62290
  return `m:a${message.timestamp}`;
62291
+ if (message.role === "custom") {
62292
+ if (!streamedCard(message.host))
62293
+ return null;
62294
+ const { details } = message.host;
62295
+ const card = stringField(details, "envoyCard") ?? stringField(details, "event_id") ?? untagged(message.host);
62296
+ return `m:c${message.timestamp}:${card}`;
62297
+ }
60987
62298
  if (message.role !== "user")
60988
62299
  return null;
60989
62300
  return message.tag === undefined ? `m:u${message.timestamp}` : `m:u${message.timestamp}:${message.tag}`;
@@ -61047,6 +62358,50 @@ function conversationParts(content) {
61047
62358
  }
61048
62359
  return parts;
61049
62360
  }
62361
+ function fenced(text) {
62362
+ let longest = 2;
62363
+ for (const run of text.matchAll(/`+/g))
62364
+ longest = Math.max(longest, run[0].length);
62365
+ const fence = "`".repeat(longest + 1);
62366
+ return `${fence}
62367
+ ${text}
62368
+ ${fence}`;
62369
+ }
62370
+ function cardText(text) {
62371
+ const card = readInboundCard(text);
62372
+ const head = card?.from === undefined ? "Envoy message:" : `Envoy message from ${card.from}:`;
62373
+ const words = card === undefined || card.dispatch ? undefined : card.words?.text;
62374
+ if (words === undefined)
62375
+ return `${head}
62376
+
62377
+ ${fenced(text)}`;
62378
+ const notes = [
62379
+ ...card?.note === undefined ? [] : [`note: ${card.note}`],
62380
+ ...card?.bodyNote === undefined ? [] : [`body_note: ${card.bodyNote}`]
62381
+ ];
62382
+ return [head, words, ...notes].join(`
62383
+
62384
+ `);
62385
+ }
62386
+ function cardParts(content) {
62387
+ const { partChars } = AGENT_STREAM_LIMITS;
62388
+ const blocks = typeof content === "string" ? [{ text: content, type: "text" }] : Array.isArray(content) ? content : [];
62389
+ const parts = [];
62390
+ let read = false;
62391
+ for (const raw of blocks) {
62392
+ if (typeof raw !== "object" || raw === null)
62393
+ continue;
62394
+ const part = raw;
62395
+ if (part.type === "text" && typeof part.text === "string") {
62396
+ const text = read ? part.text : cardText(part.text);
62397
+ read = true;
62398
+ parts.push({ text: capAgentStreamText(text, partChars), type: "text" });
62399
+ } else if (typeof part.type === "string") {
62400
+ parts.push({ text: blockPlaceholder(part.type), type: "text" });
62401
+ }
62402
+ }
62403
+ return parts;
62404
+ }
61050
62405
  function frameFor(entry) {
61051
62406
  const { dispatchMessageId, message } = entry;
61052
62407
  if (message.role === "toolResult" && message.toolCallId !== undefined) {
@@ -61063,6 +62418,20 @@ function frameFor(entry) {
61063
62418
  v: AGENT_STREAM_PROTOCOL
61064
62419
  };
61065
62420
  }
62421
+ if (message.role === "custom") {
62422
+ return {
62423
+ kind: "message",
62424
+ message: {
62425
+ at: message.timestamp,
62426
+ id: entry.key.slice(2),
62427
+ parts: cardParts(message.host.content),
62428
+ role: "user",
62429
+ streaming: false
62430
+ },
62431
+ seq: entry.seq,
62432
+ v: AGENT_STREAM_PROTOCOL
62433
+ };
62434
+ }
61066
62435
  return {
61067
62436
  kind: "message",
61068
62437
  message: {
@@ -61084,6 +62453,8 @@ class AgentStreamPublisher {
61084
62453
  #history = new Map;
61085
62454
  #settled = new Set;
61086
62455
  #publishedAt = new Map;
62456
+ #untaggedCards = new WeakMap;
62457
+ #untaggedCount = 0;
61087
62458
  #seq;
61088
62459
  #watchedUntil = 0;
61089
62460
  #listedCommands;
@@ -61248,7 +62619,15 @@ class AgentStreamPublisher {
61248
62619
  const message = readMessage(raw);
61249
62620
  if (message === null)
61250
62621
  return false;
61251
- const key = keyFor(message);
62622
+ const key = keyFor(message, (host) => {
62623
+ let number = this.#untaggedCards.get(host);
62624
+ if (number === undefined) {
62625
+ this.#untaggedCount += 1;
62626
+ number = this.#untaggedCount;
62627
+ this.#untaggedCards.set(host, number);
62628
+ }
62629
+ return number;
62630
+ });
61252
62631
  if (key === null)
61253
62632
  return false;
61254
62633
  const stillStreaming = message.role === "assistant" && streaming;