MCPcopy
hub / github.com/Azure/fetch-event-source / getMessages

Function getMessages

src/parse.ts:119–163  ·  view source on GitHub ↗
(
    onId: (id: string) => void,
    onRetry: (retry: number) => void,
    onMessage?: (msg: EventSourceMessage) => void
)

Source from the content-addressed store, hash-verified

117 * @returns A function that should be called for each incoming line buffer.
118 */
119export function getMessages(
120 onId: (id: string) => void,
121 onRetry: (retry: number) => void,
122 onMessage?: (msg: EventSourceMessage) => void
123) {
124 let message = newMessage();
125 const decoder = new TextDecoder();
126
127 // return a function that can process each incoming line buffer:
128 return function onLine(line: Uint8Array, fieldLength: number) {
129 if (line.length === 0) {
130 // empty line denotes end of message. Trigger the callback and start a new message:
131 onMessage?.(message);
132 message = newMessage();
133 } else if (fieldLength > 0) { // exclude comments and lines with no values
134 // line is of format "<field>:<value>" or "<field>: <value>"
135 // https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
136 const field = decoder.decode(line.subarray(0, fieldLength));
137 const valueOffset = fieldLength + (line[fieldLength + 1] === ControlChars.Space ? 2 : 1);
138 const value = decoder.decode(line.subarray(valueOffset));
139
140 switch (field) {
141 case 'data':
142 // if this message already has data, append the new value to the old.
143 // otherwise, just set to the new value:
144 message.data = message.data
145 ? message.data + '\n' + value
146 : value; // otherwise,
147 break;
148 case 'event':
149 message.event = value;
150 break;
151 case 'id':
152 onId(message.id = value);
153 break;
154 case 'retry':
155 const retry = parseInt(value, 10);
156 if (!isNaN(retry)) { // per spec, ignore non-integers
157 onRetry(message.retry = retry);
158 }
159 break;
160 }
161 }
162 }
163}
164
165function concat(a: Uint8Array, b: Uint8Array) {
166 const res = new Uint8Array(a.length + b.length);

Callers 1

createFunction · 0.90

Calls 1

newMessageFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…