{"version":3,"file":"iti.mjs","sources":["../src/_utils.ts","../src/errors.ts","../src/iti.ts","../src/nanoevents.ts"],"sourcesContent":["export type UnPromisify<T> = T extends Promise<infer U> ? U : T\n\nexport type GetContainerFormat<ProviderFunction extends (...args: any) => any> =\n  UnPromisify<ReturnType<ProviderFunction>>\n\nexport function addGetter(object, key, fn: any) {\n  Object.defineProperty(object, key, {\n    get() {\n      return fn()\n    },\n    enumerable: true,\n  })\n}\n\nexport type Assign<OldContext extends object, NewContext extends object> = {\n  [Token in keyof ({\n    [K in keyof OldContext]: OldContext[K]\n  } & {\n    [K in keyof NewContext]: NewContext[K]\n  })]: Token extends keyof NewContext\n    ? NewContext[Token]\n    : Token extends keyof OldContext\n    ? OldContext[Token]\n    : never\n}\n\nexport type Prettify<T> = T extends infer U ? { [K in keyof U]: U[K] } : never\n\nexport type UnpackFunction<T> = T extends (...args: any) => infer U ? U : T\nexport type UnpackObject<T> = {\n  [K in keyof T]: UnpackFunction<T[K]>\n}\n\nexport type UnpromisifyObject<T> = {\n  [K in keyof T]: UnPromisify<T[K]>\n}\n// keep\n// type AssignAndUnpackObjects<O1 extends {}, O2 extends {}> = UnpromisifyObject<\n//   UnpackObject<Assign4<O1, O2>>\n// >\n\nexport type FullyUnpackObject<T extends {}> = UnpromisifyObject<UnpackObject<T>>\n\nexport type KeysOrCb<Context extends {}> =\n  | Array<keyof Context>\n  | ((t: { [K in keyof Context]: K }) => Array<keyof Context>)\n\nexport type MyRecord<O extends {}, T> = {\n  [K in keyof O]: T\n}\nexport type ContextGetter<Context extends {}> = {\n  [CK in keyof Context]: UnpackFunction<Context[CK]>\n}\n\nexport type UnpackFunctionReturn<T> = T extends (arg: T) => infer U ? U : T\nexport type ContextGetterWithCache<Context extends {}> = {\n  [CK in keyof Context]: UnpackFunctionReturn<Context[CK]>\n}\n\nexport function _intersectionKeys(\n  needle: { [key: string]: any },\n  haystack: { [key: string]: any },\n) {\n  let haystackKeys = Object.keys(haystack)\n  let duplicates = haystackKeys.filter((x) => x in needle)\n  if (duplicates.length === 0) {\n    return undefined\n  }\n  return duplicates.join(\"', '\")\n}\n","export class ItiError extends Error {}\nexport class ItiResolveError extends ItiError {}\nexport class ItiTokenError extends ItiError {}\n","import { createNanoEvents, Emitter } from \"./nanoevents.js\"\nimport {\n  addGetter,\n  Prettify,\n  Assign,\n  KeysOrCb,\n  ContextGetter,\n  UnpackFunction,\n  MyRecord,\n  FullyUnpackObject,\n  _intersectionKeys,\n  UnPromisify,\n  UnpackFunctionReturn,\n} from \"./_utils.js\"\nimport { ItiResolveError, ItiTokenError } from \"./errors.js\"\nimport type { Intersection } from \"utility-types\"\n\nabstract class AbstractContainer<Context extends {}> {\n  public abstract get<T extends keyof Context>(\n    token: T,\n  ): UnpackFunction<Context[T]>\n\n  public abstract getTokens<T extends keyof Context>(): { [M in T]: T }\n}\n\ntype Events<Context> = {\n  // Used only in tests for now\n  containerUpdated: (payload: {\n    key: keyof Context\n    newContainer: Context[keyof Context]\n    newItem: Context[keyof Context]\n  }) => void\n  containerUpserted: (payload: {\n    key: keyof Context\n    newContainer: Context[keyof Context] | null\n    newItem: Context[keyof Context] | null\n  }) => void\n  containerDeleted: (payload: { key: keyof Context }) => void\n  containerDisposed: (payload: { key: keyof Context }) => void\n\n  // Used only in tests for now\n  itemUpdated: (payload: {\n    key: keyof Context\n    newItem: Context[keyof Context] | null\n  }) => void\n  itemUpserted: (payload: {\n    key: keyof Context\n    newItem: Context[keyof Context] | null\n  }) => void\n  itemDeleted: (payload: { key: keyof Context }) => void\n  itemDisposed: (payload: { key: keyof Context }) => void\n\n  // Older events\n  // containerCreated: (payload: {\n  //   key: keyof Context\n  //   newContainer: Context[keyof Context]\n  // }) => void\n  // containerRemoved: (payload: { key: keyof Context }) => void\n  // containerRequested: (payload: { key: keyof Context }) => void\n}\n\nclass InternalContainer<\n  Context extends {},\n  DisposeContext extends {},\n> extends AbstractContainer<Context> {\n  /**\n   * When we create a new class instance or function, we cache the output\n   */\n  private _cache: { [K in keyof Context]?: any } = {}\n  private _cacheSync: { [K in keyof Context]?: any } = {}\n\n  /**\n   * Holds key:value factories in a form token:factory\n   */\n  public _context: Context = <Context>{}\n\n  /**\n   * Here we hold references to \"disposers\".\n   * A disposer is a function assigned to a token that will be called when\n   * `dispose` call is made.\n   */\n  public _disposeCtx: { [K in keyof DisposeContext]?: any } = {}\n\n  /**\n   * EventEmitter Logic\n   */\n  protected ee: Emitter<Events<Context>>\n  // public on = this.ee.on\n  on<E extends keyof Events<Context>>(event: E, callback: Events<Context>[E]) {\n    return this.ee.on(event, callback)\n  }\n\n  constructor() {\n    super()\n    this.ee = createNanoEvents<Events<Context>>()\n    this.subscribeToContainer = this.subscribeToItem.bind(this)\n  }\n\n  protected _storeInSyncCache(token: keyof Context, v: any) {\n    this._cacheSync[token] = v\n  }\n  protected _storeInCache(token: keyof Context, v: any) {\n    this._cache[token] = v\n\n    if (v instanceof Promise) {\n      v.then((resolvedValue) => {\n        this._storeInSyncCache(token, resolvedValue)\n      }).catch((err) => {\n        // we should't do anything with an error here\n        // because this is our internal cache\n        // in userspace he will get __another__ throw error\n      })\n    }\n\n    /**\n     * Not remember why this is here.\n     * I think to indicate when we create an instance\n     * or cache a function result\n     */\n    this.ee.emit(\"containerUpserted\", {\n      key: token,\n      newContainer: v,\n      newItem: v,\n    })\n    this.ee.emit(\"itemUpserted\", {\n      key: token,\n      newItem: v,\n    })\n  }\n\n  public get<SearchToken extends keyof Context>(\n    token: SearchToken,\n  ): UnpackFunction<Context[SearchToken]> {\n    /**\n     * FLOW A: We have this is in a current context\n     */\n    if (token in this._context) {\n      // Case 1: If this token was a function / provider it might be in a cache\n      if (token in this._cache) {\n        const cachedValue = this._cache[token]\n        return cachedValue\n      }\n\n      // Case 2: If this token is a function we must launch and cache it\n      const tokenValue = this._context[token]\n      if (typeof tokenValue === \"function\") {\n        const providedValue = tokenValue()\n        this._storeInCache(token, providedValue)\n        return providedValue\n      }\n\n      // Case 3: This is a simple literal so we just send it\n      this._storeInCache(token, tokenValue) // We store it send events too\n      return tokenValue as any\n    }\n\n    throw new ItiResolveError(`Can't find token '${String(token)}' value`)\n  }\n\n  public getSync<SearchToken extends keyof Context>(\n    token: SearchToken,\n  ): UnpackFunction<Context[SearchToken]> {\n    /**\n     * FLOW A: We have this is in a current context\n     */\n    if (token in this._context) {\n      if (token in this._cacheSync) {\n        const cachedValue = this._cacheSync[token]\n        return cachedValue\n      } else {\n        return this.get(token)\n      }\n    }\n\n    throw new ItiResolveError(`Can't find token '${String(token)}' value`)\n  }\n\n  public delete<SearchToken extends keyof Context>(\n    token: SearchToken,\n  ): Container<Omit<Context, SearchToken>, DisposeContext> {\n    delete this._context[token]\n    delete this._cache[token]\n    // There is no need to check for disposer existence, since delete will not throw\n    // @ts-expect-error\n    delete this._disposeCtx[token]\n\n    this.ee.emit(\"containerDeleted\", {\n      key: token as any,\n    })\n    this.ee.emit(\"itemDeleted\", {\n      key: token as any,\n    })\n\n    return this as any\n  }\n\n  public async dispose<\n    DisposeToken extends keyof DisposeContext & keyof Context,\n  >(token: DisposeToken): Promise<void> {\n    const tokenHasDisposerFn = token in this._disposeCtx\n    const tokenHasBeenResolved = token in this._cache\n\n    if (!tokenHasDisposerFn || !tokenHasBeenResolved) return\n\n    const disposerFn = this._disposeCtx[token]\n\n    if (typeof disposerFn === \"function\") {\n      const cachedValue = this._cache[token]\n      const cachedValueResolved = await Promise.resolve(cachedValue)\n\n      const disposeResult = disposerFn(cachedValueResolved)\n\n      const cleanup = () => {\n        delete this._cache[token]\n        this.ee.emit(\"containerDisposed\", { key: token })\n        this.ee.emit(\"itemDisposed\", { key: token })\n      }\n      if (disposeResult instanceof Promise) {\n        disposeResult.then(cleanup)\n      } else {\n        cleanup()\n      }\n      return disposeResult\n    }\n  }\n\n  /**\n   * Will naively dispose all the containers in the dispose context.\n   *\n   * It will only dispose values we've touched / created.\n   *\n   * Always async, because disposing is 95% async anyway\n   */\n  public async disposeAll() {\n    const thingsToDispose = Object.keys(this._disposeCtx).map((token) =>\n      this.dispose(token as any),\n    )\n\n    // We wait for all the disposers to finish and clear all cache\n    await Promise.all(thingsToDispose)\n  }\n\n  protected _updateContext(updatedContext: Context) {\n    for (const [token, value] of Object.entries(updatedContext)) {\n      if (token in this._context) {\n        this.ee.emit(\"containerUpdated\", {\n          key: token as any,\n          newContainer: value as any,\n          newItem: value as any,\n        })\n        this.ee.emit(\"itemUpdated\", {\n          key: token as any,\n          newItem: value as any,\n        })\n      }\n      // Save state and clear cache\n      this._context[token] = value\n      delete this._cache[token]\n      this.ee.emit(\"containerUpserted\", {\n        key: token as any,\n        newContainer: value,\n        newItem: value,\n      } as any)\n      this.ee.emit(\"itemUpserted\", {\n        key: token as any,\n        newItem: value,\n      } as any)\n    }\n  }\n\n  public subscribeToItem<T extends keyof Context>(\n    token: T,\n    cb: (err: any, container: UnpackFunction<Context[T]>) => void,\n  ): () => void {\n    const upsertUnsubscribe = this.ee.on(\"itemUpserted\", async (ev) => {\n      if (token === ev.key) {\n        try {\n          const data = await this.get(token)\n          cb(null, data)\n        } catch (error) {\n          cb(error, undefined as any)\n        }\n      }\n    })\n    const deleteUnsubscribe = this.ee.on(\"itemDeleted\", async (ev) => {\n      if (token === ev.key) {\n        cb({ containerRemoved: token, itemRemoved: token }, undefined as any)\n      }\n    })\n    return () => {\n      upsertUnsubscribe()\n      deleteUnsubscribe()\n    }\n  }\n\n  /**\n   * @deprecated Use `subscribeToItem` instead. This method will be removed in a future version.\n   */\n  public subscribeToContainer: <T extends keyof Context>(\n    token: T,\n    cb: (err: any, container: UnpackFunction<Context[T]>) => void,\n  ) => () => void\n\n  public getTokens(): {\n    [T in keyof Context]: T\n  } {\n    let tokens = Object.fromEntries(\n      Object.keys(this._context).map((el) => [el, el]),\n    ) as any\n    return tokens\n  }\n}\n\nexport class Container<\n  Context extends {},\n  DisposeContext extends {},\n> extends InternalContainer<Context, DisposeContext> {\n  constructor() {\n    super()\n    this.getContainerSet = this.getItems.bind(this)\n    this.subscribeToContainerSet = this.subscribeToItems.bind(this)\n  }\n\n  // SAVE: NewContext extends {! [T in keyof NewContext]: NewContext[T] }\n  public upsert<NewContext extends {}>(\n    newContext:\n      | NewContext\n      | ((\n          containers: ContextGetter<Context>,\n          self: Container<Context, DisposeContext>,\n        ) => NewContext),\n  ): Container<Prettify<Assign<Context, NewContext>>, DisposeContext> {\n    let nc =\n      typeof newContext === \"function\"\n        ? // @ts-expect-error\n          newContext(this.items, this)\n        : newContext\n    this._updateContext(nc)\n    return this as any\n  }\n\n  public add<\n    // This \"magic\" type gives user an Error in an IDE with a helpful message\n    NewContext extends Intersection<\n      MyRecord<\n        Context,\n        \"You are overwriting this token. It is not safe. Use an unsafe `upsert` method\"\n      >,\n      NewContext\n    >,\n  >(\n    newContextOrCb:\n      | NewContext\n      | ((\n          items: ContextGetter<Context>,\n          self: Container<Context, DisposeContext>,\n        ) => NewContext),\n  ): Container<Prettify<Assign<Context, NewContext>>, DisposeContext> {\n    let newContext =\n      typeof newContextOrCb === \"function\"\n        ? newContextOrCb(this.items, this)\n        : newContextOrCb\n\n    // Step 1: Runtime check for existing tokens in context\n    const duplicates = _intersectionKeys(newContext, this.getTokens())\n    if (duplicates)\n      throw new ItiTokenError(`Tokens already exist: ['${duplicates}']`)\n\n    // Step 2: If everything is fine add a newContext\n    let m = this.upsert(newContext)\n    return m as any\n  }\n  // {! [T in keyof NewContext]: NewContext[T] }\n  public addDisposer<\n    NewDisposerContext extends {\n      [T in keyof Context]?: (\n        cachedValue: UnPromisify<UnpackFunctionReturn<Context[T]>>,\n      ) => any\n    },\n  >(\n    newContextOrCb:\n      | NewDisposerContext\n      | ((\n          items: ContextGetter<Context>,\n          self: Container<Context, DisposeContext>,\n        ) => NewDisposerContext),\n  ): Container<Context, Assign<DisposeContext, NewDisposerContext>> {\n    let newDisposingCtx =\n      typeof newContextOrCb === \"function\"\n        ? newContextOrCb(this.items, this)\n        : newContextOrCb\n\n    // Step 1: Runtime check for existing tokens in a Dispose Context\n    const duplicates = _intersectionKeys(newDisposingCtx, this._disposeCtx)\n    if (duplicates)\n      throw new ItiTokenError(`Tokens already exist: ['${duplicates}']`)\n\n    // Step 2: Add disposer context\n    for (const [token, value] of Object.entries(newDisposingCtx)) {\n      this._disposeCtx[token] = value\n    }\n\n    return this as any\n  }\n\n  public _extractTokens<T extends keyof Context>(\n    tokensOrCb: KeysOrCb<Context>,\n  ): T[] {\n    if (typeof tokensOrCb === \"function\") {\n      return tokensOrCb(this.getTokens()) as any\n    } else {\n      return tokensOrCb as any\n    }\n  }\n\n  public subscribeToItems<T extends (keyof Context)[]>(\n    tokensOrCb: T | ((t: { [K in keyof Context]: K }) => T),\n    cb: (\n      err: any,\n      container: {\n        [K in T[number]]: FullyUnpackObject<Context>[K]\n      },\n    ) => void,\n  ): () => void {\n    let tokens = this._extractTokens(tokensOrCb)\n    const upsertUnsubscribe = this.ee.on(\"itemUpserted\", async (ev) => {\n      if (tokens.includes(ev.key)) {\n        try {\n          const cSet = await this.getItems(tokens)\n          cb(null, cSet)\n        } catch (err) {\n          cb(err, undefined as any)\n        }\n      }\n    })\n    const deleteUnsubscribe = this.ee.on(\"itemDeleted\", async (ev) => {\n      if (tokens.includes(ev.key)) {\n        cb({ containerRemoved: ev.key, itemRemoved: ev.key }, undefined as any)\n      }\n    })\n    return () => {\n      upsertUnsubscribe()\n      deleteUnsubscribe()\n    }\n  }\n\n  public getItemsSync<T extends keyof Context>(\n    tokensOrCb: KeysOrCb<Context>,\n  ):\n    | Promise<{\n        [K in T]: FullyUnpackObject<Context>[K]\n      }>\n    | {\n        [K in T]: FullyUnpackObject<Context>[K]\n      } {\n    let tokens: T[] = this._extractTokens(tokensOrCb)\n\n    let itemDecoratedMap = {} as any\n\n    // Step 1: Assign all values\n    let hasAnyPromise = false\n    tokens.forEach((token) => {\n      const value = this.getSync(token)\n      itemDecoratedMap[token as any] = value\n      if (value instanceof Promise) {\n        hasAnyPromise = true\n      }\n    })\n\n    if (hasAnyPromise) {\n      return this.getItems(tokensOrCb)\n    }\n\n    return itemDecoratedMap\n  }\n\n  /**\n   * Gets multiple items from the container by their tokens.\n   * Handles both synchronous and asynchronous values properly.\n   */\n  public async getItems<T extends (keyof Context)[]>(\n    tokensOrCb: T | ((t: { [K in keyof Context]: K }) => T),\n  ): Promise<{\n    [K in T[number]]: FullyUnpackObject<Context>[K]\n  }> {\n    let tokens: T = this._extractTokens(tokensOrCb) as any\n    let promiseTokens: any = []\n    let allPromises: any = []\n    for (let token of tokens) {\n      if (this.items[token] instanceof Promise) {\n        promiseTokens.push(token)\n        allPromises.push(this.items[token])\n      }\n    }\n\n    let itemDecoratedMap: {\n      [K in T[number]]: FullyUnpackObject<Context>[K]\n    } = {} as any\n\n    // Step 1: Assign all values\n    tokens.forEach((token) => {\n      itemDecoratedMap[token as any] = this.items[token]\n    })\n\n    // Step 2: Overwrite Promise like values with promise results\n    const rez = await Promise.all(allPromises)\n    promiseTokens.forEach((token, index) => {\n      itemDecoratedMap[token] = rez[index]\n    })\n\n    return itemDecoratedMap\n  }\n\n  public get items(): ContextGetter<Context> {\n    let itemMap = <ContextGetter<Context>>{}\n    for (let key in this.getTokens()) {\n      addGetter(itemMap, key, () => {\n        return this.get(key as any)\n      })\n    }\n    return itemMap\n  }\n\n  /**\n   * This is used to get a container from the context.\n   * It should always return a promise?\n   * But it seems that it is not possible to do that with the current implementation.\n   * @deprecated\n   */\n  public get containers() {\n    return this.items\n  }\n\n  /**\n   * @deprecated Use `getItems` instead. This method will be removed in a future version.\n   */\n  public getContainerSet: <T extends (keyof Context)[]>(\n    tokensOrCb: T | ((t: { [K in keyof Context]: K }) => T),\n  ) => Promise<{ [K in T[number]]: FullyUnpackObject<Context>[K] }>\n\n  /**\n   * @deprecated Use `subscribeToItems` instead. This method will be removed in a future version.\n   */\n  public subscribeToContainerSet: <T extends (keyof Context)[]>(\n    tokensOrCb: T | ((t: { [K in keyof Context]: K }) => T),\n    cb: (\n      err: any,\n      container: {\n        [K in T[number]]: FullyUnpackObject<Context>[K]\n      },\n    ) => void,\n  ) => () => void\n}\n\nexport function createContainer() {\n  return new Container()\n}\n","/**\n * From\n * https://github.com/ai/nanoevents\n *\n * Sadly, can't install it via npm. Some build issue\n */\n\n//////////////////\n\ninterface EventsMap {\n  [event: string]: any\n}\n\ninterface DefaultEvents extends EventsMap {\n  [event: string]: (...args: any) => void\n}\n\nexport interface Unsubscribe {\n  (): void\n}\n\nexport declare class Emitter<Events extends EventsMap = DefaultEvents> {\n  /**\n   * Event names in keys and arrays with listeners in values.\n   *\n   * ```js\n   * emitter1.events = emitter2.events\n   * emitter2.events = { }\n   * ```\n   */\n  events: Partial<{ [E in keyof Events]: Events[E][] }>\n\n  /**\n   * Add a listener for a given event.\n   *\n   * ```js\n   * const unbind = ee.on('tick', (tickType, tickDuration) => {\n   *   count += 1\n   * })\n   *\n   * disable () {\n   *   unbind()\n   * }\n   * ```\n   *\n   * @param event The event name.\n   * @param cb The listener function.\n   * @returns Unbind listener from event.\n   */\n  on<K extends keyof Events>(this: this, event: K, cb: Events[K]): Unsubscribe\n\n  /**\n   * Calls each of the listeners registered for a given event.\n   *\n   * ```js\n   * ee.emit('tick', tickType, tickDuration)\n   * ```\n   *\n   * @param event The event name.\n   * @param args The arguments for listeners.\n   */\n  emit<K extends keyof Events>(\n    this: this,\n    event: K,\n    ...args: Parameters<Events[K]>\n  ): void\n}\n\n/**\n * Create event emitter.\n *\n * ```js\n * import { createNanoEvents } from 'nanoevents'\n *\n * class Ticker {\n *   constructor() {\n *     this.emitter = createNanoEvents()\n *   }\n *   on(...args) {\n *     return this.emitter.on(...args)\n *   }\n *   tick() {\n *     this.emitter.emit('tick')\n *   }\n * }\n * ```\n */\n\nexport function createNanoEvents<\n  Events extends EventsMap = DefaultEvents,\n>(): Emitter<Events> {\n  return {\n    events: {},\n    emit(event, ...args) {\n      // @ts-ignore\n      ;(this.events[event] || []).forEach((i) => i(...args))\n    },\n    on(event, cb) {\n      // @ts-ignore\n      ;(this.events[event] = this.events[event] || []).push(cb)\n      return () =>\n        // @ts-ignore\n        (this.events[event] = (this.events[event] || []).filter(\n          (i) => i !== cb,\n        ))\n    },\n  }\n}\n"],"names":["addGetter","object","key","fn","Object","defineProperty","get","enumerable","_intersectionKeys","needle","haystack","duplicates","keys","filter","x","length","join","ItiError","Error","ItiResolveError","ItiTokenError","Container","on","event","callback","ee","constructor","super","_cache","_cacheSync","_context","_disposeCtx","subscribeToContainer","this","events","emit","args","forEach","i","cb","push","subscribeToItem","bind","_storeInSyncCache","token","v","_storeInCache","Promise","then","resolvedValue","catch","err","newContainer","newItem","tokenValue","providedValue","String","getSync","delete","async","disposerFn","cachedValue","disposeResult","resolve","cleanup","thingsToDispose","map","dispose","all","_updateContext","updatedContext","value","entries","upsertUnsubscribe","ev","data","_this","error","undefined","deleteUnsubscribe","containerRemoved","itemRemoved","getTokens","fromEntries","el","getContainerSet","subscribeToContainerSet","getItems","subscribeToItems","upsert","newContext","nc","items","add","newContextOrCb","addDisposer","newDisposingCtx","_extractTokens","tokensOrCb","tokens","includes","cSet","_this2","getItemsSync","itemDecoratedMap","hasAnyPromise","promiseTokens","allPromises","rez","index","itemMap","containers","createContainer"],"mappings":"SAKgBA,EAAUC,EAAQC,EAAKC,GACrCC,OAAOC,eAAeJ,EAAQC,EAAK,CACjCI,IAAG,IACMH,IAETI,YAAY,aAiDAC,EACdC,EACAC,GAEA,IACIC,EADeP,OAAOQ,KAAKF,GACDG,OAAQC,GAAMA,KAAKL,GACjD,GAA0B,IAAtBE,EAAWI,OAGf,OAAOJ,EAAWK,KAAK,cCpEZC,UAAiBC,aACjBC,UAAwBF,SACxBG,UAAsBH,SCuTtBI,UA5Pb,cA5CA,QAuEEC,GAAoCC,EAAUC,GAC5C,YAAYC,GAAGH,GAAGC,EAAOC,GAG3BE,cACEC,aAzBMC,OAAyC,QACzCC,WAA6C,QAK9CC,SAA6B,QAO7BC,YAAqD,QAKlDN,eAoNHO,4BA5MLC,KAAKR,GCHA,CACLS,OAAQ,GACR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