@wavemaker/rn-codegen 11.16.0-rc.647821 → 11.16.1-rc.647845

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.
Files changed (142) hide show
  1. package/command.js +111 -269
  2. package/command.js.map +1 -1
  3. package/index.js +1 -1
  4. package/index.js.map +1 -1
  5. package/npm-shrinkwrap.json +4840 -3624
  6. package/package-lock.json +4840 -3624
  7. package/package.json +62 -42
  8. package/src/app.generator.js +249 -87
  9. package/src/app.generator.js.map +1 -1
  10. package/src/fomatter.js.map +1 -1
  11. package/src/handlebar-helpers.js.map +1 -1
  12. package/src/increment-builder.js.map +1 -1
  13. package/src/pipeline/build-common.js +63 -0
  14. package/src/pipeline/build-common.js.map +1 -0
  15. package/src/pipeline/build-pipeline.js +152 -0
  16. package/src/pipeline/build-pipeline.js.map +1 -0
  17. package/src/pipeline/generation-store.js +288 -0
  18. package/src/pipeline/generation-store.js.map +1 -0
  19. package/src/pipeline/shared-node-modules.js +775 -0
  20. package/src/pipeline/shared-node-modules.js.map +1 -0
  21. package/src/pipeline/web-preview-templates.js +80 -0
  22. package/src/pipeline/web-preview-templates.js.map +1 -0
  23. package/src/pipeline/working-set.js +103 -0
  24. package/src/pipeline/working-set.js.map +1 -0
  25. package/src/profiles/legacy-web-preview.profile.js +15 -0
  26. package/src/profiles/legacy-web-preview.profile.js.map +1 -0
  27. package/src/project.service.js +17 -7
  28. package/src/project.service.js.map +1 -1
  29. package/src/templates/babel.config.js.template +0 -1
  30. package/src/templates/bootstrap.template +3 -1
  31. package/src/templates/device-plugin-service.template +7 -9
  32. package/src/templates/package.web.json +108 -83
  33. package/src/templates/page-stub.template +27 -0
  34. package/src/templates/project/app.json +4 -11
  35. package/src/templates/project/esbuild/esbuild.script.js +129 -89
  36. package/src/templates/project/metro/container-limits.js +195 -0
  37. package/src/templates/project/metro/metro.script.js +833 -0
  38. package/src/templates/project/metro/module-path.js +237 -0
  39. package/src/templates/project/metro/split.serializer.js +184 -0
  40. package/src/templates/project/metro/split.static.js +633 -0
  41. package/src/templates/project/metro/stable-module-ids.js +54 -0
  42. package/src/templates/project/metro/vendor-cache.js +475 -0
  43. package/src/templates/project/metro/wm-boundary.js +138 -0
  44. package/src/templates/project/metro/wm-crawl-override.js +147 -0
  45. package/src/templates/project/metro/wm-fastbuild.js +196 -0
  46. package/src/templates/project/metro/wm-live-reload.js +482 -0
  47. package/src/templates/project/metro/wm-metro-adapter.js +25 -0
  48. package/src/templates/project/metro.config.js +209 -8
  49. package/src/templates/project/package.json +106 -83
  50. package/src/templates/project/patch-utils.js +331 -0
  51. package/src/templates/project/scripts/post-build.js +3 -0
  52. package/src/theme/app-override-css.generator.js +10 -4
  53. package/src/theme/app-override-css.generator.js.map +1 -1
  54. package/src/theme/components/basic/base.styledef.js.map +1 -1
  55. package/src/theme/components/style-definition.provider.js.map +1 -1
  56. package/src/theme/font-stylesheet.transpiler.js +17 -7
  57. package/src/theme/font-stylesheet.transpiler.js.map +1 -1
  58. package/src/theme/rn-stylesheet.transpiler.js +17 -7
  59. package/src/theme/rn-stylesheet.transpiler.js.map +1 -1
  60. package/src/theme/theme.service.js +7 -19
  61. package/src/theme/theme.service.js.map +1 -1
  62. package/src/theme/token.transpiler.js +17 -7
  63. package/src/theme/token.transpiler.js.map +1 -1
  64. package/src/transpile/bind.ex.transformer.js +36 -23
  65. package/src/transpile/bind.ex.transformer.js.map +1 -1
  66. package/src/transpile/components/advanced/carousel.transformer.js.map +1 -1
  67. package/src/transpile/components/advanced/customwidget.transformer.js.map +1 -1
  68. package/src/transpile/components/advanced/login.transformer.js.map +1 -1
  69. package/src/transpile/components/advanced/webview.transformer.js.map +1 -1
  70. package/src/transpile/components/basic/buttongroup.transformer.js.map +1 -1
  71. package/src/transpile/components/basic/custom.transformer.js.map +1 -1
  72. package/src/transpile/components/basic/picture.transformer.js.map +1 -1
  73. package/src/transpile/components/basic/progress-bar.transformer.js.map +1 -1
  74. package/src/transpile/components/basic/search.transformer.js.map +1 -1
  75. package/src/transpile/components/chart/area-chart.transformer.js.map +1 -1
  76. package/src/transpile/components/container/accordion/accordionpane.transformer.js.map +1 -1
  77. package/src/transpile/components/container/accordion.transformer.js.map +1 -1
  78. package/src/transpile/components/container/container.transformer.js.map +1 -1
  79. package/src/transpile/components/container/layoutgrid/gridcolumn.transformer.js.map +1 -1
  80. package/src/transpile/components/container/layoutgrid/gridrow.transformer.js.map +1 -1
  81. package/src/transpile/components/container/layoutgrid.transformer.js.map +1 -1
  82. package/src/transpile/components/container/linearlayout.transformer.js.map +1 -1
  83. package/src/transpile/components/container/panel.transformer.js.map +1 -1
  84. package/src/transpile/components/container/tabs/tabpane.transformer.js.map +1 -1
  85. package/src/transpile/components/container/tabs.transformer.js.map +1 -1
  86. package/src/transpile/components/container/wizard/wizardstep.transformer.js.map +1 -1
  87. package/src/transpile/components/container/wizard.transformer.js.map +1 -1
  88. package/src/transpile/components/data/card/card-content.transformer.js.map +1 -1
  89. package/src/transpile/components/data/form/form-action.transformer.js.map +1 -1
  90. package/src/transpile/components/data/form/form-field.transformer.js.map +1 -1
  91. package/src/transpile/components/data/form.transformer.js.map +1 -1
  92. package/src/transpile/components/data/list.transformer.js +17 -7
  93. package/src/transpile/components/data/list.transformer.js.map +1 -1
  94. package/src/transpile/components/data/liveform.transformer.js.map +1 -1
  95. package/src/transpile/components/dialogs/dialog.transformer.js.map +1 -1
  96. package/src/transpile/components/input/checkboxset.transformer.js.map +1 -1
  97. package/src/transpile/components/input/chips.transformer.js.map +1 -1
  98. package/src/transpile/components/input/epoch/date.transformer.js.map +1 -1
  99. package/src/transpile/components/input/epoch/datetime.transformer.js.map +1 -1
  100. package/src/transpile/components/input/epoch/time.transformer.js.map +1 -1
  101. package/src/transpile/components/input/radioset.transformer.js.map +1 -1
  102. package/src/transpile/components/input/rating.transformer.js.map +1 -1
  103. package/src/transpile/components/input/select.transformer.js.map +1 -1
  104. package/src/transpile/components/input/slider.transformer.js.map +1 -1
  105. package/src/transpile/components/input/switch.transformer.js.map +1 -1
  106. package/src/transpile/components/input/textarea.transformer.js.map +1 -1
  107. package/src/transpile/components/input/toggle.transformer.js.map +1 -1
  108. package/src/transpile/components/navigation/appnavbar.transformer.js.map +1 -1
  109. package/src/transpile/components/navigation/menu.transformer.js.map +1 -1
  110. package/src/transpile/components/navigation/navbar.transformer.js.map +1 -1
  111. package/src/transpile/components/navigation/navitem.transformer.js.map +1 -1
  112. package/src/transpile/components/navigation/popover.transformer.js.map +1 -1
  113. package/src/transpile/components/page/left-panel.transformer.js.map +1 -1
  114. package/src/transpile/components/page/page.transformer.js.map +1 -1
  115. package/src/transpile/components/page/partial-container.transformer.js +17 -7
  116. package/src/transpile/components/page/partial-container.transformer.js.map +1 -1
  117. package/src/transpile/components/prefab/prefab.transformer.js.map +1 -1
  118. package/src/transpile/components/utils.js.map +1 -1
  119. package/src/transpile/property/property-parser.js.map +1 -1
  120. package/src/transpile/property/show-in-device.parser.js.map +1 -1
  121. package/src/transpile/style/background-image.parser.js.map +1 -1
  122. package/src/transpile/style/dimension-style.parser.js.map +1 -1
  123. package/src/transpile/style/multi-dimension-style.parser.js.map +1 -1
  124. package/src/transpile/style/numeric-style.parser.js.map +1 -1
  125. package/src/transpile/style.transformer.js.map +1 -1
  126. package/src/transpile/transpile.js +17 -7
  127. package/src/transpile/transpile.js.map +1 -1
  128. package/src/utils.js +8 -1
  129. package/src/utils.js.map +1 -1
  130. package/src/variables/variable.transformer.js.map +1 -1
  131. package/src/wm-namespace.js +14 -0
  132. package/src/wm-namespace.js.map +1 -0
  133. package/test/pipeline/live-reload-pacing.test.js +76 -0
  134. package/test/pipeline/live-reload-pacing.test.js.map +1 -0
  135. package/test/pipeline/npm-install-retry.test.js +57 -0
  136. package/test/pipeline/npm-install-retry.test.js.map +1 -0
  137. package/test/pipeline/repair-vendor-packages.test.js +134 -0
  138. package/test/pipeline/repair-vendor-packages.test.js.map +1 -0
  139. package/test/pipeline/web-preview-files.test.js +48 -0
  140. package/test/pipeline/web-preview-files.test.js.map +1 -0
  141. package/web-preview.js +165 -0
  142. package/web-preview.js.map +1 -0
@@ -0,0 +1,833 @@
1
+ // PREFLIGHT — MUST STAY ABOVE THE require()s BELOW. That placement is the whole point of it.
2
+ // This script and its siblings need packages the generated app's package.json does NOT declare:
3
+ // metro-cache (here), jsc-safe-url + proper-lockfile (module-path.js), cacache (vendor-cache.js).
4
+ // They arrive only as transitive dependencies of expo. installDependencies' overlay-skip compares
5
+ // DECLARED dependencies against the vendor tree (computeVendorDelta), so it structurally cannot
6
+ // notice one of these going missing and will happily skip npm install. Node's own failure for that
7
+ // is a bare MODULE_NOT_FOUND from line 1 — exactly what the old esbuild pipeline produced
8
+ // ("Cannot find module 'esbuild'"), which read as a codegen crash rather than a missing install.
9
+ // Name the packages and the remedy instead.
10
+ (() => {
11
+ const required = ['fs-extra', 'metro-cache', 'cacache', 'jsc-safe-url', 'proper-lockfile'];
12
+ const missing = required.filter((m) => {
13
+ try { require.resolve(m); return false; } catch { return true; }
14
+ });
15
+ if (missing.length) {
16
+ console.error(`[metro] cannot start — ${missing.length} required package(s) missing from the `
17
+ + `generated app's node_modules: ${missing.join(', ')}`);
18
+ console.error('[metro] these are transitive deps of expo and are NOT declared in package.json, '
19
+ + 'so the install-skip cannot see them. Re-run this build with WM_DISABLE_OVERLAY_SKIP=1 to '
20
+ + 'force a real npm install.');
21
+ process.exit(1);
22
+ }
23
+ })();
24
+
25
+ const fs = require('fs-extra');
26
+ const path = require('path');
27
+ const crypto = require('crypto');
28
+ const patches = require('../patch-utils');
29
+ const { sharedMetroCacheRoot, projectMetroCacheRoot, withLock,
30
+ buildAdmissionPath, containerMemoryLimitMB, oomKillCount, waitForBuildHeadroom, expoAssetCacheFile,
31
+ } = require('./module-path');
32
+ const { readAndReplaceFileContent, WM_NPM_SCOPE } = patches;
33
+
34
+ // A runtime change starts a new <generation> folder; drop the older ones in both the shared and project cache.
35
+ // The shared parent holds generations for every package scope (@wavemaker, @wavemaker-ai). Each generation is
36
+ // stamped with its scope, and only same-scope siblings are removed. Unstamped siblings are kept.
37
+ const readTrimmed = (file) => { try { return fs.readFileSync(file, 'utf8').trim(); } catch { return ''; } };
38
+ const cleanupStaleMetroCacheOnVersionChange = (projectRoot) => {
39
+ const vendorDir = readTrimmed(path.join(projectRoot, '.wm-vendor-generation'));
40
+ const scope = vendorDir && readTrimmed(path.join(vendorDir, '.wm-last-used'));
41
+ for (const currentRoot of [sharedMetroCacheRoot(projectRoot), projectMetroCacheRoot(projectRoot)]) {
42
+ try {
43
+ fs.mkdirpSync(currentRoot);
44
+ if (!scope) continue;
45
+ fs.writeFileSync(path.join(currentRoot, '.wm-scope'), scope);
46
+ const parent = path.dirname(currentRoot);
47
+ fs.readdirSync(parent)
48
+ .filter((entry) => entry !== path.basename(currentRoot))
49
+ .filter((entry) => readTrimmed(path.join(parent, entry, '.wm-scope')) === scope)
50
+ .forEach((entry) => fs.removeSync(path.join(parent, entry)));
51
+ } catch (err) {
52
+ console.warn(`[metro-cache] failed to prune stale transform cache under ${currentRoot}:`, err.message);
53
+ }
54
+ }
55
+ };
56
+
57
+ // The "preview" block of the project's wm_rn_config.json: { "liveReload": false } turns the live-reload
58
+ // client off (no index.html / build-status.json requests at all), { "pollIntervalMs": N } sets its interval.
59
+ // Metro runs only under the web-preview profile, so only the web preview reads this.
60
+ function previewConfig() {
61
+ const src = process.env.WM_PROJECT_SRC;
62
+ return (src && fs.readJsonSync(path.resolve(src, 'wm_rn_config.json'), { throws: false })?.preview) || {};
63
+ }
64
+
65
+ // Poll interval while a build is running, from wm_rn_config.json "preview": { "pollIntervalMs": N }.
66
+ function previewPollIntervalMs() {
67
+ const override = parseInt(process.env.WM_LIVE_RELOAD_INTERVAL_MS, 10);
68
+ if (override > 0) return override;
69
+ const ms = Number(previewConfig().pollIntervalMs);
70
+ return Number.isInteger(ms) && ms > 0 ? ms : 2000;
71
+ }
72
+
73
+ function exportHeapCapMB() {
74
+ const override = parseInt(process.env.WM_MAX_OLD_SPACE_MB, 10);
75
+ if (override > 0) return override;
76
+ const limit = containerMemoryLimitMB();
77
+ return Math.max(512, Math.min(2560, Math.floor(limit * 0.4)));
78
+ }
79
+
80
+ function killTree(rootPid, label) {
81
+ const { execSync } = require('child_process');
82
+ const collect = (pid, acc) => {
83
+ acc.push(pid);
84
+ let out = '';
85
+ try { out = execSync(`pgrep -P ${pid} 2>/dev/null || true`, { encoding: 'utf8' }); } catch {}
86
+ for (const line of out.split('\n')) {
87
+ const child = parseInt(line.trim(), 10);
88
+ if (child > 0 && !acc.includes(child)) collect(child, acc);
89
+ }
90
+ return acc;
91
+ };
92
+ let pids = [];
93
+ try { pids = collect(rootPid, []); } catch { pids = [rootPid]; }
94
+ try { process.kill(-rootPid, 'SIGKILL'); } catch {}
95
+ for (const pid of pids.reverse()) {
96
+ try { process.kill(pid, 'SIGKILL'); } catch {}
97
+ }
98
+ const isZombie = (pid) => {
99
+ try {
100
+ // field 3 of /proc/<pid>/stat is the state char; 'Z' = zombie, already exited.
101
+ const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
102
+ return / (Z) /.test(stat.slice(stat.lastIndexOf(')') + 1, stat.lastIndexOf(')') + 4));
103
+ } catch { return false; }
104
+ };
105
+ const stillRunning = () => pids.filter((pid) => {
106
+ try { process.kill(pid, 0); } catch { return false; }
107
+ return !isZombie(pid);
108
+ });
109
+
110
+ // Synchronous sleep without spawning a process — killTree runs on the hot path.
111
+ const sleepSync = (ms) => {
112
+ try { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); } catch {}
113
+ };
114
+
115
+ let survivors = stillRunning();
116
+ // ~500ms total, enough for the kernel to deliver SIGKILL to a healthy tree.
117
+ for (let attempt = 0; attempt < 10 && survivors.length; attempt++) {
118
+ sleepSync(50);
119
+ survivors = stillRunning();
120
+ }
121
+
122
+ if (survivors.length) {
123
+ console.log(`[metro] reaped ${pids.length - survivors.length}/${pids.length} pid(s) for ${label}`
124
+ + ` — SURVIVORS: ${survivors.join(',')} (still alive ~500ms after SIGKILL)`);
125
+ } else {
126
+ console.log(`[metro] reaped ${pids.length}/${pids.length} pid(s) for ${label}`);
127
+ }
128
+ return survivors;
129
+ }
130
+
131
+ // Expo prints no bundling progress when stdout is a pipe (MetroTerminalReporter._getStatusMessage
132
+ // returns '' when non-interactive), so a large project is silent for most of its build. Output
133
+ // alone cannot tell "busy" from "blocked on an OOM-killed worker"; CPU time can — a parent waiting
134
+ // on a dead worker sits near zero, while transforming or serializing keeps a core busy.
135
+ const PROC_AVAILABLE = fs.existsSync('/proc/self/stat');
136
+
137
+ /**
138
+ * Samples CPU and resident memory of rootPid's tree (its descendants plus anything left in its
139
+ * process group) from /proc. sample() returns null where /proc is unavailable.
140
+ */
141
+ function createTreeSampler(rootPid) {
142
+ if (!PROC_AVAILABLE) { return { sample: () => null }; }
143
+ const { execSync } = require('child_process');
144
+ const getconf = (name, fallback) => {
145
+ try { return parseInt(execSync(`getconf ${name}`, { encoding: 'utf8' }), 10) || fallback; } catch { return fallback; }
146
+ };
147
+ const clkTck = getconf('CLK_TCK', 100);
148
+ const pageSize = getconf('PAGESIZE', 4096);
149
+ let prevTicks = new Map();
150
+ let prevAt = Date.now();
151
+
152
+ const readProcs = () => {
153
+ const procs = new Map();
154
+ for (const entry of fs.readdirSync('/proc')) {
155
+ if (!/^\d+$/.test(entry)) { continue; }
156
+ try {
157
+ const stat = fs.readFileSync(`/proc/${entry}/stat`, 'utf8');
158
+ // Fields after the ")" closing the command name: [1] ppid, [2] pgrp, [11] utime, [12] stime, [21] rss.
159
+ const f = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
160
+ procs.set(parseInt(entry, 10), {
161
+ ppid: parseInt(f[1], 10),
162
+ pgrp: parseInt(f[2], 10),
163
+ ticks: parseInt(f[11], 10) + parseInt(f[12], 10),
164
+ rssPages: parseInt(f[21], 10),
165
+ });
166
+ } catch {
167
+ // exited between readdir and read
168
+ }
169
+ }
170
+ return procs;
171
+ };
172
+
173
+ return {
174
+ // { cores, rssMB, procs } — cores is CPU used since the previous sample (1.0 = one core fully busy).
175
+ sample() {
176
+ let procs;
177
+ try { procs = readProcs(); } catch { return null; }
178
+ const tree = new Set([rootPid]);
179
+ for (const [pid, p] of procs) {
180
+ if (p.pgrp === rootPid) { tree.add(pid); }
181
+ }
182
+ for (let grew = true; grew;) {
183
+ grew = false;
184
+ for (const [pid, p] of procs) {
185
+ if (!tree.has(pid) && tree.has(p.ppid)) { tree.add(pid); grew = true; }
186
+ }
187
+ }
188
+ const now = Date.now();
189
+ const ticks = new Map();
190
+ let deltaTicks = 0;
191
+ let rssPages = 0;
192
+ for (const pid of tree) {
193
+ const p = procs.get(pid);
194
+ if (!p) { continue; }
195
+ ticks.set(pid, p.ticks);
196
+ // A pid new since the last sample contributes its whole (short) lifetime.
197
+ deltaTicks += Math.max(0, p.ticks - (prevTicks.get(pid) || 0));
198
+ rssPages += p.rssPages;
199
+ }
200
+ const elapsedSec = Math.max(1, (now - prevAt) / 1000);
201
+ prevTicks = ticks;
202
+ prevAt = now;
203
+ return {
204
+ cores: deltaTicks / clkTck / elapsedSec,
205
+ rssMB: Math.round((rssPages * pageSize) / (1024 * 1024)),
206
+ procs: ticks.size,
207
+ };
208
+ },
209
+ };
210
+ }
211
+
212
+ // PUBLISH GATE. "Requiring unknown module <id>" means the chunks a page loads reference a module id
213
+ // that no chunk defines. That is statically checkable, so it is checked before anything is served,
214
+ // whatever produced it — a poisoned cache, a vendor chunk built for another project, a layout change.
215
+ // Chunk format (validated on real preview chunks): __d(function(...){...},ID,[DEPS]) where DEPS may
216
+ // contain `null` for a require Metro could not resolve (an optional dependency) — those are skipped,
217
+ // not reported. Returns status 'ok' | 'broken' | 'unverified'; 'unverified' means the chunks did not
218
+ // parse the way this check expects, and the build is then published unchanged rather than blocked by
219
+ // a checker bug.
220
+ const DEFINE_TRAILER = /\},(\d+),\[((?:\d+|null)(?:,(?:\d+|null))*)?\]\)/g;
221
+ const SERVED_CHUNK = /src="(?:\.?\/)?([0-9a-f]+-(?:vendor|user|extras|wmx|modified|boot)\.js)"/g;
222
+
223
+ function readChunkSource(staging, file) {
224
+ const code = fs.readFileSync(path.join(staging, file), 'utf8');
225
+ if (code.length || !/-vendor\.js$/.test(file)) return code;
226
+ // The vendor chunk is hardlinked from the shared cache after this check, so staging only holds a
227
+ // 0-byte placeholder; the real bytes are at the cache path recorded by the serializer.
228
+ const link = fs.readJSONSync(path.join(__dirname, '..', '.wm-vendor-link.json'));
229
+ if (path.basename(link.filename) !== file || !link.cachePath) {
230
+ throw new Error(`vendor bytes for ${file} are not where .wm-vendor-link.json says`);
231
+ }
232
+ return fs.readFileSync(link.cachePath, 'utf8');
233
+ }
234
+
235
+ function checkChunkIntegrity(staging) {
236
+ try {
237
+ const html = fs.readFileSync(path.join(staging, 'index.html'), 'utf8');
238
+ const files = [...html.matchAll(SERVED_CHUNK)].map(m => m[1]);
239
+ if (!files.length) return { status: 'unverified', reason: 'no chunk <script> tags in index.html' };
240
+ const defined = new Set();
241
+ // First registration wins, so the chunk that defines an id first (in load order) owns it.
242
+ const owner = new Map();
243
+ const refs = [];
244
+ for (const file of files) {
245
+ const code = readChunkSource(staging, file);
246
+ const opens = (code.match(/__d\(/g) || []).length;
247
+ let found = 0;
248
+ let m;
249
+ DEFINE_TRAILER.lastIndex = 0;
250
+ while ((m = DEFINE_TRAILER.exec(code))) {
251
+ found++;
252
+ defined.add(m[1]);
253
+ if (!owner.has(m[1])) owner.set(m[1], chunkKind(file));
254
+ for (const dep of (m[2] ? m[2].split(',') : [])) {
255
+ if (dep !== 'null') refs.push({ id: dep, by: m[1], file });
256
+ }
257
+ }
258
+ if (found !== opens) {
259
+ return { status: 'unverified', reason: `${file}: ${opens} __d( but ${found} parsed definitions` };
260
+ }
261
+ if (/-boot\.js$/.test(file)) {
262
+ for (const b of code.matchAll(/__r\((\d+)\)/g)) refs.push({ id: b[1], by: 'entry', file });
263
+ }
264
+ }
265
+ const missing = refs.filter(r => !defined.has(r.id));
266
+ // Layering: vendor may require only vendor, extras only vendor + extras. An edge that climbs a
267
+ // layer is safe for THIS page (the id is defined) but not for the next project served the same
268
+ // cached chunk, so it is caught here rather than when it surfaces as "Requiring unknown module".
269
+ const layering = refs.filter((r) => {
270
+ const from = chunkKind(r.file);
271
+ const to = owner.get(r.id);
272
+ if (!to || r.by === 'entry') return false;
273
+ if (from === 'vendor') return to !== 'vendor';
274
+ if (from === 'extras') return to !== 'vendor' && to !== 'extras';
275
+ return false;
276
+ });
277
+ return {
278
+ status: missing.length ? 'broken' : layering.length ? 'layering' : 'ok',
279
+ chunks: files.length,
280
+ defined: defined.size,
281
+ missing,
282
+ layering,
283
+ };
284
+ } catch (err) {
285
+ return { status: 'unverified', reason: err.message };
286
+ }
287
+ }
288
+
289
+ function chunkKind(file) {
290
+ const m = /-([a-z]+)\.js$/.exec(file);
291
+ return m ? m[1] : 'unknown';
292
+ }
293
+
294
+ function reportGate(gate) {
295
+ if (gate.status === 'ok') {
296
+ console.log(`[gate] chunk set consistent: ${gate.defined} modules across ${gate.chunks} chunks`);
297
+ } else if (gate.status === 'layering') {
298
+ console.warn(`[gate] ${gate.layering.length} dependency edge(s) climb a chunk layer `
299
+ + '(vendor must require only vendor, extras only vendor + extras):');
300
+ for (const r of gate.layering.slice(0, 10)) {
301
+ console.warn(`[gate] ${r.file} module ${r.by} -> ${r.id}`);
302
+ }
303
+ } else if (gate.status === 'unverified') {
304
+ console.warn(`[gate] could not verify the chunk set (${gate.reason}) — publishing unchecked`);
305
+ } else {
306
+ const ids = [...new Set(gate.missing.map(r => r.id))];
307
+ console.error(`[gate] ${ids.length} module id(s) are required but defined in no chunk:`);
308
+ for (const id of ids.slice(0, 10)) {
309
+ const r = gate.missing.find(x => x.id === id);
310
+ console.error(`[gate] ${id} <- module ${r.by} in ${r.file}`);
311
+ }
312
+ }
313
+ }
314
+
315
+ class MetroBuilder {
316
+
317
+ async patchMetroConfig() {
318
+ const metroConfigPath = `${__dirname}/../metro.config.js`;
319
+ await readAndReplaceFileContent(metroConfigPath, (c) => {
320
+ if (c.includes('createSplitSerializer')) {
321
+ return c;
322
+ }
323
+ return c.replace(
324
+ "const path = require('path');",
325
+ `const path = require('path');
326
+ const crypto = require('crypto');
327
+ const createSplitSerializer = require('./metro/split.serializer');
328
+ const createStableModuleIdFactory = require('./metro/stable-module-ids');
329
+ const { createExpoExportWrapper } = require('./metro/split.static');
330
+ const { createMetroCacheStores, PROJECT_CACHE_DIR } = require('./metro/module-path');`,
331
+ );
332
+ });
333
+
334
+ await readAndReplaceFileContent(metroConfigPath, (c) => {
335
+ if (c.includes('createSplitSerializer()')) {
336
+ return c;
337
+ }
338
+ const splitConfig = `
339
+ config.cacheVersion = crypto.createHash('md5')
340
+ .update(fs.readFileSync(__filename))
341
+ .digest('hex');
342
+ config.serializer = {
343
+ ...config.serializer,
344
+ customSerializer: createExpoExportWrapper(
345
+ config.serializer.customSerializer,
346
+ createSplitSerializer(),
347
+ config,
348
+ ),
349
+ createModuleIdFactory: createStableModuleIdFactory,
350
+ };
351
+
352
+ config.cacheStores = createMetroCacheStores(projectRoot);
353
+ config.resolver.blockList = [].concat(config.resolver.blockList || [], PROJECT_CACHE_DIR);
354
+
355
+ config.maxWorkers = 2;
356
+
357
+ return config;
358
+ `;
359
+
360
+ return c.replace('return config;', splitConfig);
361
+ });
362
+
363
+ console.log('Patched Metro Config.');
364
+ }
365
+
366
+ buildLibraries() {
367
+ const usesSharedVendor = fs.existsSync(`${__dirname}/../.wm-vendor-generation`);
368
+ const promises = (usesSharedVendor ? [] : [{
369
+ name: 'expo-web-browser',
370
+ build: (libPath) => {
371
+ fs.writeFileSync(`${libPath}/build/WebBrowser.js`, `
372
+ export const openBrowserAsync = (url) => {
373
+ window.open(url, '_blank');
374
+ };`);
375
+ }
376
+ }]).map(p => {
377
+ let libPath = `${__dirname}/../node_modules/${p.name}`;
378
+ if (!fs.existsSync(libPath)) {
379
+ libPath = `${__dirname}/../node_modules/${WM_NPM_SCOPE}/app-rn-runtime/node_modules/${p.name}`;
380
+ }
381
+ if (!fs.existsSync(libPath)) {
382
+ const msg = `${p.name} library is not found`;
383
+ console.error(msg);
384
+ return Promise.reject(msg);
385
+ }
386
+ return p.build && p.build(libPath);
387
+ });
388
+ const nodeModulePatches = usesSharedVendor ? Promise.resolve() : Promise.all(promises)
389
+ .then(() => patches.patchPackageLib(['@koale/useworker', 'victory',
390
+ 'd3-array', 'd3-color', 'd3-ease', 'd3-format', 'd3-interpolate',
391
+ 'd3-path', 'd3-scale', 'd3-shape', 'd3-time', 'd3-time-format',
392
+ 'd3-timer', 'd3-voronoi']))
393
+ .then(() => patches.patchWithDevTools('expo/build/launch/withDevTools.js'))
394
+ // .then(() => patches.patchReactNativeWeb())
395
+ .then(() => patches.patchReactNativeAssets())
396
+ // .then(() => patches.patchBabelExpoPreset())
397
+ .then(() => patches.patchTouchableRipple())
398
+ .then(() => patches.patchReactNativeReanimated())
399
+ .then(() => patches.patchExpoVideo());
400
+ return nodeModulePatches
401
+ .catch((e) => {
402
+ console.error(e);
403
+ console.log('*********** FAILED TO APPLY NODE_MODULES PATCHES **************');
404
+ })
405
+ .then(() => this.patchMetroConfig())
406
+ .then(() => {
407
+ fs.writeFileSync(`${__dirname}/../.wm-prepare-lib-done`, '1');
408
+ console.log('*********** LIBRARIES ARE BUILT FOR ESBUILD **************');
409
+ }, (e) => {
410
+ console.error(e);
411
+ console.log('*********** FAILED TO BUILD LIBRARIES FOR ESBUILD **************');
412
+ });
413
+ }
414
+
415
+ async build(webapp, boundaryDisabled = false, { bypassChunkCache = false } = {}) {
416
+ const projectRoot = path.resolve(__dirname, '..');
417
+ const { spawn } = require('child_process');
418
+ // Force-kills expo export on its "Exported: " stdout match; this timeout is the backstop if that match never fires.
419
+ // parseInt's 2nd arg is a RADIX, not a default — WM_EXPO_EXPORT_TIMEOUT_MINUTES=45 must parse as 45 minutes in base 10, not base 30.
420
+ const timeoutMs = (parseInt(process.env.WM_EXPO_EXPORT_TIMEOUT_MINUTES, 10) || 60) * 60 * 1000;
421
+ const maxOldSpaceMB = exportHeapCapMB();
422
+ // Stalled = no output AND (where /proc exists) the export tree using under idleCores of CPU.
423
+ const stallMs = (parseInt(process.env.WM_EXPO_EXPORT_STALL_MINUTES, 10) || 5) * 60 * 1000;
424
+ const idleCores = parseFloat(process.env.WM_EXPO_EXPORT_IDLE_CORES) || 0.02;
425
+ // After a container-wide oom_kill rise, how long the tree must sit idle before it counts as ours.
426
+ const oomGraceMs = 60 * 1000;
427
+ console.log(`[metro] expo export heap cap ${maxOldSpaceMB}MB (container limit ${containerMemoryLimitMB()}MB), `
428
+ + `stall watchdog ${stallMs / 60000}min `
429
+ + (PROC_AVAILABLE ? `(no output and cpu < ${Math.round(idleCores * 100)}% of a core)` : '(no output; /proc unavailable)')
430
+ + `, hard timeout ${timeoutMs / 60000}min`);
431
+ const expoBin = path.join(projectRoot, 'node_modules', '.bin', 'expo');
432
+ const useDirectBin = fs.existsSync(expoBin);
433
+ const maxWorkers = parseInt(process.env.WM_METRO_MAX_WORKERS, 10) || 1;
434
+ const exportArgs = ['export', '--platform', 'web',
435
+ '--output-dir', `${webapp}/rn-bundle-next`, '--max-workers', String(maxWorkers)];
436
+
437
+ // Preloaded rather than patched into node_modules so they survive a vendor reinstall.
438
+ const crawlOverride = path.join(__dirname, 'wm-crawl-override.js');
439
+ const boundary = path.join(__dirname, 'wm-boundary.js');
440
+ const nodeOptions = [`--max-old-space-size=${maxOldSpaceMB}`];
441
+ if (process.env.WM_CRAWL_OVERRIDE !== '0' && fs.existsSync(crawlOverride)) {
442
+ nodeOptions.push(`--require ${crawlOverride}`);
443
+ }
444
+ // Without a cached asset list the serializer refuses boundary mode only after the whole graph is
445
+ // transformed (~14 min on large apps), so go straight to the full traversal.
446
+ const boundaryEnabled = process.env.WM_BOUNDARY !== '0' && !boundaryDisabled && fs.existsSync(boundary)
447
+ && fs.existsSync(path.join(projectRoot, expoAssetCacheFile('web')));
448
+ if (boundaryEnabled) {
449
+ nodeOptions.push(`--require ${boundary}`);
450
+ }
451
+
452
+ return new Promise((resolve, reject) => {
453
+ const child = spawn(
454
+ useDirectBin ? expoBin : 'npx',
455
+ useDirectBin ? exportArgs : ['expo', ...exportArgs],
456
+ {
457
+ cwd: projectRoot,
458
+ stdio: ['ignore', 'pipe', 'pipe'],
459
+ detached: true,
460
+ env: {
461
+ ...process.env,
462
+ NODE_OPTIONS: nodeOptions.join(' '),
463
+ WM_CRAWL_PROJECT_ROOT: projectRoot,
464
+ WM_BOUNDARY: boundaryEnabled ? '1' : '0',
465
+ WM_BYPASS_CHUNK_CACHE: bypassChunkCache ? '1' : '0',
466
+ EXPO_IMAGE_UTILS_NO_SHARP: '1',
467
+ EXPO_NO_TELEMETRY: '1',
468
+ EXPO_OFFLINE: '1',
469
+ },
470
+ },
471
+ );
472
+
473
+ let done = false;
474
+ let stallTimer = null;
475
+ const finish = (fn, arg) => {
476
+ if (done) return;
477
+ done = true;
478
+ clearTimeout(timeout);
479
+ clearInterval(stallTimer);
480
+ fn(arg);
481
+ };
482
+
483
+ const timeout = setTimeout(() => {
484
+ killTree(child.pid, 'expo export (hard timeout)');
485
+ finish(reject, new Error(
486
+ `expo export timed out after ${timeoutMs / 60000} minute(s) without exiting or printing ` +
487
+ `its completion message — this may mean the Expo CLI's output format changed (see the ` +
488
+ `"Exported: " match in build()) or the export genuinely hung. Override with ` +
489
+ `WM_EXPO_EXPORT_TIMEOUT_MINUTES if this is just a slow build.`,
490
+ ));
491
+ }, timeoutMs);
492
+
493
+ const tree = createTreeSampler(child.pid);
494
+ const oomAtStart = oomKillCount();
495
+ const startedAt = Date.now();
496
+ let lastOutputAt = startedAt;
497
+ let lastBusyAt = startedAt;
498
+ let lastHeartbeatAt = startedAt;
499
+ let oomSeen = null;
500
+ stallTimer = setInterval(() => {
501
+ if (done) return;
502
+ const now = Date.now();
503
+ const s = tree.sample();
504
+ if (s && s.cores >= idleCores) { lastBusyAt = now; }
505
+ const oom = oomKillCount();
506
+ if (!oomSeen && oomAtStart !== null && oom > oomAtStart) {
507
+ oomSeen = { at: now, count: oom };
508
+ console.log(`[metro] cgroup oom_kill rose ${oomAtStart} -> ${oom} during expo export`);
509
+ }
510
+
511
+ const quietMs = now - lastOutputAt;
512
+ if (quietMs >= 60000 && now - lastHeartbeatAt >= 60000) {
513
+ lastHeartbeatAt = now;
514
+ console.log(`[metro] expo export running ${Math.floor((now - startedAt) / 60000)}m — `
515
+ + (s ? `cpu ${Math.round(s.cores * 100)}% across ${s.procs} process(es), rss ${s.rssMB}MB, ` : '')
516
+ + `no output for ${Math.floor(quietMs / 60000)}m`);
517
+ }
518
+
519
+ // Without /proc, lastBusyAt never moves and this is the plain no-output check.
520
+ const idleMs = now - Math.max(lastOutputAt, lastBusyAt);
521
+ // The oom_kill counter is container-wide, so a rise is only taken as ours once our tree has
522
+ // gone idle; that fails a worker-OOM hang in about a minute instead of the full window.
523
+ const oomHang = oomSeen && s && now - oomSeen.at >= oomGraceMs && idleMs >= oomGraceMs;
524
+ if (idleMs < stallMs && !oomHang) return;
525
+ clearInterval(stallTimer);
526
+ killTree(child.pid, oomHang ? 'expo export (hung after oom_kill)' : 'expo export (stalled)');
527
+ finish(reject, new Error(oomHang
528
+ ? `expo export was reaped: the container's cgroup oom_kill counter rose `
529
+ + `(${oomAtStart} -> ${oomSeen.count}) and the export then used no CPU for `
530
+ + `${Math.round(idleMs / 1000)}s — a Metro transform worker was OOM-killed and the parent `
531
+ + `left waiting on it. Lower WM_MAX_OLD_SPACE_MB / WM_METRO_MAX_WORKERS or raise the `
532
+ + `container memory limit.`
533
+ : `expo export produced no output for ${Math.round(quietMs / 60000)} minute(s)`
534
+ + (s ? ` and used under ${Math.round(idleCores * 100)}% of a core for the last `
535
+ + `${Math.round(idleMs / 60000)} minute(s)` : '')
536
+ + ` and was reaped. This usually means a Metro transform worker was OOM-killed and the `
537
+ + `parent was left waiting on it — check the container's cgroup memory.events for `
538
+ + `oom_kill, and lower WM_MAX_OLD_SPACE_MB / raise the container limit. Override the `
539
+ + `window with WM_EXPO_EXPORT_STALL_MINUTES.`,
540
+ ));
541
+ }, 15000);
542
+
543
+ let boundaryRefused = false;
544
+ const onData = (d) => {
545
+ lastOutputAt = Date.now();
546
+ const text = d.toString();
547
+ process.stdout.write(d);
548
+ if (text.includes('WM_BOUNDARY_INVALID')) { boundaryRefused = true; }
549
+ if (!done && /Exported:\s/.test(text)) {
550
+ killTree(child.pid, 'expo export (completed)');
551
+ finish(resolve);
552
+ }
553
+ };
554
+ child.stdout.on('data', onData);
555
+ child.stderr.on('data', onData);
556
+
557
+ child.on('close', (code, signal) => {
558
+ if (code === 0) { return finish(resolve); }
559
+ const oom = oomKillCount();
560
+ const err = new Error(`expo export failed with exit code ${code}`
561
+ + (signal ? ` (${signal})` : '')
562
+ + (oomAtStart !== null && oom > oomAtStart
563
+ ? ` — the container's cgroup oom_kill counter rose ${oomAtStart} -> ${oom} during the export`
564
+ : ''));
565
+ // The serializer refused boundary mode because the cached vendor chunk is missing a module.
566
+ // That is an expected outcome, not a build failure — the caller retries a full traversal.
567
+ if (boundaryRefused) { err.wmBoundaryInvalid = true; }
568
+ return finish(reject, err);
569
+ });
570
+ child.on('error', (err) => finish(reject, err));
571
+ });
572
+ }
573
+
574
+ // Serializes this project's full build (expo export into staging, then the served-directory
575
+ // mutation below) against another concurrent build of the SAME project — two overlapping builds
576
+ // would otherwise both write into the same rn-bundle-next staging dir and race on the served copy.
577
+ // Re-emits just the changed project modules into the served bundle, skipping expo export entirely.
578
+ // On by default; disable with WM_FASTPATH=0. It bypasses Metro, so anything it cannot prove safe
579
+ // returns {ok:false} and the full build runs instead — it never guesses. Runs under the same
580
+ // per-project lock as a real build, but deliberately BEFORE build admission, since it costs a
581
+ // fraction of the memory a build does and should never queue behind one.
582
+ async tryFastPath(webapp, served) {
583
+ if (process.env.WM_FASTPATH === '0') { return false; }
584
+ if (!fs.existsSync(path.join(served, 'index.html'))) { return false; }
585
+
586
+ const projectRoot = path.resolve(__dirname, '..');
587
+ const started = Date.now();
588
+ try {
589
+ const { fastBuild } = require('./wm-fastbuild');
590
+ const result = await withLock(webapp, () => fastBuild({ projectRoot, bundleDir: served }));
591
+ if (result.ok) {
592
+ console.log(`[fastpath] ${result.changedCount} changed, ${result.emittedCount} emitted `
593
+ + `in ${Date.now() - started}ms -> ${result.filename}`
594
+ + `${result.pruned ? ` (pruned ${result.pruned} stale)` : ''}`);
595
+ console.log(`[fastpath] changed: ${result.files.join(', ')}`);
596
+ return true;
597
+ }
598
+ console.log(`[fastpath] full build needed: ${result.reason}`);
599
+ } catch (err) {
600
+ console.warn('[fastpath] errored, falling back to full build:', err.message);
601
+ }
602
+ return false;
603
+ }
604
+
605
+ async triggerBuild() {
606
+ console.log('*********** REACT NATIVE METRO STARTED **************');
607
+ console.time('react native with metro');
608
+ const webapp = process.env.WM_PROJECT_SRC
609
+ ? path.resolve(process.env.WM_PROJECT_SRC)
610
+ : path.resolve(__dirname, '..', '..', 'src', 'main', 'webapp');
611
+ const staging = path.join(webapp, 'rn-bundle-next');
612
+ const served = path.join(webapp, 'rn-bundle');
613
+
614
+ if (await this.tryFastPath(webapp, served)) {
615
+ console.timeEnd('react native with metro');
616
+ console.log('*********** REACT NATIVE METRO SUCCESSFUL **************');
617
+ return;
618
+ }
619
+
620
+ cleanupStaleMetroCacheOnVersionChange(path.resolve(__dirname, '..'));
621
+
622
+ const isIncrementalBuild = process.env.WM_INCREMENTAL_BUILD === '1';
623
+ const defaultAdmissionWaitMinutes = isIncrementalBuild ? 2 : 3;
624
+ const admissionWaitMs =
625
+ (parseInt(process.env.WM_BUILD_ADMISSION_WAIT_MINUTES, 10) || defaultAdmissionWaitMinutes) * 60 * 1000;
626
+ const queueStart = Date.now();
627
+
628
+ // Builds of different projects run side by side while memory allows; WM_BUILD_ADMISSION_MODE=mutex runs one at a time.
629
+ if (process.env.WM_BUILD_ADMISSION_MODE !== 'mutex') {
630
+ await waitForBuildHeadroom(admissionWaitMs);
631
+ const waited = Date.now() - queueStart;
632
+ if (waited > 1000) {
633
+ console.log(`[build-queue] waited ${Math.round(waited / 1000)}s for container memory to free up`);
634
+ }
635
+ await withLock(webapp, () => this.buildAndPublish(webapp, staging, served));
636
+ return;
637
+ }
638
+
639
+ const admissionPath = buildAdmissionPath(path.resolve(__dirname, '..'));
640
+ await withLock(admissionPath, async () => {
641
+ const waited = Date.now() - queueStart;
642
+ if (waited > 1000) {
643
+ console.log(`[build-queue] waited ${Math.round(waited / 1000)}s for another build to finish`);
644
+ }
645
+ return withLock(webapp, () => this.buildAndPublish(webapp, staging, served));
646
+ }, {
647
+ retries: {
648
+ retries: Math.max(1, Math.round(admissionWaitMs / 10000)),
649
+ factor: 1,
650
+ minTimeout: 10000,
651
+ maxTimeout: 10000,
652
+ },
653
+ });
654
+ }
655
+
656
+ /* Emits the live-reload client and its <script> tag, after the chunks so __d/__r/__c exist. */
657
+ writeLiveReload(staging) {
658
+ if (process.env.WM_LIVE_RELOAD === '0' || previewConfig().liveReload === false) {
659
+ console.log('[wm-live] live reload is off for this project; reload the page to see a new build');
660
+ return;
661
+ }
662
+
663
+ const clientSrc = path.join(__dirname, 'wm-live-reload.js');
664
+ if (!fs.existsSync(clientSrc)) return;
665
+ fs.copyFileSync(clientSrc, path.join(staging, 'wm-live-reload.js'));
666
+
667
+ const html = path.join(staging, 'index.html');
668
+ if (!fs.existsSync(html)) return;
669
+ const cur = fs.readFileSync(html, 'utf8');
670
+ if (cur.includes('wm-live-reload.js')) return;
671
+ if (!cur.includes('</body>')) return; // unexpected shape: leave a working page alone
672
+
673
+ const intervalMs = previewPollIntervalMs();
674
+ const tag = `<script>window.__WM_LIVE_RELOAD__={intervalMs:${intervalMs}};</script>`
675
+ + `<script src="./wm-live-reload.js"></script>`;
676
+ fs.writeFileSync(html, cur.replace('</body>', `${tag}</body>`));
677
+ console.log(`[wm-live] client injected (poll ${intervalMs}ms)`);
678
+ }
679
+
680
+ // expo export into staging (with the one boundary retry), then the path fixups every served chunk
681
+ // needs. Separate from publishing so the publish gate can re-run it.
682
+ async exportToStaging(webapp, staging, { boundaryDisabled = false, bypassChunkCache = false } = {}) {
683
+ try {
684
+ await this.build(webapp, boundaryDisabled, { bypassChunkCache });
685
+ } catch (err) {
686
+ if (!err || !err.wmBoundaryInvalid) { throw err; }
687
+ console.log('[boundary] cached vendor chunk is incomplete — retrying with a full traversal');
688
+ await this.build(webapp, true, { bypassChunkCache });
689
+ }
690
+ const html = path.join(staging, 'index.html');
691
+ if (fs.existsSync(html)) {
692
+ fs.writeFileSync(html, fs.readFileSync(html, 'utf8').replace(/(\b(?:src|href)=")\/(?!\/)/g, '$1'));
693
+ }
694
+ const jsChunkPattern = /^[0-9a-f]+-(?:vendor|user|extras|wmx|modified|boot)\.js$/;
695
+ for (const f of fs.readdirSync(staging)) {
696
+ if (!jsChunkPattern.test(f)) continue;
697
+ const chunkPath = path.join(staging, f);
698
+ const code = fs.readFileSync(chunkPath, 'utf8');
699
+ const fixed = code.replace(/(["'])\/assets\//g, '$1assets/');
700
+ if (fixed !== code) {
701
+ fs.writeFileSync(chunkPath, fixed);
702
+ }
703
+ }
704
+ }
705
+
706
+ // Runs inside triggerBuild()'s lock: expo export into staging, then the served-directory mutation.
707
+ async buildAndPublish(webapp, staging, served) {
708
+ try {
709
+ await this.exportToStaging(webapp, staging);
710
+ let gate = checkChunkIntegrity(staging);
711
+ reportGate(gate);
712
+ if (gate.status === 'broken' || gate.status === 'layering') {
713
+ // Never serve a chunk set the page cannot run. Rebuild once from a full traversal with every
714
+ // chunk cache bypassed; the fresh chunks also overwrite whatever cache entry was bad.
715
+ console.log('[gate] rebuilding with a full traversal and all chunk caches bypassed');
716
+ fs.removeSync(staging);
717
+ await this.exportToStaging(webapp, staging, { boundaryDisabled: true, bypassChunkCache: true });
718
+ gate = checkChunkIntegrity(staging);
719
+ reportGate(gate);
720
+ if (gate.status === 'broken') {
721
+ throw new Error('[gate] chunk set still references undefined modules after a clean rebuild '
722
+ + '— refusing to publish a preview that would fail with "Requiring unknown module"');
723
+ }
724
+ if (gate.status === 'layering') {
725
+ // Every id is defined, so this page runs; the violation is in how chunks were split and a
726
+ // rebuild cannot change it. Publish, but loudly — it is a split-serializer bug to fix.
727
+ console.error('[gate] layering violation survives a clean rebuild — publishing (all ids are '
728
+ + 'defined), but the shared chunks are not self-contained');
729
+ }
730
+ }
731
+ // Best-effort: the bundle is already correct on disk, so this must never fail the build.
732
+ try {
733
+ this.writeLiveReload(staging);
734
+ } catch (e) {
735
+ console.log(`[wm-live] skipped: ${e && e.message}`);
736
+ }
737
+ const vendorLinkFile = path.join(__dirname, '..', '.wm-vendor-link.json');
738
+ const vendorHardlinkTargets = new Set();
739
+ if (fs.existsSync(vendorLinkFile)) {
740
+ try {
741
+ const { cachePath, mapPath, filename } = fs.readJSONSync(vendorLinkFile);
742
+ const jsBase = path.basename(filename);
743
+ for (const [srcPath, base] of [[cachePath, jsBase], [mapPath, `${jsBase}.map`]]) {
744
+ const destPath = path.join(served, base);
745
+ if (fs.existsSync(destPath)) {
746
+ vendorHardlinkTargets.add(base);
747
+ continue;
748
+ }
749
+ if (!srcPath || !fs.existsSync(srcPath)) continue;
750
+ try {
751
+ fs.linkSync(srcPath, destPath);
752
+ vendorHardlinkTargets.add(base);
753
+ } catch (err) {
754
+ console.warn(`[metro] hardlink failed for ${base}, leaving it for the normal staging copy:`, err.message);
755
+ }
756
+ }
757
+ } catch (err) {
758
+ console.warn('[metro] failed to read .wm-vendor-link.json, vendor chunk falls back to normal copy:', err.message);
759
+ }
760
+ }
761
+
762
+ const rewriteVersionFile = path.join(served, '.wm-rewrite-version');
763
+ const currentRewriteVersion = crypto.createHash('md5').update(fs.readFileSync(__filename)).digest('hex');
764
+ const rewriteLogicUnchanged = fs.existsSync(rewriteVersionFile)
765
+ && fs.readFileSync(rewriteVersionFile, 'utf8') === currentRewriteVersion;
766
+
767
+ const hitsManifest = path.join(staging, 'wm-chunk-cache-hits.json');
768
+ const cacheHitFilenames = (rewriteLogicUnchanged && fs.existsSync(hitsManifest))
769
+ ? new Set(fs.readJSONSync(hitsManifest))
770
+ : new Set();
771
+ const chunkPattern = /^[0-9a-f]+-(?:vendor|user|extras|wmx|modified|boot)\.js(?:\.map)?$/;
772
+ fs.copySync(staging, served, {
773
+ overwrite: true,
774
+ filter: (src, dest) => {
775
+ if (fs.statSync(src).isDirectory()) return true;
776
+ const base = path.basename(src);
777
+ if (vendorHardlinkTargets.has(base)) return false;
778
+ // Explicit: the catch-all below only copies files that don't already exist,
779
+ // so without this the client would ship once and never update again.
780
+ if (base === 'index.html' || base === 'wm-live-reload.js' || base.endsWith('.json')) return true;
781
+ if (chunkPattern.test(base)) {
782
+ const stem = base.replace(/\.map$/, '');
783
+ if (cacheHitFilenames.has(stem) && fs.existsSync(dest)) return false;
784
+ return true;
785
+ }
786
+ return !fs.existsSync(dest);
787
+ },
788
+ });
789
+ fs.writeFileSync(rewriteVersionFile, currentRewriteVersion);
790
+ const currentChunks = new Set(fs.readdirSync(staging).filter((f) => chunkPattern.test(f)));
791
+ for (const f of fs.readdirSync(served)) {
792
+ // A vendor cache hit leaves only a JS placeholder in staging, never the .map, so the hardlinked
793
+ // map must not be mistaken for a previous build's leftover.
794
+ if (chunkPattern.test(f) && !currentChunks.has(f) && !vendorHardlinkTargets.has(f)) {
795
+ fs.removeSync(path.join(served, f));
796
+ }
797
+ }
798
+ // build-pipeline.ts writes a PLACEHOLDER index.html into the served dir before every build,
799
+ // so by the time the next build's fast path runs there are no chunk tags left to read. Keep a
800
+ // snapshot of the real one here; wm-fastbuild.js falls back to it when it sees the placeholder.
801
+ try {
802
+ fs.copyFileSync(path.join(served, 'index.html'),
803
+ path.join(path.resolve(__dirname, '..'), '.wm-index-template.html'));
804
+ } catch (err) {
805
+ console.warn('[metro] could not snapshot index.html for the fast path:', err.message);
806
+ }
807
+
808
+ fs.removeSync(staging);
809
+ console.timeEnd('react native with metro');
810
+ console.log('*********** REACT NATIVE METRO SUCCESSFUL **************');
811
+ } catch (error) {
812
+ console.log('*********** REACT PROJECT METRO ERROR **************');
813
+ console.error(error);
814
+ try {
815
+ if (fs.existsSync(staging)) {
816
+ fs.removeSync(staging);
817
+ }
818
+ } catch (cleanupErr) {
819
+ console.warn('[metro] failed to clean up stale staging dir:', cleanupErr.message);
820
+ }
821
+ console.timeEnd('react native with metro');
822
+ // No manual lock release: proper-lockfile's default 10s stale-lock detection reclaims
823
+ // it on the next build attempt, and process.exit() here never reaches a finally block anyway.
824
+ process.exit(1);
825
+ }
826
+ }
827
+ }
828
+
829
+ if (process.argv[2] === '--prepare-lib') {
830
+ (new MetroBuilder()).buildLibraries();
831
+ } else {
832
+ (new MetroBuilder()).triggerBuild();
833
+ }