angular-intlayer 9.8.2 → 9.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/esbuild/angularWatcherTypesBridge.cjs +218 -0
- package/dist/cjs/esbuild/angularWatcherTypesBridge.cjs.map +1 -0
- package/dist/cjs/esbuild/plugin.cjs +20 -13
- package/dist/cjs/esbuild/plugin.cjs.map +1 -1
- package/dist/esm/esbuild/angularWatcherTypesBridge.mjs +212 -0
- package/dist/esm/esbuild/angularWatcherTypesBridge.mjs.map +1 -0
- package/dist/esm/esbuild/plugin.mjs +20 -13
- package/dist/esm/esbuild/plugin.mjs.map +1 -1
- package/dist/types/esbuild/angularWatcherTypesBridge.d.ts +63 -0
- package/dist/types/esbuild/angularWatcherTypesBridge.d.ts.map +1 -0
- package/dist/types/esbuild/plugin.d.ts.map +1 -1
- package/package.json +9 -9
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
let node_module = require("node:module");
|
|
3
|
+
let node_path = require("node:path");
|
|
4
|
+
let node_fs = require("node:fs");
|
|
5
|
+
|
|
6
|
+
// src/esbuild/angularWatcherTypesBridge.ts
|
|
7
|
+
/** Module running `ng serve` / `ng build --watch` rebuild loops. */
|
|
8
|
+
const BUILD_ACTION_MODULE_SUFFIX = [
|
|
9
|
+
"@angular",
|
|
10
|
+
"build",
|
|
11
|
+
"src",
|
|
12
|
+
"builders",
|
|
13
|
+
"application",
|
|
14
|
+
"build-action.js"
|
|
15
|
+
].join(node_path.sep);
|
|
16
|
+
/** Marks a watcher module already wrapped, so repeated setups wrap it once. */
|
|
17
|
+
const WRAPPED_MARKER = Symbol.for("intlayer.angular.watcherWrapped");
|
|
18
|
+
/** Delay letting a burst of declaration writes settle into one rebuild. */
|
|
19
|
+
const SETTLE_DELAY_MS = 50;
|
|
20
|
+
/** Name of the script whose rewrite makes TypeScript re-check every file. */
|
|
21
|
+
const TYPES_REVISION_FILE_NAME = "angular-types-revision.d.ts";
|
|
22
|
+
/**
|
|
23
|
+
* Reads the declaration files of `directories`. A missing directory counts as
|
|
24
|
+
* empty.
|
|
25
|
+
*/
|
|
26
|
+
const readFileContents = (directories) => {
|
|
27
|
+
const fileContents = /* @__PURE__ */ new Map();
|
|
28
|
+
for (const directory of directories) {
|
|
29
|
+
let fileNames;
|
|
30
|
+
try {
|
|
31
|
+
fileNames = (0, node_fs.readdirSync)(directory);
|
|
32
|
+
} catch {
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
for (const fileName of fileNames) {
|
|
36
|
+
if (!fileName.endsWith(".ts") || fileName === "angular-types-revision.d.ts") continue;
|
|
37
|
+
const filePath = (0, node_path.normalize)((0, node_path.join)(directory, fileName));
|
|
38
|
+
try {
|
|
39
|
+
fileContents.set(filePath, (0, node_fs.readFileSync)(filePath, "utf-8"));
|
|
40
|
+
} catch {}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return fileContents;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Files added, modified or removed between two snapshots. Comparing contents
|
|
47
|
+
* rather than times keeps an identical rewrite from triggering a rebuild.
|
|
48
|
+
*/
|
|
49
|
+
const diffFileContents = (previousContents, currentContents, changedFiles) => {
|
|
50
|
+
for (const [filePath, contents] of currentContents) {
|
|
51
|
+
const previous = previousContents.get(filePath);
|
|
52
|
+
if (previous === void 0) changedFiles.added.add(filePath);
|
|
53
|
+
else if (previous !== contents) changedFiles.modified.add(filePath);
|
|
54
|
+
}
|
|
55
|
+
for (const filePath of previousContents.keys()) if (!currentContents.has(filePath)) changedFiles.removed.add(filePath);
|
|
56
|
+
return changedFiles;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Contents of the revision script. It has no import or export, so TypeScript
|
|
60
|
+
* treats it as affecting the global scope: rewriting it re-checks every file.
|
|
61
|
+
*/
|
|
62
|
+
const getTypesRevisionContents = (revision) => [
|
|
63
|
+
"// Generated by angular-intlayer. Rewritten when the dictionary types",
|
|
64
|
+
"// change, so the Angular dev server re-checks every template.",
|
|
65
|
+
`interface IntlayerAngularTypesRevision { revision: ${revision} }`,
|
|
66
|
+
""
|
|
67
|
+
].join("\n");
|
|
68
|
+
/**
|
|
69
|
+
* Wraps an Angular watcher so it also yields the batches `subscribe` reports.
|
|
70
|
+
*
|
|
71
|
+
* The rebuild loop awaits one `next()` at a time: a pending call of the
|
|
72
|
+
* original watcher is kept across calls, so no change it reports is lost when
|
|
73
|
+
* an injected batch is returned first.
|
|
74
|
+
*/
|
|
75
|
+
const mergeInjectedChanges = (angularWatcher, subscribe) => {
|
|
76
|
+
let pendingNext;
|
|
77
|
+
let queuedChanges;
|
|
78
|
+
let wakeUp;
|
|
79
|
+
const unsubscribe = subscribe((changedFiles) => {
|
|
80
|
+
if (queuedChanges) {
|
|
81
|
+
changedFiles.added.forEach((path) => queuedChanges.added.add(path));
|
|
82
|
+
changedFiles.modified.forEach((path) => queuedChanges.modified.add(path));
|
|
83
|
+
changedFiles.removed.forEach((path) => queuedChanges.removed.add(path));
|
|
84
|
+
} else queuedChanges = changedFiles;
|
|
85
|
+
wakeUp?.();
|
|
86
|
+
});
|
|
87
|
+
const bridgedWatcher = {
|
|
88
|
+
[Symbol.asyncIterator]: () => bridgedWatcher,
|
|
89
|
+
next: async () => {
|
|
90
|
+
if (!queuedChanges) {
|
|
91
|
+
pendingNext ??= angularWatcher.next();
|
|
92
|
+
await Promise.race([pendingNext, new Promise((resolve) => {
|
|
93
|
+
wakeUp = resolve;
|
|
94
|
+
})]);
|
|
95
|
+
wakeUp = void 0;
|
|
96
|
+
}
|
|
97
|
+
if (queuedChanges) {
|
|
98
|
+
const changedFiles = queuedChanges;
|
|
99
|
+
queuedChanges = void 0;
|
|
100
|
+
return {
|
|
101
|
+
value: changedFiles,
|
|
102
|
+
done: false
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
const result = await pendingNext;
|
|
106
|
+
pendingNext = void 0;
|
|
107
|
+
return result;
|
|
108
|
+
},
|
|
109
|
+
add: (paths) => angularWatcher.add(paths),
|
|
110
|
+
remove: (paths) => angularWatcher.remove(paths),
|
|
111
|
+
close: async () => {
|
|
112
|
+
unsubscribe();
|
|
113
|
+
await angularWatcher.close();
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
return bridgedWatcher;
|
|
117
|
+
};
|
|
118
|
+
/**
|
|
119
|
+
* Watches `directories` and reports each settled batch of changed
|
|
120
|
+
* declarations, one listener per running Angular watcher.
|
|
121
|
+
*/
|
|
122
|
+
const createTypesChangeSource = (directories, revisionFilePath, ChangedFiles) => {
|
|
123
|
+
let revision = 0;
|
|
124
|
+
(0, node_fs.mkdirSync)((0, node_path.dirname)(revisionFilePath), { recursive: true });
|
|
125
|
+
(0, node_fs.writeFileSync)(revisionFilePath, getTypesRevisionContents(revision));
|
|
126
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
127
|
+
let fileContents = readFileContents(directories);
|
|
128
|
+
let settleTimeout;
|
|
129
|
+
let directoryWatchers = [];
|
|
130
|
+
const emitChanges = () => {
|
|
131
|
+
const currentContents = readFileContents(directories);
|
|
132
|
+
const changedFiles = diffFileContents(fileContents, currentContents, new ChangedFiles());
|
|
133
|
+
fileContents = currentContents;
|
|
134
|
+
if (changedFiles.all.length === 0) return;
|
|
135
|
+
revision += 1;
|
|
136
|
+
(0, node_fs.writeFileSync)(revisionFilePath, getTypesRevisionContents(revision));
|
|
137
|
+
changedFiles.modified.add(revisionFilePath);
|
|
138
|
+
for (const listener of listeners) listener(changedFiles);
|
|
139
|
+
};
|
|
140
|
+
const scheduleEmit = () => {
|
|
141
|
+
clearTimeout(settleTimeout);
|
|
142
|
+
settleTimeout = setTimeout(emitChanges, SETTLE_DELAY_MS);
|
|
143
|
+
settleTimeout.unref?.();
|
|
144
|
+
};
|
|
145
|
+
const startWatching = () => {
|
|
146
|
+
directoryWatchers = directories.flatMap((directory) => {
|
|
147
|
+
try {
|
|
148
|
+
const directoryWatcher = (0, node_fs.watch)(directory, { persistent: false }, scheduleEmit);
|
|
149
|
+
directoryWatcher.on("error", () => directoryWatcher.close());
|
|
150
|
+
return [directoryWatcher];
|
|
151
|
+
} catch {
|
|
152
|
+
return [];
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
};
|
|
156
|
+
return (listener) => {
|
|
157
|
+
if (listeners.size === 0) startWatching();
|
|
158
|
+
listeners.add(listener);
|
|
159
|
+
return () => {
|
|
160
|
+
listeners.delete(listener);
|
|
161
|
+
if (listeners.size > 0) return;
|
|
162
|
+
for (const directoryWatcher of directoryWatchers) directoryWatcher.close();
|
|
163
|
+
directoryWatchers = [];
|
|
164
|
+
clearTimeout(settleTimeout);
|
|
165
|
+
};
|
|
166
|
+
};
|
|
167
|
+
};
|
|
168
|
+
/**
|
|
169
|
+
* `@angular/build` watcher modules of the builders loaded in this process.
|
|
170
|
+
* Located from the module cache rather than resolved, so the wrap hits the
|
|
171
|
+
* copy the running builder uses even when several are installed.
|
|
172
|
+
*/
|
|
173
|
+
const getAngularWatcherModules = () => {
|
|
174
|
+
const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
|
|
175
|
+
return Object.keys(require$1.cache).filter((modulePath) => modulePath.endsWith(BUILD_ACTION_MODULE_SUFFIX)).flatMap((buildActionPath) => {
|
|
176
|
+
try {
|
|
177
|
+
return [require$1((0, node_path.join)((0, node_path.dirname)(buildActionPath), "../../tools/esbuild/watcher.js"))];
|
|
178
|
+
} catch {
|
|
179
|
+
return [];
|
|
180
|
+
}
|
|
181
|
+
}).filter((watcherModule) => typeof watcherModule?.createWatcher === "function" && typeof watcherModule.ChangedFiles === "function");
|
|
182
|
+
};
|
|
183
|
+
/**
|
|
184
|
+
* Reports the declarations Intlayer rewrites under a dot-directory to the
|
|
185
|
+
* Angular dev server's watcher.
|
|
186
|
+
*
|
|
187
|
+
* That watcher ignores `<workspace>/**\/.*\/**`, so a rewritten
|
|
188
|
+
* `.intlayer/types` file is never reported and the TypeScript cache keeps the
|
|
189
|
+
* stale declaration: a key added to a dictionary fails template type-checking
|
|
190
|
+
* until `ng serve` restarts. Wrapping `createWatcher` — read by the builder
|
|
191
|
+
* only once the first build is done, after plugin setup — makes it yield the
|
|
192
|
+
* changed declarations too, so Angular rebuilds and re-reads them itself.
|
|
193
|
+
*
|
|
194
|
+
* @param directories - Absolute directories holding the generated declarations.
|
|
195
|
+
* @param revisionDirectory - Directory, covered by the tsconfig `include`, that
|
|
196
|
+
* receives the revision script (the module augmentation one).
|
|
197
|
+
* @returns Whether a loaded Angular watcher module was wrapped.
|
|
198
|
+
*/
|
|
199
|
+
const bridgeTypesToAngularWatcher = (directories, revisionDirectory) => {
|
|
200
|
+
const watcherModules = getAngularWatcherModules();
|
|
201
|
+
for (const watcherModule of watcherModules) {
|
|
202
|
+
const wrappableModule = watcherModule;
|
|
203
|
+
if (wrappableModule[WRAPPED_MARKER]) continue;
|
|
204
|
+
const originalCreateWatcher = watcherModule.createWatcher;
|
|
205
|
+
const subscribe = createTypesChangeSource(directories, (0, node_path.normalize)((0, node_path.join)(revisionDirectory, TYPES_REVISION_FILE_NAME)), watcherModule.ChangedFiles);
|
|
206
|
+
watcherModule.createWatcher = (options) => mergeInjectedChanges(originalCreateWatcher(options), subscribe);
|
|
207
|
+
wrappableModule[WRAPPED_MARKER] = true;
|
|
208
|
+
}
|
|
209
|
+
return watcherModules.length > 0;
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
exports.TYPES_REVISION_FILE_NAME = TYPES_REVISION_FILE_NAME;
|
|
213
|
+
exports.bridgeTypesToAngularWatcher = bridgeTypesToAngularWatcher;
|
|
214
|
+
exports.diffFileContents = diffFileContents;
|
|
215
|
+
exports.getTypesRevisionContents = getTypesRevisionContents;
|
|
216
|
+
exports.mergeInjectedChanges = mergeInjectedChanges;
|
|
217
|
+
exports.readFileContents = readFileContents;
|
|
218
|
+
//# sourceMappingURL=angularWatcherTypesBridge.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"angularWatcherTypesBridge.cjs","names":["sep","readdirSync","normalize","join","readFileSync","dirname","watch","require","createRequire"],"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,KAAKA,aAAG;;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,gBAAYC,qBAAY,SAAS;EACnC,QAAQ;GACN;EACF;EAEA,KAAK,MAAM,YAAY,WAAW;GAChC,IAAI,CAAC,SAAS,SAAS,KAAK,KAAK,4CAC/B;GAGF,MAAM,eAAWC,yBAAUC,gBAAK,WAAW,QAAQ,CAAC;GAEpD,IAAI;IACF,aAAa,IAAI,cAAUC,sBAAa,UAAU,OAAO,CAAC;GAC5D,QAAQ,CAER;EACF;CACF;CAEA,OAAO;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BAAoB,CAAC;GACrB,aAAa,aAAa;EAC5B;CACF;AACF;;;;;;AAOA,MAAM,iCAAyD;CAC7D,MAAMC,gBAAUC,wEAA6B;CAE7C,OAAO,OAAO,KAAKD,UAAQ,KAAK,CAAC,CAC9B,QAAQ,eAAe,WAAW,SAAS,0BAA0B,CAAC,CAAC,CACvE,SAAS,oBAAoB;EAC5B,IAAI;GACF,OAAO,CACLA,cACEJ,oBAAKE,mBAAQ,eAAe,GAAG,gCAAgC,CACjE,CACF;EACF,QAAQ;GACN,OAAO,CAAC;EACV;CACF,CAAC,CAAC,CACD,QACE,kBACC,OAAO,eAAe,kBAAkB,cACxC,OAAO,cAAc,iBAAiB,UAC1C;AACJ;;;;;;;;;;;;;;;;;AAkBA,MAAa,+BACX,aACA,sBACY;CACZ,MAAM,iBAAiB,yBAAyB;CAEhD,KAAK,MAAM,iBAAiB,gBAAgB;EAC1C,MAAM,kBAAkB;EAGxB,IAAI,gBAAgB,iBAAiB;EAErC,MAAM,wBAAwB,cAAc;EAC5C,MAAM,YAAY,wBAChB,iBACAH,yBAAUC,gBAAK,mBAAmB,wBAAwB,CAAC,GAC3D,cAAc,YAChB;EAEA,cAAc,iBAAiB,YAC7B,qBAAqB,sBAAsB,OAAO,GAAG,SAAS;EAEhE,gBAAgB,kBAAkB;CACpC;CAEA,OAAO,eAAe,SAAS;AACjC"}
|
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_esbuild_angularWatcherTypesBridge = require("./angularWatcherTypesBridge.cjs");
|
|
2
3
|
const require_esbuild_hiddenDirectory = require("./hiddenDirectory.cjs");
|
|
3
4
|
const require_esbuild_resolvePackageExport = require("./resolvePackageExport.cjs");
|
|
5
|
+
let node_fs_promises = require("node:fs/promises");
|
|
4
6
|
let node_module = require("node:module");
|
|
5
7
|
let node_path = require("node:path");
|
|
6
|
-
let _intlayer_config_node = require("@intlayer/config/node");
|
|
7
|
-
let _intlayer_config_utils = require("@intlayer/config/utils");
|
|
8
|
-
let node_fs_promises = require("node:fs/promises");
|
|
9
8
|
let _intlayer_config_dictionaryPreload = require("@intlayer/config/dictionaryPreload");
|
|
10
9
|
let _intlayer_config_envVars = require("@intlayer/config/envVars");
|
|
11
10
|
let _intlayer_config_logger = require("@intlayer/config/logger");
|
|
11
|
+
let _intlayer_config_node = require("@intlayer/config/node");
|
|
12
|
+
let _intlayer_config_utils = require("@intlayer/config/utils");
|
|
12
13
|
let _intlayer_dictionaries_entry = require("@intlayer/dictionaries-entry");
|
|
13
14
|
let _intlayer_engine_build = require("@intlayer/engine/build");
|
|
14
15
|
let _intlayer_engine_cli = require("@intlayer/engine/cli");
|
|
@@ -39,13 +40,15 @@ const DEFAULT_EXPORT_PATTERN = /\bexport\s+default\b|\bas\s+default\b|\{\s*defau
|
|
|
39
40
|
/**
|
|
40
41
|
* The dev server's file watcher skips dot-directories, so type declarations
|
|
41
42
|
* generated there are never re-read: a key added to a dictionary stays unknown
|
|
42
|
-
* to template type-checking until `ng serve` restarts.
|
|
43
|
-
*
|
|
43
|
+
* to template type-checking until `ng serve` restarts. The plugin reports the
|
|
44
|
+
* rewritten declarations to the Angular watcher itself; when no Angular
|
|
45
|
+
* watcher is loaded to bridge, it warns to generate the types elsewhere.
|
|
44
46
|
*/
|
|
45
|
-
const
|
|
47
|
+
const handleHiddenTypesDirectory = (configuration, appLogger) => {
|
|
46
48
|
const { baseDir, typesDir, moduleAugmentationDir } = configuration.system;
|
|
47
49
|
const hiddenDirectories = [.../* @__PURE__ */ new Set([typesDir, moduleAugmentationDir])].filter((directory) => require_esbuild_hiddenDirectory.isInHiddenDirectory(baseDir, directory));
|
|
48
50
|
if (hiddenDirectories.length === 0) return;
|
|
51
|
+
if (require_esbuild_angularWatcherTypesBridge.bridgeTypesToAngularWatcher(hiddenDirectories, moduleAugmentationDir)) return;
|
|
49
52
|
appLogger([
|
|
50
53
|
`Type declarations are generated under ${hiddenDirectories.map((directory) => (0, node_path.relative)(baseDir, directory)).join(", ")}.`,
|
|
51
54
|
"The Angular dev server does not watch dot-directories, so keys added to a dictionary stay unknown to template type-checking until 'ng serve' restarts.",
|
|
@@ -79,6 +82,7 @@ const intlayerEsbuildPlugin = (options) => {
|
|
|
79
82
|
let alias = null;
|
|
80
83
|
let preparePromise = null;
|
|
81
84
|
let isBuildMode = false;
|
|
85
|
+
let hasHandledHiddenTypesDirectory = false;
|
|
82
86
|
return {
|
|
83
87
|
name: "intlayer",
|
|
84
88
|
async setup(build) {
|
|
@@ -177,14 +181,17 @@ const intlayerEsbuildPlugin = (options) => {
|
|
|
177
181
|
});
|
|
178
182
|
}
|
|
179
183
|
build.onStart(async () => {
|
|
180
|
-
if (externalizesPackages === void 0) {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
184
|
+
if (externalizesPackages === void 0) externalizesPackages = (await build.resolve("@angular/core", {
|
|
185
|
+
kind: "import-statement",
|
|
186
|
+
resolveDir: config.system.baseDir
|
|
187
|
+
})).external;
|
|
188
|
+
if (options?.watch ?? !isBuildMode) {
|
|
189
|
+
(0, _intlayer_engine_utils.startContentWatcher)(config, { label: "angular-intlayer" });
|
|
190
|
+
if (!hasHandledHiddenTypesDirectory) {
|
|
191
|
+
hasHandledHiddenTypesDirectory = true;
|
|
192
|
+
handleHiddenTypesDirectory(config, appLogger);
|
|
193
|
+
}
|
|
186
194
|
}
|
|
187
|
-
if (options?.watch ?? !isBuildMode) (0, _intlayer_engine_utils.startContentWatcher)(config, { label: "angular-intlayer" });
|
|
188
195
|
});
|
|
189
196
|
}
|
|
190
197
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.cjs","names":["normalizePath","resolvePreloadModuleId","createRequire","isInHiddenDirectory","relative","getConfiguration","getAlias","join","getAppLogger","getConfigEnvVars","prepareIntlayer","getDictionaries","getUnusedNodeTypesAsync","formatNodeTypeToEnvVar","formatDictionarySelectorEnvVar","getHasDictionarySelector","resolvePackageExport","dirname","readFile","basename","createDynamicEntryFilter","addDynamicEntryPreload"],"sources":["../../../src/esbuild/plugin.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { basename, dirname, join, relative } from 'node:path';\nimport {\n addDynamicEntryPreload,\n createDynamicEntryFilter,\n resolvePreloadModuleId,\n} from '@intlayer/config/dictionaryPreload';\nimport {\n formatDictionarySelectorEnvVar,\n formatNodeTypeToEnvVar,\n getConfigEnvVars,\n} from '@intlayer/config/envVars';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n getAlias,\n getHasDictionarySelector,\n getUnusedNodeTypesAsync,\n normalizePath,\n} from '@intlayer/config/utils';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport { prepareIntlayer } from '@intlayer/engine/build';\nimport { logConfigDetails } from '@intlayer/engine/cli';\nimport { startContentWatcher } from '@intlayer/engine/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { isInHiddenDirectory } from './hiddenDirectory';\nimport { resolvePackageExport } from './resolvePackageExport';\n\n/**\n * Absolute id of the locale resolver the injected preamble imports.\n *\n * Resolved from this package, which declares `@intlayer/core` as a dependency,\n * rather than left bare in the emitted source: the importer is a generated\n * entry point under the application's `.intlayer` directory, and an application\n * only depends on `intlayer` and its framework binding, so the bare specifier\n * would resolve from a tree that need not contain the package at all.\n *\n * Always built from `import.meta.url`: the bundler shims it to `__filename` in\n * the CommonJS output, whereas a `typeof require` guard is unreliable here —\n * the ESM output rewrites `require` into an always-defined proxy that has no\n * `resolve` method.\n */\nconst preloadModuleId = normalizePath(\n resolvePreloadModuleId(createRequire(import.meta.url))\n);\n\n/** Bare specifiers of the packages this plugin keeps inside its own build. */\nconst INTLAYER_PACKAGE_FILTER =\n /^(?:intlayer|angular-intlayer|@intlayer\\/[^/]+)(?:\\/|$)/;\n\n/** Namespace of the re-export shims standing in for externalised packages. */\nconst INTLAYER_PACKAGE_NAMESPACE = 'intlayer-package';\n\n/** Matches a module that has a default export, on unminified sources. */\nconst DEFAULT_EXPORT_PATTERN =\n /\\bexport\\s+default\\b|\\bas\\s+default\\b|\\{\\s*default\\s*[,}]/;\n\n// Minimal subset of the esbuild Plugin interface to avoid a hard dependency on\n// the `esbuild` package for type resolution. The shape is compatible with\n// esbuild >=0.17, `@angular-builders/custom-esbuild`, and NX esbuild builders.\nexport type EsbuildResolveArgs = {\n path: string;\n importer: string;\n namespace: string;\n resolveDir: string;\n kind: string;\n pluginData?: unknown;\n};\n\nexport type EsbuildResolveResult = {\n path?: string;\n namespace?: string;\n external?: boolean;\n sideEffects?: boolean;\n pluginData?: unknown;\n errors?: unknown[];\n warnings?: unknown[];\n};\n\nexport type EsbuildLoadArgs = {\n path: string;\n namespace: string;\n pluginData?: unknown;\n};\n\nexport type EsbuildLoadResult = {\n contents: string;\n loader?: string;\n /** Directory relative imports of `contents` resolve from. */\n resolveDir?: string;\n};\n\nexport interface EsbuildPluginBuild {\n initialOptions: {\n alias?: Record<string, string>;\n define?: Record<string, string>;\n minify?: boolean;\n watch?: unknown;\n /** Absolute working directory of the esbuild context (set by Angular's builder). */\n absWorkingDir?: string;\n };\n onStart(callback: () => void | Promise<void>): void;\n /** Intercept module resolution — works even for imports inside node_modules. */\n onResolve(\n options: { filter: RegExp; namespace?: string },\n callback: (\n args: EsbuildResolveArgs\n ) =>\n | EsbuildResolveResult\n | null\n | undefined\n | Promise<EsbuildResolveResult | null | undefined>\n ): void;\n /** Run the remaining resolution pipeline (other plugins, then esbuild). */\n resolve(\n path: string,\n options: Partial<Omit<EsbuildResolveArgs, 'path'>>\n ): Promise<EsbuildResolveResult & { path: string; external: boolean }>;\n /** Intercept module contents, so a resolved file can be rewritten. */\n onLoad(\n options: { filter: RegExp; namespace?: string },\n callback: (\n args: EsbuildLoadArgs\n ) =>\n | EsbuildLoadResult\n | null\n | undefined\n | Promise<EsbuildLoadResult | null | undefined>\n ): void;\n}\n\nexport interface EsbuildPlugin {\n name: string;\n setup(build: EsbuildPluginBuild): void | Promise<void>;\n}\n\nexport type IntlayerEsbuildPluginOptions = {\n configOptions?: GetConfigurationOptions;\n /**\n * Whether to start the Intlayer file watcher for dictionary regeneration.\n * - `true`: always start the watcher (useful for `ng serve`)\n * - `false`: never start the watcher (useful for `ng build`)\n * - `undefined` (default): auto-detect based on the build context\n * (skips the watcher when a production build is detected)\n */\n watch?: boolean;\n};\n\n/**\n * The dev server's file watcher skips dot-directories, so type declarations\n * generated there are never re-read: a key added to a dictionary stays unknown\n * to template type-checking until `ng serve` restarts. Nothing in the plugin\n * can reach that cache, so the fix is to generate the types elsewhere.\n */\nconst warnAboutHiddenTypesDirectory = (\n configuration: IntlayerConfig,\n appLogger: ReturnType<typeof getAppLogger>\n) => {\n const { baseDir, typesDir, moduleAugmentationDir } = configuration.system;\n\n const hiddenDirectories = [\n ...new Set([typesDir, moduleAugmentationDir]),\n ].filter((directory) => isInHiddenDirectory(baseDir, directory));\n\n if (hiddenDirectories.length === 0) return;\n\n appLogger(\n [\n `Type declarations are generated under ${hiddenDirectories.map((directory) => relative(baseDir, directory)).join(', ')}.`,\n \"The Angular dev server does not watch dot-directories, so keys added to a dictionary stay unknown to template type-checking until 'ng serve' restarts.\",\n \"Set 'system.typesDir' and 'system.moduleAugmentationDir' to a directory outside any dot-directory (e.g. 'intlayer-types') and point the tsconfig 'include' at it.\",\n ].join(' '),\n { level: 'warn' }\n );\n};\n\n/**\n * esbuild plugin that integrates Intlayer into the Angular (or any esbuild-based) build process.\n *\n * Handles:\n * 1. Injecting `alias` entries so `@intlayer/dictionaries-entry` etc. resolve to\n * the generated files under `.intlayer/`.\n * 2. Defining `process.env.*` tree-shaking constants for production builds.\n * 3. Running `prepareIntlayer` (dictionary generation) before the first build.\n * 4. Starting the chokidar file-watcher in dev / serve mode.\n *\n * Compatible with:\n * - `@angular-builders/custom-esbuild` (`application` or `browser-esbuild` builder)\n * - NX `@nx/angular:browser-esbuild`\n * - Any raw esbuild setup that accepts the standard `Plugin` interface\n *\n * @example\n * ```ts\n * // esbuild.plugins.ts (referenced from angular.json \"plugins\" option)\n * import { intlayerEsbuildPlugin } from 'angular-intlayer/esbuild';\n * export default [intlayerEsbuildPlugin()];\n * ```\n */\nexport const intlayerEsbuildPlugin = (\n options?: IntlayerEsbuildPluginOptions\n): EsbuildPlugin => {\n // All Node.js-heavy initialization (getConfiguration, getAlias, …) is deferred\n // into setup() so it runs in esbuild's Node.js context, not at module-evaluation\n // time. @angular/build loads the plugin file through Vite's SSR module runner\n // (ESM) where CommonJS globals like __filename are undefined. Calling\n // getConfiguration() here would trigger: buildSync → worker threads →\n // __filename → ReferenceError, crashing the plugin before setup() ever runs.\n let config: ReturnType<typeof getConfiguration> | null = null;\n let alias: Record<string, string> | null = null;\n\n // Shared across parallel setup() calls (Angular spawns one per bundle context).\n let preparePromise: Promise<void> | null = null;\n // Once any esbuild context (browser or server) detects a production build,\n // suppress the watcher for all contexts so `ng build` can exit cleanly.\n let isBuildMode = false;\n\n return {\n name: 'intlayer',\n\n async setup(build) {\n if (!config) {\n const baseDir =\n build.initialOptions.absWorkingDir ??\n options?.configOptions?.baseDir ??\n process.cwd();\n\n config = getConfiguration({ baseDir, ...options?.configOptions });\n logConfigDetails({ baseDir, ...options?.configOptions });\n\n alias = getAlias({\n configuration: config,\n formatter: (value: string) => join(config!.system.baseDir, value),\n });\n }\n\n const appLogger = getAppLogger(config);\n const nodeEnvDefine =\n build.initialOptions.define?.['process.env.NODE_ENV'];\n\n // Angular's esbuild builder doesn't set `minify` or `process.env.NODE_ENV`\n // on initialOptions — it handles optimisation through its own pipeline.\n // Instead, Angular defines `ngDevMode` as `\"false\"` in production builds.\n const isProduction =\n nodeEnvDefine === '\"production\"' ||\n nodeEnvDefine === \"'production'\" ||\n build.initialOptions.minify === true ||\n build.initialOptions.define?.['ngDevMode'] === 'false';\n\n if (isProduction) {\n isBuildMode = true;\n }\n\n const wrapKey = (key: string) => `process.env.${key}`;\n const wrapValue = (value: string) => `\"${value}\"`;\n\n const envVars: Record<string, string> = {\n // Catch-all so that any `process.env.*` read NOT covered by a specific\n // key below resolves to `undefined` instead of dereferencing a bare\n // `process`, which is not defined in browser bundles and throws\n // `process is not defined`. esbuild resolves the most specific define\n // first, so the keys below keep their tree-shaking effect.\n 'process.env': '{}',\n [wrapKey('INTLAYER')]: wrapValue('true'),\n [wrapKey('NODE_ENV')]: wrapValue(\n isProduction ? 'production' : 'development'\n ),\n // Tree shaking flags derived from the config (routing / storage /\n // editor). Emitted in every mode so behaviour is consistent in dev.\n ...getConfigEnvVars(config, wrapKey, wrapValue),\n };\n\n // Dictionaries must exist on disk before the tree-shaking flags below\n // are derived from them: on a clean checkout (CI, Vercel…) nothing is\n // generated yet, so reading them first reports every node type as\n // unused and strips the translation plugin from the production bundle.\n if (!preparePromise) {\n preparePromise = prepareIntlayer(config, {\n clean: isProduction,\n cacheTimeoutMs: isProduction ? 1000 * 30 : 1000 * 60 * 60,\n env: isProduction ? 'prod' : 'dev',\n });\n }\n\n await preparePromise;\n\n if (isProduction) {\n const dictionaries = getDictionaries(config);\n if (Object.keys(dictionaries).length === 0) {\n appLogger('No dictionaries found. Please check your configuration.', {\n isVerbose: true,\n });\n }\n\n const unusedNodeTypes = await getUnusedNodeTypesAsync(dictionaries);\n Object.assign(\n envVars,\n // Tree shaking based on unused node types\n formatNodeTypeToEnvVar(unusedNodeTypes, wrapKey, wrapValue),\n // Tree shaking the dictionary selector logic\n // (collections / variants)\n formatDictionarySelectorEnvVar(\n getHasDictionarySelector(dictionaries),\n wrapKey,\n wrapValue\n )\n );\n }\n\n // Existing defines (Angular's own, or the user's angular.json `define`\n // block) take precedence over the Intlayer ones.\n build.initialOptions.define = {\n ...envVars,\n ...(build.initialOptions.define ?? {}),\n };\n\n build.initialOptions.alias = {\n ...alias,\n ...(build.initialOptions.alias ?? {}),\n };\n\n for (const [from, to] of Object.entries(alias!)) {\n const escapedFrom = from.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n build.onResolve({ filter: new RegExp(`^${escapedFrom}$`) }, () => ({\n path: to,\n }));\n }\n\n // Angular's dev server marks every import that resolves under\n // `node_modules` as external so Vite can pre-bundle it. Vite's\n // pre-bundler runs without this plugin, so the aliases above never apply\n // there and the real `@intlayer/config/built` — a Node config loader —\n // ends up in the browser. Angular's externalising plugin is registered\n // ahead of this one and only lets a resolution through when the path it\n // gets back is outside `node_modules`; so in that mode an Intlayer\n // package resolves to a re-export shim in its own namespace, whose\n // relative import of the real file the pipeline then bundles as usual.\n // Whether the pipeline externalises packages is probed once, at the\n // first build, so production builds keep the bundler's own resolution.\n let externalizesPackages: boolean | undefined;\n\n build.onResolve({ filter: INTLAYER_PACKAGE_FILTER }, (args) => {\n if (!externalizesPackages || !args.resolveDir) return null;\n\n const importCondition = args.kind.startsWith('require')\n ? 'require'\n : 'import';\n const resolved = resolvePackageExport(args.path, args.resolveDir, [\n 'browser',\n 'module',\n importCondition,\n ]);\n\n if (!resolved) return null;\n\n return {\n // Neither a `node_modules` segment nor a script extension, which the\n // externalising plugin and Angular's own JS loader key on. Ends with\n // the specifier so a lazy chunk is named after it, and starts with\n // the encoded directory so two copies of a package stay distinct.\n path: `${encodeURIComponent(dirname(resolved.path))}/${args.path}`,\n namespace: INTLAYER_PACKAGE_NAMESPACE,\n pluginData: { realPath: resolved.path },\n sideEffects: resolved.sideEffects,\n };\n });\n\n build.onLoad(\n { filter: /.*/, namespace: INTLAYER_PACKAGE_NAMESPACE },\n async (args) => {\n const { realPath } = args.pluginData as { realPath: string };\n const source = await readFile(realPath, 'utf-8');\n const specifier = JSON.stringify(`./${basename(realPath)}`);\n\n const contents = [\n `export * from ${specifier};`,\n DEFAULT_EXPORT_PATTERN.test(source) &&\n `export { default } from ${specifier};`,\n ]\n .filter(Boolean)\n .join('\\n');\n\n return { contents, loader: 'js', resolveDir: dirname(realPath) };\n }\n );\n\n // Dictionaries load with the chunk that needs them rather than being\n // fetched once that chunk renders: the entry point starts the browsing\n // locale's load as it evaluates, so a lazily loaded route requests its\n // content on `import()` instead of on first render. Without it every\n // dictionary read renders an empty placeholder first and fills in a tick\n // later.\n //\n // Not gated on the configured `importMode`: a `.content` file can set\n // `importMode: 'dynamic'` on a single dictionary under a `static` or\n // `fetch` global mode, and that dictionary needs the preload just the\n // same. Only entry points the optimizer imported are ever loaded, so the\n // path check below is the accurate gate.\n if (config.build.dictionariesPreload) {\n const dynamicDictionariesDir = normalizePath(\n config.system.dynamicDictionariesDir\n );\n\n build.onLoad(\n { filter: createDynamicEntryFilter(dynamicDictionariesDir) },\n async ({ path }) => {\n const posixPath = normalizePath(path);\n if (!posixPath.startsWith(`${dynamicDictionariesDir}/`))\n return null;\n\n const code = await readFile(path, 'utf-8');\n const result = addDynamicEntryPreload(code, preloadModuleId);\n\n if (result.skipped) return null;\n\n return { contents: result.code, loader: 'js' };\n }\n );\n }\n\n build.onStart(async () => {\n // `@angular/core` is always installed and never worth excluding from\n // pre-bundling, so its fate tells whether packages get externalised.\n if (externalizesPackages === undefined) {\n externalizesPackages = (\n await build.resolve('@angular/core', {\n kind: 'import-statement',\n resolveDir: config!.system.baseDir,\n })\n ).external;\n\n if (externalizesPackages) {\n warnAboutHiddenTypesDirectory(config!, appLogger);\n }\n }\n\n // Determine whether the watcher should run:\n // 1. Explicit option from the caller takes precedence\n // 2. If any esbuild context detected a production build, skip\n // 3. esbuild's own watch mode is a positive signal\n const shouldWatch = options?.watch ?? !isBuildMode;\n\n if (shouldWatch) {\n startContentWatcher(config!, { label: 'angular-intlayer' });\n }\n });\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,sBAAkBA,0CACtBC,+DAAuBC,wEAA6B,CAAC,CACvD;;AAGA,MAAM,0BACJ;;AAGF,MAAM,6BAA6B;;AAGnC,MAAM,yBACJ;;;;;;;AAmGF,MAAM,iCACJ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;AACF"}
|
|
1
|
+
{"version":3,"file":"plugin.cjs","names":["normalizePath","resolvePreloadModuleId","createRequire","isInHiddenDirectory","bridgeTypesToAngularWatcher","relative","getConfiguration","getAlias","join","getAppLogger","getConfigEnvVars","prepareIntlayer","getDictionaries","getUnusedNodeTypesAsync","formatNodeTypeToEnvVar","formatDictionarySelectorEnvVar","getHasDictionarySelector","resolvePackageExport","dirname","readFile","basename","createDynamicEntryFilter","addDynamicEntryPreload"],"sources":["../../../src/esbuild/plugin.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { basename, dirname, join, relative } from 'node:path';\nimport {\n addDynamicEntryPreload,\n createDynamicEntryFilter,\n resolvePreloadModuleId,\n} from '@intlayer/config/dictionaryPreload';\nimport {\n formatDictionarySelectorEnvVar,\n formatNodeTypeToEnvVar,\n getConfigEnvVars,\n} from '@intlayer/config/envVars';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n getAlias,\n getHasDictionarySelector,\n getUnusedNodeTypesAsync,\n normalizePath,\n} from '@intlayer/config/utils';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport { prepareIntlayer } from '@intlayer/engine/build';\nimport { logConfigDetails } from '@intlayer/engine/cli';\nimport { startContentWatcher } from '@intlayer/engine/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { bridgeTypesToAngularWatcher } from './angularWatcherTypesBridge';\nimport { isInHiddenDirectory } from './hiddenDirectory';\nimport { resolvePackageExport } from './resolvePackageExport';\n\n/**\n * Absolute id of the locale resolver the injected preamble imports.\n *\n * Resolved from this package, which declares `@intlayer/core` as a dependency,\n * rather than left bare in the emitted source: the importer is a generated\n * entry point under the application's `.intlayer` directory, and an application\n * only depends on `intlayer` and its framework binding, so the bare specifier\n * would resolve from a tree that need not contain the package at all.\n *\n * Always built from `import.meta.url`: the bundler shims it to `__filename` in\n * the CommonJS output, whereas a `typeof require` guard is unreliable here —\n * the ESM output rewrites `require` into an always-defined proxy that has no\n * `resolve` method.\n */\nconst preloadModuleId = normalizePath(\n resolvePreloadModuleId(createRequire(import.meta.url))\n);\n\n/** Bare specifiers of the packages this plugin keeps inside its own build. */\nconst INTLAYER_PACKAGE_FILTER =\n /^(?:intlayer|angular-intlayer|@intlayer\\/[^/]+)(?:\\/|$)/;\n\n/** Namespace of the re-export shims standing in for externalised packages. */\nconst INTLAYER_PACKAGE_NAMESPACE = 'intlayer-package';\n\n/** Matches a module that has a default export, on unminified sources. */\nconst DEFAULT_EXPORT_PATTERN =\n /\\bexport\\s+default\\b|\\bas\\s+default\\b|\\{\\s*default\\s*[,}]/;\n\n// Minimal subset of the esbuild Plugin interface to avoid a hard dependency on\n// the `esbuild` package for type resolution. The shape is compatible with\n// esbuild >=0.17, `@angular-builders/custom-esbuild`, and NX esbuild builders.\nexport type EsbuildResolveArgs = {\n path: string;\n importer: string;\n namespace: string;\n resolveDir: string;\n kind: string;\n pluginData?: unknown;\n};\n\nexport type EsbuildResolveResult = {\n path?: string;\n namespace?: string;\n external?: boolean;\n sideEffects?: boolean;\n pluginData?: unknown;\n errors?: unknown[];\n warnings?: unknown[];\n};\n\nexport type EsbuildLoadArgs = {\n path: string;\n namespace: string;\n pluginData?: unknown;\n};\n\nexport type EsbuildLoadResult = {\n contents: string;\n loader?: string;\n /** Directory relative imports of `contents` resolve from. */\n resolveDir?: string;\n};\n\nexport interface EsbuildPluginBuild {\n initialOptions: {\n alias?: Record<string, string>;\n define?: Record<string, string>;\n minify?: boolean;\n watch?: unknown;\n /** Absolute working directory of the esbuild context (set by Angular's builder). */\n absWorkingDir?: string;\n };\n onStart(callback: () => void | Promise<void>): void;\n /** Intercept module resolution — works even for imports inside node_modules. */\n onResolve(\n options: { filter: RegExp; namespace?: string },\n callback: (\n args: EsbuildResolveArgs\n ) =>\n | EsbuildResolveResult\n | null\n | undefined\n | Promise<EsbuildResolveResult | null | undefined>\n ): void;\n /** Run the remaining resolution pipeline (other plugins, then esbuild). */\n resolve(\n path: string,\n options: Partial<Omit<EsbuildResolveArgs, 'path'>>\n ): Promise<EsbuildResolveResult & { path: string; external: boolean }>;\n /** Intercept module contents, so a resolved file can be rewritten. */\n onLoad(\n options: { filter: RegExp; namespace?: string },\n callback: (\n args: EsbuildLoadArgs\n ) =>\n | EsbuildLoadResult\n | null\n | undefined\n | Promise<EsbuildLoadResult | null | undefined>\n ): void;\n}\n\nexport interface EsbuildPlugin {\n name: string;\n setup(build: EsbuildPluginBuild): void | Promise<void>;\n}\n\nexport type IntlayerEsbuildPluginOptions = {\n configOptions?: GetConfigurationOptions;\n /**\n * Whether to start the Intlayer file watcher for dictionary regeneration.\n * - `true`: always start the watcher (useful for `ng serve`)\n * - `false`: never start the watcher (useful for `ng build`)\n * - `undefined` (default): auto-detect based on the build context\n * (skips the watcher when a production build is detected)\n */\n watch?: boolean;\n};\n\n/**\n * The dev server's file watcher skips dot-directories, so type declarations\n * generated there are never re-read: a key added to a dictionary stays unknown\n * to template type-checking until `ng serve` restarts. The plugin reports the\n * rewritten declarations to the Angular watcher itself; when no Angular\n * watcher is loaded to bridge, it warns to generate the types elsewhere.\n */\nconst handleHiddenTypesDirectory = (\n configuration: IntlayerConfig,\n appLogger: ReturnType<typeof getAppLogger>\n) => {\n const { baseDir, typesDir, moduleAugmentationDir } = configuration.system;\n\n const hiddenDirectories = [\n ...new Set([typesDir, moduleAugmentationDir]),\n ].filter((directory) => isInHiddenDirectory(baseDir, directory));\n\n if (hiddenDirectories.length === 0) return;\n\n if (bridgeTypesToAngularWatcher(hiddenDirectories, moduleAugmentationDir)) {\n return;\n }\n\n appLogger(\n [\n `Type declarations are generated under ${hiddenDirectories.map((directory) => relative(baseDir, directory)).join(', ')}.`,\n \"The Angular dev server does not watch dot-directories, so keys added to a dictionary stay unknown to template type-checking until 'ng serve' restarts.\",\n \"Set 'system.typesDir' and 'system.moduleAugmentationDir' to a directory outside any dot-directory (e.g. 'intlayer-types') and point the tsconfig 'include' at it.\",\n ].join(' '),\n { level: 'warn' }\n );\n};\n\n/**\n * esbuild plugin that integrates Intlayer into the Angular (or any esbuild-based) build process.\n *\n * Handles:\n * 1. Injecting `alias` entries so `@intlayer/dictionaries-entry` etc. resolve to\n * the generated files under `.intlayer/`.\n * 2. Defining `process.env.*` tree-shaking constants for production builds.\n * 3. Running `prepareIntlayer` (dictionary generation) before the first build.\n * 4. Starting the chokidar file-watcher in dev / serve mode.\n *\n * Compatible with:\n * - `@angular-builders/custom-esbuild` (`application` or `browser-esbuild` builder)\n * - NX `@nx/angular:browser-esbuild`\n * - Any raw esbuild setup that accepts the standard `Plugin` interface\n *\n * @example\n * ```ts\n * // esbuild.plugins.ts (referenced from angular.json \"plugins\" option)\n * import { intlayerEsbuildPlugin } from 'angular-intlayer/esbuild';\n * export default [intlayerEsbuildPlugin()];\n * ```\n */\nexport const intlayerEsbuildPlugin = (\n options?: IntlayerEsbuildPluginOptions\n): EsbuildPlugin => {\n // All Node.js-heavy initialization (getConfiguration, getAlias, …) is deferred\n // into setup() so it runs in esbuild's Node.js context, not at module-evaluation\n // time. @angular/build loads the plugin file through Vite's SSR module runner\n // (ESM) where CommonJS globals like __filename are undefined. Calling\n // getConfiguration() here would trigger: buildSync → worker threads →\n // __filename → ReferenceError, crashing the plugin before setup() ever runs.\n let config: ReturnType<typeof getConfiguration> | null = null;\n let alias: Record<string, string> | null = null;\n\n // Shared across parallel setup() calls (Angular spawns one per bundle context).\n let preparePromise: Promise<void> | null = null;\n // Once any esbuild context (browser or server) detects a production build,\n // suppress the watcher for all contexts so `ng build` can exit cleanly.\n let isBuildMode = false;\n // The dev server rebuild loop is bridged once, whatever the context count.\n let hasHandledHiddenTypesDirectory = false;\n\n return {\n name: 'intlayer',\n\n async setup(build) {\n if (!config) {\n const baseDir =\n build.initialOptions.absWorkingDir ??\n options?.configOptions?.baseDir ??\n process.cwd();\n\n config = getConfiguration({ baseDir, ...options?.configOptions });\n logConfigDetails({ baseDir, ...options?.configOptions });\n\n alias = getAlias({\n configuration: config,\n formatter: (value: string) => join(config!.system.baseDir, value),\n });\n }\n\n const appLogger = getAppLogger(config);\n const nodeEnvDefine =\n build.initialOptions.define?.['process.env.NODE_ENV'];\n\n // Angular's esbuild builder doesn't set `minify` or `process.env.NODE_ENV`\n // on initialOptions — it handles optimisation through its own pipeline.\n // Instead, Angular defines `ngDevMode` as `\"false\"` in production builds.\n const isProduction =\n nodeEnvDefine === '\"production\"' ||\n nodeEnvDefine === \"'production'\" ||\n build.initialOptions.minify === true ||\n build.initialOptions.define?.['ngDevMode'] === 'false';\n\n if (isProduction) {\n isBuildMode = true;\n }\n\n const wrapKey = (key: string) => `process.env.${key}`;\n const wrapValue = (value: string) => `\"${value}\"`;\n\n const envVars: Record<string, string> = {\n // Catch-all so that any `process.env.*` read NOT covered by a specific\n // key below resolves to `undefined` instead of dereferencing a bare\n // `process`, which is not defined in browser bundles and throws\n // `process is not defined`. esbuild resolves the most specific define\n // first, so the keys below keep their tree-shaking effect.\n 'process.env': '{}',\n [wrapKey('INTLAYER')]: wrapValue('true'),\n [wrapKey('NODE_ENV')]: wrapValue(\n isProduction ? 'production' : 'development'\n ),\n // Tree shaking flags derived from the config (routing / storage /\n // editor). Emitted in every mode so behaviour is consistent in dev.\n ...getConfigEnvVars(config, wrapKey, wrapValue),\n };\n\n // Dictionaries must exist on disk before the tree-shaking flags below\n // are derived from them: on a clean checkout (CI, Vercel…) nothing is\n // generated yet, so reading them first reports every node type as\n // unused and strips the translation plugin from the production bundle.\n if (!preparePromise) {\n preparePromise = prepareIntlayer(config, {\n clean: isProduction,\n cacheTimeoutMs: isProduction ? 1000 * 30 : 1000 * 60 * 60,\n env: isProduction ? 'prod' : 'dev',\n });\n }\n\n await preparePromise;\n\n if (isProduction) {\n const dictionaries = getDictionaries(config);\n if (Object.keys(dictionaries).length === 0) {\n appLogger('No dictionaries found. Please check your configuration.', {\n isVerbose: true,\n });\n }\n\n const unusedNodeTypes = await getUnusedNodeTypesAsync(dictionaries);\n Object.assign(\n envVars,\n // Tree shaking based on unused node types\n formatNodeTypeToEnvVar(unusedNodeTypes, wrapKey, wrapValue),\n // Tree shaking the dictionary selector logic\n // (collections / variants)\n formatDictionarySelectorEnvVar(\n getHasDictionarySelector(dictionaries),\n wrapKey,\n wrapValue\n )\n );\n }\n\n // Existing defines (Angular's own, or the user's angular.json `define`\n // block) take precedence over the Intlayer ones.\n build.initialOptions.define = {\n ...envVars,\n ...(build.initialOptions.define ?? {}),\n };\n\n build.initialOptions.alias = {\n ...alias,\n ...(build.initialOptions.alias ?? {}),\n };\n\n for (const [from, to] of Object.entries(alias!)) {\n const escapedFrom = from.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n build.onResolve({ filter: new RegExp(`^${escapedFrom}$`) }, () => ({\n path: to,\n }));\n }\n\n // Angular's dev server marks every import that resolves under\n // `node_modules` as external so Vite can pre-bundle it. Vite's\n // pre-bundler runs without this plugin, so the aliases above never apply\n // there and the real `@intlayer/config/built` — a Node config loader —\n // ends up in the browser. Angular's externalising plugin is registered\n // ahead of this one and only lets a resolution through when the path it\n // gets back is outside `node_modules`; so in that mode an Intlayer\n // package resolves to a re-export shim in its own namespace, whose\n // relative import of the real file the pipeline then bundles as usual.\n // Whether the pipeline externalises packages is probed once, at the\n // first build, so production builds keep the bundler's own resolution.\n let externalizesPackages: boolean | undefined;\n\n build.onResolve({ filter: INTLAYER_PACKAGE_FILTER }, (args) => {\n if (!externalizesPackages || !args.resolveDir) return null;\n\n const importCondition = args.kind.startsWith('require')\n ? 'require'\n : 'import';\n const resolved = resolvePackageExport(args.path, args.resolveDir, [\n 'browser',\n 'module',\n importCondition,\n ]);\n\n if (!resolved) return null;\n\n return {\n // Neither a `node_modules` segment nor a script extension, which the\n // externalising plugin and Angular's own JS loader key on. Ends with\n // the specifier so a lazy chunk is named after it, and starts with\n // the encoded directory so two copies of a package stay distinct.\n path: `${encodeURIComponent(dirname(resolved.path))}/${args.path}`,\n namespace: INTLAYER_PACKAGE_NAMESPACE,\n pluginData: { realPath: resolved.path },\n sideEffects: resolved.sideEffects,\n };\n });\n\n build.onLoad(\n { filter: /.*/, namespace: INTLAYER_PACKAGE_NAMESPACE },\n async (args) => {\n const { realPath } = args.pluginData as { realPath: string };\n const source = await readFile(realPath, 'utf-8');\n const specifier = JSON.stringify(`./${basename(realPath)}`);\n\n const contents = [\n `export * from ${specifier};`,\n DEFAULT_EXPORT_PATTERN.test(source) &&\n `export { default } from ${specifier};`,\n ]\n .filter(Boolean)\n .join('\\n');\n\n return { contents, loader: 'js', resolveDir: dirname(realPath) };\n }\n );\n\n // Dictionaries load with the chunk that needs them rather than being\n // fetched once that chunk renders: the entry point starts the browsing\n // locale's load as it evaluates, so a lazily loaded route requests its\n // content on `import()` instead of on first render. Without it every\n // dictionary read renders an empty placeholder first and fills in a tick\n // later.\n //\n // Not gated on the configured `importMode`: a `.content` file can set\n // `importMode: 'dynamic'` on a single dictionary under a `static` or\n // `fetch` global mode, and that dictionary needs the preload just the\n // same. Only entry points the optimizer imported are ever loaded, so the\n // path check below is the accurate gate.\n if (config.build.dictionariesPreload) {\n const dynamicDictionariesDir = normalizePath(\n config.system.dynamicDictionariesDir\n );\n\n build.onLoad(\n { filter: createDynamicEntryFilter(dynamicDictionariesDir) },\n async ({ path }) => {\n const posixPath = normalizePath(path);\n if (!posixPath.startsWith(`${dynamicDictionariesDir}/`))\n return null;\n\n const code = await readFile(path, 'utf-8');\n const result = addDynamicEntryPreload(code, preloadModuleId);\n\n if (result.skipped) return null;\n\n return { contents: result.code, loader: 'js' };\n }\n );\n }\n\n build.onStart(async () => {\n // `@angular/core` is always installed and never worth excluding from\n // pre-bundling, so its fate tells whether packages get externalised.\n if (externalizesPackages === undefined) {\n externalizesPackages = (\n await build.resolve('@angular/core', {\n kind: 'import-statement',\n resolveDir: config!.system.baseDir,\n })\n ).external;\n }\n\n // Determine whether the watcher should run:\n // 1. Explicit option from the caller takes precedence\n // 2. If any esbuild context detected a production build, skip\n // 3. esbuild's own watch mode is a positive signal\n const shouldWatch = options?.watch ?? !isBuildMode;\n\n if (shouldWatch) {\n startContentWatcher(config!, { label: 'angular-intlayer' });\n\n if (!hasHandledHiddenTypesDirectory) {\n hasHandledHiddenTypesDirectory = true;\n handleHiddenTypesDirectory(config!, appLogger);\n }\n }\n });\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAM,sBAAkBA,0CACtBC,+DAAuBC,wEAA6B,CAAC,CACvD;;AAGA,MAAM,0BACJ;;AAGF,MAAM,6BAA6B;;AAGnC,MAAM,yBACJ;;;;;;;;AAoGF,MAAM,8BACJ,eACA,cACG;CACH,MAAM,EAAE,SAAS,UAAU,0BAA0B,cAAc;CAEnE,MAAM,oBAAoB,CACxB,mBAAG,IAAI,IAAI,CAAC,UAAU,qBAAqB,CAAC,CAC9C,CAAC,CAAC,QAAQ,cAAcC,oDAAoB,SAAS,SAAS,CAAC;CAE/D,IAAI,kBAAkB,WAAW,GAAG;CAEpC,IAAIC,sEAA4B,mBAAmB,qBAAqB,GACtE;CAGF,UACE;EACE,yCAAyC,kBAAkB,KAAK,kBAAcC,oBAAS,SAAS,SAAS,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE;EACvH;EACA;CACF,CAAC,CAAC,KAAK,GAAG,GACV,EAAE,OAAO,OAAO,CAClB;AACF;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,yBACX,YACkB;CAOlB,IAAI,SAAqD;CACzD,IAAI,QAAuC;CAG3C,IAAI,iBAAuC;CAG3C,IAAI,cAAc;CAElB,IAAI,iCAAiC;CAErC,OAAO;EACL,MAAM;EAEN,MAAM,MAAM,OAAO;GACjB,IAAI,CAAC,QAAQ;IACX,MAAM,UACJ,MAAM,eAAe,iBACrB,SAAS,eAAe,WACxB,QAAQ,IAAI;IAEd,aAASC,wCAAiB;KAAE;KAAS,GAAG,SAAS;IAAc,CAAC;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AAuB,EAAE,GACpD,OAAO;KAET,MAAM,OAAO,UAAMmB,2BAAS,MAAM,OAAO;KACzC,MAAM,aAASG,2DAAuB,MAAM,eAAe;KAE3D,IAAI,OAAO,SAAS,OAAO;KAE3B,OAAO;MAAE,UAAU,OAAO;MAAM,QAAQ;KAAK;IAC/C,CACF;GACF;GAEA,MAAM,QAAQ,YAAY;IAGxB,IAAI,yBAAyB,QAC3B,wBACE,MAAM,MAAM,QAAQ,iBAAiB;KACnC,MAAM;KACN,YAAY,OAAQ,OAAO;IAC7B,CAAC,EAAC,CACF;IASJ,IAFoB,SAAS,SAAS,CAAC,aAEtB;KACf,gDAAoB,QAAS,EAAE,OAAO,mBAAmB,CAAC;KAE1D,IAAI,CAAC,gCAAgC;MACnC,iCAAiC;MACjC,2BAA2B,QAAS,SAAS;KAC/C;IACF;GACF,CAAC;EACH;CACF;AACF"}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { dirname, join, normalize, sep } from "node:path";
|
|
3
|
+
import { mkdirSync, readFileSync, readdirSync, watch, writeFileSync } from "node:fs";
|
|
4
|
+
|
|
5
|
+
// src/esbuild/angularWatcherTypesBridge.ts
|
|
6
|
+
/** Module running `ng serve` / `ng build --watch` rebuild loops. */
|
|
7
|
+
const BUILD_ACTION_MODULE_SUFFIX = [
|
|
8
|
+
"@angular",
|
|
9
|
+
"build",
|
|
10
|
+
"src",
|
|
11
|
+
"builders",
|
|
12
|
+
"application",
|
|
13
|
+
"build-action.js"
|
|
14
|
+
].join(sep);
|
|
15
|
+
/** Marks a watcher module already wrapped, so repeated setups wrap it once. */
|
|
16
|
+
const WRAPPED_MARKER = Symbol.for("intlayer.angular.watcherWrapped");
|
|
17
|
+
/** Delay letting a burst of declaration writes settle into one rebuild. */
|
|
18
|
+
const SETTLE_DELAY_MS = 50;
|
|
19
|
+
/** Name of the script whose rewrite makes TypeScript re-check every file. */
|
|
20
|
+
const TYPES_REVISION_FILE_NAME = "angular-types-revision.d.ts";
|
|
21
|
+
/**
|
|
22
|
+
* Reads the declaration files of `directories`. A missing directory counts as
|
|
23
|
+
* empty.
|
|
24
|
+
*/
|
|
25
|
+
const readFileContents = (directories) => {
|
|
26
|
+
const fileContents = /* @__PURE__ */ new Map();
|
|
27
|
+
for (const directory of directories) {
|
|
28
|
+
let fileNames;
|
|
29
|
+
try {
|
|
30
|
+
fileNames = readdirSync(directory);
|
|
31
|
+
} catch {
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
for (const fileName of fileNames) {
|
|
35
|
+
if (!fileName.endsWith(".ts") || fileName === "angular-types-revision.d.ts") continue;
|
|
36
|
+
const filePath = normalize(join(directory, fileName));
|
|
37
|
+
try {
|
|
38
|
+
fileContents.set(filePath, readFileSync(filePath, "utf-8"));
|
|
39
|
+
} catch {}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return fileContents;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Files added, modified or removed between two snapshots. Comparing contents
|
|
46
|
+
* rather than times keeps an identical rewrite from triggering a rebuild.
|
|
47
|
+
*/
|
|
48
|
+
const diffFileContents = (previousContents, currentContents, changedFiles) => {
|
|
49
|
+
for (const [filePath, contents] of currentContents) {
|
|
50
|
+
const previous = previousContents.get(filePath);
|
|
51
|
+
if (previous === void 0) changedFiles.added.add(filePath);
|
|
52
|
+
else if (previous !== contents) changedFiles.modified.add(filePath);
|
|
53
|
+
}
|
|
54
|
+
for (const filePath of previousContents.keys()) if (!currentContents.has(filePath)) changedFiles.removed.add(filePath);
|
|
55
|
+
return changedFiles;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Contents of the revision script. It has no import or export, so TypeScript
|
|
59
|
+
* treats it as affecting the global scope: rewriting it re-checks every file.
|
|
60
|
+
*/
|
|
61
|
+
const getTypesRevisionContents = (revision) => [
|
|
62
|
+
"// Generated by angular-intlayer. Rewritten when the dictionary types",
|
|
63
|
+
"// change, so the Angular dev server re-checks every template.",
|
|
64
|
+
`interface IntlayerAngularTypesRevision { revision: ${revision} }`,
|
|
65
|
+
""
|
|
66
|
+
].join("\n");
|
|
67
|
+
/**
|
|
68
|
+
* Wraps an Angular watcher so it also yields the batches `subscribe` reports.
|
|
69
|
+
*
|
|
70
|
+
* The rebuild loop awaits one `next()` at a time: a pending call of the
|
|
71
|
+
* original watcher is kept across calls, so no change it reports is lost when
|
|
72
|
+
* an injected batch is returned first.
|
|
73
|
+
*/
|
|
74
|
+
const mergeInjectedChanges = (angularWatcher, subscribe) => {
|
|
75
|
+
let pendingNext;
|
|
76
|
+
let queuedChanges;
|
|
77
|
+
let wakeUp;
|
|
78
|
+
const unsubscribe = subscribe((changedFiles) => {
|
|
79
|
+
if (queuedChanges) {
|
|
80
|
+
changedFiles.added.forEach((path) => queuedChanges.added.add(path));
|
|
81
|
+
changedFiles.modified.forEach((path) => queuedChanges.modified.add(path));
|
|
82
|
+
changedFiles.removed.forEach((path) => queuedChanges.removed.add(path));
|
|
83
|
+
} else queuedChanges = changedFiles;
|
|
84
|
+
wakeUp?.();
|
|
85
|
+
});
|
|
86
|
+
const bridgedWatcher = {
|
|
87
|
+
[Symbol.asyncIterator]: () => bridgedWatcher,
|
|
88
|
+
next: async () => {
|
|
89
|
+
if (!queuedChanges) {
|
|
90
|
+
pendingNext ??= angularWatcher.next();
|
|
91
|
+
await Promise.race([pendingNext, new Promise((resolve) => {
|
|
92
|
+
wakeUp = resolve;
|
|
93
|
+
})]);
|
|
94
|
+
wakeUp = void 0;
|
|
95
|
+
}
|
|
96
|
+
if (queuedChanges) {
|
|
97
|
+
const changedFiles = queuedChanges;
|
|
98
|
+
queuedChanges = void 0;
|
|
99
|
+
return {
|
|
100
|
+
value: changedFiles,
|
|
101
|
+
done: false
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
const result = await pendingNext;
|
|
105
|
+
pendingNext = void 0;
|
|
106
|
+
return result;
|
|
107
|
+
},
|
|
108
|
+
add: (paths) => angularWatcher.add(paths),
|
|
109
|
+
remove: (paths) => angularWatcher.remove(paths),
|
|
110
|
+
close: async () => {
|
|
111
|
+
unsubscribe();
|
|
112
|
+
await angularWatcher.close();
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
return bridgedWatcher;
|
|
116
|
+
};
|
|
117
|
+
/**
|
|
118
|
+
* Watches `directories` and reports each settled batch of changed
|
|
119
|
+
* declarations, one listener per running Angular watcher.
|
|
120
|
+
*/
|
|
121
|
+
const createTypesChangeSource = (directories, revisionFilePath, ChangedFiles) => {
|
|
122
|
+
let revision = 0;
|
|
123
|
+
mkdirSync(dirname(revisionFilePath), { recursive: true });
|
|
124
|
+
writeFileSync(revisionFilePath, getTypesRevisionContents(revision));
|
|
125
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
126
|
+
let fileContents = readFileContents(directories);
|
|
127
|
+
let settleTimeout;
|
|
128
|
+
let directoryWatchers = [];
|
|
129
|
+
const emitChanges = () => {
|
|
130
|
+
const currentContents = readFileContents(directories);
|
|
131
|
+
const changedFiles = diffFileContents(fileContents, currentContents, new ChangedFiles());
|
|
132
|
+
fileContents = currentContents;
|
|
133
|
+
if (changedFiles.all.length === 0) return;
|
|
134
|
+
revision += 1;
|
|
135
|
+
writeFileSync(revisionFilePath, getTypesRevisionContents(revision));
|
|
136
|
+
changedFiles.modified.add(revisionFilePath);
|
|
137
|
+
for (const listener of listeners) listener(changedFiles);
|
|
138
|
+
};
|
|
139
|
+
const scheduleEmit = () => {
|
|
140
|
+
clearTimeout(settleTimeout);
|
|
141
|
+
settleTimeout = setTimeout(emitChanges, SETTLE_DELAY_MS);
|
|
142
|
+
settleTimeout.unref?.();
|
|
143
|
+
};
|
|
144
|
+
const startWatching = () => {
|
|
145
|
+
directoryWatchers = directories.flatMap((directory) => {
|
|
146
|
+
try {
|
|
147
|
+
const directoryWatcher = watch(directory, { persistent: false }, scheduleEmit);
|
|
148
|
+
directoryWatcher.on("error", () => directoryWatcher.close());
|
|
149
|
+
return [directoryWatcher];
|
|
150
|
+
} catch {
|
|
151
|
+
return [];
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
};
|
|
155
|
+
return (listener) => {
|
|
156
|
+
if (listeners.size === 0) startWatching();
|
|
157
|
+
listeners.add(listener);
|
|
158
|
+
return () => {
|
|
159
|
+
listeners.delete(listener);
|
|
160
|
+
if (listeners.size > 0) return;
|
|
161
|
+
for (const directoryWatcher of directoryWatchers) directoryWatcher.close();
|
|
162
|
+
directoryWatchers = [];
|
|
163
|
+
clearTimeout(settleTimeout);
|
|
164
|
+
};
|
|
165
|
+
};
|
|
166
|
+
};
|
|
167
|
+
/**
|
|
168
|
+
* `@angular/build` watcher modules of the builders loaded in this process.
|
|
169
|
+
* Located from the module cache rather than resolved, so the wrap hits the
|
|
170
|
+
* copy the running builder uses even when several are installed.
|
|
171
|
+
*/
|
|
172
|
+
const getAngularWatcherModules = () => {
|
|
173
|
+
const require = createRequire(import.meta.url);
|
|
174
|
+
return Object.keys(require.cache).filter((modulePath) => modulePath.endsWith(BUILD_ACTION_MODULE_SUFFIX)).flatMap((buildActionPath) => {
|
|
175
|
+
try {
|
|
176
|
+
return [require(join(dirname(buildActionPath), "../../tools/esbuild/watcher.js"))];
|
|
177
|
+
} catch {
|
|
178
|
+
return [];
|
|
179
|
+
}
|
|
180
|
+
}).filter((watcherModule) => typeof watcherModule?.createWatcher === "function" && typeof watcherModule.ChangedFiles === "function");
|
|
181
|
+
};
|
|
182
|
+
/**
|
|
183
|
+
* Reports the declarations Intlayer rewrites under a dot-directory to the
|
|
184
|
+
* Angular dev server's watcher.
|
|
185
|
+
*
|
|
186
|
+
* That watcher ignores `<workspace>/**\/.*\/**`, so a rewritten
|
|
187
|
+
* `.intlayer/types` file is never reported and the TypeScript cache keeps the
|
|
188
|
+
* stale declaration: a key added to a dictionary fails template type-checking
|
|
189
|
+
* until `ng serve` restarts. Wrapping `createWatcher` — read by the builder
|
|
190
|
+
* only once the first build is done, after plugin setup — makes it yield the
|
|
191
|
+
* changed declarations too, so Angular rebuilds and re-reads them itself.
|
|
192
|
+
*
|
|
193
|
+
* @param directories - Absolute directories holding the generated declarations.
|
|
194
|
+
* @param revisionDirectory - Directory, covered by the tsconfig `include`, that
|
|
195
|
+
* receives the revision script (the module augmentation one).
|
|
196
|
+
* @returns Whether a loaded Angular watcher module was wrapped.
|
|
197
|
+
*/
|
|
198
|
+
const bridgeTypesToAngularWatcher = (directories, revisionDirectory) => {
|
|
199
|
+
const watcherModules = getAngularWatcherModules();
|
|
200
|
+
for (const watcherModule of watcherModules) {
|
|
201
|
+
const wrappableModule = watcherModule;
|
|
202
|
+
if (wrappableModule[WRAPPED_MARKER]) continue;
|
|
203
|
+
const originalCreateWatcher = watcherModule.createWatcher;
|
|
204
|
+
const subscribe = createTypesChangeSource(directories, normalize(join(revisionDirectory, TYPES_REVISION_FILE_NAME)), watcherModule.ChangedFiles);
|
|
205
|
+
watcherModule.createWatcher = (options) => mergeInjectedChanges(originalCreateWatcher(options), subscribe);
|
|
206
|
+
wrappableModule[WRAPPED_MARKER] = true;
|
|
207
|
+
}
|
|
208
|
+
return watcherModules.length > 0;
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
export { TYPES_REVISION_FILE_NAME, bridgeTypesToAngularWatcher, diffFileContents, getTypesRevisionContents, mergeInjectedChanges, readFileContents };
|
|
212
|
+
//# sourceMappingURL=angularWatcherTypesBridge.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"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,UAAU,KAAK,WAAW,QAAQ,CAAC;GAEpD,IAAI;IACF,aAAa,IAAI,UAAU,aAAa,UAAU,OAAO,CAAC;GAC5D,QAAQ,CAER;EACF;CACF;CAEA,OAAO;AACT;;;;;AAMA,MAAa,oBACX,kBACA,iBACA,iBACqB;CACrB,KAAK,MAAM,CAAC,UAAU,aAAa,iBAAiB;EAClD,MAAM,WAAW,iBAAiB,IAAI,QAAQ;EAE9C,IAAI,aAAa,QAAW,aAAa,MAAM,IAAI,QAAQ;OACtD,IAAI,aAAa,UAAU,aAAa,SAAS,IAAI,QAAQ;CACpE;CAEA,KAAK,MAAM,YAAY,iBAAiB,KAAK,GAC3C,IAAI,CAAC,gBAAgB,IAAI,QAAQ,GAAG,aAAa,QAAQ,IAAI,QAAQ;CAGvE,OAAO;AACT;;;;;AAMA,MAAa,4BAA4B,aACvC;CACE;CACA;CA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iB,UAC1C;AACJ;;;;;;;;;;;;;;;;;AAkBA,MAAa,+BACX,aACA,sBACY;CACZ,MAAM,iBAAiB,yBAAyB;CAEhD,KAAK,MAAM,iBAAiB,gBAAgB;EAC1C,MAAM,kBAAkB;EAGxB,IAAI,gBAAgB,iBAAiB;EAErC,MAAM,wBAAwB,cAAc;EAC5C,MAAM,YAAY,wBAChB,aACA,UAAU,KAAK,mBAAmB,wBAAwB,CAAC,GAC3D,cAAc,YAChB;EAEA,cAAc,iBAAiB,YAC7B,qBAAqB,sBAAsB,OAAO,GAAG,SAAS;EAEhE,gBAAgB,kBAAkB;CACpC;CAEA,OAAO,eAAe,SAAS;AACjC"}
|
|
@@ -1,13 +1,14 @@
|
|
|
1
|
+
import { bridgeTypesToAngularWatcher } from "./angularWatcherTypesBridge.mjs";
|
|
1
2
|
import { isInHiddenDirectory } from "./hiddenDirectory.mjs";
|
|
2
3
|
import { resolvePackageExport } from "./resolvePackageExport.mjs";
|
|
3
|
-
import { readFile } from "node:fs/promises";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
5
|
import { basename, dirname, join, relative } from "node:path";
|
|
6
|
+
import { getConfiguration } from "@intlayer/config/node";
|
|
7
|
+
import { getAlias, getHasDictionarySelector, getUnusedNodeTypesAsync, normalizePath } from "@intlayer/config/utils";
|
|
8
|
+
import { readFile } from "node:fs/promises";
|
|
6
9
|
import { addDynamicEntryPreload, createDynamicEntryFilter, resolvePreloadModuleId } from "@intlayer/config/dictionaryPreload";
|
|
7
10
|
import { formatDictionarySelectorEnvVar, formatNodeTypeToEnvVar, getConfigEnvVars } from "@intlayer/config/envVars";
|
|
8
11
|
import { getAppLogger } from "@intlayer/config/logger";
|
|
9
|
-
import { getConfiguration } from "@intlayer/config/node";
|
|
10
|
-
import { getAlias, getHasDictionarySelector, getUnusedNodeTypesAsync, normalizePath } from "@intlayer/config/utils";
|
|
11
12
|
import { getDictionaries } from "@intlayer/dictionaries-entry";
|
|
12
13
|
import { prepareIntlayer } from "@intlayer/engine/build";
|
|
13
14
|
import { logConfigDetails } from "@intlayer/engine/cli";
|
|
@@ -38,13 +39,15 @@ const DEFAULT_EXPORT_PATTERN = /\bexport\s+default\b|\bas\s+default\b|\{\s*defau
|
|
|
38
39
|
/**
|
|
39
40
|
* The dev server's file watcher skips dot-directories, so type declarations
|
|
40
41
|
* generated there are never re-read: a key added to a dictionary stays unknown
|
|
41
|
-
* to template type-checking until `ng serve` restarts.
|
|
42
|
-
*
|
|
42
|
+
* to template type-checking until `ng serve` restarts. The plugin reports the
|
|
43
|
+
* rewritten declarations to the Angular watcher itself; when no Angular
|
|
44
|
+
* watcher is loaded to bridge, it warns to generate the types elsewhere.
|
|
43
45
|
*/
|
|
44
|
-
const
|
|
46
|
+
const handleHiddenTypesDirectory = (configuration, appLogger) => {
|
|
45
47
|
const { baseDir, typesDir, moduleAugmentationDir } = configuration.system;
|
|
46
48
|
const hiddenDirectories = [.../* @__PURE__ */ new Set([typesDir, moduleAugmentationDir])].filter((directory) => isInHiddenDirectory(baseDir, directory));
|
|
47
49
|
if (hiddenDirectories.length === 0) return;
|
|
50
|
+
if (bridgeTypesToAngularWatcher(hiddenDirectories, moduleAugmentationDir)) return;
|
|
48
51
|
appLogger([
|
|
49
52
|
`Type declarations are generated under ${hiddenDirectories.map((directory) => relative(baseDir, directory)).join(", ")}.`,
|
|
50
53
|
"The Angular dev server does not watch dot-directories, so keys added to a dictionary stay unknown to template type-checking until 'ng serve' restarts.",
|
|
@@ -78,6 +81,7 @@ const intlayerEsbuildPlugin = (options) => {
|
|
|
78
81
|
let alias = null;
|
|
79
82
|
let preparePromise = null;
|
|
80
83
|
let isBuildMode = false;
|
|
84
|
+
let hasHandledHiddenTypesDirectory = false;
|
|
81
85
|
return {
|
|
82
86
|
name: "intlayer",
|
|
83
87
|
async setup(build) {
|
|
@@ -176,14 +180,17 @@ const intlayerEsbuildPlugin = (options) => {
|
|
|
176
180
|
});
|
|
177
181
|
}
|
|
178
182
|
build.onStart(async () => {
|
|
179
|
-
if (externalizesPackages === void 0) {
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
183
|
+
if (externalizesPackages === void 0) externalizesPackages = (await build.resolve("@angular/core", {
|
|
184
|
+
kind: "import-statement",
|
|
185
|
+
resolveDir: config.system.baseDir
|
|
186
|
+
})).external;
|
|
187
|
+
if (options?.watch ?? !isBuildMode) {
|
|
188
|
+
startContentWatcher(config, { label: "angular-intlayer" });
|
|
189
|
+
if (!hasHandledHiddenTypesDirectory) {
|
|
190
|
+
hasHandledHiddenTypesDirectory = true;
|
|
191
|
+
handleHiddenTypesDirectory(config, appLogger);
|
|
192
|
+
}
|
|
185
193
|
}
|
|
186
|
-
if (options?.watch ?? !isBuildMode) startContentWatcher(config, { label: "angular-intlayer" });
|
|
187
194
|
});
|
|
188
195
|
}
|
|
189
196
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.mjs","names":[],"sources":["../../../src/esbuild/plugin.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { basename, dirname, join, relative } from 'node:path';\nimport {\n addDynamicEntryPreload,\n createDynamicEntryFilter,\n resolvePreloadModuleId,\n} from '@intlayer/config/dictionaryPreload';\nimport {\n formatDictionarySelectorEnvVar,\n formatNodeTypeToEnvVar,\n getConfigEnvVars,\n} from '@intlayer/config/envVars';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n getAlias,\n getHasDictionarySelector,\n getUnusedNodeTypesAsync,\n normalizePath,\n} from '@intlayer/config/utils';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport { prepareIntlayer } from '@intlayer/engine/build';\nimport { logConfigDetails } from '@intlayer/engine/cli';\nimport { startContentWatcher } from '@intlayer/engine/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { isInHiddenDirectory } from './hiddenDirectory';\nimport { resolvePackageExport } from './resolvePackageExport';\n\n/**\n * Absolute id of the locale resolver the injected preamble imports.\n *\n * Resolved from this package, which declares `@intlayer/core` as a dependency,\n * rather than left bare in the emitted source: the importer is a generated\n * entry point under the application's `.intlayer` directory, and an application\n * only depends on `intlayer` and its framework binding, so the bare specifier\n * would resolve from a tree that need not contain the package at all.\n *\n * Always built from `import.meta.url`: the bundler shims it to `__filename` in\n * the CommonJS output, whereas a `typeof require` guard is unreliable here —\n * the ESM output rewrites `require` into an always-defined proxy that has no\n * `resolve` method.\n */\nconst preloadModuleId = normalizePath(\n resolvePreloadModuleId(createRequire(import.meta.url))\n);\n\n/** Bare specifiers of the packages this plugin keeps inside its own build. */\nconst INTLAYER_PACKAGE_FILTER =\n /^(?:intlayer|angular-intlayer|@intlayer\\/[^/]+)(?:\\/|$)/;\n\n/** Namespace of the re-export shims standing in for externalised packages. */\nconst INTLAYER_PACKAGE_NAMESPACE = 'intlayer-package';\n\n/** Matches a module that has a default export, on unminified sources. */\nconst DEFAULT_EXPORT_PATTERN =\n /\\bexport\\s+default\\b|\\bas\\s+default\\b|\\{\\s*default\\s*[,}]/;\n\n// Minimal subset of the esbuild Plugin interface to avoid a hard dependency on\n// the `esbuild` package for type resolution. The shape is compatible with\n// esbuild >=0.17, `@angular-builders/custom-esbuild`, and NX esbuild builders.\nexport type EsbuildResolveArgs = {\n path: string;\n importer: string;\n namespace: string;\n resolveDir: string;\n kind: string;\n pluginData?: unknown;\n};\n\nexport type EsbuildResolveResult = {\n path?: string;\n namespace?: string;\n external?: boolean;\n sideEffects?: boolean;\n pluginData?: unknown;\n errors?: unknown[];\n warnings?: unknown[];\n};\n\nexport type EsbuildLoadArgs = {\n path: string;\n namespace: string;\n pluginData?: unknown;\n};\n\nexport type EsbuildLoadResult = {\n contents: string;\n loader?: string;\n /** Directory relative imports of `contents` resolve from. */\n resolveDir?: string;\n};\n\nexport interface EsbuildPluginBuild {\n initialOptions: {\n alias?: Record<string, string>;\n define?: Record<string, string>;\n minify?: boolean;\n watch?: unknown;\n /** Absolute working directory of the esbuild context (set by Angular's builder). */\n absWorkingDir?: string;\n };\n onStart(callback: () => void | Promise<void>): void;\n /** Intercept module resolution — works even for imports inside node_modules. */\n onResolve(\n options: { filter: RegExp; namespace?: string },\n callback: (\n args: EsbuildResolveArgs\n ) =>\n | EsbuildResolveResult\n | null\n | undefined\n | Promise<EsbuildResolveResult | null | undefined>\n ): void;\n /** Run the remaining resolution pipeline (other plugins, then esbuild). */\n resolve(\n path: string,\n options: Partial<Omit<EsbuildResolveArgs, 'path'>>\n ): Promise<EsbuildResolveResult & { path: string; external: boolean }>;\n /** Intercept module contents, so a resolved file can be rewritten. */\n onLoad(\n options: { filter: RegExp; namespace?: string },\n callback: (\n args: EsbuildLoadArgs\n ) =>\n | EsbuildLoadResult\n | null\n | undefined\n | Promise<EsbuildLoadResult | null | undefined>\n ): void;\n}\n\nexport interface EsbuildPlugin {\n name: string;\n setup(build: EsbuildPluginBuild): void | Promise<void>;\n}\n\nexport type IntlayerEsbuildPluginOptions = {\n configOptions?: GetConfigurationOptions;\n /**\n * Whether to start the Intlayer file watcher for dictionary regeneration.\n * - `true`: always start the watcher (useful for `ng serve`)\n * - `false`: never start the watcher (useful for `ng build`)\n * - `undefined` (default): auto-detect based on the build context\n * (skips the watcher when a production build is detected)\n */\n watch?: boolean;\n};\n\n/**\n * The dev server's file watcher skips dot-directories, so type declarations\n * generated there are never re-read: a key added to a dictionary stays unknown\n * to template type-checking until `ng serve` restarts. Nothing in the plugin\n * can reach that cache, so the fix is to generate the types elsewhere.\n */\nconst warnAboutHiddenTypesDirectory = (\n configuration: IntlayerConfig,\n appLogger: ReturnType<typeof getAppLogger>\n) => {\n const { baseDir, typesDir, moduleAugmentationDir } = configuration.system;\n\n const hiddenDirectories = [\n ...new Set([typesDir, moduleAugmentationDir]),\n ].filter((directory) => isInHiddenDirectory(baseDir, directory));\n\n if (hiddenDirectories.length === 0) return;\n\n appLogger(\n [\n `Type declarations are generated under ${hiddenDirectories.map((directory) => relative(baseDir, directory)).join(', ')}.`,\n \"The Angular dev server does not watch dot-directories, so keys added to a dictionary stay unknown to template type-checking until 'ng serve' restarts.\",\n \"Set 'system.typesDir' and 'system.moduleAugmentationDir' to a directory outside any dot-directory (e.g. 'intlayer-types') and point the tsconfig 'include' at it.\",\n ].join(' '),\n { level: 'warn' }\n );\n};\n\n/**\n * esbuild plugin that integrates Intlayer into the Angular (or any esbuild-based) build process.\n *\n * Handles:\n * 1. Injecting `alias` entries so `@intlayer/dictionaries-entry` etc. resolve to\n * the generated files under `.intlayer/`.\n * 2. Defining `process.env.*` tree-shaking constants for production builds.\n * 3. Running `prepareIntlayer` (dictionary generation) before the first build.\n * 4. Starting the chokidar file-watcher in dev / serve mode.\n *\n * Compatible with:\n * - `@angular-builders/custom-esbuild` (`application` or `browser-esbuild` builder)\n * - NX `@nx/angular:browser-esbuild`\n * - Any raw esbuild setup that accepts the standard `Plugin` interface\n *\n * @example\n * ```ts\n * // esbuild.plugins.ts (referenced from angular.json \"plugins\" option)\n * import { intlayerEsbuildPlugin } from 'angular-intlayer/esbuild';\n * export default [intlayerEsbuildPlugin()];\n * ```\n */\nexport const intlayerEsbuildPlugin = (\n options?: IntlayerEsbuildPluginOptions\n): EsbuildPlugin => {\n // All Node.js-heavy initialization (getConfiguration, getAlias, …) is deferred\n // into setup() so it runs in esbuild's Node.js context, not at module-evaluation\n // time. @angular/build loads the plugin file through Vite's SSR module runner\n // (ESM) where CommonJS globals like __filename are undefined. Calling\n // getConfiguration() here would trigger: buildSync → worker threads →\n // __filename → ReferenceError, crashing the plugin before setup() ever runs.\n let config: ReturnType<typeof getConfiguration> | null = null;\n let alias: Record<string, string> | null = null;\n\n // Shared across parallel setup() calls (Angular spawns one per bundle context).\n let preparePromise: Promise<void> | null = null;\n // Once any esbuild context (browser or server) detects a production build,\n // suppress the watcher for all contexts so `ng build` can exit cleanly.\n let isBuildMode = false;\n\n return {\n name: 'intlayer',\n\n async setup(build) {\n if (!config) {\n const baseDir =\n build.initialOptions.absWorkingDir ??\n options?.configOptions?.baseDir ??\n process.cwd();\n\n config = getConfiguration({ baseDir, ...options?.configOptions });\n logConfigDetails({ baseDir, ...options?.configOptions });\n\n alias = getAlias({\n configuration: config,\n formatter: (value: string) => join(config!.system.baseDir, value),\n });\n }\n\n const appLogger = getAppLogger(config);\n const nodeEnvDefine =\n build.initialOptions.define?.['process.env.NODE_ENV'];\n\n // Angular's esbuild builder doesn't set `minify` or `process.env.NODE_ENV`\n // on initialOptions — it handles optimisation through its own pipeline.\n // Instead, Angular defines `ngDevMode` as `\"false\"` in production builds.\n const isProduction =\n nodeEnvDefine === '\"production\"' ||\n nodeEnvDefine === \"'production'\" ||\n build.initialOptions.minify === true ||\n build.initialOptions.define?.['ngDevMode'] === 'false';\n\n if (isProduction) {\n isBuildMode = true;\n }\n\n const wrapKey = (key: string) => `process.env.${key}`;\n const wrapValue = (value: string) => `\"${value}\"`;\n\n const envVars: Record<string, string> = {\n // Catch-all so that any `process.env.*` read NOT covered by a specific\n // key below resolves to `undefined` instead of dereferencing a bare\n // `process`, which is not defined in browser bundles and throws\n // `process is not defined`. esbuild resolves the most specific define\n // first, so the keys below keep their tree-shaking effect.\n 'process.env': '{}',\n [wrapKey('INTLAYER')]: wrapValue('true'),\n [wrapKey('NODE_ENV')]: wrapValue(\n isProduction ? 'production' : 'development'\n ),\n // Tree shaking flags derived from the config (routing / storage /\n // editor). Emitted in every mode so behaviour is consistent in dev.\n ...getConfigEnvVars(config, wrapKey, wrapValue),\n };\n\n // Dictionaries must exist on disk before the tree-shaking flags below\n // are derived from them: on a clean checkout (CI, Vercel…) nothing is\n // generated yet, so reading them first reports every node type as\n // unused and strips the translation plugin from the production bundle.\n if (!preparePromise) {\n preparePromise = prepareIntlayer(config, {\n clean: isProduction,\n cacheTimeoutMs: isProduction ? 1000 * 30 : 1000 * 60 * 60,\n env: isProduction ? 'prod' : 'dev',\n });\n }\n\n await preparePromise;\n\n if (isProduction) {\n const dictionaries = getDictionaries(config);\n if (Object.keys(dictionaries).length === 0) {\n appLogger('No dictionaries found. Please check your configuration.', {\n isVerbose: true,\n });\n }\n\n const unusedNodeTypes = await getUnusedNodeTypesAsync(dictionaries);\n Object.assign(\n envVars,\n // Tree shaking based on unused node types\n formatNodeTypeToEnvVar(unusedNodeTypes, wrapKey, wrapValue),\n // Tree shaking the dictionary selector logic\n // (collections / variants)\n formatDictionarySelectorEnvVar(\n getHasDictionarySelector(dictionaries),\n wrapKey,\n wrapValue\n )\n );\n }\n\n // Existing defines (Angular's own, or the user's angular.json `define`\n // block) take precedence over the Intlayer ones.\n build.initialOptions.define = {\n ...envVars,\n ...(build.initialOptions.define ?? {}),\n };\n\n build.initialOptions.alias = {\n ...alias,\n ...(build.initialOptions.alias ?? {}),\n };\n\n for (const [from, to] of Object.entries(alias!)) {\n const escapedFrom = from.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n build.onResolve({ filter: new RegExp(`^${escapedFrom}$`) }, () => ({\n path: to,\n }));\n }\n\n // Angular's dev server marks every import that resolves under\n // `node_modules` as external so Vite can pre-bundle it. Vite's\n // pre-bundler runs without this plugin, so the aliases above never apply\n // there and the real `@intlayer/config/built` — a Node config loader —\n // ends up in the browser. Angular's externalising plugin is registered\n // ahead of this one and only lets a resolution through when the path it\n // gets back is outside `node_modules`; so in that mode an Intlayer\n // package resolves to a re-export shim in its own namespace, whose\n // relative import of the real file the pipeline then bundles as usual.\n // Whether the pipeline externalises packages is probed once, at the\n // first build, so production builds keep the bundler's own resolution.\n let externalizesPackages: boolean | undefined;\n\n build.onResolve({ filter: INTLAYER_PACKAGE_FILTER }, (args) => {\n if (!externalizesPackages || !args.resolveDir) return null;\n\n const importCondition = args.kind.startsWith('require')\n ? 'require'\n : 'import';\n const resolved = resolvePackageExport(args.path, args.resolveDir, [\n 'browser',\n 'module',\n importCondition,\n ]);\n\n if (!resolved) return null;\n\n return {\n // Neither a `node_modules` segment nor a script extension, which the\n // externalising plugin and Angular's own JS loader key on. Ends with\n // the specifier so a lazy chunk is named after it, and starts with\n // the encoded directory so two copies of a package stay distinct.\n path: `${encodeURIComponent(dirname(resolved.path))}/${args.path}`,\n namespace: INTLAYER_PACKAGE_NAMESPACE,\n pluginData: { realPath: resolved.path },\n sideEffects: resolved.sideEffects,\n };\n });\n\n build.onLoad(\n { filter: /.*/, namespace: INTLAYER_PACKAGE_NAMESPACE },\n async (args) => {\n const { realPath } = args.pluginData as { realPath: string };\n const source = await readFile(realPath, 'utf-8');\n const specifier = JSON.stringify(`./${basename(realPath)}`);\n\n const contents = [\n `export * from ${specifier};`,\n DEFAULT_EXPORT_PATTERN.test(source) &&\n `export { default } from ${specifier};`,\n ]\n .filter(Boolean)\n .join('\\n');\n\n return { contents, loader: 'js', resolveDir: dirname(realPath) };\n }\n );\n\n // Dictionaries load with the chunk that needs them rather than being\n // fetched once that chunk renders: the entry point starts the browsing\n // locale's load as it evaluates, so a lazily loaded route requests its\n // content on `import()` instead of on first render. Without it every\n // dictionary read renders an empty placeholder first and fills in a tick\n // later.\n //\n // Not gated on the configured `importMode`: a `.content` file can set\n // `importMode: 'dynamic'` on a single dictionary under a `static` or\n // `fetch` global mode, and that dictionary needs the preload just the\n // same. Only entry points the optimizer imported are ever loaded, so the\n // path check below is the accurate gate.\n if (config.build.dictionariesPreload) {\n const dynamicDictionariesDir = normalizePath(\n config.system.dynamicDictionariesDir\n );\n\n build.onLoad(\n { filter: createDynamicEntryFilter(dynamicDictionariesDir) },\n async ({ path }) => {\n const posixPath = normalizePath(path);\n if (!posixPath.startsWith(`${dynamicDictionariesDir}/`))\n return null;\n\n const code = await readFile(path, 'utf-8');\n const result = addDynamicEntryPreload(code, preloadModuleId);\n\n if (result.skipped) return null;\n\n return { contents: result.code, loader: 'js' };\n }\n );\n }\n\n build.onStart(async () => {\n // `@angular/core` is always installed and never worth excluding from\n // pre-bundling, so its fate tells whether packages get externalised.\n if (externalizesPackages === undefined) {\n externalizesPackages = (\n await build.resolve('@angular/core', {\n kind: 'import-statement',\n resolveDir: config!.system.baseDir,\n })\n ).external;\n\n if (externalizesPackages) {\n warnAboutHiddenTypesDirectory(config!, appLogger);\n }\n }\n\n // Determine whether the watcher should run:\n // 1. Explicit option from the caller takes precedence\n // 2. If any esbuild context detected a production build, skip\n // 3. esbuild's own watch mode is a positive signal\n const shouldWatch = options?.watch ?? !isBuildMode;\n\n if (shouldWatch) {\n startContentWatcher(config!, { label: 'angular-intlayer' });\n }\n });\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,kBAAkB,cACtB,uBAAuB,cAAc,YAAY,GAAG,CAAC,CACvD;;AAGA,MAAM,0BACJ;;AAGF,MAAM,6BAA6B;;AAGnC,MAAM,yBACJ;;;;;;;AAmGF,MAAM,iCACJ,eACA,cACG;CACH,MAAM,EAAE,SAAS,UAAU,0BAA0B,cAAc;CAEnE,MAAM,oBAAoB,CACxB,mBAAG,IAAI,IAAI,CAAC,UAAU,qBAAqB,CAAC,CAC9C,CAAC,CAAC,QAAQ,cAAc,oBAAoB,SAAS,SAAS,CAAC;CAE/D,IAAI,kBAAkB,WAAW,GAAG;CAEpC,UACE;EACE,yCAAyC,kBAAkB,KAAK,cAAc,SAAS,SAAS,SAAS,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE;EACvH;EACA;CACF,CAAC,CAAC,KAAK,GAAG,GACV,EAAE,OAAO,OAAO,CAClB;AACF;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,yBACX,YACkB;CAOlB,IAAI,SAAqD;CACzD,IAAI,QAAuC;CAG3C,IAAI,iBAAuC;CAG3C,IAAI,cAAc;CAElB,OAAO;EACL,MAAM;EAEN,MAAM,MAAM,OAAO;GACjB,IAAI,CAAC,QAAQ;IACX,MAAM,UACJ,MAAM,eAAe,iBACrB,SAAS,eAAe,WACxB,QAAQ,IAAI;IAEd,SAAS,iBAAiB;KAAE;KA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E,GACpD,OAAO;KAET,MAAM,OAAO,MAAM,SAAS,MAAM,OAAO;KACzC,MAAM,SAAS,uBAAuB,MAAM,eAAe;KAE3D,IAAI,OAAO,SAAS,OAAO;KAE3B,OAAO;MAAE,UAAU,OAAO;MAAM,QAAQ;KAAK;IAC/C,CACF;GACF;GAEA,MAAM,QAAQ,YAAY;IAGxB,IAAI,yBAAyB,QAAW;KACtC,wBACE,MAAM,MAAM,QAAQ,iBAAiB;MACnC,MAAM;MACN,YAAY,OAAQ,OAAO;KAC7B,CAAC,EAAC,CACF;KAEF,IAAI,sBACF,8BAA8B,QAAS,SAAS;IAEpD;IAQA,IAFoB,SAAS,SAAS,CAAC,aAGrC,oBAAoB,QAAS,EAAE,OAAO,mBAAmB,CAAC;GAE9D,CAAC;EACH;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"plugin.mjs","names":[],"sources":["../../../src/esbuild/plugin.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { basename, dirname, join, relative } from 'node:path';\nimport {\n addDynamicEntryPreload,\n createDynamicEntryFilter,\n resolvePreloadModuleId,\n} from '@intlayer/config/dictionaryPreload';\nimport {\n formatDictionarySelectorEnvVar,\n formatNodeTypeToEnvVar,\n getConfigEnvVars,\n} from '@intlayer/config/envVars';\nimport { getAppLogger } from '@intlayer/config/logger';\nimport {\n type GetConfigurationOptions,\n getConfiguration,\n} from '@intlayer/config/node';\nimport {\n getAlias,\n getHasDictionarySelector,\n getUnusedNodeTypesAsync,\n normalizePath,\n} from '@intlayer/config/utils';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport { prepareIntlayer } from '@intlayer/engine/build';\nimport { logConfigDetails } from '@intlayer/engine/cli';\nimport { startContentWatcher } from '@intlayer/engine/utils';\nimport type { IntlayerConfig } from '@intlayer/types/config';\nimport { bridgeTypesToAngularWatcher } from './angularWatcherTypesBridge';\nimport { isInHiddenDirectory } from './hiddenDirectory';\nimport { resolvePackageExport } from './resolvePackageExport';\n\n/**\n * Absolute id of the locale resolver the injected preamble imports.\n *\n * Resolved from this package, which declares `@intlayer/core` as a dependency,\n * rather than left bare in the emitted source: the importer is a generated\n * entry point under the application's `.intlayer` directory, and an application\n * only depends on `intlayer` and its framework binding, so the bare specifier\n * would resolve from a tree that need not contain the package at all.\n *\n * Always built from `import.meta.url`: the bundler shims it to `__filename` in\n * the CommonJS output, whereas a `typeof require` guard is unreliable here —\n * the ESM output rewrites `require` into an always-defined proxy that has no\n * `resolve` method.\n */\nconst preloadModuleId = normalizePath(\n resolvePreloadModuleId(createRequire(import.meta.url))\n);\n\n/** Bare specifiers of the packages this plugin keeps inside its own build. */\nconst INTLAYER_PACKAGE_FILTER =\n /^(?:intlayer|angular-intlayer|@intlayer\\/[^/]+)(?:\\/|$)/;\n\n/** Namespace of the re-export shims standing in for externalised packages. */\nconst INTLAYER_PACKAGE_NAMESPACE = 'intlayer-package';\n\n/** Matches a module that has a default export, on unminified sources. */\nconst DEFAULT_EXPORT_PATTERN =\n /\\bexport\\s+default\\b|\\bas\\s+default\\b|\\{\\s*default\\s*[,}]/;\n\n// Minimal subset of the esbuild Plugin interface to avoid a hard dependency on\n// the `esbuild` package for type resolution. The shape is compatible with\n// esbuild >=0.17, `@angular-builders/custom-esbuild`, and NX esbuild builders.\nexport type EsbuildResolveArgs = {\n path: string;\n importer: string;\n namespace: string;\n resolveDir: string;\n kind: string;\n pluginData?: unknown;\n};\n\nexport type EsbuildResolveResult = {\n path?: string;\n namespace?: string;\n external?: boolean;\n sideEffects?: boolean;\n pluginData?: unknown;\n errors?: unknown[];\n warnings?: unknown[];\n};\n\nexport type EsbuildLoadArgs = {\n path: string;\n namespace: string;\n pluginData?: unknown;\n};\n\nexport type EsbuildLoadResult = {\n contents: string;\n loader?: string;\n /** Directory relative imports of `contents` resolve from. */\n resolveDir?: string;\n};\n\nexport interface EsbuildPluginBuild {\n initialOptions: {\n alias?: Record<string, string>;\n define?: Record<string, string>;\n minify?: boolean;\n watch?: unknown;\n /** Absolute working directory of the esbuild context (set by Angular's builder). */\n absWorkingDir?: string;\n };\n onStart(callback: () => void | Promise<void>): void;\n /** Intercept module resolution — works even for imports inside node_modules. */\n onResolve(\n options: { filter: RegExp; namespace?: string },\n callback: (\n args: EsbuildResolveArgs\n ) =>\n | EsbuildResolveResult\n | null\n | undefined\n | Promise<EsbuildResolveResult | null | undefined>\n ): void;\n /** Run the remaining resolution pipeline (other plugins, then esbuild). */\n resolve(\n path: string,\n options: Partial<Omit<EsbuildResolveArgs, 'path'>>\n ): Promise<EsbuildResolveResult & { path: string; external: boolean }>;\n /** Intercept module contents, so a resolved file can be rewritten. */\n onLoad(\n options: { filter: RegExp; namespace?: string },\n callback: (\n args: EsbuildLoadArgs\n ) =>\n | EsbuildLoadResult\n | null\n | undefined\n | Promise<EsbuildLoadResult | null | undefined>\n ): void;\n}\n\nexport interface EsbuildPlugin {\n name: string;\n setup(build: EsbuildPluginBuild): void | Promise<void>;\n}\n\nexport type IntlayerEsbuildPluginOptions = {\n configOptions?: GetConfigurationOptions;\n /**\n * Whether to start the Intlayer file watcher for dictionary regeneration.\n * - `true`: always start the watcher (useful for `ng serve`)\n * - `false`: never start the watcher (useful for `ng build`)\n * - `undefined` (default): auto-detect based on the build context\n * (skips the watcher when a production build is detected)\n */\n watch?: boolean;\n};\n\n/**\n * The dev server's file watcher skips dot-directories, so type declarations\n * generated there are never re-read: a key added to a dictionary stays unknown\n * to template type-checking until `ng serve` restarts. The plugin reports the\n * rewritten declarations to the Angular watcher itself; when no Angular\n * watcher is loaded to bridge, it warns to generate the types elsewhere.\n */\nconst handleHiddenTypesDirectory = (\n configuration: IntlayerConfig,\n appLogger: ReturnType<typeof getAppLogger>\n) => {\n const { baseDir, typesDir, moduleAugmentationDir } = configuration.system;\n\n const hiddenDirectories = [\n ...new Set([typesDir, moduleAugmentationDir]),\n ].filter((directory) => isInHiddenDirectory(baseDir, directory));\n\n if (hiddenDirectories.length === 0) return;\n\n if (bridgeTypesToAngularWatcher(hiddenDirectories, moduleAugmentationDir)) {\n return;\n }\n\n appLogger(\n [\n `Type declarations are generated under ${hiddenDirectories.map((directory) => relative(baseDir, directory)).join(', ')}.`,\n \"The Angular dev server does not watch dot-directories, so keys added to a dictionary stay unknown to template type-checking until 'ng serve' restarts.\",\n \"Set 'system.typesDir' and 'system.moduleAugmentationDir' to a directory outside any dot-directory (e.g. 'intlayer-types') and point the tsconfig 'include' at it.\",\n ].join(' '),\n { level: 'warn' }\n );\n};\n\n/**\n * esbuild plugin that integrates Intlayer into the Angular (or any esbuild-based) build process.\n *\n * Handles:\n * 1. Injecting `alias` entries so `@intlayer/dictionaries-entry` etc. resolve to\n * the generated files under `.intlayer/`.\n * 2. Defining `process.env.*` tree-shaking constants for production builds.\n * 3. Running `prepareIntlayer` (dictionary generation) before the first build.\n * 4. Starting the chokidar file-watcher in dev / serve mode.\n *\n * Compatible with:\n * - `@angular-builders/custom-esbuild` (`application` or `browser-esbuild` builder)\n * - NX `@nx/angular:browser-esbuild`\n * - Any raw esbuild setup that accepts the standard `Plugin` interface\n *\n * @example\n * ```ts\n * // esbuild.plugins.ts (referenced from angular.json \"plugins\" option)\n * import { intlayerEsbuildPlugin } from 'angular-intlayer/esbuild';\n * export default [intlayerEsbuildPlugin()];\n * ```\n */\nexport const intlayerEsbuildPlugin = (\n options?: IntlayerEsbuildPluginOptions\n): EsbuildPlugin => {\n // All Node.js-heavy initialization (getConfiguration, getAlias, …) is deferred\n // into setup() so it runs in esbuild's Node.js context, not at module-evaluation\n // time. @angular/build loads the plugin file through Vite's SSR module runner\n // (ESM) where CommonJS globals like __filename are undefined. Calling\n // getConfiguration() here would trigger: buildSync → worker threads →\n // __filename → ReferenceError, crashing the plugin before setup() ever runs.\n let config: ReturnType<typeof getConfiguration> | null = null;\n let alias: Record<string, string> | null = null;\n\n // Shared across parallel setup() calls (Angular spawns one per bundle context).\n let preparePromise: Promise<void> | null = null;\n // Once any esbuild context (browser or server) detects a production build,\n // suppress the watcher for all contexts so `ng build` can exit cleanly.\n let isBuildMode = false;\n // The dev server rebuild loop is bridged once, whatever the context count.\n let hasHandledHiddenTypesDirectory = false;\n\n return {\n name: 'intlayer',\n\n async setup(build) {\n if (!config) {\n const baseDir =\n build.initialOptions.absWorkingDir ??\n options?.configOptions?.baseDir ??\n process.cwd();\n\n config = getConfiguration({ baseDir, ...options?.configOptions });\n logConfigDetails({ baseDir, ...options?.configOptions });\n\n alias = getAlias({\n configuration: config,\n formatter: (value: string) => join(config!.system.baseDir, value),\n });\n }\n\n const appLogger = getAppLogger(config);\n const nodeEnvDefine =\n build.initialOptions.define?.['process.env.NODE_ENV'];\n\n // Angular's esbuild builder doesn't set `minify` or `process.env.NODE_ENV`\n // on initialOptions — it handles optimisation through its own pipeline.\n // Instead, Angular defines `ngDevMode` as `\"false\"` in production builds.\n const isProduction =\n nodeEnvDefine === '\"production\"' ||\n nodeEnvDefine === \"'production'\" ||\n build.initialOptions.minify === true ||\n build.initialOptions.define?.['ngDevMode'] === 'false';\n\n if (isProduction) {\n isBuildMode = true;\n }\n\n const wrapKey = (key: string) => `process.env.${key}`;\n const wrapValue = (value: string) => `\"${value}\"`;\n\n const envVars: Record<string, string> = {\n // Catch-all so that any `process.env.*` read NOT covered by a specific\n // key below resolves to `undefined` instead of dereferencing a bare\n // `process`, which is not defined in browser bundles and throws\n // `process is not defined`. esbuild resolves the most specific define\n // first, so the keys below keep their tree-shaking effect.\n 'process.env': '{}',\n [wrapKey('INTLAYER')]: wrapValue('true'),\n [wrapKey('NODE_ENV')]: wrapValue(\n isProduction ? 'production' : 'development'\n ),\n // Tree shaking flags derived from the config (routing / storage /\n // editor). Emitted in every mode so behaviour is consistent in dev.\n ...getConfigEnvVars(config, wrapKey, wrapValue),\n };\n\n // Dictionaries must exist on disk before the tree-shaking flags below\n // are derived from them: on a clean checkout (CI, Vercel…) nothing is\n // generated yet, so reading them first reports every node type as\n // unused and strips the translation plugin from the production bundle.\n if (!preparePromise) {\n preparePromise = prepareIntlayer(config, {\n clean: isProduction,\n cacheTimeoutMs: isProduction ? 1000 * 30 : 1000 * 60 * 60,\n env: isProduction ? 'prod' : 'dev',\n });\n }\n\n await preparePromise;\n\n if (isProduction) {\n const dictionaries = getDictionaries(config);\n if (Object.keys(dictionaries).length === 0) {\n appLogger('No dictionaries found. Please check your configuration.', {\n isVerbose: true,\n });\n }\n\n const unusedNodeTypes = await getUnusedNodeTypesAsync(dictionaries);\n Object.assign(\n envVars,\n // Tree shaking based on unused node types\n formatNodeTypeToEnvVar(unusedNodeTypes, wrapKey, wrapValue),\n // Tree shaking the dictionary selector logic\n // (collections / variants)\n formatDictionarySelectorEnvVar(\n getHasDictionarySelector(dictionaries),\n wrapKey,\n wrapValue\n )\n );\n }\n\n // Existing defines (Angular's own, or the user's angular.json `define`\n // block) take precedence over the Intlayer ones.\n build.initialOptions.define = {\n ...envVars,\n ...(build.initialOptions.define ?? {}),\n };\n\n build.initialOptions.alias = {\n ...alias,\n ...(build.initialOptions.alias ?? {}),\n };\n\n for (const [from, to] of Object.entries(alias!)) {\n const escapedFrom = from.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n build.onResolve({ filter: new RegExp(`^${escapedFrom}$`) }, () => ({\n path: to,\n }));\n }\n\n // Angular's dev server marks every import that resolves under\n // `node_modules` as external so Vite can pre-bundle it. Vite's\n // pre-bundler runs without this plugin, so the aliases above never apply\n // there and the real `@intlayer/config/built` — a Node config loader —\n // ends up in the browser. Angular's externalising plugin is registered\n // ahead of this one and only lets a resolution through when the path it\n // gets back is outside `node_modules`; so in that mode an Intlayer\n // package resolves to a re-export shim in its own namespace, whose\n // relative import of the real file the pipeline then bundles as usual.\n // Whether the pipeline externalises packages is probed once, at the\n // first build, so production builds keep the bundler's own resolution.\n let externalizesPackages: boolean | undefined;\n\n build.onResolve({ filter: INTLAYER_PACKAGE_FILTER }, (args) => {\n if (!externalizesPackages || !args.resolveDir) return null;\n\n const importCondition = args.kind.startsWith('require')\n ? 'require'\n : 'import';\n const resolved = resolvePackageExport(args.path, args.resolveDir, [\n 'browser',\n 'module',\n importCondition,\n ]);\n\n if (!resolved) return null;\n\n return {\n // Neither a `node_modules` segment nor a script extension, which the\n // externalising plugin and Angular's own JS loader key on. Ends with\n // the specifier so a lazy chunk is named after it, and starts with\n // the encoded directory so two copies of a package stay distinct.\n path: `${encodeURIComponent(dirname(resolved.path))}/${args.path}`,\n namespace: INTLAYER_PACKAGE_NAMESPACE,\n pluginData: { realPath: resolved.path },\n sideEffects: resolved.sideEffects,\n };\n });\n\n build.onLoad(\n { filter: /.*/, namespace: INTLAYER_PACKAGE_NAMESPACE },\n async (args) => {\n const { realPath } = args.pluginData as { realPath: string };\n const source = await readFile(realPath, 'utf-8');\n const specifier = JSON.stringify(`./${basename(realPath)}`);\n\n const contents = [\n `export * from ${specifier};`,\n DEFAULT_EXPORT_PATTERN.test(source) &&\n `export { default } from ${specifier};`,\n ]\n .filter(Boolean)\n .join('\\n');\n\n return { contents, loader: 'js', resolveDir: dirname(realPath) };\n }\n );\n\n // Dictionaries load with the chunk that needs them rather than being\n // fetched once that chunk renders: the entry point starts the browsing\n // locale's load as it evaluates, so a lazily loaded route requests its\n // content on `import()` instead of on first render. Without it every\n // dictionary read renders an empty placeholder first and fills in a tick\n // later.\n //\n // Not gated on the configured `importMode`: a `.content` file can set\n // `importMode: 'dynamic'` on a single dictionary under a `static` or\n // `fetch` global mode, and that dictionary needs the preload just the\n // same. Only entry points the optimizer imported are ever loaded, so the\n // path check below is the accurate gate.\n if (config.build.dictionariesPreload) {\n const dynamicDictionariesDir = normalizePath(\n config.system.dynamicDictionariesDir\n );\n\n build.onLoad(\n { filter: createDynamicEntryFilter(dynamicDictionariesDir) },\n async ({ path }) => {\n const posixPath = normalizePath(path);\n if (!posixPath.startsWith(`${dynamicDictionariesDir}/`))\n return null;\n\n const code = await readFile(path, 'utf-8');\n const result = addDynamicEntryPreload(code, preloadModuleId);\n\n if (result.skipped) return null;\n\n return { contents: result.code, loader: 'js' };\n }\n );\n }\n\n build.onStart(async () => {\n // `@angular/core` is always installed and never worth excluding from\n // pre-bundling, so its fate tells whether packages get externalised.\n if (externalizesPackages === undefined) {\n externalizesPackages = (\n await build.resolve('@angular/core', {\n kind: 'import-statement',\n resolveDir: config!.system.baseDir,\n })\n ).external;\n }\n\n // Determine whether the watcher should run:\n // 1. Explicit option from the caller takes precedence\n // 2. If any esbuild context detected a production build, skip\n // 3. esbuild's own watch mode is a positive signal\n const shouldWatch = options?.watch ?? !isBuildMode;\n\n if (shouldWatch) {\n startContentWatcher(config!, { label: 'angular-intlayer' });\n\n if (!hasHandledHiddenTypesDirectory) {\n hasHandledHiddenTypesDirectory = true;\n handleHiddenTypesDirectory(config!, appLogger);\n }\n }\n });\n },\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAM,kBAAkB,cACtB,uBAAuB,cAAc,YAAY,GAAG,CAAC,CACvD;;AAGA,MAAM,0BACJ;;AAGF,MAAM,6BAA6B;;AAGnC,MAAM,yBACJ;;;;;;;;AAoGF,MAAM,8BACJ,eACA,cACG;CACH,MAAM,EAAE,SAAS,UAAU,0BAA0B,cAAc;CAEnE,MAAM,oBAAoB,CACxB,mBAAG,IAAI,IAAI,CAAC,UAAU,qBAAqB,CAAC,CAC9C,CAAC,CAAC,QAAQ,cAAc,oBAAoB,SAAS,SAAS,CAAC;CAE/D,IAAI,kBAAkB,WAAW,GAAG;CAEpC,IAAI,4BAA4B,mBAAmB,qBAAqB,GACtE;CAGF,UACE;EACE,yCAAyC,kBAAkB,KAAK,cAAc,SAAS,SAAS,SAAS,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE;EACvH;EACA;CACF,CAAC,CAAC,KAAK,GAAG,GACV,EAAE,OAAO,OAAO,CAClB;AACF;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,yBACX,YACkB;CAOlB,IAAI,SAAqD;CACzD,IAAI,QAAuC;CAG3C,IA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A,IAAI,OAAO,MAAM,qBAAqB;IACpC,MAAM,yBAAyB,cAC7B,OAAO,OAAO,sBAChB;IAEA,MAAM,OACJ,EAAE,QAAQ,yBAAyB,sBAAsB,EAAE,GAC3D,OAAO,EAAE,WAAW;KAElB,IAAI,CADc,cAAc,IACnB,CAAC,CAAC,WAAW,GAAG,uBAAuB,EAAE,GACpD,OAAO;KAET,MAAM,OAAO,MAAM,SAAS,MAAM,OAAO;KACzC,MAAM,SAAS,uBAAuB,MAAM,eAAe;KAE3D,IAAI,OAAO,SAAS,OAAO;KAE3B,OAAO;MAAE,UAAU,OAAO;MAAM,QAAQ;KAAK;IAC/C,CACF;GACF;GAEA,MAAM,QAAQ,YAAY;IAGxB,IAAI,yBAAyB,QAC3B,wBACE,MAAM,MAAM,QAAQ,iBAAiB;KACnC,MAAM;KACN,YAAY,OAAQ,OAAO;IAC7B,CAAC,EAAC,CACF;IASJ,IAFoB,SAAS,SAAS,CAAC,aAEtB;KACf,oBAAoB,QAAS,EAAE,OAAO,mBAAmB,CAAC;KAE1D,IAAI,CAAC,gCAAgC;MACnC,iCAAiC;MACjC,2BAA2B,QAAS,SAAS;KAC/C;IACF;GACF,CAAC;EACH;CACF;AACF"}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/** Batch of changed paths, as `@angular/build`'s watcher yields it. */
|
|
2
|
+
export type ChangedFilesLike = {
|
|
3
|
+
added: Set<string>;
|
|
4
|
+
modified: Set<string>;
|
|
5
|
+
removed: Set<string>;
|
|
6
|
+
readonly all: string[];
|
|
7
|
+
};
|
|
8
|
+
/** Watcher returned by `@angular/build`'s `createWatcher`. */
|
|
9
|
+
export type AngularWatcher = AsyncIterableIterator<ChangedFilesLike> & {
|
|
10
|
+
add: (paths: string | readonly string[]) => void;
|
|
11
|
+
remove: (paths: string | readonly string[]) => void;
|
|
12
|
+
close: () => Promise<void>;
|
|
13
|
+
};
|
|
14
|
+
/** Exports of `@angular/build/src/tools/esbuild/watcher.js` the bridge uses. */
|
|
15
|
+
export type AngularWatcherModule = {
|
|
16
|
+
createWatcher: (options?: unknown) => AngularWatcher;
|
|
17
|
+
ChangedFiles: new () => ChangedFilesLike;
|
|
18
|
+
};
|
|
19
|
+
/** Name of the script whose rewrite makes TypeScript re-check every file. */
|
|
20
|
+
export declare const TYPES_REVISION_FILE_NAME = "angular-types-revision.d.ts";
|
|
21
|
+
/** Generated declaration files: absolute path → contents. */
|
|
22
|
+
export type FileContents = Map<string, string>;
|
|
23
|
+
/**
|
|
24
|
+
* Reads the declaration files of `directories`. A missing directory counts as
|
|
25
|
+
* empty.
|
|
26
|
+
*/
|
|
27
|
+
export declare const readFileContents: (directories: string[]) => FileContents;
|
|
28
|
+
/**
|
|
29
|
+
* Files added, modified or removed between two snapshots. Comparing contents
|
|
30
|
+
* rather than times keeps an identical rewrite from triggering a rebuild.
|
|
31
|
+
*/
|
|
32
|
+
export declare const diffFileContents: (previousContents: FileContents, currentContents: FileContents, changedFiles: ChangedFilesLike) => ChangedFilesLike;
|
|
33
|
+
/**
|
|
34
|
+
* Contents of the revision script. It has no import or export, so TypeScript
|
|
35
|
+
* treats it as affecting the global scope: rewriting it re-checks every file.
|
|
36
|
+
*/
|
|
37
|
+
export declare const getTypesRevisionContents: (revision: number) => string;
|
|
38
|
+
/**
|
|
39
|
+
* Wraps an Angular watcher so it also yields the batches `subscribe` reports.
|
|
40
|
+
*
|
|
41
|
+
* The rebuild loop awaits one `next()` at a time: a pending call of the
|
|
42
|
+
* original watcher is kept across calls, so no change it reports is lost when
|
|
43
|
+
* an injected batch is returned first.
|
|
44
|
+
*/
|
|
45
|
+
export declare const mergeInjectedChanges: (angularWatcher: AngularWatcher, subscribe: (listener: (changedFiles: ChangedFilesLike) => void) => () => void) => AngularWatcher;
|
|
46
|
+
/**
|
|
47
|
+
* Reports the declarations Intlayer rewrites under a dot-directory to the
|
|
48
|
+
* Angular dev server's watcher.
|
|
49
|
+
*
|
|
50
|
+
* That watcher ignores `<workspace>/**\/.*\/**`, so a rewritten
|
|
51
|
+
* `.intlayer/types` file is never reported and the TypeScript cache keeps the
|
|
52
|
+
* stale declaration: a key added to a dictionary fails template type-checking
|
|
53
|
+
* until `ng serve` restarts. Wrapping `createWatcher` — read by the builder
|
|
54
|
+
* only once the first build is done, after plugin setup — makes it yield the
|
|
55
|
+
* changed declarations too, so Angular rebuilds and re-reads them itself.
|
|
56
|
+
*
|
|
57
|
+
* @param directories - Absolute directories holding the generated declarations.
|
|
58
|
+
* @param revisionDirectory - Directory, covered by the tsconfig `include`, that
|
|
59
|
+
* receives the revision script (the module augmentation one).
|
|
60
|
+
* @returns Whether a loaded Angular watcher module was wrapped.
|
|
61
|
+
*/
|
|
62
|
+
export declare const bridgeTypesToAngularWatcher: (directories: string[], revisionDirectory: string) => boolean;
|
|
63
|
+
//# sourceMappingURL=angularWatcherTypesBridge.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"angularWatcherTypesBridge.d.ts","names":[],"sources":["../../../src/esbuild/angularWatcherTypesBridge.ts"],"mappings":";YAYY;EACV,OAAO;EACP,UAAU;EACV,SAAS;WACA;;;YAIC,iBAAiB,sBAAsB;EACjD,MAAM;EACN,SAAS;EACT,aAAa;;;YAIH;EACV,gBAAgB,sBAAsB;EACtC,wBAAwB;;;qBAoBb;;YAGD,eAAe;;;;;qBAMd,mBAAgB,0BAA4B;;;;;qBAkC5C,mBAAgB,kBACT,cAAY,iBACb,cAAY,cACf,qBACb;;;;;qBAmBU,2BAAwB;;;;;;;;qBAiBxB,uBAAoB,gBACf,gBAAc,YAClB,WAAW,cAAc,6CACpC;;;;;;;;;;;;;;;;;qBA0LU,8BAA2B,uBACjB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.d.ts","names":[],"sources":["../../../src/esbuild/plugin.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"plugin.d.ts","names":[],"sources":["../../../src/esbuild/plugin.ts"],"mappings":";YAiEY;EACV;EACA;EACA;EACA;EACA;EACA;;YAGU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;;YAGU;EACV;EACA;EACA;;YAGU;EACV;EACA;;EAEA;;iBAGe;EACf;IACE,QAAQ;IACR,SAAS;IACT;IACA;;IAEA;;EAEF,QAAQ,uBAAuB;;EAE/B,UACE;IAAW,QAAQ;IAAQ;KAC3B,WACE,MAAM,uBAEJ,0CAGA,QAAQ;;EAGd,QACE,cACA,SAAS,QAAQ,KAAK,+BACrB,QAAQ;IAAyB;IAAc;;;EAElD,OACE;IAAW,QAAQ;IAAQ;KAC3B,WACE,MAAM,oBAEJ,uCAGA,QAAQ;;iBAIC;EACf;EACA,MAAM,OAAO,4BAA4B;;YAG/B;EACV,gBAAgB;;;;;;;;EAQhB;;;;;;;;;;;;;;;;;;;;;;;;qBA0DW,wBAAqB,UACtB,iCACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "angular-intlayer",
|
|
3
|
-
"version": "9.8.
|
|
3
|
+
"version": "9.8.4",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Easily internationalize i18n your Angular applications with type-safe multilingual content management.",
|
|
6
6
|
"keywords": [
|
|
@@ -120,13 +120,13 @@
|
|
|
120
120
|
"@babel/core": "^8.0.1",
|
|
121
121
|
"@babel/plugin-syntax-import-attributes": "7.29.7",
|
|
122
122
|
"@babel/preset-env": "8.0.7",
|
|
123
|
-
"@intlayer/config": "9.8.
|
|
124
|
-
"@intlayer/core": "9.8.
|
|
125
|
-
"@intlayer/dictionaries-entry": "9.8.
|
|
126
|
-
"@intlayer/editor": "9.8.
|
|
127
|
-
"@intlayer/engine": "9.8.
|
|
128
|
-
"@intlayer/types": "9.8.
|
|
129
|
-
"@intlayer/webpack": "9.8.
|
|
123
|
+
"@intlayer/config": "9.8.4",
|
|
124
|
+
"@intlayer/core": "9.8.4",
|
|
125
|
+
"@intlayer/dictionaries-entry": "9.8.4",
|
|
126
|
+
"@intlayer/editor": "9.8.4",
|
|
127
|
+
"@intlayer/engine": "9.8.4",
|
|
128
|
+
"@intlayer/types": "9.8.4",
|
|
129
|
+
"@intlayer/webpack": "9.8.4",
|
|
130
130
|
"babel-loader": "10.1.1",
|
|
131
131
|
"defu": "6.1.7"
|
|
132
132
|
},
|
|
@@ -156,7 +156,7 @@
|
|
|
156
156
|
}
|
|
157
157
|
},
|
|
158
158
|
"optionalDependencies": {
|
|
159
|
-
"@intlayer/analytics": "9.8.
|
|
159
|
+
"@intlayer/analytics": "9.8.4"
|
|
160
160
|
},
|
|
161
161
|
"engines": {
|
|
162
162
|
"node": ">=14.18"
|