{"version":3,"file":"runtime.mjs","names":[],"sources":["../../../../src/plugins/A2UI/runtime.tsx"],"sourcesContent":["// The part of the A2UI renderer that runs the official A2UI packages. It loads in the browser\n// when a reply first shows A2UI, because the packages define custom elements, which a server\n// cannot, and are of no use to an app whose agent never writes A2UI.\nimport React, {\n  createContext,\n  useContext,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n} from 'react';\nimport { useSyncExternalStore } from 'use-sync-external-store/shim';\nimport {\n  A2uiSurface,\n  createBinderlessComponentImplementation,\n  createComponentImplementation,\n} from '@a2ui/react';\nimport {\n  type ActionPayload,\n  Catalog,\n  type ComponentApi,\n  type ComponentContext,\n  createFunctionImplementation,\n  effect,\n  getValue,\n  MessageProcessor,\n  peekValue,\n  setValue,\n  signal,\n  type SurfaceModel,\n} from '@a2ui/web_core';\nimport {\n  basicCatalog,\n  createBasicCatalogFunctions,\n  OpenUrlApi,\n} from '@a2ui/web_core/catalogs/basic/v1';\n\nimport {\n  type AIUIComponent,\n  AIUIComponentView,\n} from '../AIComponents/GenerativeUI/AIUIComponent';\nimport type { AIUIDocument } from '../AIComponents/GenerativeUI/AIUIDocument';\nimport {\n  aiUIWords,\n  isRecord,\n  withoutSecretValues,\n} from '../AIComponents/GenerativeUI/AIUIHelpers';\nimport { A2UIPlaceholder } from './A2UIPlaceholder';\nimport type { A2UIEngine, A2UIError } from './A2UIRenderer';\nimport { A2UIEngineContext, STREAM_BASIC_COMPONENTS } from './basicComponents';\nimport {\n  A2UI_DEFAULT_CATALOG_ID,\n  A2UI_LEGACY_CATALOG_ID,\n  a2uiAppCatalogDocument,\n  a2uiTypeName,\n} from './catalogDocument';\nimport {\n  A2UI_VERSION,\n  a2uiMessagesIn,\n  a2uiSourceOf,\n  normalizeA2UIMessage,\n} from './A2UIStream';\n\n// A catalog entry, as web_core reads it. `@a2ui/react` types its entries against the Zod the app\n// resolves, which can be another major than web_core's own; at runtime only web_core's runs.\ntype Entry = ComponentApi;\n\ntype A2UIReplyContextValue = { isStreaming: boolean; messageId: string };\n\nconst A2UIReplyContext = createContext<A2UIReplyContextValue | undefined>(undefined);\n\n// The declared parameters of an app's component as the agent wrote them, bindings and functions\n// worked out, following the data model and the component's updates.\nconst useResolvedArguments = (context: ComponentContext, names: string[]) => {\n  const namesKey = names.join('\\u0000');\n  const store = useMemo(() => {\n    const declared = namesKey.split('\\u0000');\n    const signalOf = () => {\n      const { properties } = context.componentModel;\n      const written = Object.fromEntries(\n        declared\n          .filter((name) => name in properties)\n          .map((name) => [name, properties[name]]),\n      );\n      return context.dataContext.resolveSignal<Record<string, unknown>>(written);\n    };\n    let value: Record<string, unknown> = {};\n    try {\n      value = peekValue(signalOf()) ?? {};\n    } catch {\n      value = {};\n    }\n    return {\n      get: () => value,\n      subscribe: (onChange: () => void) => {\n        let stop = () => undefined as void;\n        const watch = () => {\n          stop();\n          try {\n            const signal = signalOf();\n            stop = effect(() => {\n              value = getValue(signal) ?? {};\n              onChange();\n            });\n          } catch {\n            value = {};\n            onChange();\n          }\n        };\n        watch();\n        const updates = context.componentModel.onUpdated.subscribe(watch);\n        return () => {\n          stop();\n          updates.unsubscribe();\n        };\n      },\n    };\n  }, [context, namesKey]);\n  return useSyncExternalStore(store.subscribe, store.get);\n};\n\n// One of the app's components where the agent placed it in a reply's surface.\nconst PlacedComponent = ({\n  component,\n  context,\n  engine,\n}: {\n  component: AIUIComponent;\n  context: ComponentContext;\n  engine: A2UIEngine;\n}) => {\n  const reply = useContext(A2UIReplyContext);\n  const args = useResolvedArguments(\n    context,\n    component.definition.parameters.map(({ name }) => name),\n  );\n  if (!reply) return null;\n  const { messageId } = reply;\n  const { name } = component.definition;\n  return (\n    <AIUIComponentView\n      args={args}\n      component={component}\n      context={{\n        emit: (event, label, payload = {}) =>\n          void engine.host.send({\n            format: 'a2ui',\n            label,\n            messageId,\n            name: event,\n            payload: { ...payload, component: name },\n          }),\n        host: engine.host,\n        isStreaming: reply.isStreaming,\n        messageId,\n      }}\n    />\n  );\n};\n\nconst catalogsByEngine = new WeakMap<A2UIEngine, Catalog<Entry>[]>();\n\n/**\n * The catalogs a reply's surfaces are made with: the basic catalog with the app's components,\n * under the renderer's catalog id (and the default's former id, for the default) and under the\n * basic catalog's own, so a surface naming any of them shows them. Links open the way the host allows.\n */\nexport const catalogsOf = (engine: A2UIEngine) => {\n  const made = catalogsByEngine.get(engine);\n  if (made) return made;\n  const basicFunctions = [\n    ...createBasicCatalogFunctions().filter(({ name }) => name !== OpenUrlApi.name),\n    createFunctionImplementation(OpenUrlApi, ({ url }) => {\n      engine.host.open(String(url));\n    }),\n  ];\n  // The app's tools, called as functions the catalog doesn't define, as StreamChatA2UI calls\n  // them: one that changes something runs only from what the person did, such as a tap.\n  const anyArguments = OpenUrlApi.schema.pick({}).passthrough();\n  const toolFunctions = engine.host.toolNames.flatMap((name) => {\n    if (basicFunctions.some((basic) => basic.name === name)) {\n      engine.report({\n        code: 'CATALOG_ERROR',\n        message: `The tool ${name} is left out of A2UI: the catalog has a function of that name`,\n      });\n      return [];\n    }\n    return [\n      createFunctionImplementation(\n        { name, returnType: 'any', schema: anyArguments },\n        (args, context) => {\n          const output = signal<unknown>(undefined);\n          engine.host\n            .runTool(name, withoutSecretValues(args, secretValuesOf(context.surface)), {\n              userInitiated: context.isUserActivated,\n            })\n            .then(\n              (value) => setValue(output, value),\n              (error: unknown) =>\n                engine.report({\n                  code: 'EXECUTION_ERROR',\n                  message: error instanceof Error ? error.message : String(error),\n                }),\n            );\n          return output;\n        },\n      ),\n    ];\n  });\n  const functions = [...basicFunctions, ...toolFunctions];\n  const basicNames = new Set(basicCatalog.components.keys());\n  const appComponents: Entry[] = [];\n  for (const component of engine.host.components) {\n    const type = a2uiTypeName(component.definition.name);\n    // One named like a basic component would replace it, so it is left out, as on iOS.\n    if (basicNames.has(type) && engine.basicComponents[type as never] !== null) {\n      engine.report({\n        code: 'CATALOG_ERROR',\n        message: `The component ${component.definition.name} is left out of A2UI: it would replace the catalog's ${type}`,\n      });\n      continue;\n    }\n    try {\n      const api = Catalog.fromJson(\n        a2uiAppCatalogDocument(engine.catalogId, [component]),\n        A2UI_VERSION,\n      ).components.get(type);\n      if (!api) continue;\n      const implementation = createBinderlessComponentImplementation(\n        api as never,\n        ({ context }) => (\n          <PlacedComponent component={component} context={context} engine={engine} />\n        ),\n      );\n      appComponents.push(implementation as unknown as Entry);\n    } catch (error) {\n      engine.report({\n        code: 'CATALOG_ERROR',\n        message: `The component ${component.definition.name} can't join the catalog: ${String(error)}`,\n      });\n    }\n  }\n  // The basic catalog's components: the app's where it draws one its own way, none where it\n  // leaves one out, else Stream's where Stream draws them, else A2UI's own.\n  const components: Entry[] = [\n    ...[...basicCatalog.components.values()].flatMap((entry) => {\n      const own = engine.basicComponents[entry.name as never] as unknown;\n      if (own === null) return [];\n      const view = own ?? STREAM_BASIC_COMPONENTS[entry.name];\n      return view\n        ? [\n            createComponentImplementation(\n              entry as never,\n              view as never,\n            ) as unknown as Entry,\n          ]\n        : [entry];\n    }),\n    ...appComponents,\n  ];\n  // A renderer with the default id also shows surfaces naming the default's former id, which\n  // A2UI written before it changed names.\n  const ids = [\n    engine.catalogId,\n    ...(engine.catalogId === A2UI_DEFAULT_CATALOG_ID ? [A2UI_LEGACY_CATALOG_ID] : []),\n    basicCatalog.id,\n  ];\n  const catalogs = [...new Set(ids)].map(\n    (id) => new Catalog<Entry>(id, A2UI_VERSION, components, functions),\n  );\n  catalogsByEngine.set(engine, catalogs);\n  return catalogs;\n};\n\ntype RendererError = {\n  code?: unknown;\n  message?: unknown;\n  path?: unknown;\n  surfaceId?: unknown;\n};\n\n// A data model path as A2UI resolves it from where a component is drawn: an absolute one as it\n// is, a relative one, such as in a list's row, under the row's path.\nconst resolvedPath = (base: string, path: string) => {\n  if (path.startsWith('/')) return path;\n  const parent = base === '/' ? '' : base.replace(/\\/$/, '');\n  return path === '' || path === '.' ? parent || '/' : `${parent}/${path}`;\n};\n\n// Each component of a surface with the data path it is drawn at, from its root: a list's\n// template once for each of the list's items, as A2UI draws them. A component nothing reaches\n// is drawn at the root, if at all.\nconst placesOf = (surface: SurfaceModel<Entry>) => {\n  const places: Array<{ dataPath: string; id: string }> = [];\n  const seen = new Set<string>();\n  const visit = (id: string, dataPath: string) => {\n    const key = `${id}\\u0000${dataPath}`;\n    const component = surface.componentsModel.get(id);\n    if (!component || seen.has(key)) return;\n    seen.add(key);\n    places.push({ dataPath, id });\n    // A component's children are ids in any of its properties, such as `child`, `children`\n    // or a tab's `child`, or a template of a list in the data model.\n    const children = (value: unknown): void => {\n      if (typeof value === 'string') return visit(value, dataPath);\n      if (Array.isArray(value)) return value.forEach(children);\n      if (!isRecord(value)) return;\n      const { componentId, path } = value;\n      if (typeof componentId === 'string' && typeof path === 'string') {\n        const listPath = resolvedPath(dataPath, path);\n        const items: unknown = surface.dataModel.get(listPath);\n        if (Array.isArray(items)) {\n          items.forEach((_, index) =>\n            visit(componentId, resolvedPath(listPath, `${index}`)),\n          );\n        }\n        return;\n      }\n      Object.values(value).forEach(children);\n    };\n    Object.values(component.properties).forEach(children);\n  };\n  visit(surface.rootId, '/');\n  for (const component of surface.componentsModel.values) {\n    if (!places.some(({ id }) => id === component.id)) visit(component.id, '/');\n  }\n  return places;\n};\n\n// The data model paths an obscured TextField writes, such as a password's, in each place it is\n// drawn: a list's row has its own.\nconst secretPathsOf = (surface: SurfaceModel<Entry> | undefined) => {\n  if (!surface) return [];\n  return placesOf(surface).flatMap(({ dataPath, id }) => {\n    const component = surface.componentsModel.get(id);\n    const { value, variant } = component?.properties ?? {};\n    if (component?.type !== 'TextField' || variant !== 'obscured' || !isRecord(value))\n      return [];\n    const path = value['@path'];\n    return typeof path === 'string' ? [resolvedPath(dataPath, path)] : [];\n  });\n};\n\n// What the person typed in a surface's obscured fields, so none of it leaves the device.\nconst secretValuesOf = (surface: SurfaceModel<Entry> | undefined): string[] =>\n  secretPathsOf(surface).flatMap((path) => {\n    const value: unknown = surface?.dataModel.get(path);\n    return typeof value === 'string' && value !== '' ? [value] : [];\n  });\n\n// A copy of a surface's data model without what its obscured fields hold.\nconst dataModelWithoutSecrets = (surface: SurfaceModel<Entry>) => {\n  const copy = JSON.parse(JSON.stringify(surface.dataModel.get('/') ?? {})) as unknown;\n  for (const path of secretPathsOf(surface)) {\n    const keys = path.split('/').filter(Boolean);\n    const last = keys.pop();\n    let parent: unknown = copy;\n    for (const key of keys) parent = isRecord(parent) ? parent[key] : undefined;\n    if (isRecord(parent) && last !== undefined) delete parent[last];\n  }\n  return withoutSecretValues(copy, secretValuesOf(surface));\n};\n\nconst errorOf = (error: RendererError): A2UIError => ({\n  code: typeof error.code === 'string' ? error.code : 'EXECUTION_ERROR',\n  message: typeof error.message === 'string' ? error.message : String(error.message),\n  ...(typeof error.path === 'string' ? { path: error.path } : {}),\n  ...(typeof error.surfaceId === 'string' ? { surfaceId: error.surfaceId } : {}),\n});\n\n/**\n * The surfaces of one reply: its own processor, fed the messages of its document as they\n * complete. Messages that changed, rather than grew, start its surfaces again.\n */\nexport class A2UIReplyState {\n  isStreaming = false;\n\n  private applied: string[] = [];\n  private readonly engine: A2UIEngine;\n  private listeners = new Set<() => void>();\n  private readonly messageId: string;\n  private processor: MessageProcessor<Entry>;\n  private reported = new Set<string>();\n  private shown: SurfaceModel<Entry>[] = [];\n  private showedNothing = false;\n  private stopWatching: () => void;\n\n  constructor(engine: A2UIEngine, messageId: string) {\n    this.engine = engine;\n    this.messageId = messageId;\n    this.processor = this.makeProcessor();\n    this.stopWatching = this.watch();\n  }\n\n  /** The reply's surfaces, in the order the agent made them. */\n  surfaces = () => this.shown;\n\n  subscribe = (listener: () => void) => {\n    this.listeners.add(listener);\n    return () => {\n      this.listeners.delete(listener);\n    };\n  };\n\n  /** Applies the messages of `source` not applied yet. */\n  update(source: string, isStreaming: boolean) {\n    this.isStreaming = isStreaming;\n    const messages = a2uiMessagesIn(source);\n    const grew =\n      messages.length >= this.applied.length &&\n      this.applied.every((message, index) => messages[index] === message);\n    if (!grew) {\n      this.stopWatching();\n      this.processor.dispose();\n      this.processor = this.makeProcessor();\n      this.stopWatching = this.watch();\n      this.applied = [];\n    }\n    for (const raw of messages.slice(this.applied.length)) {\n      let json: unknown;\n      try {\n        json = JSON.parse(raw);\n      } catch {\n        json = undefined;\n      }\n      if (!isRecord(json)) {\n        this.report({\n          code: 'VALIDATION_FAILED',\n          message: 'A message isn’t a JSON object',\n        });\n        continue;\n      }\n      this.feed(normalizeA2UIMessage(json, this.engine.catalogId));\n    }\n    this.applied = messages;\n    this.refresh();\n    // A finished reply that made no surface shows its text, which the host shows when asked\n    // again: it asked before these messages were applied.\n    const showsNothing = !isStreaming && this.shown.length === 0;\n    if (showsNothing !== this.showedNothing) {\n      this.showedNothing = showsNothing;\n      this.engine.host.refresh();\n    }\n  }\n\n  dispose() {\n    this.stopWatching();\n    this.processor.dispose();\n    this.listeners.clear();\n  }\n\n  // Feeds a message to the processor. A batch of components that one bad component spoils is\n  // fed again a component at a time, so the rest show, as they would while being written.\n  private feed(message: Record<string, unknown>) {\n    const errors = this.processor.processMessagesWithErrors(message);\n    const reported = errors.length ? (this.oneAtATime(message) ?? errors) : errors;\n    for (const { error } of reported) this.report(errorOf(error));\n  }\n\n  // The components of a message one at a time, with what goes wrong with each, or `undefined`\n  // when the message has no batch of them to feed again. A surface made with components is made\n  // before they are added, and stays when they fail, so they are added to it.\n  private oneAtATime(message: Record<string, unknown>) {\n    const { createSurface, updateComponents } = message;\n    const batch = isRecord(updateComponents)\n      ? updateComponents\n      : isRecord(createSurface)\n        ? createSurface\n        : undefined;\n    if (!batch || !Array.isArray(batch.components) || batch.components.length < 2) {\n      return undefined;\n    }\n    const { surfaceId } = batch;\n    if (\n      batch === createSurface &&\n      (typeof surfaceId !== 'string' || !this.processor.model.getSurface(surfaceId))\n    ) {\n      return undefined;\n    }\n    return batch.components.flatMap((component: unknown) =>\n      this.processor.processMessagesWithErrors({\n        updateComponents: { components: [component], surfaceId },\n        version: message.version,\n      }),\n    );\n  }\n\n  private makeProcessor() {\n    return new MessageProcessor<Entry>(catalogsOf(this.engine), (action) =>\n      this.act(action),\n    );\n  }\n\n  // Tells the agent what the person did, as StreamChatA2UI does: their message says what the\n  // button they tapped says, else the event's name as words, and what the agent wrote for it,\n  // its `userMessage`, goes with it. So does the surface's data model when the agent asked for\n  // it, and never what the person typed in an obscured field.\n  private act(action: ActionPayload) {\n    const surface = this.processor.model.getSurface(action.surfaceId);\n    const secrets = secretValuesOf(surface);\n    const context = withoutSecretValues(action.context ?? {}, secrets);\n    for (const key of this.secretContextKeys(surface, action)) delete context[key];\n    const userMessage = withoutSecretValues(action.userMessage ?? '', secrets).trim();\n    void this.engine.host.send({\n      format: 'a2ui',\n      label: this.buttonText(surface, action) ?? aiUIWords(action.name),\n      messageId: this.messageId,\n      name: action.name,\n      payload: {\n        context,\n        ...(surface?.sendDataModel\n          ? { dataModel: dataModelWithoutSecrets(surface) }\n          : {}),\n        sourceComponentId: action.sourceComponentId,\n        surfaceId: action.surfaceId,\n        ...(userMessage ? { userMessage } : {}),\n      },\n    });\n  }\n\n  // The keys of an event's context the agent bound to an obscured field.\n  private secretContextKeys(\n    surface: SurfaceModel<Entry> | undefined,\n    action: ActionPayload,\n  ) {\n    const secretPaths = secretPathsOf(surface);\n    const event: unknown = surface?.componentsModel.get(action.sourceComponentId)\n      ?.properties.action;\n    const written =\n      isRecord(event) && isRecord(event.event) ? event.event.context : undefined;\n    if (!isRecord(written) || !surface) return [];\n    // Where the button is drawn, such as in each of a list's rows: the action doesn't say which.\n    const dataPaths = placesOf(surface)\n      .filter(({ id }) => id === action.sourceComponentId)\n      .map(({ dataPath }) => dataPath);\n    return Object.entries(written).flatMap(([key, value]) => {\n      const path = isRecord(value) ? value['@path'] : undefined;\n      if (typeof path !== 'string') return [];\n      return dataPaths.some((dataPath) => {\n        const absolute = resolvedPath(dataPath, path);\n        return secretPaths.some(\n          (secret) => absolute === secret || absolute.startsWith(`${secret}/`),\n        );\n      })\n        ? [key]\n        : [];\n    });\n  }\n\n  // What the button the person tapped says: its Text child, written or bound to the data model.\n  private buttonText(surface: SurfaceModel<Entry> | undefined, action: ActionPayload) {\n    const components = surface?.componentsModel;\n    const child: unknown = components?.get(action.sourceComponentId)?.properties.child;\n    if (typeof child !== 'string') return undefined;\n    const text: unknown = components?.get(child)?.properties.text;\n    const shown =\n      isRecord(text) && typeof text['@path'] === 'string' && text['@path'].startsWith('/')\n        ? (surface?.dataModel.get(text['@path']) as unknown)\n        : text;\n    return typeof shown === 'string' && shown.trim() !== '' ? shown.trim() : undefined;\n  }\n\n  private watch() {\n    const subscriptions = [\n      this.processor.onSurfaceCreated(() => this.refresh()),\n      this.processor.onSurfaceDeleted(() => this.refresh()),\n      this.processor.model.onError.subscribe((error) => this.report(errorOf(error))),\n    ];\n    return () => subscriptions.forEach((subscription) => subscription.unsubscribe());\n  }\n\n  private refresh() {\n    const surfaces = [...this.processor.getSurfaces().values()];\n    if (\n      surfaces.length === this.shown.length &&\n      surfaces.every((surface, index) => surface === this.shown[index])\n    ) {\n      return;\n    }\n    this.shown = surfaces;\n    this.listeners.forEach((listener) => listener());\n  }\n\n  // Each error once: a reply's messages are fed again as it streams, and the processor tells\n  // the same error both as it fails a message, with the place in it, and to the surface.\n  private report(error: A2UIError) {\n    const key = [error.code, error.message, error.surfaceId].join('\\u0000');\n    if (this.reported.has(key)) return;\n    this.reported.add(key);\n    this.engine.report(error, this.messageId);\n  }\n}\n\n/** The surfaces of a reply, made with its messages so far the first time they are asked for. */\nexport const replyOf = (\n  engine: A2UIEngine,\n  document: AIUIDocument,\n  messageId: string,\n) => {\n  let reply = engine.replies.get(messageId);\n  if (!reply) {\n    reply = new A2UIReplyState(engine, messageId);\n    engine.replies.set(messageId, reply);\n    reply.update(a2uiSourceOf(document) ?? '', document.isStreaming);\n  }\n  return reply;\n};\n\n/** Whether a finished reply's A2UI made no surface, so its text shows instead. */\nexport const showsNothing = (\n  engine: A2UIEngine,\n  document: AIUIDocument,\n  messageId: string,\n) =>\n  !document.isStreaming && replyOf(engine, document, messageId).surfaces().length === 0;\n\n// The layout effect warns under server rendering; this module only runs in the browser, but\n// tests may render it either way.\nconst useIsomorphicLayoutEffect =\n  typeof window === 'undefined' ? useEffect : useLayoutEffect;\n\n/** A reply's surfaces, following its document as the agent writes it. */\nexport const A2UIReplyContent = ({\n  document,\n  engine,\n  messageId,\n}: {\n  document: AIUIDocument;\n  engine: A2UIEngine;\n  messageId: string;\n}) => {\n  const reply = replyOf(engine, document, messageId);\n  const source = a2uiSourceOf(document) ?? '';\n  const { isStreaming } = document;\n  useIsomorphicLayoutEffect(() => {\n    reply.update(source, isStreaming);\n  }, [isStreaming, reply, source]);\n  const surfaces = useSyncExternalStore(reply.subscribe, reply.surfaces);\n  const replyContext = useMemo(\n    () => ({ isStreaming, messageId }),\n    [isStreaming, messageId],\n  );\n  if (surfaces.length === 0) return isStreaming ? <A2UIPlaceholder /> : null;\n  return (\n    <A2UIEngineContext.Provider value={engine}>\n      <A2UIReplyContext.Provider value={replyContext}>\n        <div className='str-chat__a2ui'>\n          {surfaces.map((surface) => (\n            <div className='str-chat__a2ui__surface' key={surface.id}>\n              <A2uiSurface surface={surface as never} />\n            </div>\n          ))}\n        </div>\n      </A2UIReplyContext.Provider>\n    </A2UIEngineContext.Provider>\n  );\n};\n\n/** What the renderer's entry reaches once the runtime loads. */\nexport type A2UIRuntime = {\n  A2UIReplyContent: typeof A2UIReplyContent;\n  showsNothing: typeof showsNothing;\n};\n"],"mappings":";;;;;;;;;;;;;AAoEA,IAAM,mBAAmB,cAAiD,KAAA,CAAS;AAInF,IAAM,wBAAwB,SAA2B,UAAoB;CAC3E,MAAM,WAAW,MAAM,KAAK,IAAQ;CACpC,MAAM,QAAQ,cAAc;EAC1B,MAAM,WAAW,SAAS,MAAM,IAAQ;EACxC,MAAM,iBAAiB;GACrB,MAAM,EAAE,eAAe,QAAQ;GAC/B,MAAM,UAAU,OAAO,YACrB,SACG,QAAQ,SAAS,QAAQ,UAAU,CAAC,CACpC,KAAK,S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