@effect-uai/mistral 0.10.0 → 0.12.0

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.
Files changed (41) hide show
  1. package/dist/Mistral.d.mts +1 -1
  2. package/dist/Mistral.d.mts.map +1 -1
  3. package/dist/Mistral.mjs +2 -2
  4. package/dist/Mistral.mjs.map +1 -1
  5. package/dist/MistralRealtimeTranscriber.d.mts +1 -1
  6. package/dist/MistralRealtimeTranscriber.mjs +1 -1
  7. package/dist/MistralRealtimeTranscriber.mjs.map +1 -1
  8. package/dist/MistralSynthesizer.d.mts +1 -1
  9. package/dist/MistralSynthesizer.mjs +1 -1
  10. package/dist/MistralSynthesizer.mjs.map +1 -1
  11. package/dist/MistralTranscriber.d.mts +1 -1
  12. package/dist/MistralTranscriber.mjs +1 -1
  13. package/dist/MistralTranscriber.mjs.map +1 -1
  14. package/dist/codec.d.mts +5 -80
  15. package/dist/codec.d.mts.map +1 -1
  16. package/dist/codec.mjs +10 -160
  17. package/dist/codec.mjs.map +1 -1
  18. package/dist/codec.test.mjs +1 -13630
  19. package/dist/codec.test.mjs.map +1 -1
  20. package/dist/index.d.mts +1 -1
  21. package/dist/{magic-string.es-PAZgLX4h.mjs → magic-string.es-CaWgF-3p.mjs} +1 -1
  22. package/dist/{magic-string.es-PAZgLX4h.mjs.map → magic-string.es-CaWgF-3p.mjs.map} +1 -1
  23. package/dist/{models-DnDmylpj.d.mts → models-B1wZuvz5.d.mts} +1 -1
  24. package/dist/models-B1wZuvz5.d.mts.map +1 -0
  25. package/dist/models.d.mts +1 -1
  26. package/dist/onHalt.test.d.mts +1 -0
  27. package/dist/onHalt.test.mjs +61 -0
  28. package/dist/onHalt.test.mjs.map +1 -0
  29. package/dist/{realtimeStt-ClXWXbXX.d.mts → realtimeStt-BFcctqFC.d.mts} +1 -1
  30. package/dist/{realtimeStt-ClXWXbXX.d.mts.map → realtimeStt-BFcctqFC.d.mts.map} +1 -1
  31. package/dist/realtimeStt.d.mts +1 -1
  32. package/dist/test.DNmyFkvJ-CPKukVWS.mjs +13633 -0
  33. package/dist/test.DNmyFkvJ-CPKukVWS.mjs.map +1 -0
  34. package/package.json +7 -4
  35. package/src/Mistral.ts +7 -2
  36. package/src/MistralRealtimeTranscriber.ts +1 -1
  37. package/src/MistralSynthesizer.ts +1 -1
  38. package/src/MistralTranscriber.ts +1 -1
  39. package/src/codec.ts +40 -232
  40. package/src/onHalt.test.ts +75 -0
  41. package/dist/models-DnDmylpj.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"codec.mjs","names":["Arr"],"sources":["../src/codec.ts"],"sourcesContent":["import { Array as Arr, Encoding, Match, Option, Schema } from \"effect\"\nimport type {\n ContentBlock,\n HistoryItem,\n InputImage,\n StopReason,\n Usage,\n} from \"@effect-uai/core/Items\"\nimport type { StructuredFormat } from \"@effect-uai/core/StructuredFormat\"\nimport type { ToolDescriptor } from \"@effect-uai/core/Tool\"\nimport type { Turn } from \"@effect-uai/core/Turn\"\nimport { TurnEvent } from \"@effect-uai/core/Turn\"\n\n// ---------------------------------------------------------------------------\n// History → Mistral chat `messages`\n//\n// Mistral speaks the OpenAI chat-completions dialect: a flat list of\n// `{ role, content, ... }` objects where an assistant turn's tool calls live\n// on the assistant message (`tool_calls`) and each tool result is its own\n// `{ role: \"tool\", tool_call_id, content }` message. Our history is a flatter\n// item list (assistant message, then separate `function_call` items), so we\n// fold consecutive `function_call`s onto the preceding assistant message.\n// ---------------------------------------------------------------------------\n\ntype WireMessage = {\n role: string\n content: string | ReadonlyArray<Record<string, unknown>>\n tool_calls?: ReadonlyArray<Record<string, unknown>>\n tool_call_id?: string\n}\n\n/** A `data:` URI for inline image bytes; URLs pass through untouched. */\nconst imageSourceToUrl = Match.type<InputImage[\"source\"]>().pipe(\n Match.tag(\"url\", (s) => s.url),\n Match.tag(\"base64\", (s) => `data:${s.mimeType};base64,${s.base64}`),\n Match.tag(\"bytes\", (s) => `data:${s.mimeType};base64,${Encoding.encodeBase64(s.bytes)}`),\n Match.exhaustive,\n)\n\nconst blockToPart = Match.type<ContentBlock>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n input_text: (b) => ({ type: \"text\", text: b.text }),\n output_text: (b) => ({ type: \"text\", text: b.text }),\n refusal: (b) => ({ type: \"text\", text: b.text }),\n input_image: (b) => ({ type: \"image_url\", image_url: imageSourceToUrl(b.source) }),\n }),\n)\n\nconst isTextBlock = (b: ContentBlock): boolean =>\n b.type === \"input_text\" || b.type === \"output_text\" || b.type === \"refusal\"\n\nconst textOfBlock = (b: ContentBlock): string => (b.type === \"input_image\" ? \"\" : b.text)\n\n/**\n * Collapse a message's content to a plain string when it is text-only\n * (the common case Mistral prefers), otherwise emit the multimodal parts\n * array.\n */\nconst encodeContent = (\n content: ReadonlyArray<ContentBlock>,\n): string | ReadonlyArray<Record<string, unknown>> =>\n Arr.every(content, isTextBlock) ? content.map(textOfBlock).join(\"\") : content.map(blockToPart)\n\nconst toolCallWire = (call_id: string, name: string, args: string): Record<string, unknown> => ({\n id: call_id,\n type: \"function\",\n function: { name, arguments: args },\n})\n\nconst appendToolCall = (\n acc: ReadonlyArray<WireMessage>,\n call_id: string,\n name: string,\n args: string,\n): ReadonlyArray<WireMessage> => {\n const last = acc[acc.length - 1]\n const wire = toolCallWire(call_id, name, args)\n // Attach to the immediately-preceding assistant message (not a tool result),\n // matching the OpenAI/Mistral shape where tool calls ride the assistant turn.\n if (last !== undefined && last.role === \"assistant\" && last.tool_call_id === undefined) {\n return [...acc.slice(0, -1), { ...last, tool_calls: [...(last.tool_calls ?? []), wire] }]\n }\n return [...acc, { role: \"assistant\", content: \"\", tool_calls: [wire] }]\n}\n\nconst foldItem = (acc: ReadonlyArray<WireMessage>, item: HistoryItem): ReadonlyArray<WireMessage> =>\n Match.value(item).pipe(\n Match.discriminatorsExhaustive(\"type\")({\n message: (m) => [...acc, { role: m.role, content: encodeContent(m.content) }],\n function_call: (f) => appendToolCall(acc, f.call_id, f.name, f.arguments),\n function_call_output: (o) => [\n ...acc,\n { role: \"tool\", tool_call_id: o.call_id, content: o.output },\n ],\n // Reasoning items are not replayed to the chat-completions endpoint.\n reasoning: () => acc,\n }),\n )\n\n/** Convert our `HistoryItem[]` history into Mistral chat `messages`. */\nexport const itemsToMessages = (items: ReadonlyArray<HistoryItem>): ReadonlyArray<WireMessage> =>\n Arr.reduce(items, [] as ReadonlyArray<WireMessage>, foldItem)\n\n// ---------------------------------------------------------------------------\n// tools / tool_choice / response_format\n// ---------------------------------------------------------------------------\n\nexport const toolsWire = (\n descriptors: ReadonlyArray<ToolDescriptor>,\n): Option.Option<ReadonlyArray<Record<string, unknown>>> =>\n descriptors.length > 0\n ? Option.some(\n descriptors.map((t) => ({\n type: \"function\",\n function: {\n name: t.name,\n description: t.description,\n parameters: t.inputSchema,\n ...(t.strict !== undefined && { strict: t.strict }),\n },\n })),\n )\n : Option.none()\n\ntype ToolChoice =\n | \"auto\"\n | \"required\"\n | \"none\"\n | { readonly type: \"function\"; readonly name: string }\n\n// Mistral uses \"any\" for forced tool use (OpenAI's \"required\").\nexport const toolChoiceWire = (choice: ToolChoice): string | Record<string, unknown> =>\n Match.value(choice).pipe(\n Match.when(\"auto\", () => \"auto\" as const),\n Match.when(\"required\", () => \"any\" as const),\n Match.when(\"none\", () => \"none\" as const),\n Match.orElse((c) => ({ type: \"function\", function: { name: c.name } })),\n )\n\nexport const responseFormatWire = (\n structured: StructuredFormat<unknown>,\n): Record<string, unknown> => ({\n type: \"json_schema\",\n json_schema: {\n name: structured.name,\n schema: structured.schema[\"~standard\"].jsonSchema.input({ target: \"draft-2020-12\" }),\n ...(structured.strict !== undefined && { strict: structured.strict }),\n },\n})\n\n// ---------------------------------------------------------------------------\n// Streaming decode: chat.completion.chunk → TurnEvent\n// ---------------------------------------------------------------------------\n\nconst WireFunction = Schema.Struct({\n name: Schema.optional(Schema.NullOr(Schema.String)),\n arguments: Schema.optional(Schema.NullOr(Schema.String)),\n})\n\nconst WireToolCall = Schema.Struct({\n index: Schema.optional(Schema.Number),\n id: Schema.optional(Schema.NullOr(Schema.String)),\n function: Schema.optional(WireFunction),\n})\n\nconst WireDelta = Schema.Struct({\n role: Schema.optional(Schema.NullOr(Schema.String)),\n content: Schema.optional(Schema.NullOr(Schema.String)),\n tool_calls: Schema.optional(Schema.NullOr(Schema.Array(WireToolCall))),\n})\n\nconst WireChoice = Schema.Struct({\n index: Schema.optional(Schema.Number),\n delta: Schema.optional(WireDelta),\n finish_reason: Schema.optional(Schema.NullOr(Schema.String)),\n})\n\nconst WireUsage = Schema.Struct({\n prompt_tokens: Schema.optional(Schema.Number),\n completion_tokens: Schema.optional(Schema.Number),\n total_tokens: Schema.optional(Schema.Number),\n})\n\nexport const WireChunk = Schema.Struct({\n choices: Schema.optional(Schema.Array(WireChoice)),\n usage: Schema.optional(Schema.NullOr(WireUsage)),\n})\nexport type WireChunk = typeof WireChunk.Type\n\nexport const decodeChunk = Schema.decodeUnknownEffect(WireChunk)\n\n// ---------------------------------------------------------------------------\n// Accumulator\n// ---------------------------------------------------------------------------\n\ntype ToolAcc = {\n readonly call_id: string\n readonly name: string\n readonly arguments: string\n}\n\nexport type Accumulator = {\n readonly text: string\n /** Tool calls keyed by their wire `index` (defaults to position when absent). */\n readonly tools: ReadonlyMap<number, ToolAcc>\n readonly order: ReadonlyArray<number>\n readonly usage: Usage\n readonly finishReason: Option.Option<string>\n}\n\nexport const emptyAccumulator: Accumulator = {\n text: \"\",\n tools: new Map(),\n order: [],\n usage: {},\n finishReason: Option.none(),\n}\n\n/** State threaded through the fold plus the events the step produced. */\ntype Step = readonly [Accumulator, ReadonlyArray<TurnEvent>]\n\nconst usageFrom = (wire: typeof WireUsage.Type): Usage => ({\n ...(wire.prompt_tokens !== undefined && { input_tokens: wire.prompt_tokens }),\n ...(wire.completion_tokens !== undefined && { output_tokens: wire.completion_tokens }),\n ...(wire.total_tokens !== undefined && { total_tokens: wire.total_tokens }),\n})\n\nconst reasonToStop = Match.type<string>().pipe(\n Match.when(\"stop\", () => \"stop\" as const),\n Match.when(\"length\", () => \"max_tokens\" as const),\n Match.when(\"model_length\", () => \"max_tokens\" as const),\n Match.when(\"tool_calls\", () => \"tool_calls\" as const),\n Match.when(\"content_filter\", () => \"content_filter\" as const),\n Match.orElse(() => \"stop\" as const),\n)\n\nconst stopReasonOf = (acc: Accumulator): StopReason =>\n Option.match(acc.finishReason, {\n onNone: () => (acc.tools.size > 0 ? \"tool_calls\" : \"stop\"),\n onSome: reasonToStop,\n })\n\nconst withTool = (acc: Accumulator, index: number, tool: ToolAcc, isNew: boolean): Accumulator => ({\n ...acc,\n tools: new Map(acc.tools).set(index, tool),\n order: isNew ? [...acc.order, index] : acc.order,\n})\n\nconst applyContent = (acc: Accumulator, delta: typeof WireDelta.Type | undefined): Step => {\n const content = delta?.content\n return content !== undefined && content !== null && content.length > 0\n ? [{ ...acc, text: acc.text + content }, [TurnEvent.TextDelta({ text: content })]]\n : [acc, []]\n}\n\nconst applyToolCall = (acc: Accumulator, tc: typeof WireToolCall.Type, position: number): Step => {\n const index = tc.index ?? position\n const argsDelta = tc.function?.arguments ?? \"\"\n const existing = acc.tools.get(index)\n if (existing === undefined) {\n const call_id = tc.id ?? `call_${index}`\n const name = tc.function?.name ?? \"\"\n return [\n withTool(acc, index, { call_id, name, arguments: argsDelta }, true),\n [\n TurnEvent.ToolCallStart({ call_id, name }),\n ...(argsDelta.length > 0\n ? [TurnEvent.ToolCallArgsDelta({ call_id, delta: argsDelta })]\n : []),\n ],\n ]\n }\n return argsDelta.length > 0\n ? [\n withTool(acc, index, { ...existing, arguments: existing.arguments + argsDelta }, false),\n [TurnEvent.ToolCallArgsDelta({ call_id: existing.call_id, delta: argsDelta })],\n ]\n : [acc, []]\n}\n\nconst chain = (step: Step, next: (acc: Accumulator) => Step): Step => {\n const [acc, events] = step\n const [acc2, more] = next(acc)\n return [acc2, [...events, ...more]]\n}\n\nconst applyChoice = (step: Step, choice: typeof WireChoice.Type): Step => {\n const withContent = chain(step, (acc) => applyContent(acc, choice.delta))\n const withTools = Arr.reduce(choice.delta?.tool_calls ?? [], withContent, (s: Step, tc, i) =>\n chain(s, (acc) => applyToolCall(acc, tc, i)),\n )\n const reason = choice.finish_reason\n return reason !== undefined && reason !== null\n ? [{ ...withTools[0], finishReason: Option.some(reason) }, withTools[1]]\n : withTools\n}\n\n/**\n * Fold one decoded chunk into the accumulator, returning the next state and\n * the `TurnEvent`s the chunk produced. Mirrors Anthropic's `deltasFromEvent`,\n * but over chat-completions deltas.\n */\nexport const applyChunk = (acc: Accumulator, chunk: WireChunk): Step => {\n const afterChoices = Arr.reduce(chunk.choices ?? [], [acc, []] as Step, applyChoice)\n const usage = chunk.usage\n return usage !== undefined && usage !== null\n ? chain(afterChoices, (a) => {\n const u = usageFrom(usage)\n return [{ ...a, usage: u }, [TurnEvent.UsageUpdate({ usage: u })]]\n })\n : afterChoices\n}\n\n/** Assemble the terminal `Turn` from the accumulated state. */\nexport const accumulatorToTurn = (acc: Accumulator): Turn => {\n const message: ReadonlyArray<HistoryItem> =\n acc.text.length > 0\n ? [{ type: \"message\", role: \"assistant\", content: [{ type: \"output_text\", text: acc.text }] }]\n : []\n const toolCalls: ReadonlyArray<HistoryItem> = acc.order.flatMap((index) => {\n const t = acc.tools.get(index)\n return t === undefined\n ? []\n : [\n {\n type: \"function_call\" as const,\n call_id: t.call_id,\n name: t.name,\n arguments: t.arguments,\n },\n ]\n })\n return {\n items: [...message, ...toolCalls],\n usage: acc.usage,\n stop_reason: stopReasonOf(acc),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgCA,MAAM,mBAAmB,MAAM,MAA4B,CAAC,KAC1D,MAAM,IAAI,QAAQ,MAAM,EAAE,IAAI,EAC9B,MAAM,IAAI,WAAW,MAAM,QAAQ,EAAE,SAAS,UAAU,EAAE,SAAS,EACnE,MAAM,IAAI,UAAU,MAAM,QAAQ,EAAE,SAAS,UAAU,SAAS,aAAa,EAAE,MAAM,GAAG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AS,IACd,CAAC;EAAE,MAAM;EAAW,MAAM;EAAa,SAAS,CAAC;GAAE,MAAM;GAAe,MAAM,IAAI;GAAM,CAAC;EAAE,CAAC,GAC5F,EAAE;CACR,MAAM,YAAwC,IAAI,MAAM,SAAS,UAAU;EACzE,MAAM,IAAI,IAAI,MAAM,IAAI,MAAM;AAC9B,SAAO,MAAM,KAAA,IACT,EAAE,GACF,CACE;GACE,MAAM;GACN,SAAS,EAAE;GACX,MAAM,EAAE;GACR,WAAW,EAAE;GACd,CACF;GACL;AACF,QAAO;EACL,OAAO,CAAC,GAAG,SAAS,GAAG,UAAU;EACjC,OAAO,IAAI;EACX,aAAa,aAAa,IAAI;EAC/B"}
1
+ {"version":3,"file":"codec.mjs","names":["Arr","decodeChunkShared"],"sources":["../src/codec.ts"],"sourcesContent":["import { Array as Arr, Effect, Encoding, Match, Option } from \"effect\"\nimport type { ContentBlock, HistoryItem, InputImage } from \"@effect-uai/core/Items\"\n\n// The streaming decoder, tool encoding, and terminal-turn assembly are the\n// generic OpenAI chat-completions codec: Mistral speaks that dialect on the\n// wire, so it reuses them verbatim. Only request encoding diverges (below).\nexport {\n type Accumulator,\n type WireChunk,\n accumulatorToTurn,\n applyChunk,\n emptyAccumulator,\n responseFormatWire,\n toolsWire,\n} from \"@effect-uai/chat-completions/codec\"\nimport {\n type WireChunk,\n decodeChunk as decodeChunkShared,\n} from \"@effect-uai/chat-completions/codec\"\n\n// ---------------------------------------------------------------------------\n// History → Mistral chat `messages`\n//\n// Same shape as the generic codec, with one wire quirk: Mistral takes a bare\n// `image_url` string, not OpenAI's `image_url: { url }` object. That is the\n// reason this half stays local rather than importing `itemsToMessages`.\n// ---------------------------------------------------------------------------\n\ntype WireMessage = {\n role: string\n content: string | ReadonlyArray<Record<string, unknown>>\n tool_calls?: ReadonlyArray<Record<string, unknown>>\n tool_call_id?: string\n}\n\n/** A `data:` URI for inline image bytes; URLs pass through untouched. */\nconst imageSourceToUrl = Match.type<InputImage[\"source\"]>().pipe(\n Match.tag(\"url\", (s) => s.url),\n Match.tag(\"base64\", (s) => `data:${s.mimeType};base64,${s.base64}`),\n Match.tag(\"bytes\", (s) => `data:${s.mimeType};base64,${Encoding.encodeBase64(s.bytes)}`),\n Match.exhaustive,\n)\n\nconst blockToPart = Match.type<ContentBlock>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n input_text: (b) => ({ type: \"text\", text: b.text }),\n output_text: (b) => ({ type: \"text\", text: b.text }),\n refusal: (b) => ({ type: \"text\", text: b.text }),\n // Bare string, not `{ url }`: the Mistral divergence from OpenAI.\n input_image: (b) => ({ type: \"image_url\", image_url: imageSourceToUrl(b.source) }),\n }),\n)\n\nconst isTextBlock = (b: ContentBlock): boolean =>\n b.type === \"input_text\" || b.type === \"output_text\" || b.type === \"refusal\"\n\nconst textOfBlock = (b: ContentBlock): string => (b.type === \"input_image\" ? \"\" : b.text)\n\n/**\n * Collapse a message's content to a plain string when it is text-only\n * (the common case Mistral prefers), otherwise emit the multimodal parts\n * array.\n */\nconst encodeContent = (\n content: ReadonlyArray<ContentBlock>,\n): string | ReadonlyArray<Record<string, unknown>> =>\n Arr.every(content, isTextBlock) ? content.map(textOfBlock).join(\"\") : content.map(blockToPart)\n\nconst toolCallWire = (call_id: string, name: string, args: string): Record<string, unknown> => ({\n id: call_id,\n type: \"function\",\n function: { name, arguments: args },\n})\n\nconst appendToolCall = (\n acc: ReadonlyArray<WireMessage>,\n call_id: string,\n name: string,\n args: string,\n): ReadonlyArray<WireMessage> => {\n const last = acc[acc.length - 1]\n const wire = toolCallWire(call_id, name, args)\n // Attach to the immediately-preceding assistant message (not a tool result),\n // matching the OpenAI/Mistral shape where tool calls ride the assistant turn.\n if (last !== undefined && last.role === \"assistant\" && last.tool_call_id === undefined) {\n return [...acc.slice(0, -1), { ...last, tool_calls: [...(last.tool_calls ?? []), wire] }]\n }\n return [...acc, { role: \"assistant\", content: \"\", tool_calls: [wire] }]\n}\n\nconst foldItem = (acc: ReadonlyArray<WireMessage>, item: HistoryItem): ReadonlyArray<WireMessage> =>\n Match.value(item).pipe(\n Match.discriminatorsExhaustive(\"type\")({\n message: (m) => [...acc, { role: m.role, content: encodeContent(m.content) }],\n function_call: (f) => appendToolCall(acc, f.call_id, f.name, f.arguments),\n function_call_output: (o) => [\n ...acc,\n { role: \"tool\", tool_call_id: o.call_id, content: o.output },\n ],\n // Reasoning items are not replayed to the chat-completions endpoint.\n reasoning: () => acc,\n }),\n )\n\n/** Convert our `HistoryItem[]` history into Mistral chat `messages`. */\nexport const itemsToMessages = (items: ReadonlyArray<HistoryItem>): ReadonlyArray<WireMessage> =>\n Arr.reduce(items, [] as ReadonlyArray<WireMessage>, foldItem)\n\n// ---------------------------------------------------------------------------\n// tool_choice\n// ---------------------------------------------------------------------------\n\ntype ToolChoice =\n | \"auto\"\n | \"required\"\n | \"none\"\n | { readonly type: \"function\"; readonly name: string }\n\n// Mistral uses \"any\" for forced tool use (OpenAI's \"required\").\nexport const toolChoiceWire = (choice: ToolChoice): string | Record<string, unknown> =>\n Match.value(choice).pipe(\n Match.when(\"auto\", () => \"auto\" as const),\n Match.when(\"required\", () => \"any\" as const),\n Match.when(\"none\", () => \"none\" as const),\n Match.orElse((c) => ({ type: \"function\", function: { name: c.name } })),\n )\n\n// ---------------------------------------------------------------------------\n// Streaming decode\n// ---------------------------------------------------------------------------\n\n// Mistral emits `model_length` when it truncates on the context window; the\n// shared decoder only knows OpenAI's `length`. Rewrite it before folding so the\n// shared accumulator maps it to `max_tokens` rather than the `stop` fallback.\nconst normalizeChunk = (chunk: WireChunk): WireChunk =>\n chunk.choices === undefined\n ? chunk\n : {\n ...chunk,\n choices: chunk.choices.map((c) =>\n c.finish_reason === \"model_length\" ? { ...c, finish_reason: \"length\" } : c,\n ),\n }\n\nexport const decodeChunk = (u: unknown): Effect.Effect<WireChunk, unknown> =>\n decodeChunkShared(u).pipe(Effect.map(normalizeChunk))\n"],"mappings":";;;;;;;;;;;;;;;AAoCA,MAAM,mBAAmB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