{"version":3,"file":"angularWatcherTypesBridge.mjs","names":[],"sources":["../../../src/esbuild/angularWatcherTypesBridge.ts"],"sourcesContent":["import {\n  type FSWatcher,\n  mkdirSync,\n  readdirSync,\n  readFileSync,\n  watch,\n  writeFileSync,\n} from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join, normalize, sep } from 'node:path';\n\n/** Batch of changed paths, as `@angular/build`'s watcher yields it. */\nexport type ChangedFilesLike = {\n  added: Set<string>;\n  modified: Set<string>;\n  removed: Set<string>;\n  readonly all: string[];\n};\n\n/** Watcher returned by `@angular/build`'s `createWatcher`. */\nexport type AngularWatcher = AsyncIterableIterator<ChangedFilesLike> & {\n  add: (paths: string | readonly string[]) => void;\n  remove: (paths: string | readonly string[]) => void;\n  close: () => Promise<void>;\n};\n\n/** Exports of `@angular/build/src/tools/esbuild/watcher.js` the bridge uses. */\nexport type AngularWatcherModule = {\n  createWatcher: (options?: unknown) => AngularWatcher;\n  ChangedFiles: new () => ChangedFilesLike;\n};\n\n/** Module running `ng serve` / `ng build --watch` rebuild loops. */\nconst BUILD_ACTION_MODULE_SUFFIX = [\n  '@angular',\n  'build',\n  'src',\n  'builders',\n  'application',\n  'build-action.js',\n].join(sep);\n\n/** Marks a watcher module already wrapped, so repeated setups wrap it once. */\nconst WRAPPED_MARKER = Symbol.for('intlayer.angular.watcherWrapped');\n\n/** Delay letting a burst of declaration writes settle into one rebuild. */\nconst SETTLE_DELAY_MS = 50;\n\n/** Name of the script whose rewrite makes TypeScript re-check every file. */\nexport const TYPES_REVISION_FILE_NAME = 'angular-types-revision.d.ts';\n\n/** Generated declaration files: absolute path → contents. */\nexport type FileContents = Map<string, string>;\n\n/**\n * Reads the declaration files of `directories`. A missing directory counts as\n * empty.\n */\nexport const readFileContents = (directories: string[]): FileContents => {\n  const fileContents: FileContents = new Map();\n\n  for (const directory of directories) {\n    let fileNames: string[];\n\n    try {\n      fileNames = readdirSync(directory);\n    } catch {\n      continue;\n    }\n\n    for (const fileName of fileNames) {\n      if (!fileName.endsWith('.ts') || fileName === TYPES_REVISION_FILE_NAME) {\n        continue;\n      }\n\n      const filePath = normalize(join(directory, fileName));\n\n      try {\n        fileContents.set(filePath, readFileSync(filePath, 'utf-8'));\n      } catch {\n        // Removed between the listing and the read: reported as removed.\n      }\n    }\n  }\n\n  return fileContents;\n};\n\n/**\n * Files added, modified or removed between two snapshots. Comparing contents\n * rather than times keeps an identical rewrite from triggering a rebuild.\n */\nexport const diffFileContents = (\n  previousContents: FileContents,\n  currentContents: FileContents,\n  changedFiles: ChangedFilesLike\n): ChangedFilesLike => {\n  for (const [filePath, contents] of currentContents) {\n    const previous = previousContents.get(filePath);\n\n    if (previous === undefined) changedFiles.added.add(filePath);\n    else if (previous !== contents) changedFiles.modified.add(filePath);\n  }\n\n  for (const filePath of previousContents.keys()) {\n    if (!currentContents.has(filePath)) changedFiles.removed.add(filePath);\n  }\n\n  return changedFiles;\n};\n\n/**\n * Contents of the revision script. It has no import or export, so TypeScript\n * treats it as affecting the global scope: rewriting it re-checks every file.\n */\nexport const getTypesRevisionContents = (revision: number): string =>\n  [\n    '// Generated by angular-intlayer. Rewritten when the dictionary types',\n    '// change, so the Angular dev server re-checks every template.',\n    // A declaration rather than a comment: TypeScript ignores comments when\n    // deciding whether a file changed in a way that affects other files.\n    `interface IntlayerAngularTypesRevision { revision: ${revision} }`,\n    '',\n  ].join('\\n');\n\n/**\n * Wraps an Angular watcher so it also yields the batches `subscribe` reports.\n *\n * The rebuild loop awaits one `next()` at a time: a pending call of the\n * original watcher is kept across calls, so no change it reports is lost when\n * an injected batch is returned first.\n */\nexport const mergeInjectedChanges = (\n  angularWatcher: AngularWatcher,\n  subscribe: (listener: (changedFiles: ChangedFilesLike) => void) => () => void\n): AngularWatcher => {\n  let pendingNext: Promise<IteratorResult<ChangedFilesLike>> | undefined;\n  let queuedChanges: ChangedFilesLike | undefined;\n  let wakeUp: (() => void) | undefined;\n\n  const unsubscribe = subscribe((changedFiles) => {\n    if (queuedChanges) {\n      // Not consumed yet: fold the new batch into the queued one.\n      changedFiles.added.forEach((path) => queuedChanges!.added.add(path));\n      changedFiles.modified.forEach((path) =>\n        queuedChanges!.modified.add(path)\n      );\n      changedFiles.removed.forEach((path) => queuedChanges!.removed.add(path));\n    } else {\n      queuedChanges = changedFiles;\n    }\n\n    wakeUp?.();\n  });\n\n  const bridgedWatcher: AngularWatcher = {\n    [Symbol.asyncIterator]: () => bridgedWatcher,\n\n    next: async () => {\n      if (!queuedChanges) {\n        pendingNext ??= angularWatcher.next();\n\n        await Promise.race([\n          pendingNext,\n          new Promise<void>((resolve) => {\n            wakeUp = resolve;\n          }),\n        ]);\n        wakeUp = undefined;\n      }\n\n      if (queuedChanges) {\n        const changedFiles = queuedChanges;\n        queuedChanges = undefined;\n\n        return { value: changedFiles, done: false };\n      }\n\n      const result = await pendingNext!;\n      pendingNext = undefined;\n\n      return result;\n    },\n\n    add: (paths) => angularWatcher.add(paths),\n    remove: (paths) => angularWatcher.remove(paths),\n\n    close: async () => {\n      unsubscribe();\n      await angularWatcher.close();\n    },\n  };\n\n  return bridgedWatcher;\n};\n\n/**\n * Watches `directories` and reports each settled batch of changed\n * declarations, one listener per running Angular watcher.\n */\nconst createTypesChangeSource = (\n  directories: string[],\n  revisionFilePath: string,\n  ChangedFiles: AngularWatcherModule['ChangedFiles']\n) => {\n  let revision = 0;\n  mkdirSync(dirname(revisionFilePath), { recursive: true });\n  writeFileSync(revisionFilePath, getTypesRevisionContents(revision));\n\n  const listeners = new Set<(changedFiles: ChangedFilesLike) => void>();\n  let fileContents = readFileContents(directories);\n  let settleTimeout: ReturnType<typeof setTimeout> | undefined;\n  let directoryWatchers: FSWatcher[] = [];\n\n  const emitChanges = () => {\n    const currentContents = readFileContents(directories);\n    const changedFiles = diffFileContents(\n      fileContents,\n      currentContents,\n      new ChangedFiles()\n    );\n    fileContents = currentContents;\n\n    if (changedFiles.all.length === 0) return;\n\n    // A dictionary type reaches components through module augmentation, not an\n    // import, so the type-checker would keep each template's diagnostics. A\n    // changed global script is the one change that re-checks every file.\n    revision += 1;\n    writeFileSync(revisionFilePath, getTypesRevisionContents(revision));\n    changedFiles.modified.add(revisionFilePath);\n\n    for (const listener of listeners) listener(changedFiles);\n  };\n\n  const scheduleEmit = () => {\n    clearTimeout(settleTimeout);\n    settleTimeout = setTimeout(emitChanges, SETTLE_DELAY_MS);\n    settleTimeout.unref?.();\n  };\n\n  const startWatching = () => {\n    directoryWatchers = directories.flatMap((directory) => {\n      try {\n        const directoryWatcher = watch(\n          directory,\n          { persistent: false },\n          scheduleEmit\n        );\n        // Unhandled, a watcher error would crash the dev server: losing the\n        // bridge only brings back the restart this works around.\n        directoryWatcher.on('error', () => directoryWatcher.close());\n\n        return [directoryWatcher];\n      } catch {\n        return [];\n      }\n    });\n  };\n\n  return (listener: (changedFiles: ChangedFilesLike) => void) => {\n    if (listeners.size === 0) startWatching();\n    listeners.add(listener);\n\n    return () => {\n      listeners.delete(listener);\n\n      if (listeners.size > 0) return;\n\n      for (const directoryWatcher of directoryWatchers)\n        directoryWatcher.close();\n      directoryWatchers = [];\n      clearTimeout(settleTimeout);\n    };\n  };\n};\n\n/**\n * `@angular/build` watcher modules of the builders loaded in this process.\n * Located from the module cache rather than resolved, so the wrap hits the\n * copy the running builder uses even when several are installed.\n */\nconst getAngularWatcherModules = (): AngularWatcherModule[] => {\n  const require = createRequire(import.meta.url);\n\n  return Object.keys(require.cache)\n    .filter((modulePath) => modulePath.endsWith(BUILD_ACTION_MODULE_SUFFIX))\n    .flatMap((buildActionPath) => {\n      try {\n        return [\n          require(\n            join(dirname(buildActionPath), '../../tools/esbuild/watcher.js')\n          ) as AngularWatcherModule,\n        ];\n      } catch {\n        return [];\n      }\n    })\n    .filter(\n      (watcherModule) =>\n        typeof watcherModule?.createWatcher === 'function' &&\n        typeof watcherModule.ChangedFiles === 'function'\n    );\n};\n\n/**\n * Reports the declarations Intlayer rewrites under a dot-directory to the\n * Angular dev server's watcher.\n *\n * That watcher ignores `<workspace>/**\\/.*\\/**`, so a rewritten\n * `.intlayer/types` file is never reported and the TypeScript cache keeps the\n * stale declaration: a key added to a dictionary fails template type-checking\n * until `ng serve` restarts. Wrapping `createWatcher` — read by the builder\n * only once the first build is done, after plugin setup — makes it yield the\n * changed declarations too, so Angular rebuilds and re-reads them itself.\n *\n * @param directories - Absolute directories holding the generated declarations.\n * @param revisionDirectory - Directory, covered by the tsconfig `include`, that\n * receives the revision script (the module augmentation one).\n * @returns Whether a loaded Angular watcher module was wrapped.\n */\nexport const bridgeTypesToAngularWatcher = (\n  directories: string[],\n  revisionDirectory: string\n): boolean => {\n  const watcherModules = getAngularWatcherModules();\n\n  for (const watcherModule of watcherModules) {\n    const wrappableModule = watcherModule as AngularWatcherModule &\n      Record<symbol, true>;\n\n    if (wrappableModule[WRAPPED_MARKER]) continue;\n\n    const originalCreateWatcher = watcherModule.createWatcher;\n    const subscribe = createTypesChangeSource(\n      directories,\n      normalize(join(revisionDirectory, TYPES_REVISION_FILE_NAME)),\n      watcherModule.ChangedFiles\n    );\n\n    watcherModule.createWatcher = (options) =>\n      mergeInjectedChanges(originalCreateWatcher(options), subscribe);\n\n    wrappableModule[WRAPPED_MARKER] = true;\n  }\n\n  return watcherModules.length > 0;\n};\n"],"mappings":";;;;;;AAiCA,MAAM,6BAA6B;CACjC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,GAAG;;AAGV,MAAM,iBAAiB,OAAO,IAAI,iCAAiC;;AAGnE,MAAM,kBAAkB;;AAGxB,MAAa,2BAA2B;;;;;AASxC,MAAa,oBAAoB,gBAAwC;CACvE,MAAM,+BAA6B,IAAI,IAAI;CAE3C,KAAK,MAAM,aAAa,aAAa;EACnC,IAAI;EAEJ,IAAI;GACF,YAAY,YAAY,SAAS;EACnC,QAAQ;GACN;EACF;EAEA,KAAK,MAAM,YAAY,WAAW;GAChC,IAAI,CAAC,SAAS,SAAS,KAAK,KAAK,4CAC/B;GAGF,MAAM,WAAW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