{"version":3,"file":"index.cjs","sources":["../../src/optimistic/state/documentMutator.ts","../../src/optimistic/state/datasetMutator.ts"],"sourcesContent":["import type {SanityClient} from '@sanity/client'\nimport {SanityEncoder, type Transaction} from '@sanity/mutate'\nimport {\n  documentMutatorMachine,\n  type DocumentMutatorMachineParentEvent,\n} from '@sanity/mutate/_unstable_machine'\nimport {enqueueActions, fromPromise} from 'xstate'\nimport type {VisualEditingNode} from '../../types'\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport const createDocumentMutator = (comlink: VisualEditingNode) => {\n  const fetchSnapshot = fromPromise(\n    async ({input, signal}: {input: {id: string; client: SanityClient}; signal: AbortSignal}) => {\n      const {id} = input\n      const {snapshot} = await comlink.fetch(\n        'visual-editing/fetch-snapshot',\n        {documentId: id},\n        {\n          signal,\n        },\n      )\n      return snapshot\n    },\n  )\n\n  const submitMutations = fromPromise(\n    async ({input}: {input: {client: SanityClient; transactions: Transaction[]}}) => {\n      const {transactions} = input\n      for (const transaction of transactions) {\n        const data = SanityEncoder.encodeTransaction(transaction)\n        return comlink.post('visual-editing/mutate', data)\n      }\n    },\n  )\n\n  return documentMutatorMachine.provide({\n    actions: {\n      'send sync event to parent': enqueueActions(({enqueue}) => {\n        // Original action provided by the `documentMutatorMachine`\n        enqueue.sendParent(\n          ({context}) =>\n            ({\n              type: 'sync',\n              id: context.id,\n              document: context.remote!,\n            }) satisfies DocumentMutatorMachineParentEvent,\n        )\n        // Additional action so that we can determine when the snapshot is ready\n        enqueue.emit(({context}) => ({type: 'ready', snapshot: context.local}))\n      }),\n    },\n    actors: {\n      'fetch remote snapshot': fetchSnapshot,\n      'submit mutations as transactions': submitMutations,\n    },\n  })\n}\n","/**\n * The logic here is intended to live inside a preview iframe, and listen to events from the parent frame.\n * It also supports running in a \"detached\" mode, where it has to setup authenticated EventSource conenctions and perform data fetching itself.\n */\n\nimport {type SanityClient} from '@sanity/client'\nimport {\n  createSharedListener,\n  documentMutatorMachine,\n  type DocumentMutatorMachineInput,\n  type DocumentMutatorMachineParentEvent,\n} from '@sanity/mutate/_unstable_machine'\nimport {assertEvent, assign, emit, setup, stopChild, type ActorRefFrom} from 'xstate'\nimport type {VisualEditingNode} from '../../types'\nimport {createDocumentMutator} from './documentMutator'\n\nexport interface DatasetMutatorMachineInput extends Omit<DocumentMutatorMachineInput, 'id'> {\n  client: SanityClient\n  /** A shared listener can be provided, if not it'll be created using `client.listen()` */\n  sharedListener?: ReturnType<typeof createSharedListener>\n}\n\nexport const datasetMutatorMachine = setup({\n  types: {} as {\n    context: {\n      client: SanityClient\n      /** A shared listener can be provided, if not it'll be created using `client.listen()` */\n      sharedListener?: ReturnType<typeof createSharedListener>\n      documents: Record<string, ActorRefFrom<ReturnType<typeof createDocumentMutator>>>\n    }\n    events:\n      | {type: 'observe'; documentId: string}\n      | {type: 'unobserve'; documentId: string}\n      | {type: 'add document actor'; documentId: string}\n      | {type: 'stop document actor'; documentId: string}\n      | DocumentMutatorMachineParentEvent\n    input: DatasetMutatorMachineInput\n    emitted: DocumentMutatorMachineParentEvent\n  },\n  actions: {\n    'emit sync event': emit(({event}) => {\n      assertEvent(event, 'sync')\n      return event\n    }),\n    'emit mutation event': emit(({event}) => {\n      assertEvent(event, 'mutation')\n      return event\n    }),\n    'emit rebased event': emit(({event}) => {\n      assertEvent(event, ['rebased.local', 'rebased.remote'])\n      return event\n    }),\n    'emit pristine event': emit(({event}) => {\n      assertEvent(event, ['pristine'])\n      return event\n    }),\n    'add document actor': assign({\n      documents: ({context, event, spawn}) => {\n        assertEvent(event, 'observe')\n        const id = event.documentId\n        // Adding the same documentId multiple times is a no-op\n        if (context.documents[id]) return context.documents\n        return {\n          ...context.documents,\n          [id]: spawn('documentMutatorMachine', {\n            input: {\n              id,\n              client: context.client,\n              sharedListener: context.sharedListener || createSharedListener(context.client),\n            },\n            id,\n          }),\n        }\n      },\n    }),\n    'stop remote snapshot': stopChild(({context, event}) => {\n      assertEvent(event, 'unobserve')\n      return context.documents[event.documentId]!\n    }),\n    'remove remote snapshot from context': assign({\n      documents: ({context, event}) => {\n        assertEvent(event, 'unobserve')\n        // Removing a non-existing documentId is a no-op\n        if (!context.documents[event.documentId]) return context.documents\n        // eslint-disable-next-line @typescript-eslint/no-unused-vars\n        const {[event.documentId]: _, ...documents} = context.documents\n        return documents\n      },\n    }),\n  },\n  actors: {\n    documentMutatorMachine,\n  },\n}).createMachine({\n  /** @xstate-layout N4IgpgJg5mDOIC5QBsD2BjAhsgIhgrgLZgB2ALgMTICWsZpA2gAwC6ioADqrNWdaiXYgAHogC0ADgBMAOgkA2ACyKArBICcTdfKXSANCACeiFQHYZpgMxWV800yYqp6gIyn5AXw8G0WXAWJyCnwSGjpGViEuHj4BIVEEKUt5OSlFU1smFwkFW0sDY0T1GRUXRXkXKVN7HSYJJkUvHwxsPHQiUjIZDgAnWj4SMApCfDJMemY2JBBo3n5BaYSXeVlbKRUsiXdFSxcXfKNERSqZTbr1zVMJNyaQX1aAzpkIah6yQwp0VEJCXkmo7hzOKLRDLFwyFxaSzXKTOKQudSKCQFRDOczqCSWJjwjbHCQqRFebwgEioCBwIT3fztQJkAExebxcQuFEIZaWGRIrF7dSXKTyFSNYlUtodcjdPp0aiDelAhagBLpVmWAmc46mNwSZTyLQuFS3EWPcUvN6FTiA2LykSoq6c6wbCqVUzparKioyRFVfkq1zqNSWIkeIA */\n  id: 'dataset-mutator',\n  context: ({input}) => ({\n    documents: {},\n    client: input.client,\n    sharedListener: input.sharedListener,\n  }),\n\n  on: {\n    'sync': {actions: ['emit sync event']},\n    'mutation': {actions: ['emit mutation event']},\n    'rebased.*': {actions: ['emit rebased event']},\n    'pristine': {actions: ['emit pristine event']},\n    'observe': {\n      actions: ['add document actor'],\n    },\n    'unobserve': {\n      actions: ['stop remote snapshot', 'remove remote snapshot from context'],\n    },\n  },\n\n  initial: 'pristine',\n\n  states: {\n    pristine: {},\n  },\n})\n\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport const createDatasetMutator = (comlink: VisualEditingNode) => {\n  return datasetMutatorMachine.provide({\n    actors: {\n      documentMutatorMachine: createDocumentMutator(comlink),\n    },\n  })\n}\n"],"names":["Object","defineProperty","exports","value","context","require","_unstable_machine","xstate","mutate","createDocumentMutator","comlink","fetchSnapshot","fromPromise","async","input","signal","id","snapshot","fetch","documentId","submitMutations","transactions","transaction","data","SanityEncoder","encodeTransaction","post","documentMutatorMachine","provide","actions","enqueueActions","enqueue","sendParent","type","document","remote","emit","local","actors","datasetMutatorMachine","setup","types","event","assertEvent","assign","documents","spawn","client","sharedListener","createSharedListener","stopChild","_","createMachine","on","sync","mutation","pristine","observe","unobserve","initial","states","enumerable","get","a","emptyActor","e","isEmptyActor","i","listeners","l","setActor","s","createDatasetMutator"],"mappings":"aAUOA,OAAAC,eAAAC,QAAA,aAAA,CAAAC,OAAA,IAAA,IAAAC,EAAAC,QAAA,8BAAAC,EAAAD,QAAA,oCAAAE,EAAAF,QAAA,UAAAG,EAAAH,QAAA,kBAAA,MAAMI,EAAwDC,IAC7DC,MAAAA,EAAgBC,EAAAA,aACpBC,OAAQC,QAAOC,aACP,MAAAC,GAACA,GAAMF,GACPG,SAACA,SAAkBP,EAAQQ,MAC/B,gCACA,CAACC,WAAYH,GACb,CACED,WAGGE,OAAAA,CAAAA,IAILG,EAAkBR,EAAAA,aACtBC,OAAQC,YACA,MAAAO,aAACA,GAAgBP,EACvB,IAAA,MAAWQ,KAAeD,EAAc,CAChCE,MAAAA,EAAOC,EAAAA,cAAcC,kBAAkBH,GACtCZ,OAAAA,EAAQgB,KAAK,wBAAyBH,EAAI,KAKhDI,OAAAA,EAAAA,uBAAuBC,QAAQ,CACpCC,QAAS,CACP,4BAA6BC,kBAAe,EAAEC,cAE5CA,EAAQC,YACN,EAAE5B,QAAAA,MACC,CACC6B,KAAM,OACNjB,GAAIZ,EAAQY,GACZkB,SAAU9B,EAAQ+B,WAIxBJ,EAAQK,MAAK,EAAEhC,QAAAA,MAAc,CAAC6B,KAA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