{"version":3,"file":"create-batch.cjs","names":["defaultProcessor"],"sources":["../../src/batch/create-batch.ts"],"sourcesContent":["import defaultProcessor from './default-processor';\nimport type {\n\tBatch,\n\tBatchProcessor,\n\tBatchRequest,\n\tBatchResult,\n\tBatchThunk,\n} from './types';\n\n/**\n * Creates a batch, which can be used to combine multiple API requests into one\n * API request using the WordPress batch processing API (/v1/batch).\n *\n * ```\n * const batch = createBatch();\n * const dunePromise = batch.add( {\n *   path: '/v1/books',\n *   method: 'POST',\n *   data: { title: 'Dune' }\n * } );\n * const lotrPromise = batch.add( {\n *   path: '/v1/books',\n *   method: 'POST',\n *   data: { title: 'Lord of the Rings' }\n * } );\n * const isSuccess = await batch.run(); // Sends one POST to /v1/batch.\n * if ( isSuccess ) {\n *   console.log(\n *     'Saved two books:',\n *     await dunePromise,\n *     await lotrPromise\n *   );\n * }\n * ```\n * @param processor\n */\nexport default function createBatch(\n\tprocessor?: undefined\n): Batch< BatchRequest >;\n/**\n * Creates a batch whose inputs a custom processor handles.\n *\n * @param processor Processor function. Can be used to replace the\n *                  default functionality which is to send an API\n *                  request to /v1/batch. Is given an array of\n *                  inputs and must return a promise that\n *                  resolves to an array of objects containing\n *                  either `output` or `error`.\n */\nexport default function createBatch< Input >(\n\tprocessor: BatchProcessor< Input >\n): Batch< Input >;\nexport default function createBatch< Input >(\n\t// Only the overload without a processor leaves the inputs API requests.\n\tprocessor = defaultProcessor as unknown as BatchProcessor< Input >\n): Batch< Input > {\n\tlet lastId = 0;\n\tlet queue: Array< {\n\t\tinput: Input;\n\t\tresolve: ( value: unknown ) => void;\n\t\treject: ( error: unknown ) => void;\n\t} > = [];\n\tconst pending = new ObservableSet< number >();\n\n\treturn {\n\t\t/**\n\t\t * Adds an input to the batch and returns a promise that is resolved or\n\t\t * rejected when the input is processed by `batch.run()`.\n\t\t *\n\t\t * You may also pass a thunk which allows inputs to be added\n\t\t * asynchronously.\n\t\t *\n\t\t * ```\n\t\t * // Both are allowed:\n\t\t * batch.add( { path: '/v1/books', ... } );\n\t\t * batch.add( ( add ) => add( { path: '/v1/books', ... } ) );\n\t\t * ```\n\t\t *\n\t\t * If a thunk is passed, `batch.run()` will pause until either:\n\t\t *\n\t\t * - The thunk calls its `add` argument, or;\n\t\t * - The thunk returns a promise and that promise resolves, or;\n\t\t * - The thunk returns a non-promise.\n\t\t *\n\t\t * @param inputOrThunk Input to add or thunk to execute.\n\t\t *\n\t\t * @return If given an input, returns a promise that\n\t\t *         is resolved or rejected when the batch is\n\t\t *         processed. If given a thunk, returns the return\n\t\t *         value of that thunk.\n\t\t */\n\t\tadd< Result = unknown >(\n\t\t\tinputOrThunk: Input | BatchThunk< Input, Result >\n\t\t): Promise< Awaited< Result > > {\n\t\t\tconst id = ++lastId;\n\t\t\tpending.add( id );\n\n\t\t\tconst add = ( input: Input ) =>\n\t\t\t\tnew Promise( ( resolve, reject ) => {\n\t\t\t\t\tqueue.push( {\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\tresolve,\n\t\t\t\t\t\treject,\n\t\t\t\t\t} );\n\t\t\t\t\tpending.delete( id );\n\t\t\t\t} );\n\n\t\t\tif ( typeof inputOrThunk === 'function' ) {\n\t\t\t\t// A function input is a thunk.\n\t\t\t\treturn Promise.resolve(\n\t\t\t\t\t( inputOrThunk as BatchThunk< Input, Result > )( add )\n\t\t\t\t).finally( () => {\n\t\t\t\t\tpending.delete( id );\n\t\t\t\t} );\n\t\t\t}\n\n\t\t\t/*\n\t\t\t * Not a function, so not a thunk. `Result` is only inferred from\n\t\t\t * a thunk, so it stays `unknown` for an input.\n\t\t\t */\n\t\t\treturn add( inputOrThunk as Input ) as Promise< Awaited< Result > >;\n\t\t},\n\n\t\t/**\n\t\t * Runs the batch. This calls `batchProcessor` and resolves or rejects\n\t\t * all promises returned by `add()`.\n\t\t *\n\t\t * @return A promise that resolves to a boolean that is true\n\t\t *         if the processor returned no errors.\n\t\t */\n\t\tasync run(): Promise< boolean > {\n\t\t\tif ( pending.size ) {\n\t\t\t\tawait new Promise( ( resolve ) => {\n\t\t\t\t\tconst unsubscribe = pending.subscribe( () => {\n\t\t\t\t\t\tif ( ! pending.size ) {\n\t\t\t\t\t\t\tunsubscribe();\n\t\t\t\t\t\t\tresolve( undefined );\n\t\t\t\t\t\t}\n\t\t\t\t\t} );\n\t\t\t\t} );\n\t\t\t}\n\n\t\t\tlet results: Array< BatchResult | undefined >;\n\n\t\t\ttry {\n\t\t\t\t// A raw output reads as a result with no `output` or `error`.\n\t\t\t\tresults = ( await processor(\n\t\t\t\t\tqueue.map( ( { input } ) => input )\n\t\t\t\t) ) as Array< BatchResult | undefined >;\n\n\t\t\t\tif ( results.length !== queue.length ) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'run: Array returned by processor must be same size as input array.'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch ( error ) {\n\t\t\t\tfor ( const { reject } of queue ) {\n\t\t\t\t\treject( error );\n\t\t\t\t}\n\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tlet isSuccess = true;\n\n\t\t\tresults.forEach( ( result, key ) => {\n\t\t\t\tconst queueItem = queue[ key ];\n\n\t\t\t\tif ( result?.error ) {\n\t\t\t\t\tqueueItem?.reject( result.error );\n\t\t\t\t\tisSuccess = false;\n\t\t\t\t} else {\n\t\t\t\t\tqueueItem?.resolve( result?.output ?? result );\n\t\t\t\t}\n\t\t\t} );\n\n\t\t\tqueue = [];\n\n\t\t\treturn isSuccess;\n\t\t},\n\t};\n}\n\nclass ObservableSet< T > {\n\tset: Set< T >;\n\tsubscribers: Set< () => void >;\n\n\tconstructor( ...args: [ values?: Iterable< T > | null ] ) {\n\t\tthis.set = new Set( ...args );\n\t\tthis.subscribers = new Set();\n\t}\n\n\tget size(): number {\n\t\treturn this.set.size;\n\t}\n\n\tadd( value: T ): this {\n\t\tthis.set.add( value );\n\t\tthis.subscribers.forEach( ( subscriber ) => subscriber() );\n\t\treturn this;\n\t}\n\n\tdelete( value: T ): boolean {\n\t\tconst isSuccess = this.set.delete( value );\n\t\tthis.subscribers.forEach( ( subscriber ) => subscriber() );\n\t\treturn isSuccess;\n\t}\n\n\tsubscribe( subscriber: () => void ): () => void {\n\t\tthis.subscribers.add( subscriber );\n\t\treturn () => {\n\t\t\tthis.subscribers.delete( subscriber );\n\t\t};\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAwB,YAEvB,YAAYA,uBAAAA,SACK;CACjB,IAAI,SAAS;CACb,IAAI,QAIE,CAAC;CACP,MAAM,UAAU,IAAI,cAAwB;CAE5C,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;EA2BN,IACC,cAC+B;GAC/B,MAAM,KAAK,EAAE;GACb,QAAQ,IAAK,EAAG;GAEhB,MAAM,OAAQ,UACb,IAAI,SAAW,SAAS,WAAY;IACnC,MAAM,KAAM;KACX;KACA;KACA;IACD,CAAE;IACF,QAAQ,OAAQ,EAAG;GACpB,CAAE;GAEH,IAAK,OAAO,iBAAiB,YAE5B,OAAO,QAAQ,QACZ,aAA+C,GAAI,CACtD,CAAC,CAAC,cAAe;IAChB,QAAQ,OAAQ,EAAG;GACpB,CAAE;GAOH,OAAO,IAAK,YAAsB;EACnC;;;;;;;;EASA,MAAM,MAA0B;GAC/B,IAAK,QAAQ,MACZ,MAAM,IAAI,SAAW,YAAa;IACjC,MAAM,cAAc,QAAQ,gBAAiB;KAC5C,IAAK,CAAE,QAAQ,MAAO;MACrB,YAAY;MACZ,QAAS,KAAA,CAAU;KACpB;IACD,CAAE;GACH,CAAE;GAGH,IAAI;GAEJ,IAAI;IAEH,UAAY,MAAM,UACjB,MAAM,KAAO,EAAE,YAAa,KAAM,CACnC;IAEA,IAAK,QAAQ,WAAW,MAAM,QAC7B,MAAM,IAAI,MACT,oEACD;GAEF,SAAU,OAAQ;IACjB,KAAM,MAAM,EAAE,YAAY,OACzB,OAAQ,KAAM;IAGf,MAAM;GACP;GAEA,IAAI,YAAY;GAEhB,QA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