{"version":3,"file":"scheduler.cjs","names":["codedMessage","contexts","getOrCreateContext"],"sources":["../../src/scheduler.ts"],"sourcesContent":["import { codedMessage, devBuild } from './error-message'\n\n/**\n * Identifier used to scope scheduled work. Maps to a transaction id for live queries.\n */\nexport type SchedulerContextId = string | symbol\n\n/**\n * Options for {@link Scheduler.schedule}. Jobs are identified by `jobId` within a context\n * and may declare dependencies.\n */\ninterface ScheduleOptions {\n  contextId?: SchedulerContextId\n  jobId: unknown\n  dependencies?: Iterable<unknown>\n  run: () => void\n}\n\n/**\n * State per context. Queue preserves order, jobs hold run functions, dependencies track\n * prerequisites. A job leaves the pending map before its callback runs, so work\n * queued by that callback is a new pending dependency.\n */\ninterface SchedulerContextState {\n  queue: Array<unknown>\n  jobs: Map<unknown, () => void>\n  dependencies: Map<unknown, Set<unknown>>\n}\n\n/**\n * Scoped scheduler that coalesces work by context and job.\n *\n * - **context** (e.g. transaction id) defines the batching boundary; work is queued until flushed.\n * - **job id** deduplicates work within a context; scheduling the same job replaces the previous run function.\n * - Without a context id, work executes immediately.\n *\n * Callers manage their own state; the scheduler only orchestrates execution order.\n */\nexport class Scheduler {\n  private contexts = new Map<SchedulerContextId, SchedulerContextState>()\n  /**\n   * Get or create the state bucket for a context.\n   */\n  private getOrCreateContext(\n    contextId: SchedulerContextId,\n  ): SchedulerContextState {\n    let context = this.contexts.get(contextId)\n    if (!context) {\n      context = {\n        queue: [],\n        jobs: new Map(),\n        dependencies: new Map(),\n      }\n      this.contexts.set(contextId, context)\n    }\n    return context\n  }\n\n  /**\n   * Schedule work. Without a context id, executes immediately.\n   * Otherwise queues the job to be flushed once dependencies are satisfied.\n   * Scheduling the same jobId again replaces the previous run function.\n   */\n  schedule({ contextId, jobId, dependencies, run }: ScheduleOptions): void {\n    if (typeof contextId === `undefined`) {\n      run()\n      return\n    }\n\n    const context = this.getOrCreateContext(contextId)\n\n    // If this is a new job, add it to the queue\n    if (!context.jobs.has(jobId)) {\n      context.queue.push(jobId)\n    }\n\n    // Store or replace the run function\n    context.jobs.set(jobId, run)\n\n    // Update dependencies\n    if (dependencies) {\n      const depSet = new Set<unknown>(dependencies)\n      depSet.delete(jobId)\n      context.dependencies.set(jobId, depSet)\n    } else if (!context.dependencies.has(jobId)) {\n      context.dependencies.set(jobId, new Set())\n    }\n  }\n\n  /**\n   * Flush all queued work for a context. Jobs with unmet dependencies are retried.\n   * Throws if a pass completes without running any job (dependency cycle).\n   */\n  flush(contextId: SchedulerContextId): void {\n    const context = this.contexts.get(contextId)\n    if (!context) return\n\n    const { queue, jobs, dependencies } = context\n\n    while (queue.length > 0) {\n      let ranThisPass = false\n      const jobsThisPass = queue.length\n\n      for (let i = 0; i < jobsThisPass; i++) {\n        const jobId = queue.shift()!\n        const run = jobs.get(jobId)\n        if (!run) {\n          dependencies.delete(jobId)\n          continue\n        }\n\n        const deps = dependencies.get(jobId)\n        let ready = !deps\n        if (deps) {\n          ready = true\n          for (const dep of deps) {\n            if (dep === jobId) continue\n\n            // A dependency blocks only while its job is queued in this context.\n            if (jobs.has(dep)) {\n              ready = false\n              break\n            }\n          }\n        }\n\n        if (ready) {\n          jobs.delete(jobId)\n          dependencies.delete(jobId)\n          // A reentrant schedule now owns a fresh pending job; finishing this\n          // callback must not mark that replacement as complete.\n          run()\n          ranThisPass = true\n        } else {\n          queue.push(jobId)\n        }\n      }\n\n      if (!ranThisPass) {\n        throw new Error(\n          devBuild() && process.env.NODE_ENV !== `production`\n            ? `Scheduler detected unresolved dependencies for context ${String(\n                contextId,\n              )}.`\n            : codedMessage(161, { contextId }),\n        )\n      }\n    }\n\n    this.contexts.delete(contextId)\n  }\n\n  /** Clear all scheduled jobs for a context. */\n  clear(contextId: SchedulerContextId): void {\n    this.contexts.delete(contextId)\n  }\n}\n\nexport const transactionScopedScheduler = new Scheduler()\n\nlet activePublicationContext: SchedulerContextId | undefined\nlet activePublicationFailure: { error: unknown } | undefined\n\nfunction getActivePublicationFailure(): { error: unknown } | undefined {\n  return activePublicationFailure\n}\n\n/**\n * Returns the Collection publication that currently owns synchronous change\n * delivery. Live-query jobs use it to coalesce all source subscriptions that\n * observe one committed batch.\n */\nexport function getActivePublicationContext(): SchedulerContextId | undefined {\n  return activePublicationContext\n}\n\n/** Report a listener failure after the whole publication graph has drained. */\nexport function recordPublicationError(error: unknown): void {\n  if (activePublicationContext === undefined) throw error\n  activePublicationFailure ??= { error }\n}\n\n/**\n * Runs one synchronous Collection publication inside a scheduler context.\n * Nested publications share the outer context, so downstream live queries run\n * only after every subscriber to the original committed batch has observed it.\n */\nexport function withPublicationContext<T>(publish: () => T): T {\n  if (activePublicationContext !== undefined) return publish()\n\n  const contextId = Symbol(`collection-publication`)\n  activePublicationContext = contextId\n  activePublicationFailure = undefined\n  let result!: T\n  let listenerFailure: { error: unknown } | undefined\n  try {\n    result = publish()\n    transactionScopedScheduler.flush(contextId)\n    listenerFailure = getActivePublicationFailure()\n  } catch (error) {\n    try {\n      transactionScopedScheduler.clear(contextId)\n    } catch {\n      // Keep the earlier publication or graph failure.\n    }\n    // Keep the first reported failure, including one from an earlier listener.\n    const publicationFailure = getActivePublicationFailure()\n    if (publicationFailure) {\n      throw publicationFailure.error\n    }\n    throw error\n  } finally {\n    activePublicationContext = undefined\n    activePublicationFailure = undefined\n  }\n  if (listenerFailure) throw listenerFailure.error\n  return result\n}\n"],"mappings":";AAsCA,IAAa,YAAb,MAAuB;;EACF,KAAAC,qBAAA,IAAI,IAA+C;;;;;CAItEC,GACE,WACuB;EACvB,IAAI,UAAU,KAAKD,GAAS,IAAI,SAAS;EACzC,IAAI,CAAC,SAAS;GACZ,UAAU;IACR,OAAO,CAAC;IACR,sBAAM,IAAI,IAAI;IACd,8BAAc,IAAI,IAAI;GACxB;GACA,KAAKA,GAAS,IAAI,WAAW,OAAO;EACtC;EACA,OAAO;CACT;;;;;;CAOA,SAAS,EAAE,WAAW,OAAO,cAAc,OAA8B;EACvE,IAAI,OAAO,cAAc,aAAa;GACpC,IAAI;GACJ;EACF;EAEA,MA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