Skip to content
Myr

devtools.ts

This file

Path

src/middleware/devtools.ts

437 lines · 13.2 KiB · TypeScript

Last changed by

chore(deps): update dev dependencies (#3560)Daishi Katobefore adoption1f531ba

History of this file

Take it

1import type {} from '@redux-devtools/extension'23import type {4  StateCreator,5  StoreApi,6  StoreMutatorIdentifier,7} from '../vanilla.ts'89type Config = Parameters<10  (Window extends { __REDUX_DEVTOOLS_EXTENSION__?: infer T }11    ? T12    : { connect: (param: any) => unknown })['connect']13>[0]1415declare module '../vanilla' {16  // eslint-disable-next-line @typescript-eslint/no-unused-vars17  interface StoreMutators<S, A> {18    'zustand/devtools': WithDevtools<S>19  }20}2122// FIXME https://github.com/reduxjs/redux-devtools/issues/109723type Message = {24  type: string25  payload?: any26  state?: any27}2829type WithDispatch = {30  dispatch: (...args: unknown[]) => void31  dispatchFromDevtools: unknown32}3334const shouldDispatchFromDevtools = (api: unknown): api is WithDispatch =>35  !!(api as WithDispatch).dispatchFromDevtools &&36  typeof (api as WithDispatch).dispatch === 'function'3738type Cast<T, U> = T extends U ? T : U39type Write<T, U> = Omit<T, keyof U> & U40type TakeTwo<T> = T extends { length: 0 }41  ? [undefined, undefined]42  : T extends { length: 1 }43    ? [...args0: Cast<T, unknown[]>, arg1: undefined]44    : T extends { length: 0 | 1 }45      ? [...args0: Cast<T, unknown[]>, arg1: undefined]46      : T extends { length: 2 }47        ? T48        : T extends { length: 1 | 2 }49          ? T50          : T extends { length: 0 | 1 | 2 }51            ? T52            : T extends [infer A0, infer A1, ...unknown[]]53              ? [A0, A1]54              : T extends [infer A0, (infer A1)?, ...unknown[]]55                ? [A0, A1?]56                : T extends [(infer A0)?, (infer A1)?, ...unknown[]]57                  ? [A0?, A1?]58                  : never5960type WithDevtools<S> = Write<S, StoreDevtools<S>>6162type Action =63  | string64  | {65      type: string66      [x: string | number | symbol]: unknown67    }68type StoreDevtools<S> = S extends {69  setState: {70    // capture both overloads of setState71    (...args: infer Sa1): infer Sr172    (...args: infer Sa2): infer Sr273  }74}75  ? {76      setState(...args: [...args: TakeTwo<Sa1>, action?: Action]): Sr177      setState(...args: [...args: TakeTwo<Sa2>, action?: Action]): Sr278      devtools: {79        cleanup: () => void80      }81    }82  : never8384export interface DevtoolsOptions extends Config {85  name?: string86  enabled?: boolean87  anonymousActionType?: string88  store?: string89}9091type Devtools = <92  T,93  Mps extends [StoreMutatorIdentifier, unknown][] = [],94  Mcs extends [StoreMutatorIdentifier, unknown][] = [],95  U = T,96>(97  initializer: StateCreator<T, [...Mps, ['zustand/devtools', never]], Mcs, U>,98  devtoolsOptions?: DevtoolsOptions,99) => StateCreator<T, Mps, [['zustand/devtools', never], ...Mcs], U>100101type DevtoolsImpl = <T>(102  storeInitializer: StateCreator<T, [], []>,103  devtoolsOptions?: DevtoolsOptions,104) => StateCreator<T, [], []>105106export type NamedSet<T> = WithDevtools<StoreApi<T>>['setState']107108type Connection = ReturnType<109  NonNullable<Window['__REDUX_DEVTOOLS_EXTENSION__']>['connect']110>111type ConnectionName = string | undefined112type StoreName = string113type StoreInformation = StoreApi<unknown>114type ConnectionInformation = {115  connection: Connection116  stores: Record<StoreName, StoreInformation>117}118119const trackedConnections: Map<ConnectionName, ConnectionInformation> = new Map()120121const getTrackedConnectionState = (122  name: string | undefined,123): Record<string, any> => {124  const api = trackedConnections.get(name)125  if (!api) return {}126  return Object.fromEntries(127    Object.entries(api.stores).map(([key, api]) => [key, api.getState()]),128  )129}130131const extractConnectionInformation = (132  store: string | undefined,133  extensionConnector: NonNullable<134    (typeof window)['__REDUX_DEVTOOLS_EXTENSION__']135  >,136  options: Omit<DevtoolsOptions, 'enabled' | 'anonymousActionType' | 'store'>,137) => {138  if (store === undefined) {139    return {140      type: 'untracked' as const,141      connection: extensionConnector.connect(options),142    }143  }144  const existingConnection = trackedConnections.get(options.name)145  if (existingConnection) {146    return { type: 'tracked' as const, store, ...existingConnection }147  }148  const newConnection: ConnectionInformation = {149    connection: extensionConnector.connect(options),150    stores: {},151  }152  trackedConnections.set(options.name, newConnection)153  return { type: 'tracked' as const, store, ...newConnection }154}155156const removeStoreFromTrackedConnections = (157  name: string | undefined,158  store: string | undefined,159) => {160  if (store === undefined) return161  const connectionInfo = trackedConnections.get(name)162  if (!connectionInfo) return163  delete connectionInfo.stores[store]164  if (Object.keys(connectionInfo.stores).length === 0) {165    trackedConnections.delete(name)166  }167}168169// V8 (Chrome/Edge/Node): "at [async|new] <name> (<source>)"170const v8StackLineRe = /^at (?:new |async )?(.+?) \(/171// SpiderMonkey (Firefox) / JavaScriptCore (Safari): "<name>@<source>"172const geckoStackLineRe = /^([^@]+)@/173174function findCallerName(stack: string | undefined) {175  if (!stack) return undefined176  const traceLines = stack.split('\n')177  const apiSetStateLineIndex = traceLines.findIndex((traceLine) =>178    traceLine.includes('api.setState'),179  )180  if (apiSetStateLineIndex < 0) return undefined181  const callerLine = traceLines[apiSetStateLineIndex + 1]?.trim() || ''182  return (183    v8StackLineRe.exec(callerLine)?.[1] ||184    geckoStackLineRe.exec(callerLine)?.[1]185  )186}187188const devtoolsImpl: DevtoolsImpl =189  (fn, devtoolsOptions = {}) =>190  (set, get, api) => {191    const { enabled, anonymousActionType, store, ...options } = devtoolsOptions192193    type S = ReturnType<typeof fn> & {194      [store: string]: ReturnType<typeof fn>195    }196    type PartialState = Partial<S> | ((s: S) => Partial<S>)197198    let extensionConnector:199      (typeof window)['__REDUX_DEVTOOLS_EXTENSION__'] | false200    try {201      extensionConnector =202        (enabled ?? import.meta.env?.MODE !== 'production') &&203        window.__REDUX_DEVTOOLS_EXTENSION__204    } catch {205      // ignored206    }207208    if (!extensionConnector) {209      return fn(set, get, api)210    }211212    const { connection, ...connectionInformation } =213      extractConnectionInformation(store, extensionConnector, options)214215    let isRecording = true216    api.setState = ((state, replace, nameOrAction: Action) => {217      const r = set(state, replace as any)218      if (!isRecording) return r219      const action: { type: string } =220        nameOrAction === undefined221          ? {222              type:223                anonymousActionType ||224                findCallerName(new Error().stack) ||225                'anonymous',226            }227          : typeof nameOrAction === 'string'228            ? { type: nameOrAction }229            : nameOrAction230      if (store === undefined) {231        connection?.send(action, get())232        return r233      }234      connection?.send(235        {236          ...action,237          type: `${store}/${action.type}`,238        },239        {240          ...getTrackedConnectionState(options.name),241          [store]: api.getState(),242        },243      )244      return r245    }) as NamedSet<S>246    ;(api as StoreApi<S> & StoreDevtools<S>).devtools = {247      cleanup: () => {248        if (249          connection &&250          typeof (connection as any).unsubscribe === 'function'251        ) {252          ;(connection as any).unsubscribe()253        }254        removeStoreFromTrackedConnections(options.name, store)255      },256    }257258    const setStateFromDevtools: StoreApi<S>['setState'] = (...a) => {259      const originalIsRecording = isRecording260      isRecording = false261      set(...(a as Parameters<typeof set>))262      isRecording = originalIsRecording263    }264265    const initialState = fn(api.setState, get, api)266    if (connectionInformation.type === 'untracked') {267      connection?.init(initialState)268    } else {269      connectionInformation.stores[connectionInformation.store] = api270      connection?.init(271        Object.fromEntries(272          Object.entries(connectionInformation.stores).map(([key, store]) => [273            key,274            key === connectionInformation.store275              ? initialState276              : store.getState(),277          ]),278        ),279      )280    }281282    if (shouldDispatchFromDevtools(api)) {283      let didWarnAboutReservedActionType = false284      const originalDispatch = api.dispatch285      api.dispatch = (...args: any[]) => {286        if (287          import.meta.env?.MODE !== 'production' &&288          args[0].type === '__setState' &&289          !didWarnAboutReservedActionType290        ) {291          console.warn(292            '[zustand devtools middleware] "__setState" action type is reserved ' +293              'to set state from the devtools. Avoid using it.',294          )295          didWarnAboutReservedActionType = true296        }297        originalDispatch(...args)298      }299    }300301    ;(302      connection as unknown as {303        // FIXME https://github.com/reduxjs/redux-devtools/issues/1097304        subscribe: (305          listener: (message: Message) => void,306        ) => (() => void) | undefined307      }308    ).subscribe((message) => {309      switch (message.type) {310        case 'ACTION':311          if (typeof message.payload !== 'string') {312            console.error(313              '[zustand devtools middleware] Unsupported action format',314            )315            return316          }317          return parseJsonThen<{ type: unknown; state?: PartialState }>(318            message.payload,319            (action) => {320              if (action.type === '__setState') {321                if (store === undefined) {322                  setStateFromDevtools(action.state as PartialState)323                  return324                }325                if (Object.keys(action.state as S).length !== 1) {326                  console.error(327                    `328                    [zustand devtools middleware] Unsupported __setState action format.329                    When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),330                    and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }331                    `,332                  )333                }334                const stateFromDevtools = (action.state as S)[store]335                if (336                  stateFromDevtools === undefined ||337                  stateFromDevtools === null338                ) {339                  return340                }341                if (342                  JSON.stringify(api.getState()) !==343                  JSON.stringify(stateFromDevtools)344                ) {345                  setStateFromDevtools(stateFromDevtools)346                }347                return348              }349350              if (shouldDispatchFromDevtools(api)) {351                api.dispatch(action)352              }353            },354          )355356        case 'DISPATCH':357          switch (message.payload.type) {358            case 'RESET':359              setStateFromDevtools(initialState as S)360              if (store === undefined) {361                return connection?.init(api.getState())362              }363              return connection?.init(getTrackedConnectionState(options.name))364365            case 'COMMIT':366              if (store === undefined) {367                connection?.init(api.getState())368                return369              }370              return connection?.init(getTrackedConnectionState(options.name))371372            case 'ROLLBACK':373              return parseJsonThen<S>(message.state, (state) => {374                if (store === undefined) {375                  setStateFromDevtools(state)376                  connection?.init(api.getState())377                  return378                }379                setStateFromDevtools(state[store] as S)380                connection?.init(getTrackedConnectionState(options.name))381              })382383            case 'JUMP_TO_STATE':384            case 'JUMP_TO_ACTION':385              return parseJsonThen<S>(message.state, (state) => {386                if (store === undefined) {387                  setStateFromDevtools(state)388                  return389                }390                if (391                  JSON.stringify(api.getState()) !==392                  JSON.stringify(state[store])393                ) {394                  setStateFromDevtools(state[store] as S)395                }396              })397398            case 'IMPORT_STATE': {399              const { nextLiftedState } = message.payload400              const lastComputedState =401                nextLiftedState.computedStates.slice(-1)[0]?.state402              if (!lastComputedState) return403              if (store === undefined) {404                setStateFromDevtools(lastComputedState)405              } else {406                setStateFromDevtools(lastComputedState[store])407              }408              connection?.send(409                null as any, // FIXME no-any410                nextLiftedState,411              )412              return413            }414415            case 'PAUSE_RECORDING':416              return (isRecording = !isRecording)417          }418          return419      }420    })421422    return initialState423  }424export const devtools = devtoolsImpl as unknown as Devtools425426const parseJsonThen = <T>(stringified: string, fn: (parsed: T) => void) => {427  let parsed: T | undefined428  try {429    parsed = JSON.parse(stringified)430  } catch (e) {431    console.error(432      '[zustand devtools middleware] Could not parse the received json',433      e,434    )435  }436  if (parsed !== undefined) fn(parsed as T)437}