@zntc/react-native 0.1.0
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/LICENSE +21 -0
- package/README.md +48 -0
- package/dist/dev-server/hmr-bridge.d.ts +22 -0
- package/dist/dev-server/http-server.d.ts +32 -0
- package/dist/dev-server/http-utils.d.ts +11 -0
- package/dist/dev-server/index.d.ts +18 -0
- package/dist/dev-server/logger.d.ts +35 -0
- package/dist/dev-server/middleware/cli-server-api.d.ts +25 -0
- package/dist/dev-server/middleware/dev-middleware.d.ts +33 -0
- package/dist/dev-server/options.d.ts +30 -0
- package/dist/dev-server/platform-state.d.ts +37 -0
- package/dist/dev-server/routes/_shared.d.ts +3 -0
- package/dist/dev-server/routes/assets.d.ts +12 -0
- package/dist/dev-server/routes/bundle.d.ts +8 -0
- package/dist/dev-server/routes/devmenu.d.ts +4 -0
- package/dist/dev-server/routes/index-page.d.ts +3 -0
- package/dist/dev-server/routes/open-url.d.ts +4 -0
- package/dist/dev-server/routes/reload.d.ts +4 -0
- package/dist/dev-server/routes/status.d.ts +3 -0
- package/dist/dev-server/routes/symbolicate.d.ts +5 -0
- package/dist/dev-server/serve.d.ts +27 -0
- package/dist/dev-server/sourcemap.d.ts +15 -0
- package/dist/dev-server/symbolicate-source.d.ts +54 -0
- package/dist/dev-server/terminal-actions.d.ts +32 -0
- package/dist/dev-server/types.d.ts +22 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +3471 -0
- package/dist/metro-hmr-adapter.d.ts +29 -0
- package/dist/metro-resolver-types.d.ts +39 -0
- package/dist/plugins/asset.d.ts +11 -0
- package/dist/plugins/babel.d.ts +42 -0
- package/dist/plugins/codegen.d.ts +16 -0
- package/dist/plugins/escape-regex.d.ts +1 -0
- package/dist/plugins/internal.d.ts +37 -0
- package/dist/plugins/metro-resolve-request.d.ts +7 -0
- package/dist/plugins/require-context.d.ts +7 -0
- package/dist/plugins/styled-components-native.d.ts +11 -0
- package/dist/plugins/types.d.ts +25 -0
- package/dist/preset.d.ts +142 -0
- package/dist/rn-constants.d.ts +21 -0
- package/dist/runtime-loader.d.ts +14 -0
- package/dist/withExpo.d.ts +60 -0
- package/package.json +70 -0
- package/runtime/.gitkeep +0 -0
- package/runtime/zntc-hmr-client.cjs +328 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,3471 @@
|
|
|
1
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
2
|
+
if (mod) return mod.exports;
|
|
3
|
+
mod = { exports: {} };
|
|
4
|
+
try { (0, cb[Object.keys(cb)[0]])(mod.exports, mod); }
|
|
5
|
+
catch (e) { mod = void 0; throw e; }
|
|
6
|
+
return mod.exports;
|
|
7
|
+
};
|
|
8
|
+
var __create = Object.create;
|
|
9
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
10
|
+
var __defProp = Object.defineProperty;
|
|
11
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
12
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
13
|
+
var __hasOwn = Object.prototype.hasOwnProperty;
|
|
14
|
+
var __copyProps = (to, from, desc) => {
|
|
15
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
16
|
+
for (var keys = __getOwnPropNames(from), i = 0, key; i < keys.length; i++) {
|
|
17
|
+
key = keys[i];
|
|
18
|
+
if (!__hasOwn.call(to, key))
|
|
19
|
+
__defProp(to, key, { get: ((k) => from[k]).bind(null, key), enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return to;
|
|
23
|
+
};
|
|
24
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
|
|
25
|
+
import { Buffer as Buffer$1 } from "node:buffer";
|
|
26
|
+
import { createHash } from "node:crypto";
|
|
27
|
+
import { createRequire } from "node:module";
|
|
28
|
+
var createRequire$1 = createRequire;
|
|
29
|
+
var createRequire$2 = createRequire;
|
|
30
|
+
var createRequire$3 = createRequire;
|
|
31
|
+
var createRequire$4 = createRequire;
|
|
32
|
+
var createRequire$5 = createRequire;
|
|
33
|
+
import { resolve, dirname, extname, sep, join, basename, isAbsolute, relative } from "node:path";
|
|
34
|
+
var resolve$1 = resolve;
|
|
35
|
+
var dirname$1 = dirname;
|
|
36
|
+
var extname$1 = extname;
|
|
37
|
+
var dirname$2 = dirname;
|
|
38
|
+
var resolve$2 = resolve;
|
|
39
|
+
var dirname$3 = dirname;
|
|
40
|
+
var join$1 = join;
|
|
41
|
+
var resolve$3 = resolve;
|
|
42
|
+
var dirname$4 = dirname;
|
|
43
|
+
var resolve$4 = resolve;
|
|
44
|
+
var isAbsolute$1 = isAbsolute;
|
|
45
|
+
var resolve$5 = resolve;
|
|
46
|
+
var join$2 = join;
|
|
47
|
+
var pathResolve = resolve;
|
|
48
|
+
var join$3 = join;
|
|
49
|
+
var extname$2 = extname;
|
|
50
|
+
var join$4 = join;
|
|
51
|
+
var dirname$5 = dirname;
|
|
52
|
+
var join$5 = join;
|
|
53
|
+
import { existsSync, lstatSync, readdirSync, realpathSync, readFileSync, mkdtempSync } from "node:fs";
|
|
54
|
+
var readFileSync$1 = readFileSync;
|
|
55
|
+
var readdirSync$1 = readdirSync;
|
|
56
|
+
var existsSync$1 = existsSync;
|
|
57
|
+
var existsSync$2 = existsSync;
|
|
58
|
+
var readFileSync$2 = readFileSync;
|
|
59
|
+
var existsSync$3 = existsSync;
|
|
60
|
+
var existsSync$4 = existsSync;
|
|
61
|
+
var readFileSync$3 = readFileSync;
|
|
62
|
+
import { readFile } from "node:fs/promises";
|
|
63
|
+
var readFile$1 = readFile;
|
|
64
|
+
import { fileURLToPath } from "node:url";
|
|
65
|
+
import { build, init, watch } from "@zntc/core";
|
|
66
|
+
import { tmpdir } from "node:os";
|
|
67
|
+
import { spawn } from "node:child_process";
|
|
68
|
+
var spawn$1 = spawn;
|
|
69
|
+
import { createServer } from "node:http";
|
|
70
|
+
//#region index.js
|
|
71
|
+
var require_jsc_safe_url_index = __commonJS({
|
|
72
|
+
"index.js"(exports, module) {
|
|
73
|
+
const URI_REGEX = /^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
|
|
74
|
+
function _rfc3986Parse(url) {
|
|
75
|
+
const match = url.match(URI_REGEX);
|
|
76
|
+
if (match == null) {
|
|
77
|
+
throw new Error("Unexpected error - failed to regex-match URL");
|
|
78
|
+
}
|
|
79
|
+
return { schemeAndAuthority: (match[1] || "") + (match[3] || ""), path: match[5] || "", hasQueryPart: match[6] != null, queryWithoutQuestionMark: match[7] || "", fragmentWithHash: match[8] || "" };
|
|
80
|
+
}
|
|
81
|
+
function isJscSafeUrl(url) {
|
|
82
|
+
const parsedUrl = _rfc3986Parse(url);
|
|
83
|
+
return !parsedUrl.hasQueryPart;
|
|
84
|
+
}
|
|
85
|
+
function toNormalUrl(urlToNormalize) {
|
|
86
|
+
const parsedUrl = _rfc3986Parse(urlToNormalize);
|
|
87
|
+
if (parsedUrl.path.indexOf("//&") === -1) {
|
|
88
|
+
return urlToNormalize;
|
|
89
|
+
}
|
|
90
|
+
return (parsedUrl.schemeAndAuthority + parsedUrl.path.replace("//&", "?") + (parsedUrl.queryWithoutQuestionMark.length > 0 ? "&" + parsedUrl.queryWithoutQuestionMark : "") + parsedUrl.fragmentWithHash);
|
|
91
|
+
}
|
|
92
|
+
function toJscSafeUrl(urlToConvert) {
|
|
93
|
+
if (!_rfc3986Parse(urlToConvert).hasQueryPart) {
|
|
94
|
+
return urlToConvert;
|
|
95
|
+
}
|
|
96
|
+
const parsedUrl = _rfc3986Parse(toNormalUrl(urlToConvert));
|
|
97
|
+
if (parsedUrl.queryWithoutQuestionMark.length > 0 && (parsedUrl.path === "" || parsedUrl.path === "/")) {
|
|
98
|
+
throw new Error(`The given URL "${urlToConvert}" has an empty path and cannot be converted to a JSC-safe format.`);
|
|
99
|
+
}
|
|
100
|
+
return (parsedUrl.schemeAndAuthority + parsedUrl.path + (parsedUrl.queryWithoutQuestionMark.length > 0 ? "//&" + parsedUrl.queryWithoutQuestionMark.replace(/\?/g, "%3F") : "") + parsedUrl.fragmentWithHash);
|
|
101
|
+
}
|
|
102
|
+
module.exports = { isJscSafeUrl, toNormalUrl, toJscSafeUrl };
|
|
103
|
+
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
//#endregion
|
|
107
|
+
//#region (disabled):url
|
|
108
|
+
var require__disabled__url = __commonJS({
|
|
109
|
+
"(disabled):url"(exports, module) {
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
//#endregion
|
|
113
|
+
//#region (optional-missing):
|
|
114
|
+
var require__optional_missing__ = __commonJS({
|
|
115
|
+
"(optional-missing):"(exports, module) {
|
|
116
|
+
var e = new Error("Cannot find module \"" + "" + "\"");
|
|
117
|
+
e.code = "MODULE_NOT_FOUND";
|
|
118
|
+
throw e;
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
//#endregion
|
|
122
|
+
//#region array-set.js
|
|
123
|
+
var require_source_map_lib_array_set = __commonJS({
|
|
124
|
+
"array-set.js"(exports, module) {
|
|
125
|
+
class ArraySet {
|
|
126
|
+
constructor() {
|
|
127
|
+
this._array = [];
|
|
128
|
+
this._set = new Map();
|
|
129
|
+
}
|
|
130
|
+
static fromArray(aArray,aAllowDuplicates) {
|
|
131
|
+
const set = new ArraySet();
|
|
132
|
+
for (let i = 0,len = aArray.length; i < len; i++) {
|
|
133
|
+
set.add(aArray[i], aAllowDuplicates);
|
|
134
|
+
}
|
|
135
|
+
return set;
|
|
136
|
+
}
|
|
137
|
+
size() {
|
|
138
|
+
return this._set.size;
|
|
139
|
+
}
|
|
140
|
+
add(aStr,aAllowDuplicates) {
|
|
141
|
+
const isDuplicate = this.has(aStr),idx = this._array.length;
|
|
142
|
+
if (!isDuplicate || aAllowDuplicates) {
|
|
143
|
+
this._array.push(aStr);
|
|
144
|
+
}
|
|
145
|
+
if (!isDuplicate) {
|
|
146
|
+
this._set.set(aStr, idx);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
has(aStr) {
|
|
150
|
+
return this._set.has(aStr);
|
|
151
|
+
}
|
|
152
|
+
indexOf(aStr) {
|
|
153
|
+
const idx = this._set.get(aStr);
|
|
154
|
+
if (idx >= 0) {
|
|
155
|
+
return idx;
|
|
156
|
+
}
|
|
157
|
+
throw new Error("\"" + aStr + "\" is not in the set.");
|
|
158
|
+
}
|
|
159
|
+
at(aIdx) {
|
|
160
|
+
if (aIdx >= 0 && aIdx < this._array.length) {
|
|
161
|
+
return this._array[aIdx];
|
|
162
|
+
}
|
|
163
|
+
throw new Error("No element indexed by " + aIdx);
|
|
164
|
+
}
|
|
165
|
+
toArray() {
|
|
166
|
+
return this._array.slice();
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
exports.ArraySet = ArraySet;
|
|
170
|
+
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
//#endregion
|
|
174
|
+
//#region base64-vlq.js
|
|
175
|
+
var require_source_map_lib_base64_vlq = __commonJS({
|
|
176
|
+
"base64-vlq.js"(exports, module) {
|
|
177
|
+
const base64 = require_source_map_lib_base64(),VLQ_BASE_SHIFT = 5,VLQ_BASE = 1 << VLQ_BASE_SHIFT,VLQ_BASE_MASK = VLQ_BASE - 1,VLQ_CONTINUATION_BIT = VLQ_BASE;
|
|
178
|
+
function toVLQSigned(aValue) {
|
|
179
|
+
return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0;
|
|
180
|
+
}
|
|
181
|
+
exports.encode = function base64VLQ_encode(aValue) {
|
|
182
|
+
let encoded = "",digit,vlq = toVLQSigned(aValue);
|
|
183
|
+
do {
|
|
184
|
+
digit = vlq & VLQ_BASE_MASK;
|
|
185
|
+
vlq >>>= VLQ_BASE_SHIFT;
|
|
186
|
+
if (vlq > 0) {
|
|
187
|
+
digit |= VLQ_CONTINUATION_BIT;
|
|
188
|
+
}
|
|
189
|
+
encoded += base64.encode(digit);
|
|
190
|
+
} while (vlq > 0);
|
|
191
|
+
return encoded;
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
}
|
|
195
|
+
});
|
|
196
|
+
//#endregion
|
|
197
|
+
//#region base64.js
|
|
198
|
+
var require_source_map_lib_base64 = __commonJS({
|
|
199
|
+
"base64.js"(exports, module) {
|
|
200
|
+
const intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
|
|
201
|
+
exports.encode = function(number) {
|
|
202
|
+
if (0 <= number && number < intToCharMap.length) {
|
|
203
|
+
return intToCharMap[number];
|
|
204
|
+
}
|
|
205
|
+
throw new TypeError("Must be between 0 and 63: " + number);
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
//#endregion
|
|
211
|
+
//#region binary-search.js
|
|
212
|
+
var require_source_map_lib_binary_search = __commonJS({
|
|
213
|
+
"binary-search.js"(exports, module) {
|
|
214
|
+
exports.GREATEST_LOWER_BOUND = 1;
|
|
215
|
+
exports.LEAST_UPPER_BOUND = 2;
|
|
216
|
+
function recursiveSearch(aLow,aHigh,aNeedle,aHaystack,aCompare,aBias) {
|
|
217
|
+
const mid = Math.floor((aHigh - aLow) / 2) + aLow,cmp = aCompare(aNeedle, aHaystack[mid], true);
|
|
218
|
+
if (cmp === 0) {
|
|
219
|
+
return mid;
|
|
220
|
+
} else if (cmp > 0) {
|
|
221
|
+
if (aHigh - mid > 1) {
|
|
222
|
+
return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
|
|
223
|
+
}
|
|
224
|
+
if (aBias === exports.LEAST_UPPER_BOUND) {
|
|
225
|
+
return aHigh < aHaystack.length ? aHigh : -1;
|
|
226
|
+
}
|
|
227
|
+
return mid;
|
|
228
|
+
}
|
|
229
|
+
if (mid - aLow > 1) {
|
|
230
|
+
return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
|
|
231
|
+
}
|
|
232
|
+
if (aBias == exports.LEAST_UPPER_BOUND) {
|
|
233
|
+
return mid;
|
|
234
|
+
}
|
|
235
|
+
return aLow < 0 ? -1 : aLow;
|
|
236
|
+
}
|
|
237
|
+
exports.search = function search(aNeedle,aHaystack,aCompare,aBias) {
|
|
238
|
+
if (aHaystack.length === 0) {
|
|
239
|
+
return -1;
|
|
240
|
+
}
|
|
241
|
+
let index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports.GREATEST_LOWER_BOUND);
|
|
242
|
+
if (index < 0) {
|
|
243
|
+
return -1;
|
|
244
|
+
}
|
|
245
|
+
while (index - 1 >= 0) {
|
|
246
|
+
if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
|
|
247
|
+
break;
|
|
248
|
+
}
|
|
249
|
+
--index;
|
|
250
|
+
}
|
|
251
|
+
return index;
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
//#endregion
|
|
257
|
+
//#region mapping-list.js
|
|
258
|
+
var require_source_map_lib_mapping_list = __commonJS({
|
|
259
|
+
"mapping-list.js"(exports, module) {
|
|
260
|
+
const util = require_source_map_lib_util();
|
|
261
|
+
function generatedPositionAfter(mappingA,mappingB) {
|
|
262
|
+
const lineA = mappingA.generatedLine,lineB = mappingB.generatedLine,columnA = mappingA.generatedColumn,columnB = mappingB.generatedColumn;
|
|
263
|
+
return (lineB > lineA || (lineB == lineA && columnB >= columnA) || util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0);
|
|
264
|
+
}
|
|
265
|
+
class MappingList {
|
|
266
|
+
constructor() {
|
|
267
|
+
this._array = [];
|
|
268
|
+
this._sorted = true;
|
|
269
|
+
this._last = { generatedLine: -1, generatedColumn: 0 };
|
|
270
|
+
}
|
|
271
|
+
unsortedForEach(aCallback,aThisArg) {
|
|
272
|
+
this._array.forEach(aCallback, aThisArg);
|
|
273
|
+
}
|
|
274
|
+
add(aMapping) {
|
|
275
|
+
if (generatedPositionAfter(this._last, aMapping)) {
|
|
276
|
+
this._last = aMapping;
|
|
277
|
+
this._array.push(aMapping);
|
|
278
|
+
} else {
|
|
279
|
+
this._sorted = false;
|
|
280
|
+
this._array.push(aMapping);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
toArray() {
|
|
284
|
+
if (!this._sorted) {
|
|
285
|
+
this._array.sort(util.compareByGeneratedPositionsInflated);
|
|
286
|
+
this._sorted = true;
|
|
287
|
+
}
|
|
288
|
+
return this._array;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
exports.MappingList = MappingList;
|
|
292
|
+
|
|
293
|
+
}
|
|
294
|
+
});
|
|
295
|
+
//#endregion
|
|
296
|
+
//#region read-wasm-browser.js
|
|
297
|
+
var require_source_map_lib_read_wasm_browser = __commonJS({
|
|
298
|
+
"read-wasm-browser.js"(exports, module) {
|
|
299
|
+
"use strict";
|
|
300
|
+
let mappingsWasm = null;
|
|
301
|
+
module.exports = function readWasm() {
|
|
302
|
+
if (typeof mappingsWasm == "string") {
|
|
303
|
+
return fetch(mappingsWasm).then((response) => response.arrayBuffer());
|
|
304
|
+
}
|
|
305
|
+
if (mappingsWasm instanceof ArrayBuffer) {
|
|
306
|
+
return Promise.resolve(mappingsWasm);
|
|
307
|
+
}
|
|
308
|
+
throw new Error("You must provide the string URL or ArrayBuffer contents of lib/mappings.wasm by calling SourceMapConsumer.initialize({ 'lib/mappings.wasm': ... }) before using SourceMapConsumer");
|
|
309
|
+
};
|
|
310
|
+
module.exports.initialize = (input) => {
|
|
311
|
+
mappingsWasm = input;
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
}
|
|
315
|
+
});
|
|
316
|
+
//#endregion
|
|
317
|
+
//#region source-map-consumer.js
|
|
318
|
+
var require_source_map_lib_source_map_consumer = __commonJS({
|
|
319
|
+
"source-map-consumer.js"(exports, module) {
|
|
320
|
+
const util = require_source_map_lib_util(),binarySearch = require_source_map_lib_binary_search(),ArraySet = require_source_map_lib_array_set().ArraySet,base64VLQ = require_source_map_lib_base64_vlq(),readWasm = require_source_map_lib_read_wasm_browser(),wasm = require_source_map_lib_wasm(),INTERNAL = Symbol("smcInternal");
|
|
321
|
+
class SourceMapConsumer {
|
|
322
|
+
constructor(aSourceMap,aSourceMapURL) {
|
|
323
|
+
if (aSourceMap == INTERNAL) {
|
|
324
|
+
return Promise.resolve(this);
|
|
325
|
+
}
|
|
326
|
+
return _factory(aSourceMap, aSourceMapURL);
|
|
327
|
+
}
|
|
328
|
+
static initialize(opts) {
|
|
329
|
+
readWasm.initialize(opts["lib/mappings.wasm"]);
|
|
330
|
+
}
|
|
331
|
+
static fromSourceMap(aSourceMap,aSourceMapURL) {
|
|
332
|
+
return _factoryBSM(aSourceMap, aSourceMapURL);
|
|
333
|
+
}
|
|
334
|
+
static async with(rawSourceMap,sourceMapUrl,f) {
|
|
335
|
+
const consumer = await new SourceMapConsumer(rawSourceMap, sourceMapUrl);
|
|
336
|
+
try {
|
|
337
|
+
return await f(consumer);
|
|
338
|
+
} finally {
|
|
339
|
+
consumer.destroy();
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
eachMapping(aCallback,aContext,aOrder) {
|
|
343
|
+
throw new Error("Subclasses must implement eachMapping");
|
|
344
|
+
}
|
|
345
|
+
allGeneratedPositionsFor(aArgs) {
|
|
346
|
+
throw new Error("Subclasses must implement allGeneratedPositionsFor");
|
|
347
|
+
}
|
|
348
|
+
destroy() {
|
|
349
|
+
throw new Error("Subclasses must implement destroy");
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
SourceMapConsumer.prototype._version = 3;
|
|
353
|
+
SourceMapConsumer.GENERATED_ORDER = 1;
|
|
354
|
+
SourceMapConsumer.ORIGINAL_ORDER = 2;
|
|
355
|
+
SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
|
|
356
|
+
SourceMapConsumer.LEAST_UPPER_BOUND = 2;
|
|
357
|
+
exports.SourceMapConsumer = SourceMapConsumer;
|
|
358
|
+
class BasicSourceMapConsumer extends SourceMapConsumer {
|
|
359
|
+
constructor(aSourceMap,aSourceMapURL) {
|
|
360
|
+
return super(INTERNAL).then((that) => {
|
|
361
|
+
let sourceMap = aSourceMap;
|
|
362
|
+
if (typeof aSourceMap == "string") {
|
|
363
|
+
sourceMap = util.parseSourceMapInput(aSourceMap);
|
|
364
|
+
}
|
|
365
|
+
const version = util.getArg(sourceMap, "version"),sources = util.getArg(sourceMap, "sources").map(String),names = util.getArg(sourceMap, "names", []),sourceRoot = util.getArg(sourceMap, "sourceRoot", null),sourcesContent = util.getArg(sourceMap, "sourcesContent", null),mappings = util.getArg(sourceMap, "mappings"),file = util.getArg(sourceMap, "file", null),x_google_ignoreList = util.getArg(sourceMap, "x_google_ignoreList", null);
|
|
366
|
+
if (version != that._version) {
|
|
367
|
+
throw new Error("Unsupported version: " + version);
|
|
368
|
+
}
|
|
369
|
+
that._sourceLookupCache = new Map();
|
|
370
|
+
that._names = ArraySet.fromArray(names.map(String), true);
|
|
371
|
+
that._sources = ArraySet.fromArray(sources, true);
|
|
372
|
+
that._absoluteSources = ArraySet.fromArray(that._sources.toArray().map(function(s) {
|
|
373
|
+
return util.computeSourceURL(sourceRoot, s, aSourceMapURL);
|
|
374
|
+
}), true);
|
|
375
|
+
that.sourceRoot = sourceRoot;
|
|
376
|
+
that.sourcesContent = sourcesContent;
|
|
377
|
+
that._mappings = mappings;
|
|
378
|
+
that._sourceMapURL = aSourceMapURL;
|
|
379
|
+
that.file = file;
|
|
380
|
+
that.x_google_ignoreList = x_google_ignoreList;
|
|
381
|
+
that._computedColumnSpans = false;
|
|
382
|
+
that._mappingsPtr = 0;
|
|
383
|
+
that._wasm = null;
|
|
384
|
+
return wasm().then((w) => {
|
|
385
|
+
that._wasm = w;
|
|
386
|
+
return that;
|
|
387
|
+
});
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
_findSourceIndex(aSource) {
|
|
391
|
+
const cachedIndex = this._sourceLookupCache.get(aSource);
|
|
392
|
+
if (typeof cachedIndex == "number") {
|
|
393
|
+
return cachedIndex;
|
|
394
|
+
}
|
|
395
|
+
const sourceAsMapRelative = util.computeSourceURL(null, aSource, this._sourceMapURL);
|
|
396
|
+
if (this._absoluteSources.has(sourceAsMapRelative)) {
|
|
397
|
+
const index = this._absoluteSources.indexOf(sourceAsMapRelative);
|
|
398
|
+
this._sourceLookupCache.set(aSource, index);
|
|
399
|
+
return index;
|
|
400
|
+
}
|
|
401
|
+
const sourceAsSourceRootRelative = util.computeSourceURL(this.sourceRoot, aSource, this._sourceMapURL);
|
|
402
|
+
if (this._absoluteSources.has(sourceAsSourceRootRelative)) {
|
|
403
|
+
const index = this._absoluteSources.indexOf(sourceAsSourceRootRelative);
|
|
404
|
+
this._sourceLookupCache.set(aSource, index);
|
|
405
|
+
return index;
|
|
406
|
+
}
|
|
407
|
+
return -1;
|
|
408
|
+
}
|
|
409
|
+
static fromSourceMap(aSourceMap,aSourceMapURL) {
|
|
410
|
+
return new BasicSourceMapConsumer(aSourceMap.toString());
|
|
411
|
+
}
|
|
412
|
+
get sources() {
|
|
413
|
+
return this._absoluteSources.toArray();
|
|
414
|
+
}
|
|
415
|
+
_getMappingsPtr() {
|
|
416
|
+
if (this._mappingsPtr === 0) {
|
|
417
|
+
this._parseMappings();
|
|
418
|
+
}
|
|
419
|
+
return this._mappingsPtr;
|
|
420
|
+
}
|
|
421
|
+
_parseMappings() {
|
|
422
|
+
const aStr = this._mappings,size = aStr.length,mappingsBufPtr = this._wasm.exports.allocate_mappings(size) >>> 0,mappingsBuf = new Uint8Array(this._wasm.exports.memory.buffer, mappingsBufPtr, size);
|
|
423
|
+
for (let i = 0; i < size; i++) {
|
|
424
|
+
mappingsBuf[i] = aStr.charCodeAt(i);
|
|
425
|
+
}
|
|
426
|
+
const mappingsPtr = this._wasm.exports.parse_mappings(mappingsBufPtr);
|
|
427
|
+
if (!mappingsPtr) {
|
|
428
|
+
const error = this._wasm.exports.get_last_error();
|
|
429
|
+
let msg = `Error parsing mappings (code ${error}): `;
|
|
430
|
+
switch (error) {
|
|
431
|
+
case 1:
|
|
432
|
+
msg += "the mappings contained a negative line, column, source index, or name index";
|
|
433
|
+
break;
|
|
434
|
+
case 2:
|
|
435
|
+
msg += "the mappings contained a number larger than 2**32";
|
|
436
|
+
break;
|
|
437
|
+
case 3:
|
|
438
|
+
msg += "reached EOF while in the middle of parsing a VLQ";
|
|
439
|
+
break;
|
|
440
|
+
case 4:
|
|
441
|
+
msg += "invalid base 64 character while parsing a VLQ";
|
|
442
|
+
break;
|
|
443
|
+
default:
|
|
444
|
+
msg += "unknown error code";
|
|
445
|
+
break;
|
|
446
|
+
}
|
|
447
|
+
throw new Error(msg);
|
|
448
|
+
}
|
|
449
|
+
this._mappingsPtr = mappingsPtr;
|
|
450
|
+
}
|
|
451
|
+
eachMapping(aCallback,aContext,aOrder) {
|
|
452
|
+
const context = aContext || null,order = aOrder || SourceMapConsumer.GENERATED_ORDER;
|
|
453
|
+
this._wasm.withMappingCallback((mapping) => {
|
|
454
|
+
if (mapping.source !== null) {
|
|
455
|
+
mapping.source = this._absoluteSources.at(mapping.source);
|
|
456
|
+
if (mapping.name !== null) {
|
|
457
|
+
mapping.name = this._names.at(mapping.name);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
if (this._computedColumnSpans && mapping.lastGeneratedColumn === null) {
|
|
461
|
+
mapping.lastGeneratedColumn = Infinity;
|
|
462
|
+
}
|
|
463
|
+
aCallback.call(context, mapping);
|
|
464
|
+
}, () => {
|
|
465
|
+
switch (order) {
|
|
466
|
+
case SourceMapConsumer.GENERATED_ORDER:
|
|
467
|
+
this._wasm.exports.by_generated_location(this._getMappingsPtr());
|
|
468
|
+
break;
|
|
469
|
+
case SourceMapConsumer.ORIGINAL_ORDER:
|
|
470
|
+
this._wasm.exports.by_original_location(this._getMappingsPtr());
|
|
471
|
+
break;
|
|
472
|
+
default:
|
|
473
|
+
throw new Error("Unknown order of iteration.");
|
|
474
|
+
}
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
allGeneratedPositionsFor(aArgs) {
|
|
478
|
+
let source = util.getArg(aArgs, "source");
|
|
479
|
+
const originalLine = util.getArg(aArgs, "line"),originalColumn = aArgs.column || 0;
|
|
480
|
+
source = this._findSourceIndex(source);
|
|
481
|
+
if (source < 0) {
|
|
482
|
+
return [];
|
|
483
|
+
}
|
|
484
|
+
if (originalLine < 1) {
|
|
485
|
+
throw new Error("Line numbers must be >= 1");
|
|
486
|
+
}
|
|
487
|
+
if (originalColumn < 0) {
|
|
488
|
+
throw new Error("Column numbers must be >= 0");
|
|
489
|
+
}
|
|
490
|
+
const mappings = [];
|
|
491
|
+
this._wasm.withMappingCallback((m) => {
|
|
492
|
+
let lastColumn = m.lastGeneratedColumn;
|
|
493
|
+
if (this._computedColumnSpans && lastColumn === null) {
|
|
494
|
+
lastColumn = Infinity;
|
|
495
|
+
}
|
|
496
|
+
mappings.push({ line: m.generatedLine, column: m.generatedColumn, lastColumn });
|
|
497
|
+
}, () => {
|
|
498
|
+
this._wasm.exports.all_generated_locations_for(this._getMappingsPtr(), source, originalLine - 1, "column" in aArgs, originalColumn);
|
|
499
|
+
});
|
|
500
|
+
return mappings;
|
|
501
|
+
}
|
|
502
|
+
destroy() {
|
|
503
|
+
if (this._mappingsPtr !== 0) {
|
|
504
|
+
this._wasm.exports.free_mappings(this._mappingsPtr);
|
|
505
|
+
this._mappingsPtr = 0;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
computeColumnSpans() {
|
|
509
|
+
if (this._computedColumnSpans) {
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
this._wasm.exports.compute_column_spans(this._getMappingsPtr());
|
|
513
|
+
this._computedColumnSpans = true;
|
|
514
|
+
}
|
|
515
|
+
originalPositionFor(aArgs) {
|
|
516
|
+
const needle = { generatedLine: util.getArg(aArgs, "line"), generatedColumn: util.getArg(aArgs, "column") };
|
|
517
|
+
if (needle.generatedLine < 1) {
|
|
518
|
+
throw new Error("Line numbers must be >= 1");
|
|
519
|
+
}
|
|
520
|
+
if (needle.generatedColumn < 0) {
|
|
521
|
+
throw new Error("Column numbers must be >= 0");
|
|
522
|
+
}
|
|
523
|
+
let bias = util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND);
|
|
524
|
+
if (bias == null) {
|
|
525
|
+
bias = SourceMapConsumer.GREATEST_LOWER_BOUND;
|
|
526
|
+
}
|
|
527
|
+
let mapping;
|
|
528
|
+
this._wasm.withMappingCallback((m) => (mapping = m), () => {
|
|
529
|
+
this._wasm.exports.original_location_for(this._getMappingsPtr(), needle.generatedLine - 1, needle.generatedColumn, bias);
|
|
530
|
+
});
|
|
531
|
+
if (mapping) {
|
|
532
|
+
if (mapping.generatedLine === needle.generatedLine) {
|
|
533
|
+
let source = util.getArg(mapping, "source", null);
|
|
534
|
+
if (source !== null) {
|
|
535
|
+
source = this._absoluteSources.at(source);
|
|
536
|
+
}
|
|
537
|
+
let name = util.getArg(mapping, "name", null);
|
|
538
|
+
if (name !== null) {
|
|
539
|
+
name = this._names.at(name);
|
|
540
|
+
}
|
|
541
|
+
return { source, line: util.getArg(mapping, "originalLine", null), column: util.getArg(mapping, "originalColumn", null), name };
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
return { source: null, line: null, column: null, name: null };
|
|
545
|
+
}
|
|
546
|
+
hasContentsOfAllSources() {
|
|
547
|
+
if (!this.sourcesContent) {
|
|
548
|
+
return false;
|
|
549
|
+
}
|
|
550
|
+
return (this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function(sc) {
|
|
551
|
+
return sc == null;
|
|
552
|
+
}));
|
|
553
|
+
}
|
|
554
|
+
sourceContentFor(aSource,nullOnMissing) {
|
|
555
|
+
if (!this.sourcesContent) {
|
|
556
|
+
return null;
|
|
557
|
+
}
|
|
558
|
+
const index = this._findSourceIndex(aSource);
|
|
559
|
+
if (index >= 0) {
|
|
560
|
+
return this.sourcesContent[index];
|
|
561
|
+
}
|
|
562
|
+
if (nullOnMissing) {
|
|
563
|
+
return null;
|
|
564
|
+
}
|
|
565
|
+
throw new Error("\"" + aSource + "\" is not in the SourceMap.");
|
|
566
|
+
}
|
|
567
|
+
generatedPositionFor(aArgs) {
|
|
568
|
+
let source = util.getArg(aArgs, "source");
|
|
569
|
+
source = this._findSourceIndex(source);
|
|
570
|
+
if (source < 0) {
|
|
571
|
+
return { line: null, column: null, lastColumn: null };
|
|
572
|
+
}
|
|
573
|
+
const needle = { source, originalLine: util.getArg(aArgs, "line"), originalColumn: util.getArg(aArgs, "column") };
|
|
574
|
+
if (needle.originalLine < 1) {
|
|
575
|
+
throw new Error("Line numbers must be >= 1");
|
|
576
|
+
}
|
|
577
|
+
if (needle.originalColumn < 0) {
|
|
578
|
+
throw new Error("Column numbers must be >= 0");
|
|
579
|
+
}
|
|
580
|
+
let bias = util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND);
|
|
581
|
+
if (bias == null) {
|
|
582
|
+
bias = SourceMapConsumer.GREATEST_LOWER_BOUND;
|
|
583
|
+
}
|
|
584
|
+
let mapping;
|
|
585
|
+
this._wasm.withMappingCallback((m) => (mapping = m), () => {
|
|
586
|
+
this._wasm.exports.generated_location_for(this._getMappingsPtr(), needle.source, needle.originalLine - 1, needle.originalColumn, bias);
|
|
587
|
+
});
|
|
588
|
+
if (mapping) {
|
|
589
|
+
if (mapping.source === needle.source) {
|
|
590
|
+
let lastColumn = mapping.lastGeneratedColumn;
|
|
591
|
+
if (this._computedColumnSpans && lastColumn === null) {
|
|
592
|
+
lastColumn = Infinity;
|
|
593
|
+
}
|
|
594
|
+
return { line: util.getArg(mapping, "generatedLine", null), column: util.getArg(mapping, "generatedColumn", null), lastColumn };
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
return { line: null, column: null, lastColumn: null };
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
|
|
601
|
+
exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
|
|
602
|
+
class IndexedSourceMapConsumer extends SourceMapConsumer {
|
|
603
|
+
constructor(aSourceMap,aSourceMapURL) {
|
|
604
|
+
return super(INTERNAL).then((that) => {
|
|
605
|
+
let sourceMap = aSourceMap;
|
|
606
|
+
if (typeof aSourceMap == "string") {
|
|
607
|
+
sourceMap = util.parseSourceMapInput(aSourceMap);
|
|
608
|
+
}
|
|
609
|
+
const version = util.getArg(sourceMap, "version"),sections = util.getArg(sourceMap, "sections");
|
|
610
|
+
if (version != that._version) {
|
|
611
|
+
throw new Error("Unsupported version: " + version);
|
|
612
|
+
}
|
|
613
|
+
let lastOffset = { line: -1, column: 0 };
|
|
614
|
+
return Promise.all(sections.map((s) => {
|
|
615
|
+
if (s.url) {
|
|
616
|
+
throw new Error("Support for url field in sections not implemented.");
|
|
617
|
+
}
|
|
618
|
+
const offset = util.getArg(s, "offset"),offsetLine = util.getArg(offset, "line"),offsetColumn = util.getArg(offset, "column");
|
|
619
|
+
if (offsetLine < lastOffset.line || (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
|
|
620
|
+
throw new Error("Section offsets must be ordered and non-overlapping.");
|
|
621
|
+
}
|
|
622
|
+
lastOffset = offset;
|
|
623
|
+
const cons = new SourceMapConsumer(util.getArg(s, "map"), aSourceMapURL);
|
|
624
|
+
return cons.then((consumer) => {
|
|
625
|
+
return { generatedOffset: { generatedLine: offsetLine + 1, generatedColumn: offsetColumn + 1 }, consumer };
|
|
626
|
+
});
|
|
627
|
+
})).then((s) => {
|
|
628
|
+
that._sections = s;
|
|
629
|
+
return that;
|
|
630
|
+
});
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
get sources() {
|
|
634
|
+
const sources = [];
|
|
635
|
+
for (let i = 0; i < this._sections.length; i++) {
|
|
636
|
+
for (let j = 0; j < this._sections[i].consumer.sources.length; j++) {
|
|
637
|
+
sources.push(this._sections[i].consumer.sources[j]);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
return sources;
|
|
641
|
+
}
|
|
642
|
+
originalPositionFor(aArgs) {
|
|
643
|
+
const needle = { generatedLine: util.getArg(aArgs, "line"), generatedColumn: util.getArg(aArgs, "column") },sectionIndex = binarySearch.search(needle, this._sections, function(aNeedle,section) {
|
|
644
|
+
const cmp = aNeedle.generatedLine - section.generatedOffset.generatedLine;
|
|
645
|
+
if (cmp) {
|
|
646
|
+
return cmp;
|
|
647
|
+
}
|
|
648
|
+
return (aNeedle.generatedColumn - (section.generatedOffset.generatedColumn - 1));
|
|
649
|
+
}),section = this._sections[sectionIndex];
|
|
650
|
+
if (!section) {
|
|
651
|
+
return { source: null, line: null, column: null, name: null };
|
|
652
|
+
}
|
|
653
|
+
return section.consumer.originalPositionFor({ line: needle.generatedLine - (section.generatedOffset.generatedLine - 1), column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), bias: aArgs.bias });
|
|
654
|
+
}
|
|
655
|
+
hasContentsOfAllSources() {
|
|
656
|
+
return this._sections.every(function(s) {
|
|
657
|
+
return s.consumer.hasContentsOfAllSources();
|
|
658
|
+
});
|
|
659
|
+
}
|
|
660
|
+
sourceContentFor(aSource,nullOnMissing) {
|
|
661
|
+
for (let i = 0; i < this._sections.length; i++) {
|
|
662
|
+
const section = this._sections[i],content = section.consumer.sourceContentFor(aSource, true);
|
|
663
|
+
if (content) {
|
|
664
|
+
return content;
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
if (nullOnMissing) {
|
|
668
|
+
return null;
|
|
669
|
+
}
|
|
670
|
+
throw new Error("\"" + aSource + "\" is not in the SourceMap.");
|
|
671
|
+
}
|
|
672
|
+
_findSectionIndex(source) {
|
|
673
|
+
for (let i = 0; i < this._sections.length; i++) {
|
|
674
|
+
const { consumer:consumer } = this._sections[i];
|
|
675
|
+
if (consumer._findSourceIndex(source) !== -1) {
|
|
676
|
+
return i;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
return -1;
|
|
680
|
+
}
|
|
681
|
+
generatedPositionFor(aArgs) {
|
|
682
|
+
const index = this._findSectionIndex(util.getArg(aArgs, "source")),section = index >= 0 ? this._sections[index] : null,nextSection = index >= 0 && index + 1 < this._sections.length ? this._sections[index + 1] : null,generatedPosition = section && section.consumer.generatedPositionFor(aArgs);
|
|
683
|
+
if (generatedPosition && generatedPosition.line !== null) {
|
|
684
|
+
const lineShift = section.generatedOffset.generatedLine - 1,columnShift = section.generatedOffset.generatedColumn - 1;
|
|
685
|
+
if (generatedPosition.line === 1) {
|
|
686
|
+
generatedPosition.column += columnShift;
|
|
687
|
+
if (typeof generatedPosition.lastColumn == "number") {
|
|
688
|
+
generatedPosition.lastColumn += columnShift;
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
if (generatedPosition.lastColumn === Infinity && nextSection && generatedPosition.line === nextSection.generatedOffset.generatedLine) {
|
|
692
|
+
generatedPosition.lastColumn = nextSection.generatedOffset.generatedColumn - 2;
|
|
693
|
+
}
|
|
694
|
+
generatedPosition.line += lineShift;
|
|
695
|
+
return generatedPosition;
|
|
696
|
+
}
|
|
697
|
+
return { line: null, column: null, lastColumn: null };
|
|
698
|
+
}
|
|
699
|
+
allGeneratedPositionsFor(aArgs) {
|
|
700
|
+
const index = this._findSectionIndex(util.getArg(aArgs, "source")),section = index >= 0 ? this._sections[index] : null,nextSection = index >= 0 && index + 1 < this._sections.length ? this._sections[index + 1] : null;
|
|
701
|
+
if (!section)return [];
|
|
702
|
+
return section.consumer.allGeneratedPositionsFor(aArgs).map((generatedPosition) => {
|
|
703
|
+
const lineShift = section.generatedOffset.generatedLine - 1,columnShift = section.generatedOffset.generatedColumn - 1;
|
|
704
|
+
if (generatedPosition.line === 1) {
|
|
705
|
+
generatedPosition.column += columnShift;
|
|
706
|
+
if (typeof generatedPosition.lastColumn == "number") {
|
|
707
|
+
generatedPosition.lastColumn += columnShift;
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
if (generatedPosition.lastColumn === Infinity && nextSection && generatedPosition.line === nextSection.generatedOffset.generatedLine) {
|
|
711
|
+
generatedPosition.lastColumn = nextSection.generatedOffset.generatedColumn - 2;
|
|
712
|
+
}
|
|
713
|
+
generatedPosition.line += lineShift;
|
|
714
|
+
return generatedPosition;
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
eachMapping(aCallback,aContext,aOrder) {
|
|
718
|
+
this._sections.forEach((section, index) => {
|
|
719
|
+
const nextSection = index + 1 < this._sections.length ? this._sections[index + 1] : null,{ generatedOffset:generatedOffset } = section,lineShift = generatedOffset.generatedLine - 1,columnShift = generatedOffset.generatedColumn - 1;
|
|
720
|
+
section.consumer.eachMapping(function(mapping) {
|
|
721
|
+
if (mapping.generatedLine === 1) {
|
|
722
|
+
mapping.generatedColumn += columnShift;
|
|
723
|
+
if (typeof mapping.lastGeneratedColumn == "number") {
|
|
724
|
+
mapping.lastGeneratedColumn += columnShift;
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
if (mapping.lastGeneratedColumn === Infinity && nextSection && mapping.generatedLine === nextSection.generatedOffset.generatedLine) {
|
|
728
|
+
mapping.lastGeneratedColumn = nextSection.generatedOffset.generatedColumn - 2;
|
|
729
|
+
}
|
|
730
|
+
mapping.generatedLine += lineShift;
|
|
731
|
+
aCallback.call(this, mapping);
|
|
732
|
+
}, aContext, aOrder);
|
|
733
|
+
});
|
|
734
|
+
}
|
|
735
|
+
computeColumnSpans() {
|
|
736
|
+
for (let i = 0; i < this._sections.length; i++) {
|
|
737
|
+
this._sections[i].consumer.computeColumnSpans();
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
destroy() {
|
|
741
|
+
for (let i = 0; i < this._sections.length; i++) {
|
|
742
|
+
this._sections[i].consumer.destroy();
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
|
|
747
|
+
function _factory(aSourceMap,aSourceMapURL) {
|
|
748
|
+
let sourceMap = aSourceMap;
|
|
749
|
+
if (typeof aSourceMap == "string") {
|
|
750
|
+
sourceMap = util.parseSourceMapInput(aSourceMap);
|
|
751
|
+
}
|
|
752
|
+
const consumer = sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
|
|
753
|
+
return Promise.resolve(consumer);
|
|
754
|
+
}
|
|
755
|
+
function _factoryBSM(aSourceMap,aSourceMapURL) {
|
|
756
|
+
return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
}
|
|
760
|
+
});
|
|
761
|
+
//#endregion
|
|
762
|
+
//#region source-map-generator.js
|
|
763
|
+
var require_source_map_lib_source_map_generator = __commonJS({
|
|
764
|
+
"source-map-generator.js"(exports, module) {
|
|
765
|
+
const base64VLQ = require_source_map_lib_base64_vlq(),util = require_source_map_lib_util(),ArraySet = require_source_map_lib_array_set().ArraySet,MappingList = require_source_map_lib_mapping_list().MappingList;
|
|
766
|
+
class SourceMapGenerator {
|
|
767
|
+
constructor(aArgs) {
|
|
768
|
+
if (!aArgs) {
|
|
769
|
+
aArgs = {};
|
|
770
|
+
}
|
|
771
|
+
this._file = util.getArg(aArgs, "file", null);
|
|
772
|
+
this._sourceRoot = util.getArg(aArgs, "sourceRoot", null);
|
|
773
|
+
this._skipValidation = util.getArg(aArgs, "skipValidation", false);
|
|
774
|
+
this._sources = new ArraySet();
|
|
775
|
+
this._names = new ArraySet();
|
|
776
|
+
this._mappings = new MappingList();
|
|
777
|
+
this._sourcesContents = null;
|
|
778
|
+
}
|
|
779
|
+
static fromSourceMap(aSourceMapConsumer) {
|
|
780
|
+
const sourceRoot = aSourceMapConsumer.sourceRoot,generator = new SourceMapGenerator({ file: aSourceMapConsumer.file, sourceRoot });
|
|
781
|
+
aSourceMapConsumer.eachMapping(function(mapping) {
|
|
782
|
+
const newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } };
|
|
783
|
+
if (mapping.source != null) {
|
|
784
|
+
newMapping.source = mapping.source;
|
|
785
|
+
if (sourceRoot != null) {
|
|
786
|
+
newMapping.source = util.relative(sourceRoot, newMapping.source);
|
|
787
|
+
}
|
|
788
|
+
newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn };
|
|
789
|
+
if (mapping.name != null) {
|
|
790
|
+
newMapping.name = mapping.name;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
generator.addMapping(newMapping);
|
|
794
|
+
});
|
|
795
|
+
aSourceMapConsumer.sources.forEach(function(sourceFile) {
|
|
796
|
+
let sourceRelative = sourceFile;
|
|
797
|
+
if (sourceRoot != null) {
|
|
798
|
+
sourceRelative = util.relative(sourceRoot, sourceFile);
|
|
799
|
+
}
|
|
800
|
+
if (!generator._sources.has(sourceRelative)) {
|
|
801
|
+
generator._sources.add(sourceRelative);
|
|
802
|
+
}
|
|
803
|
+
const content = aSourceMapConsumer.sourceContentFor(sourceFile);
|
|
804
|
+
if (content != null) {
|
|
805
|
+
generator.setSourceContent(sourceFile, content);
|
|
806
|
+
}
|
|
807
|
+
});
|
|
808
|
+
return generator;
|
|
809
|
+
}
|
|
810
|
+
addMapping(aArgs) {
|
|
811
|
+
const generated = util.getArg(aArgs, "generated"),original = util.getArg(aArgs, "original", null);
|
|
812
|
+
let source = util.getArg(aArgs, "source", null),name = util.getArg(aArgs, "name", null);
|
|
813
|
+
if (!this._skipValidation) {
|
|
814
|
+
this._validateMapping(generated, original, source, name);
|
|
815
|
+
}
|
|
816
|
+
if (source != null) {
|
|
817
|
+
source = String(source);
|
|
818
|
+
if (!this._sources.has(source)) {
|
|
819
|
+
this._sources.add(source);
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
if (name != null) {
|
|
823
|
+
name = String(name);
|
|
824
|
+
if (!this._names.has(name)) {
|
|
825
|
+
this._names.add(name);
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
this._mappings.add({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original && original.line, originalColumn: original && original.column, source, name });
|
|
829
|
+
}
|
|
830
|
+
setSourceContent(aSourceFile,aSourceContent) {
|
|
831
|
+
let source = aSourceFile;
|
|
832
|
+
if (this._sourceRoot != null) {
|
|
833
|
+
source = util.relative(this._sourceRoot, source);
|
|
834
|
+
}
|
|
835
|
+
if (aSourceContent != null) {
|
|
836
|
+
if (!this._sourcesContents) {
|
|
837
|
+
this._sourcesContents = Object.create(null);
|
|
838
|
+
}
|
|
839
|
+
this._sourcesContents[util.toSetString(source)] = aSourceContent;
|
|
840
|
+
} else if (this._sourcesContents) {
|
|
841
|
+
delete this._sourcesContents[util.toSetString(source)];
|
|
842
|
+
if (Object.keys(this._sourcesContents).length === 0) {
|
|
843
|
+
this._sourcesContents = null;
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
applySourceMap(aSourceMapConsumer,aSourceFile,aSourceMapPath) {
|
|
848
|
+
let sourceFile = aSourceFile;
|
|
849
|
+
if (aSourceFile == null) {
|
|
850
|
+
if (aSourceMapConsumer.file == null) {
|
|
851
|
+
throw new Error("SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, " + "or the source map's \"file\" property. Both were omitted.");
|
|
852
|
+
}
|
|
853
|
+
sourceFile = aSourceMapConsumer.file;
|
|
854
|
+
}
|
|
855
|
+
const sourceRoot = this._sourceRoot;
|
|
856
|
+
if (sourceRoot != null) {
|
|
857
|
+
sourceFile = util.relative(sourceRoot, sourceFile);
|
|
858
|
+
}
|
|
859
|
+
const newSources = this._mappings.toArray().length > 0 ? new ArraySet() : this._sources,newNames = new ArraySet();
|
|
860
|
+
this._mappings.unsortedForEach(function(mapping) {
|
|
861
|
+
if (mapping.source === sourceFile && mapping.originalLine != null) {
|
|
862
|
+
const original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn });
|
|
863
|
+
if (original.source != null) {
|
|
864
|
+
mapping.source = original.source;
|
|
865
|
+
if (aSourceMapPath != null) {
|
|
866
|
+
mapping.source = util.join(aSourceMapPath, mapping.source);
|
|
867
|
+
}
|
|
868
|
+
if (sourceRoot != null) {
|
|
869
|
+
mapping.source = util.relative(sourceRoot, mapping.source);
|
|
870
|
+
}
|
|
871
|
+
mapping.originalLine = original.line;
|
|
872
|
+
mapping.originalColumn = original.column;
|
|
873
|
+
if (original.name != null) {
|
|
874
|
+
mapping.name = original.name;
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
const source = mapping.source;
|
|
879
|
+
if (source != null && !newSources.has(source)) {
|
|
880
|
+
newSources.add(source);
|
|
881
|
+
}
|
|
882
|
+
const name = mapping.name;
|
|
883
|
+
if (name != null && !newNames.has(name)) {
|
|
884
|
+
newNames.add(name);
|
|
885
|
+
}
|
|
886
|
+
}, this);
|
|
887
|
+
this._sources = newSources;
|
|
888
|
+
this._names = newNames;
|
|
889
|
+
aSourceMapConsumer.sources.forEach(function(srcFile) {
|
|
890
|
+
const content = aSourceMapConsumer.sourceContentFor(srcFile);
|
|
891
|
+
if (content != null) {
|
|
892
|
+
if (aSourceMapPath != null) {
|
|
893
|
+
srcFile = util.join(aSourceMapPath, srcFile);
|
|
894
|
+
}
|
|
895
|
+
if (sourceRoot != null) {
|
|
896
|
+
srcFile = util.relative(sourceRoot, srcFile);
|
|
897
|
+
}
|
|
898
|
+
this.setSourceContent(srcFile, content);
|
|
899
|
+
}
|
|
900
|
+
}, this);
|
|
901
|
+
}
|
|
902
|
+
_validateMapping(aGenerated,aOriginal,aSource,aName) {
|
|
903
|
+
if (aOriginal && typeof aOriginal.line != "number" && typeof aOriginal.column != "number") {
|
|
904
|
+
throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");
|
|
905
|
+
}
|
|
906
|
+
if (aGenerated && "line" in aGenerated && "column" in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) {
|
|
907
|
+
} else if (aGenerated && "line" in aGenerated && "column" in aGenerated && aOriginal && "line" in aOriginal && "column" in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) {
|
|
908
|
+
} else {
|
|
909
|
+
throw new Error("Invalid mapping: " + JSON.stringify({ generated: aGenerated, source: aSource, original: aOriginal, name: aName }));
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
_serializeMappings() {
|
|
913
|
+
let previousGeneratedColumn = 0,previousGeneratedLine = 1,previousOriginalColumn = 0,previousOriginalLine = 0,previousName = 0,previousSource = 0,result = "",next,mapping,nameIdx,sourceIdx;
|
|
914
|
+
const mappings = this._mappings.toArray();
|
|
915
|
+
for (let i = 0,len = mappings.length; i < len; i++) {
|
|
916
|
+
mapping = mappings[i];
|
|
917
|
+
next = "";
|
|
918
|
+
if (mapping.generatedLine !== previousGeneratedLine) {
|
|
919
|
+
previousGeneratedColumn = 0;
|
|
920
|
+
while (mapping.generatedLine !== previousGeneratedLine) {
|
|
921
|
+
next += ";";
|
|
922
|
+
previousGeneratedLine++;
|
|
923
|
+
}
|
|
924
|
+
} else if (i > 0) {
|
|
925
|
+
if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
|
|
926
|
+
continue;
|
|
927
|
+
}
|
|
928
|
+
next += ",";
|
|
929
|
+
}
|
|
930
|
+
next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn);
|
|
931
|
+
previousGeneratedColumn = mapping.generatedColumn;
|
|
932
|
+
if (mapping.source != null) {
|
|
933
|
+
sourceIdx = this._sources.indexOf(mapping.source);
|
|
934
|
+
next += base64VLQ.encode(sourceIdx - previousSource);
|
|
935
|
+
previousSource = sourceIdx;
|
|
936
|
+
next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine);
|
|
937
|
+
previousOriginalLine = mapping.originalLine - 1;
|
|
938
|
+
next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn);
|
|
939
|
+
previousOriginalColumn = mapping.originalColumn;
|
|
940
|
+
if (mapping.name != null) {
|
|
941
|
+
nameIdx = this._names.indexOf(mapping.name);
|
|
942
|
+
next += base64VLQ.encode(nameIdx - previousName);
|
|
943
|
+
previousName = nameIdx;
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
result += next;
|
|
947
|
+
}
|
|
948
|
+
return result;
|
|
949
|
+
}
|
|
950
|
+
_generateSourcesContent(aSources,aSourceRoot) {
|
|
951
|
+
return aSources.map(function(source) {
|
|
952
|
+
if (!this._sourcesContents) {
|
|
953
|
+
return null;
|
|
954
|
+
}
|
|
955
|
+
if (aSourceRoot != null) {
|
|
956
|
+
source = util.relative(aSourceRoot, source);
|
|
957
|
+
}
|
|
958
|
+
const key = util.toSetString(source);
|
|
959
|
+
return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null;
|
|
960
|
+
}, this);
|
|
961
|
+
}
|
|
962
|
+
toJSON() {
|
|
963
|
+
const map = { version: this._version, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() };
|
|
964
|
+
if (this._file != null) {
|
|
965
|
+
map.file = this._file;
|
|
966
|
+
}
|
|
967
|
+
if (this._sourceRoot != null) {
|
|
968
|
+
map.sourceRoot = this._sourceRoot;
|
|
969
|
+
}
|
|
970
|
+
if (this._sourcesContents) {
|
|
971
|
+
map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
|
|
972
|
+
}
|
|
973
|
+
return map;
|
|
974
|
+
}
|
|
975
|
+
toString() {
|
|
976
|
+
return JSON.stringify(this.toJSON());
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
SourceMapGenerator.prototype._version = 3;
|
|
980
|
+
exports.SourceMapGenerator = SourceMapGenerator;
|
|
981
|
+
|
|
982
|
+
}
|
|
983
|
+
});
|
|
984
|
+
//#endregion
|
|
985
|
+
//#region source-node.js
|
|
986
|
+
var require_source_map_lib_source_node = __commonJS({
|
|
987
|
+
"source-node.js"(exports, module) {
|
|
988
|
+
const SourceMapGenerator = require_source_map_lib_source_map_generator().SourceMapGenerator,util = require_source_map_lib_util(),REGEX_NEWLINE = /(\r?\n)/,NEWLINE_CODE = 10,isSourceNode = "$$$isSourceNode$$$";
|
|
989
|
+
class SourceNode {
|
|
990
|
+
constructor(aLine,aColumn,aSource,aChunks,aName) {
|
|
991
|
+
this.children = [];
|
|
992
|
+
this.sourceContents = {};
|
|
993
|
+
this.line = aLine == null ? null : aLine;
|
|
994
|
+
this.column = aColumn == null ? null : aColumn;
|
|
995
|
+
this.source = aSource == null ? null : aSource;
|
|
996
|
+
this.name = aName == null ? null : aName;
|
|
997
|
+
this[isSourceNode] = true;
|
|
998
|
+
if (aChunks != null)this.add(aChunks);
|
|
999
|
+
}
|
|
1000
|
+
static fromStringWithSourceMap(aGeneratedCode,aSourceMapConsumer,aRelativePath) {
|
|
1001
|
+
const node = new SourceNode(),remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
|
|
1002
|
+
let remainingLinesIndex = 0;
|
|
1003
|
+
const shiftNextLine = function() {
|
|
1004
|
+
const lineContents = getNextLine(),newLine = getNextLine() || "";
|
|
1005
|
+
return lineContents + newLine;
|
|
1006
|
+
function getNextLine() {
|
|
1007
|
+
return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : undefined;
|
|
1008
|
+
}
|
|
1009
|
+
};
|
|
1010
|
+
let lastGeneratedLine = 1,lastGeneratedColumn = 0,lastMapping = null,nextLine;
|
|
1011
|
+
aSourceMapConsumer.eachMapping(function(mapping) {
|
|
1012
|
+
if (lastMapping !== null) {
|
|
1013
|
+
if (lastGeneratedLine < mapping.generatedLine) {
|
|
1014
|
+
addMappingWithCode(lastMapping, shiftNextLine());
|
|
1015
|
+
lastGeneratedLine++;
|
|
1016
|
+
lastGeneratedColumn = 0;
|
|
1017
|
+
} else {
|
|
1018
|
+
nextLine = remainingLines[remainingLinesIndex] || "";
|
|
1019
|
+
const code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn);
|
|
1020
|
+
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn);
|
|
1021
|
+
lastGeneratedColumn = mapping.generatedColumn;
|
|
1022
|
+
addMappingWithCode(lastMapping, code);
|
|
1023
|
+
lastMapping = mapping;
|
|
1024
|
+
return;
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
while (lastGeneratedLine < mapping.generatedLine) {
|
|
1028
|
+
node.add(shiftNextLine());
|
|
1029
|
+
lastGeneratedLine++;
|
|
1030
|
+
}
|
|
1031
|
+
if (lastGeneratedColumn < mapping.generatedColumn) {
|
|
1032
|
+
nextLine = remainingLines[remainingLinesIndex] || "";
|
|
1033
|
+
node.add(nextLine.substr(0, mapping.generatedColumn));
|
|
1034
|
+
remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
|
|
1035
|
+
lastGeneratedColumn = mapping.generatedColumn;
|
|
1036
|
+
}
|
|
1037
|
+
lastMapping = mapping;
|
|
1038
|
+
}, this);
|
|
1039
|
+
if (remainingLinesIndex < remainingLines.length) {
|
|
1040
|
+
if (lastMapping) {
|
|
1041
|
+
addMappingWithCode(lastMapping, shiftNextLine());
|
|
1042
|
+
}
|
|
1043
|
+
node.add(remainingLines.splice(remainingLinesIndex).join(""));
|
|
1044
|
+
}
|
|
1045
|
+
aSourceMapConsumer.sources.forEach(function(sourceFile) {
|
|
1046
|
+
const content = aSourceMapConsumer.sourceContentFor(sourceFile);
|
|
1047
|
+
if (content != null) {
|
|
1048
|
+
if (aRelativePath != null) {
|
|
1049
|
+
sourceFile = util.join(aRelativePath, sourceFile);
|
|
1050
|
+
}
|
|
1051
|
+
node.setSourceContent(sourceFile, content);
|
|
1052
|
+
}
|
|
1053
|
+
});
|
|
1054
|
+
return node;
|
|
1055
|
+
function addMappingWithCode(mapping,code) {
|
|
1056
|
+
if (mapping === null || mapping.source === undefined) {
|
|
1057
|
+
node.add(code);
|
|
1058
|
+
} else {
|
|
1059
|
+
const source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source;
|
|
1060
|
+
node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name));
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
add(aChunk) {
|
|
1065
|
+
if (Array.isArray(aChunk)) {
|
|
1066
|
+
aChunk.forEach(function(chunk) {
|
|
1067
|
+
this.add(chunk);
|
|
1068
|
+
}, this);
|
|
1069
|
+
} else if (aChunk[isSourceNode] || typeof aChunk == "string") {
|
|
1070
|
+
if (aChunk) {
|
|
1071
|
+
this.children.push(aChunk);
|
|
1072
|
+
}
|
|
1073
|
+
} else {
|
|
1074
|
+
throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk);
|
|
1075
|
+
}
|
|
1076
|
+
return this;
|
|
1077
|
+
}
|
|
1078
|
+
prepend(aChunk) {
|
|
1079
|
+
if (Array.isArray(aChunk)) {
|
|
1080
|
+
for (let i = aChunk.length - 1; i >= 0; i--) {
|
|
1081
|
+
this.prepend(aChunk[i]);
|
|
1082
|
+
}
|
|
1083
|
+
} else if (aChunk[isSourceNode] || typeof aChunk == "string") {
|
|
1084
|
+
this.children.unshift(aChunk);
|
|
1085
|
+
} else {
|
|
1086
|
+
throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk);
|
|
1087
|
+
}
|
|
1088
|
+
return this;
|
|
1089
|
+
}
|
|
1090
|
+
walk(aFn) {
|
|
1091
|
+
let chunk;
|
|
1092
|
+
for (let i = 0,len = this.children.length; i < len; i++) {
|
|
1093
|
+
chunk = this.children[i];
|
|
1094
|
+
if (chunk[isSourceNode]) {
|
|
1095
|
+
chunk.walk(aFn);
|
|
1096
|
+
} else if (chunk !== "") {
|
|
1097
|
+
aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name });
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
join(aSep) {
|
|
1102
|
+
let newChildren,i;
|
|
1103
|
+
const len = this.children.length;
|
|
1104
|
+
if (len > 0) {
|
|
1105
|
+
newChildren = [];
|
|
1106
|
+
for (i = 0; i < len - 1; i++) {
|
|
1107
|
+
newChildren.push(this.children[i]);
|
|
1108
|
+
newChildren.push(aSep);
|
|
1109
|
+
}
|
|
1110
|
+
newChildren.push(this.children[i]);
|
|
1111
|
+
this.children = newChildren;
|
|
1112
|
+
}
|
|
1113
|
+
return this;
|
|
1114
|
+
}
|
|
1115
|
+
replaceRight(aPattern,aReplacement) {
|
|
1116
|
+
const lastChild = this.children[this.children.length - 1];
|
|
1117
|
+
if (lastChild[isSourceNode]) {
|
|
1118
|
+
lastChild.replaceRight(aPattern, aReplacement);
|
|
1119
|
+
} else if (typeof lastChild == "string") {
|
|
1120
|
+
this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
|
|
1121
|
+
} else {
|
|
1122
|
+
this.children.push("".replace(aPattern, aReplacement));
|
|
1123
|
+
}
|
|
1124
|
+
return this;
|
|
1125
|
+
}
|
|
1126
|
+
setSourceContent(aSourceFile,aSourceContent) {
|
|
1127
|
+
this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
|
|
1128
|
+
}
|
|
1129
|
+
walkSourceContents(aFn) {
|
|
1130
|
+
for (let i = 0,len = this.children.length; i < len; i++) {
|
|
1131
|
+
if (this.children[i][isSourceNode]) {
|
|
1132
|
+
this.children[i].walkSourceContents(aFn);
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
const sources = Object.keys(this.sourceContents);
|
|
1136
|
+
for (let i = 0,len = sources.length; i < len; i++) {
|
|
1137
|
+
aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
toString() {
|
|
1141
|
+
let str = "";
|
|
1142
|
+
this.walk(function(chunk) {
|
|
1143
|
+
str += chunk;
|
|
1144
|
+
});
|
|
1145
|
+
return str;
|
|
1146
|
+
}
|
|
1147
|
+
toStringWithSourceMap(aArgs) {
|
|
1148
|
+
const generated = { code: "", line: 1, column: 0 },map = new SourceMapGenerator(aArgs);
|
|
1149
|
+
let sourceMappingActive = false,lastOriginalSource = null,lastOriginalLine = null,lastOriginalColumn = null,lastOriginalName = null;
|
|
1150
|
+
this.walk(function(chunk,original) {
|
|
1151
|
+
generated.code += chunk;
|
|
1152
|
+
if (original.source !== null && original.line !== null && original.column !== null) {
|
|
1153
|
+
if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) {
|
|
1154
|
+
map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name });
|
|
1155
|
+
}
|
|
1156
|
+
lastOriginalSource = original.source;
|
|
1157
|
+
lastOriginalLine = original.line;
|
|
1158
|
+
lastOriginalColumn = original.column;
|
|
1159
|
+
lastOriginalName = original.name;
|
|
1160
|
+
sourceMappingActive = true;
|
|
1161
|
+
} else if (sourceMappingActive) {
|
|
1162
|
+
map.addMapping({ generated: { line: generated.line, column: generated.column } });
|
|
1163
|
+
lastOriginalSource = null;
|
|
1164
|
+
sourceMappingActive = false;
|
|
1165
|
+
}
|
|
1166
|
+
for (let idx = 0,length = chunk.length; idx < length; idx++) {
|
|
1167
|
+
if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
|
|
1168
|
+
generated.line++;
|
|
1169
|
+
generated.column = 0;
|
|
1170
|
+
if (idx + 1 === length) {
|
|
1171
|
+
lastOriginalSource = null;
|
|
1172
|
+
sourceMappingActive = false;
|
|
1173
|
+
} else if (sourceMappingActive) {
|
|
1174
|
+
map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name });
|
|
1175
|
+
}
|
|
1176
|
+
} else {
|
|
1177
|
+
generated.column++;
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
});
|
|
1181
|
+
this.walkSourceContents(function(sourceFile,sourceContent) {
|
|
1182
|
+
map.setSourceContent(sourceFile, sourceContent);
|
|
1183
|
+
});
|
|
1184
|
+
return { code: generated.code, map };
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
exports.SourceNode = SourceNode;
|
|
1188
|
+
|
|
1189
|
+
}
|
|
1190
|
+
});
|
|
1191
|
+
//#endregion
|
|
1192
|
+
//#region url.js
|
|
1193
|
+
var require_source_map_lib_url = __commonJS({
|
|
1194
|
+
"url.js"(exports, module) {
|
|
1195
|
+
"use strict";
|
|
1196
|
+
module.exports = typeof URL == "function" ? URL : require__disabled__url().URL;
|
|
1197
|
+
|
|
1198
|
+
}
|
|
1199
|
+
});
|
|
1200
|
+
//#endregion
|
|
1201
|
+
//#region util.js
|
|
1202
|
+
var require_source_map_lib_util = __commonJS({
|
|
1203
|
+
"util.js"(exports, module) {
|
|
1204
|
+
const URL = require_source_map_lib_url();
|
|
1205
|
+
function getArg(aArgs,aName,aDefaultValue) {
|
|
1206
|
+
if (aName in aArgs) {
|
|
1207
|
+
return aArgs[aName];
|
|
1208
|
+
} else if (arguments.length === 3) {
|
|
1209
|
+
return aDefaultValue;
|
|
1210
|
+
}
|
|
1211
|
+
throw new Error("\"" + aName + "\" is a required argument.");
|
|
1212
|
+
}
|
|
1213
|
+
exports.getArg = getArg;
|
|
1214
|
+
const supportsNullProto = (function() {
|
|
1215
|
+
const obj = Object.create(null);
|
|
1216
|
+
return !("__proto__" in obj);
|
|
1217
|
+
})();
|
|
1218
|
+
function identity(s) {
|
|
1219
|
+
return s;
|
|
1220
|
+
}
|
|
1221
|
+
function toSetString(aStr) {
|
|
1222
|
+
if (isProtoString(aStr)) {
|
|
1223
|
+
return "$" + aStr;
|
|
1224
|
+
}
|
|
1225
|
+
return aStr;
|
|
1226
|
+
}
|
|
1227
|
+
exports.toSetString = supportsNullProto ? identity : toSetString;
|
|
1228
|
+
function fromSetString(aStr) {
|
|
1229
|
+
if (isProtoString(aStr)) {
|
|
1230
|
+
return aStr.slice(1);
|
|
1231
|
+
}
|
|
1232
|
+
return aStr;
|
|
1233
|
+
}
|
|
1234
|
+
exports.fromSetString = supportsNullProto ? identity : fromSetString;
|
|
1235
|
+
function isProtoString(s) {
|
|
1236
|
+
if (!s) {
|
|
1237
|
+
return false;
|
|
1238
|
+
}
|
|
1239
|
+
const length = s.length;
|
|
1240
|
+
if (length < 9) {
|
|
1241
|
+
return false;
|
|
1242
|
+
}
|
|
1243
|
+
if (s.charCodeAt(length - 1) !== 95 || s.charCodeAt(length - 2) !== 95 || s.charCodeAt(length - 3) !== 111 || s.charCodeAt(length - 4) !== 116 || s.charCodeAt(length - 5) !== 111 || s.charCodeAt(length - 6) !== 114 || s.charCodeAt(length - 7) !== 112 || s.charCodeAt(length - 8) !== 95 || s.charCodeAt(length - 9) !== 95) {
|
|
1244
|
+
return false;
|
|
1245
|
+
}
|
|
1246
|
+
for (let i = length - 10; i >= 0; i--) {
|
|
1247
|
+
if (s.charCodeAt(i) !== 36) {
|
|
1248
|
+
return false;
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
return true;
|
|
1252
|
+
}
|
|
1253
|
+
function strcmp(aStr1,aStr2) {
|
|
1254
|
+
if (aStr1 === aStr2) {
|
|
1255
|
+
return 0;
|
|
1256
|
+
}
|
|
1257
|
+
if (aStr1 === null) {
|
|
1258
|
+
return 1;
|
|
1259
|
+
}
|
|
1260
|
+
if (aStr2 === null) {
|
|
1261
|
+
return -1;
|
|
1262
|
+
}
|
|
1263
|
+
if (aStr1 > aStr2) {
|
|
1264
|
+
return 1;
|
|
1265
|
+
}
|
|
1266
|
+
return -1;
|
|
1267
|
+
}
|
|
1268
|
+
function compareByGeneratedPositionsInflated(mappingA,mappingB) {
|
|
1269
|
+
let cmp = mappingA.generatedLine - mappingB.generatedLine;
|
|
1270
|
+
if (cmp !== 0) {
|
|
1271
|
+
return cmp;
|
|
1272
|
+
}
|
|
1273
|
+
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
|
|
1274
|
+
if (cmp !== 0) {
|
|
1275
|
+
return cmp;
|
|
1276
|
+
}
|
|
1277
|
+
cmp = strcmp(mappingA.source, mappingB.source);
|
|
1278
|
+
if (cmp !== 0) {
|
|
1279
|
+
return cmp;
|
|
1280
|
+
}
|
|
1281
|
+
cmp = mappingA.originalLine - mappingB.originalLine;
|
|
1282
|
+
if (cmp !== 0) {
|
|
1283
|
+
return cmp;
|
|
1284
|
+
}
|
|
1285
|
+
cmp = mappingA.originalColumn - mappingB.originalColumn;
|
|
1286
|
+
if (cmp !== 0) {
|
|
1287
|
+
return cmp;
|
|
1288
|
+
}
|
|
1289
|
+
return strcmp(mappingA.name, mappingB.name);
|
|
1290
|
+
}
|
|
1291
|
+
exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
|
|
1292
|
+
function parseSourceMapInput(str) {
|
|
1293
|
+
return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, ""));
|
|
1294
|
+
}
|
|
1295
|
+
exports.parseSourceMapInput = parseSourceMapInput;
|
|
1296
|
+
const PROTOCOL = "http:",PROTOCOL_AND_HOST = `${PROTOCOL}//host`;
|
|
1297
|
+
function createSafeHandler(cb) {
|
|
1298
|
+
return (input) => {
|
|
1299
|
+
const type = getURLType(input),base = buildSafeBase(input),url = new URL(input, base);
|
|
1300
|
+
cb(url);
|
|
1301
|
+
const result = url.toString();
|
|
1302
|
+
if (type === "absolute") {
|
|
1303
|
+
return result;
|
|
1304
|
+
} else if (type === "scheme-relative") {
|
|
1305
|
+
return result.slice(PROTOCOL.length);
|
|
1306
|
+
} else if (type === "path-absolute") {
|
|
1307
|
+
return result.slice(PROTOCOL_AND_HOST.length);
|
|
1308
|
+
}
|
|
1309
|
+
return computeRelativeURL(base, result);
|
|
1310
|
+
};
|
|
1311
|
+
}
|
|
1312
|
+
function withBase(url,base) {
|
|
1313
|
+
return new URL(url, base).toString();
|
|
1314
|
+
}
|
|
1315
|
+
function buildUniqueSegment(prefix,str) {
|
|
1316
|
+
let id = 0;
|
|
1317
|
+
do {
|
|
1318
|
+
const ident = prefix + id++;
|
|
1319
|
+
if (str.indexOf(ident) === -1)return ident;
|
|
1320
|
+
} while (true);
|
|
1321
|
+
}
|
|
1322
|
+
function buildSafeBase(str) {
|
|
1323
|
+
const maxDotParts = str.split("..").length - 1,segment = buildUniqueSegment("p", str);
|
|
1324
|
+
let base = `${PROTOCOL_AND_HOST}/`;
|
|
1325
|
+
for (let i = 0; i < maxDotParts; i++) {
|
|
1326
|
+
base += `${segment}/`;
|
|
1327
|
+
}
|
|
1328
|
+
return base;
|
|
1329
|
+
}
|
|
1330
|
+
const ABSOLUTE_SCHEME = /^[A-Za-z0-9\+\-\.]+:/;
|
|
1331
|
+
function getURLType(url) {
|
|
1332
|
+
if (url[0] === "/") {
|
|
1333
|
+
if (url[1] === "/")return "scheme-relative";
|
|
1334
|
+
return "path-absolute";
|
|
1335
|
+
}
|
|
1336
|
+
return ABSOLUTE_SCHEME.test(url) ? "absolute" : "path-relative";
|
|
1337
|
+
}
|
|
1338
|
+
function computeRelativeURL(rootURL,targetURL) {
|
|
1339
|
+
if (typeof rootURL == "string")rootURL = new URL(rootURL);
|
|
1340
|
+
if (typeof targetURL == "string")targetURL = new URL(targetURL);
|
|
1341
|
+
const targetParts = targetURL.pathname.split("/"),rootParts = rootURL.pathname.split("/");
|
|
1342
|
+
if (rootParts.length > 0 && !rootParts[rootParts.length - 1]) {
|
|
1343
|
+
rootParts.pop();
|
|
1344
|
+
}
|
|
1345
|
+
while (targetParts.length > 0 && rootParts.length > 0 && targetParts[0] === rootParts[0]) {
|
|
1346
|
+
targetParts.shift();
|
|
1347
|
+
rootParts.shift();
|
|
1348
|
+
}
|
|
1349
|
+
const relativePath = rootParts.map(() => "..").concat(targetParts).join("/");
|
|
1350
|
+
return relativePath + targetURL.search + targetURL.hash;
|
|
1351
|
+
}
|
|
1352
|
+
const ensureDirectory = createSafeHandler((url) => {
|
|
1353
|
+
url.pathname = url.pathname.replace(/\/?$/, "/");
|
|
1354
|
+
}),trimFilename = createSafeHandler((url) => {
|
|
1355
|
+
url.href = new URL(".", url.toString()).toString();
|
|
1356
|
+
}),normalize = createSafeHandler((url) => {
|
|
1357
|
+
});
|
|
1358
|
+
exports.normalize = normalize;
|
|
1359
|
+
function join(aRoot,aPath) {
|
|
1360
|
+
const pathType = getURLType(aPath),rootType = getURLType(aRoot);
|
|
1361
|
+
aRoot = ensureDirectory(aRoot);
|
|
1362
|
+
if (pathType === "absolute") {
|
|
1363
|
+
return withBase(aPath, undefined);
|
|
1364
|
+
}
|
|
1365
|
+
if (rootType === "absolute") {
|
|
1366
|
+
return withBase(aPath, aRoot);
|
|
1367
|
+
}
|
|
1368
|
+
if (pathType === "scheme-relative") {
|
|
1369
|
+
return normalize(aPath);
|
|
1370
|
+
}
|
|
1371
|
+
if (rootType === "scheme-relative") {
|
|
1372
|
+
return withBase(aPath, withBase(aRoot, PROTOCOL_AND_HOST)).slice(PROTOCOL.length);
|
|
1373
|
+
}
|
|
1374
|
+
if (pathType === "path-absolute") {
|
|
1375
|
+
return normalize(aPath);
|
|
1376
|
+
}
|
|
1377
|
+
if (rootType === "path-absolute") {
|
|
1378
|
+
return withBase(aPath, withBase(aRoot, PROTOCOL_AND_HOST)).slice(PROTOCOL_AND_HOST.length);
|
|
1379
|
+
}
|
|
1380
|
+
const base = buildSafeBase(aPath + aRoot),newPath = withBase(aPath, withBase(aRoot, base));
|
|
1381
|
+
return computeRelativeURL(base, newPath);
|
|
1382
|
+
}
|
|
1383
|
+
exports.join = join;
|
|
1384
|
+
function relative(rootURL,targetURL) {
|
|
1385
|
+
const result = relativeIfPossible(rootURL, targetURL);
|
|
1386
|
+
return typeof result == "string" ? result : normalize(targetURL);
|
|
1387
|
+
}
|
|
1388
|
+
exports.relative = relative;
|
|
1389
|
+
function relativeIfPossible(rootURL,targetURL) {
|
|
1390
|
+
const urlType = getURLType(rootURL);
|
|
1391
|
+
if (urlType !== getURLType(targetURL)) {
|
|
1392
|
+
return null;
|
|
1393
|
+
}
|
|
1394
|
+
const base = buildSafeBase(rootURL + targetURL),root = new URL(rootURL, base),target = new URL(targetURL, base);
|
|
1395
|
+
try {
|
|
1396
|
+
new URL("", target.toString());
|
|
1397
|
+
} catch (err) {
|
|
1398
|
+
return null;
|
|
1399
|
+
}
|
|
1400
|
+
if (target.protocol !== root.protocol || target.user !== root.user || target.password !== root.password || target.hostname !== root.hostname || target.port !== root.port) {
|
|
1401
|
+
return null;
|
|
1402
|
+
}
|
|
1403
|
+
return computeRelativeURL(root, target);
|
|
1404
|
+
}
|
|
1405
|
+
function computeSourceURL(sourceRoot,sourceURL,sourceMapURL) {
|
|
1406
|
+
if (sourceRoot && getURLType(sourceURL) === "path-absolute") {
|
|
1407
|
+
sourceURL = sourceURL.replace(/^\//, "");
|
|
1408
|
+
}
|
|
1409
|
+
let url = normalize(sourceURL || "");
|
|
1410
|
+
if (sourceRoot)url = join(sourceRoot, url);
|
|
1411
|
+
if (sourceMapURL)url = join(trimFilename(sourceMapURL), url);
|
|
1412
|
+
return url;
|
|
1413
|
+
}
|
|
1414
|
+
exports.computeSourceURL = computeSourceURL;
|
|
1415
|
+
|
|
1416
|
+
}
|
|
1417
|
+
});
|
|
1418
|
+
//#endregion
|
|
1419
|
+
//#region wasm.js
|
|
1420
|
+
var require_source_map_lib_wasm = __commonJS({
|
|
1421
|
+
"wasm.js"(exports, module) {
|
|
1422
|
+
const readWasm = require_source_map_lib_read_wasm_browser();
|
|
1423
|
+
function Mapping() {
|
|
1424
|
+
this.generatedLine = 0;
|
|
1425
|
+
this.generatedColumn = 0;
|
|
1426
|
+
this.lastGeneratedColumn = null;
|
|
1427
|
+
this.source = null;
|
|
1428
|
+
this.originalLine = null;
|
|
1429
|
+
this.originalColumn = null;
|
|
1430
|
+
this.name = null;
|
|
1431
|
+
}
|
|
1432
|
+
let cachedWasm = null;
|
|
1433
|
+
module.exports = function wasm() {
|
|
1434
|
+
if (cachedWasm) {
|
|
1435
|
+
return cachedWasm;
|
|
1436
|
+
}
|
|
1437
|
+
const callbackStack = [];
|
|
1438
|
+
cachedWasm = readWasm().then((buffer) => {
|
|
1439
|
+
return WebAssembly.instantiate(buffer, { env: { mapping_callback(generatedLine,generatedColumn,hasLastGeneratedColumn,lastGeneratedColumn,hasOriginal,source,originalLine,originalColumn,hasName,name) {
|
|
1440
|
+
const mapping = new Mapping();
|
|
1441
|
+
mapping.generatedLine = generatedLine + 1;
|
|
1442
|
+
mapping.generatedColumn = generatedColumn;
|
|
1443
|
+
if (hasLastGeneratedColumn) {
|
|
1444
|
+
mapping.lastGeneratedColumn = lastGeneratedColumn - 1;
|
|
1445
|
+
}
|
|
1446
|
+
if (hasOriginal) {
|
|
1447
|
+
mapping.source = source;
|
|
1448
|
+
mapping.originalLine = originalLine + 1;
|
|
1449
|
+
mapping.originalColumn = originalColumn;
|
|
1450
|
+
if (hasName) {
|
|
1451
|
+
mapping.name = name;
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
callbackStack[callbackStack.length - 1](mapping);
|
|
1455
|
+
}, start_all_generated_locations_for() {
|
|
1456
|
+
console.time("all_generated_locations_for");
|
|
1457
|
+
}, end_all_generated_locations_for() {
|
|
1458
|
+
console.timeEnd("all_generated_locations_for");
|
|
1459
|
+
}, start_compute_column_spans() {
|
|
1460
|
+
console.time("compute_column_spans");
|
|
1461
|
+
}, end_compute_column_spans() {
|
|
1462
|
+
console.timeEnd("compute_column_spans");
|
|
1463
|
+
}, start_generated_location_for() {
|
|
1464
|
+
console.time("generated_location_for");
|
|
1465
|
+
}, end_generated_location_for() {
|
|
1466
|
+
console.timeEnd("generated_location_for");
|
|
1467
|
+
}, start_original_location_for() {
|
|
1468
|
+
console.time("original_location_for");
|
|
1469
|
+
}, end_original_location_for() {
|
|
1470
|
+
console.timeEnd("original_location_for");
|
|
1471
|
+
}, start_parse_mappings() {
|
|
1472
|
+
console.time("parse_mappings");
|
|
1473
|
+
}, end_parse_mappings() {
|
|
1474
|
+
console.timeEnd("parse_mappings");
|
|
1475
|
+
}, start_sort_by_generated_location() {
|
|
1476
|
+
console.time("sort_by_generated_location");
|
|
1477
|
+
}, end_sort_by_generated_location() {
|
|
1478
|
+
console.timeEnd("sort_by_generated_location");
|
|
1479
|
+
}, start_sort_by_original_location() {
|
|
1480
|
+
console.time("sort_by_original_location");
|
|
1481
|
+
}, end_sort_by_original_location() {
|
|
1482
|
+
console.timeEnd("sort_by_original_location");
|
|
1483
|
+
} } });
|
|
1484
|
+
}).then((Wasm) => {
|
|
1485
|
+
return { exports: Wasm.instance.exports, withMappingCallback: (mappingCallback, f) => {
|
|
1486
|
+
callbackStack.push(mappingCallback);
|
|
1487
|
+
try {
|
|
1488
|
+
f();
|
|
1489
|
+
} finally {
|
|
1490
|
+
callbackStack.pop();
|
|
1491
|
+
}
|
|
1492
|
+
} };
|
|
1493
|
+
}).then(null, (e) => {
|
|
1494
|
+
cachedWasm = null;
|
|
1495
|
+
throw e;
|
|
1496
|
+
});
|
|
1497
|
+
return cachedWasm;
|
|
1498
|
+
};
|
|
1499
|
+
|
|
1500
|
+
}
|
|
1501
|
+
});
|
|
1502
|
+
//#endregion
|
|
1503
|
+
//#region source-map.js
|
|
1504
|
+
var require_source_map_source_map = __commonJS({
|
|
1505
|
+
"source-map.js"(exports, module) {
|
|
1506
|
+
exports.SourceMapGenerator = require_source_map_lib_source_map_generator().SourceMapGenerator;
|
|
1507
|
+
exports.SourceMapConsumer = require_source_map_lib_source_map_consumer().SourceMapConsumer;
|
|
1508
|
+
exports.SourceNode = require_source_map_lib_source_node().SourceNode;
|
|
1509
|
+
|
|
1510
|
+
}
|
|
1511
|
+
});
|
|
1512
|
+
//#endregion
|
|
1513
|
+
//#region protocol.ts
|
|
1514
|
+
const HMR_MSG = Object.freeze({ Connected: "connected", CssUpdate: "css-update", ClearError: "clear-error", Error: "error", FullReload: "full-reload" }),HMR_WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
1515
|
+
function normalizeHmrErrors(errors) {
|
|
1516
|
+
if (!Array.isArray(errors) || errors.length === 0) {
|
|
1517
|
+
return [{ file: "", message: "Unknown build error" }];
|
|
1518
|
+
}
|
|
1519
|
+
return errors.map((error) => {
|
|
1520
|
+
const e = (error ?? {}),file = typeof e.location?.file == "string" ? e.location.file : "",message = String(e.text ?? e.message ?? error);
|
|
1521
|
+
return { file, message };
|
|
1522
|
+
});
|
|
1523
|
+
}
|
|
1524
|
+
const HMR_RN_MSG = Object.freeze({ UpdateStart: "hmr:update-start", Update: "hmr:update", UpdateDone: "hmr:update-done", Reload: "hmr:reload", Error: "hmr:error", Log: "log" });
|
|
1525
|
+
//#endregion
|
|
1526
|
+
//#region ws-frame.ts
|
|
1527
|
+
const TEXT_FRAME_FIN_OPCODE = 0x81,PAYLOAD_LEN_SHORT_MAX = 125,PAYLOAD_LEN_EXTENDED_16 = 126,PAYLOAD_LEN_EXTENDED_64 = 127,PAYLOAD_LEN_16BIT_MAX = 65535;
|
|
1528
|
+
function buildTextFrame(text) {
|
|
1529
|
+
const payload = Buffer$1.from(text);
|
|
1530
|
+
return Buffer$1.concat([buildTextHeader(payload.length), payload]);
|
|
1531
|
+
}
|
|
1532
|
+
function buildTextHeader(payloadLength) {
|
|
1533
|
+
if (payloadLength <= PAYLOAD_LEN_SHORT_MAX) {
|
|
1534
|
+
return Buffer$1.from([TEXT_FRAME_FIN_OPCODE, payloadLength]);
|
|
1535
|
+
}
|
|
1536
|
+
if (payloadLength <= PAYLOAD_LEN_16BIT_MAX) {
|
|
1537
|
+
const header = Buffer$1.allocUnsafe(4);
|
|
1538
|
+
header[0] = TEXT_FRAME_FIN_OPCODE;
|
|
1539
|
+
header[1] = PAYLOAD_LEN_EXTENDED_16;
|
|
1540
|
+
header.writeUInt16BE(payloadLength, 2);
|
|
1541
|
+
return header;
|
|
1542
|
+
}
|
|
1543
|
+
const header = Buffer$1.allocUnsafe(10);
|
|
1544
|
+
header[0] = TEXT_FRAME_FIN_OPCODE;
|
|
1545
|
+
header[1] = PAYLOAD_LEN_EXTENDED_64;
|
|
1546
|
+
header.writeBigUInt64BE(BigInt(payloadLength), 2);
|
|
1547
|
+
return header;
|
|
1548
|
+
}
|
|
1549
|
+
function writeTextFrame(socket,text) {
|
|
1550
|
+
if (socket.destroyed)return;
|
|
1551
|
+
socket.write(buildTextFrame(text));
|
|
1552
|
+
}
|
|
1553
|
+
function computeAcceptKey(secWebSocketKey) {
|
|
1554
|
+
return createHash("sha1").update(`${secWebSocketKey}${HMR_WS_GUID}`).digest("base64");
|
|
1555
|
+
}
|
|
1556
|
+
function buildHandshakeResponse(secWebSocketKey) {
|
|
1557
|
+
return ["HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade", `Sec-WebSocket-Accept: ${computeAcceptKey(secWebSocketKey)}`, "", ""].join("\r\n");
|
|
1558
|
+
}
|
|
1559
|
+
function parseTextFrame(buffer) {
|
|
1560
|
+
if (buffer.length < 2)return null;
|
|
1561
|
+
const byte0 = buffer[0],byte1 = buffer[1];
|
|
1562
|
+
;
|
|
1563
|
+
;
|
|
1564
|
+
;
|
|
1565
|
+
if (!((byte0 & 0x80) !== 0) || (byte0 & 0x0f) !== 0x1 || !((byte1 & 0x80) !== 0))return null;
|
|
1566
|
+
let payloadLen = byte1 & 0x7f,offset = 2;
|
|
1567
|
+
if (payloadLen === PAYLOAD_LEN_EXTENDED_16) {
|
|
1568
|
+
if (buffer.length < 4)return null;
|
|
1569
|
+
payloadLen = buffer.readUInt16BE(2);
|
|
1570
|
+
offset = 4;
|
|
1571
|
+
} else if (payloadLen === PAYLOAD_LEN_EXTENDED_64) {
|
|
1572
|
+
if (buffer.length < 10)return null;
|
|
1573
|
+
const big = buffer.readBigUInt64BE(2);
|
|
1574
|
+
if (big > BigInt(Number.MAX_SAFE_INTEGER))return null;
|
|
1575
|
+
payloadLen = Number(big);
|
|
1576
|
+
offset = 10;
|
|
1577
|
+
}
|
|
1578
|
+
if (buffer.length < offset + 4 + payloadLen)return null;
|
|
1579
|
+
const maskKey = buffer.subarray(offset, offset + 4),payload = Buffer$1.allocUnsafe(payloadLen);
|
|
1580
|
+
for (let i = 0; i < payloadLen; i++) {
|
|
1581
|
+
payload[i] = buffer[offset + 4 + i] ^ maskKey[i % 4];
|
|
1582
|
+
}
|
|
1583
|
+
return { text: payload.toString("utf-8"), consumed: offset + 4 + payloadLen };
|
|
1584
|
+
}
|
|
1585
|
+
//#endregion
|
|
1586
|
+
//#region hmr-channel.ts
|
|
1587
|
+
function extractErrorText(error) {
|
|
1588
|
+
const e = (error ?? {});
|
|
1589
|
+
return ((typeof e.stack == "string" && e.stack) || (typeof e.message == "string" && e.message) || String(error));
|
|
1590
|
+
}
|
|
1591
|
+
function createHmrChannel() {
|
|
1592
|
+
const nodeSockets = new Set(),bunClients = new Set(),incomingHandlers = [],connectedText = JSON.stringify({ type: HMR_MSG.Connected });
|
|
1593
|
+
let currentError = null,currentErrorText = null;
|
|
1594
|
+
function broadcastText(text) {
|
|
1595
|
+
for (const socket of nodeSockets)writeTextFrame(socket, text);
|
|
1596
|
+
for (const ws of bunClients)ws.send(text);
|
|
1597
|
+
}
|
|
1598
|
+
function greetNode(socket) {
|
|
1599
|
+
writeTextFrame(socket, connectedText);
|
|
1600
|
+
if (currentErrorText)writeTextFrame(socket, currentErrorText);
|
|
1601
|
+
}
|
|
1602
|
+
function greetBun(ws) {
|
|
1603
|
+
ws.send(connectedText);
|
|
1604
|
+
if (currentErrorText)ws.send(currentErrorText);
|
|
1605
|
+
}
|
|
1606
|
+
return { accept(req,socket) {
|
|
1607
|
+
const key = req.headers["sec-websocket-key"];
|
|
1608
|
+
if (typeof key != "string") {
|
|
1609
|
+
socket.destroy();
|
|
1610
|
+
return;
|
|
1611
|
+
}
|
|
1612
|
+
socket.write(buildHandshakeResponse(key));
|
|
1613
|
+
nodeSockets.add(socket);
|
|
1614
|
+
let recvBuffer = Buffer.alloc(0);
|
|
1615
|
+
socket.on("data", (chunk) => {
|
|
1616
|
+
if (incomingHandlers.length === 0)return;
|
|
1617
|
+
recvBuffer = (recvBuffer.length === 0 ? chunk : Buffer.concat([recvBuffer, chunk]));
|
|
1618
|
+
while (recvBuffer.length > 0) {
|
|
1619
|
+
const parsed = parseTextFrame(recvBuffer);
|
|
1620
|
+
if (!parsed)break;
|
|
1621
|
+
recvBuffer = recvBuffer.subarray(parsed.consumed);
|
|
1622
|
+
for (const handler of incomingHandlers) {
|
|
1623
|
+
try {
|
|
1624
|
+
handler(parsed.text, socket);
|
|
1625
|
+
} catch {
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
});
|
|
1630
|
+
socket.on("close", () => nodeSockets.delete(socket));
|
|
1631
|
+
socket.on("error", () => nodeSockets.delete(socket));
|
|
1632
|
+
greetNode(socket);
|
|
1633
|
+
}, addBunClient(ws) {
|
|
1634
|
+
bunClients.add(ws);
|
|
1635
|
+
greetBun(ws);
|
|
1636
|
+
}, removeBunClient(ws) {
|
|
1637
|
+
bunClients.delete(ws);
|
|
1638
|
+
}, onIncoming(handler) {
|
|
1639
|
+
incomingHandlers.push(handler);
|
|
1640
|
+
}, broadcast(message) {
|
|
1641
|
+
broadcastText(JSON.stringify(message));
|
|
1642
|
+
}, reportError(errors) {
|
|
1643
|
+
currentError = { type: HMR_MSG.Error, errors: normalizeHmrErrors(errors), timestamp: Date.now() };
|
|
1644
|
+
currentErrorText = JSON.stringify(currentError);
|
|
1645
|
+
broadcastText(currentErrorText);
|
|
1646
|
+
}, reportThrownError(error) {
|
|
1647
|
+
this.reportError([{ text: extractErrorText(error) }]);
|
|
1648
|
+
}, clearError() {
|
|
1649
|
+
currentError = null;
|
|
1650
|
+
currentErrorText = null;
|
|
1651
|
+
}, get clientCount() {
|
|
1652
|
+
return nodeSockets.size + bunClients.size;
|
|
1653
|
+
} };
|
|
1654
|
+
}
|
|
1655
|
+
//#endregion
|
|
1656
|
+
//#region metro-hmr-adapter.ts
|
|
1657
|
+
const ZNTC_LOCATION_RE = /([^\s]+\.[jt]sx?):(\d+):(\d+)/;
|
|
1658
|
+
function formatBuildError(message) {
|
|
1659
|
+
const match = message.match(ZNTC_LOCATION_RE),errors = match ? [{ description: message, filename: match[1], lineNumber: Number.parseInt(match[2], 10), column: Number.parseInt(match[3], 10) }] : [{ description: message }];
|
|
1660
|
+
return { type: "BuildError", message, errors };
|
|
1661
|
+
}
|
|
1662
|
+
function createMetroHmrAdapter() {
|
|
1663
|
+
const channel = createHmrChannel();
|
|
1664
|
+
return { channel, sendInitialGreeting() {
|
|
1665
|
+
channel.broadcast({ type: HMR_RN_MSG.UpdateStart, isInitialUpdate: true });
|
|
1666
|
+
channel.broadcast({ type: HMR_RN_MSG.UpdateDone });
|
|
1667
|
+
}, sendUpdate(modules) {
|
|
1668
|
+
channel.broadcast({ type: HMR_RN_MSG.UpdateStart });
|
|
1669
|
+
channel.broadcast({ type: HMR_RN_MSG.Update, modules: [...modules] });
|
|
1670
|
+
channel.broadcast({ type: HMR_RN_MSG.UpdateDone });
|
|
1671
|
+
}, sendReload() {
|
|
1672
|
+
channel.broadcast({ type: HMR_RN_MSG.Reload });
|
|
1673
|
+
}, sendError(message) {
|
|
1674
|
+
channel.broadcast({ type: HMR_RN_MSG.Error, message, body: formatBuildError(message) });
|
|
1675
|
+
} };
|
|
1676
|
+
}
|
|
1677
|
+
//#endregion
|
|
1678
|
+
//#region logger.ts
|
|
1679
|
+
const colors = { reset: "\x1b[0m", bold: "\x1b[1m", dim: "\x1b[2m", inverse: "\x1b[7m", white: "\x1b[37m", gray: "\x1b[90m", red: "\x1b[31m", green: "\x1b[32m", yellow: "\x1b[33m", blue: "\x1b[34m", magenta: "\x1b[35m", cyan: "\x1b[36m", brightYellow: "\x1b[93m", brightRed: "\x1b[91m" };
|
|
1680
|
+
function logInfo(...args) {
|
|
1681
|
+
console.log(`${colors.inverse}${colors.bold}${colors.cyan} INFO ${colors.reset}`, ...args);
|
|
1682
|
+
}
|
|
1683
|
+
function logWarn(...args) {
|
|
1684
|
+
console.warn(`${colors.inverse}${colors.bold}${colors.yellow} WARN ${colors.reset}`, ...args);
|
|
1685
|
+
}
|
|
1686
|
+
function logError(...args) {
|
|
1687
|
+
console.error(`${colors.inverse}${colors.bold}${colors.red} ERROR ${colors.reset}`, ...args);
|
|
1688
|
+
}
|
|
1689
|
+
function formatLogBadge(level) {
|
|
1690
|
+
const color = level === "error" ? colors.red : level === "warn" ? colors.yellow : level === "debug" ? colors.magenta : level === "info" ? colors.cyan : colors.white;
|
|
1691
|
+
return `${color}${colors.inverse}${colors.bold} ${level.toUpperCase()} ${colors.reset}`;
|
|
1692
|
+
}
|
|
1693
|
+
function logBundle(phase,platform,subject,detail) {
|
|
1694
|
+
const color = phase === "done" ? colors.green : phase === "failed" ? colors.red : colors.yellow,badge = `${color}${colors.inverse}${colors.bold} BUNDLE ${colors.reset}`,tail = detail ? ` ${colors.dim}${detail}${colors.reset}` : "";
|
|
1695
|
+
console.log(`${badge} ${colors.dim}[${platform}]${colors.reset} ${subject}${tail}`);
|
|
1696
|
+
}
|
|
1697
|
+
const BANNER_WIDTH = 59;
|
|
1698
|
+
function bannerLine(content) {
|
|
1699
|
+
const visibleLen = content.replace(/\x1b\[[0-9;]*m/g, "").length,padding = Math.max(0, BANNER_WIDTH - visibleLen),left = Math.floor(padding / 2);
|
|
1700
|
+
;
|
|
1701
|
+
return `${colors.cyan} ║${colors.reset}${" ".repeat(left)}${content}${" ".repeat((padding - left))}${colors.cyan}║${colors.reset}`;
|
|
1702
|
+
}
|
|
1703
|
+
const ZNTC_ASCII = ["▀▀▀▀▀▀▀▀", "▀▀▀▀▀▀▀▀▀▀▀▀", "▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀", "▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀", "▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀"],ZNTC_GRADIENT = [colors.brightYellow, colors.brightYellow, colors.yellow, colors.brightRed, colors.brightRed];
|
|
1704
|
+
if (ZNTC_ASCII.length !== ZNTC_GRADIENT.length) {
|
|
1705
|
+
throw new Error(`ZNTC banner: ZNTC_ASCII(${ZNTC_ASCII.length}) / ZNTC_GRADIENT(${ZNTC_GRADIENT.length}) 길이 불일치`);
|
|
1706
|
+
}
|
|
1707
|
+
function printZntcRnBanner(version) {
|
|
1708
|
+
const versionText = version ? `v${version}` : "",logoLines = ZNTC_ASCII.map((line, i) => bannerLine(`${colors.bold}${ZNTC_GRADIENT[i]}${line}${colors.reset}`)),lines = ["", `${colors.cyan} ╔${"═".repeat(BANNER_WIDTH)}╗${colors.reset}`, bannerLine(""), ...logoLines, bannerLine(""), bannerLine(`${colors.cyan}Lightning Fast React Native Bundler${colors.reset}`), bannerLine(`${colors.gray}${versionText}${colors.reset}`), bannerLine(""), `${colors.cyan} ╚${"═".repeat(BANNER_WIDTH)}╝${colors.reset}`, ""];
|
|
1709
|
+
console.log(lines.join("\n"));
|
|
1710
|
+
}
|
|
1711
|
+
//#endregion
|
|
1712
|
+
//#region hmr-bridge.ts
|
|
1713
|
+
function annotateUpdates(updates,platform) {
|
|
1714
|
+
return updates.map((u) => {
|
|
1715
|
+
const sourceMappingURL = `/__zntc_hmr_map/${encodeURIComponent(u.id)}?platform=${platform}`;
|
|
1716
|
+
return { ...u, code: `${u.code}\n//# sourceMappingURL=${sourceMappingURL}\n` };
|
|
1717
|
+
});
|
|
1718
|
+
}
|
|
1719
|
+
function buildOnRebuild(adapter,opts={}) {
|
|
1720
|
+
return (state, event) => {
|
|
1721
|
+
if (!event.success) {
|
|
1722
|
+
const errMsg = state.buildError ?? event.error ?? "Unknown build error";
|
|
1723
|
+
adapter.sendError(errMsg);
|
|
1724
|
+
if (!opts.silent)logError(`Build failed [${state.platform}]: ${errMsg}`);
|
|
1725
|
+
return;
|
|
1726
|
+
}
|
|
1727
|
+
const changedCount = event.changed?.length ?? 0,ms = event.phaseDurations?.total ?? Date.now() - state.lastRebuildTime;
|
|
1728
|
+
if (event.graphChanged) {
|
|
1729
|
+
adapter.sendReload();
|
|
1730
|
+
if (!opts.silent) {
|
|
1731
|
+
logInfo(`Graph changed ${colors.dim}[${state.platform}] (${changedCount} files, ${ms}ms)${colors.reset}, full reload`);
|
|
1732
|
+
}
|
|
1733
|
+
return;
|
|
1734
|
+
}
|
|
1735
|
+
if (event.updates && event.updates.length > 0) {
|
|
1736
|
+
const annotated = annotateUpdates(event.updates, state.platform);
|
|
1737
|
+
adapter.sendUpdate(annotated);
|
|
1738
|
+
if (!opts.silent) {
|
|
1739
|
+
logInfo(`HMR update ${colors.dim}[${state.platform}] ${event.updates.length} module(s) (${ms}ms)${colors.reset}`);
|
|
1740
|
+
}
|
|
1741
|
+
return;
|
|
1742
|
+
}
|
|
1743
|
+
if (!opts.silent && changedCount > 0) {
|
|
1744
|
+
logInfo(`Rebuilt ${colors.dim}[${state.platform}] (${changedCount} files, ${ms}ms, no code change)${colors.reset}`);
|
|
1745
|
+
}
|
|
1746
|
+
};
|
|
1747
|
+
}
|
|
1748
|
+
function buildIncomingHandler(adapter,getLogsEnabled) {
|
|
1749
|
+
return (text, socket) => {
|
|
1750
|
+
let msg = null;
|
|
1751
|
+
try {
|
|
1752
|
+
msg = JSON.parse(text);
|
|
1753
|
+
} catch {
|
|
1754
|
+
return;
|
|
1755
|
+
}
|
|
1756
|
+
if (!msg || typeof msg.type != "string")return;
|
|
1757
|
+
if (msg.type === "register-entrypoints") {
|
|
1758
|
+
socket.write(buildAckFrame());
|
|
1759
|
+
return;
|
|
1760
|
+
}
|
|
1761
|
+
if (msg.type === "log") {
|
|
1762
|
+
if (!getLogsEnabled())return;
|
|
1763
|
+
const level = typeof msg.level == "string" ? msg.level : "log",data = Array.isArray(msg.data) ? msg.data : [msg.data],formatted = data.map((arg) => {
|
|
1764
|
+
if (typeof arg == "object" && arg !== null) {
|
|
1765
|
+
try {
|
|
1766
|
+
return JSON.stringify(arg, null, 2);
|
|
1767
|
+
} catch {
|
|
1768
|
+
return String(arg);
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1771
|
+
return String(arg);
|
|
1772
|
+
}).join(" ");
|
|
1773
|
+
console.log(`${formatLogBadge(level)} ${formatted}`);
|
|
1774
|
+
;
|
|
1775
|
+
}
|
|
1776
|
+
};
|
|
1777
|
+
}
|
|
1778
|
+
const ACK_TEXT = JSON.stringify({ type: "bundle-registered" });
|
|
1779
|
+
function buildAckFrame() {
|
|
1780
|
+
const payload = Buffer.from(ACK_TEXT);
|
|
1781
|
+
return Buffer.concat([Buffer.from([0x81, payload.length]), payload]);
|
|
1782
|
+
}
|
|
1783
|
+
function createHmrBridge(options) {
|
|
1784
|
+
const adapter = createMetroHmrAdapter(),onRebuild = buildOnRebuild(adapter, { silent: options.silent });
|
|
1785
|
+
let logsEnabled = options.forwardClientLogs !== false;
|
|
1786
|
+
adapter.channel.onIncoming(buildIncomingHandler(adapter, () => logsEnabled));
|
|
1787
|
+
return { adapter, callbacks: { onRebuild }, path: options.path, acceptUpgrade(req,socket) {
|
|
1788
|
+
adapter.channel.accept(req, socket);
|
|
1789
|
+
adapter.sendInitialGreeting();
|
|
1790
|
+
}, toggleLogs() {
|
|
1791
|
+
logsEnabled = !logsEnabled;
|
|
1792
|
+
return logsEnabled;
|
|
1793
|
+
} };
|
|
1794
|
+
}
|
|
1795
|
+
//#endregion
|
|
1796
|
+
//#region http-utils.ts
|
|
1797
|
+
function sendText(res,statusCode,text,contentType="text/plain") {
|
|
1798
|
+
res.writeHead(statusCode, { "Content-Type": contentType, "Content-Length": Buffer.byteLength(text) });
|
|
1799
|
+
res.end(text);
|
|
1800
|
+
}
|
|
1801
|
+
function sendJson(res,statusCode,data) {
|
|
1802
|
+
const body = JSON.stringify(data);
|
|
1803
|
+
res.writeHead(statusCode, { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) });
|
|
1804
|
+
res.end(body);
|
|
1805
|
+
}
|
|
1806
|
+
function parseCachedBody(cached) {
|
|
1807
|
+
if (cached == null)return null;
|
|
1808
|
+
if (typeof cached == "string")return JSON.parse(cached);
|
|
1809
|
+
if (Buffer.isBuffer(cached))return JSON.parse(cached.toString("utf-8"));
|
|
1810
|
+
if (typeof cached == "object")return cached;
|
|
1811
|
+
return null;
|
|
1812
|
+
}
|
|
1813
|
+
async function readJsonBody(req) {
|
|
1814
|
+
const augmented = req;
|
|
1815
|
+
if (req.complete && !req.readable) {
|
|
1816
|
+
return parseCachedBody(augmented.body) ?? parseCachedBody(augmented.rawBody) ?? {};
|
|
1817
|
+
}
|
|
1818
|
+
return new Promise((resolve, reject) => {
|
|
1819
|
+
let body = "";
|
|
1820
|
+
req.on("data", (chunk) => {
|
|
1821
|
+
body += chunk.toString();
|
|
1822
|
+
});
|
|
1823
|
+
req.on("end", () => {
|
|
1824
|
+
try {
|
|
1825
|
+
resolve(JSON.parse(body));
|
|
1826
|
+
} catch (error) {
|
|
1827
|
+
reject(error);
|
|
1828
|
+
}
|
|
1829
|
+
});
|
|
1830
|
+
req.on("error", reject);
|
|
1831
|
+
});
|
|
1832
|
+
}
|
|
1833
|
+
function parseRequestUrl(req,fallbackHost,fallbackPort) {
|
|
1834
|
+
const hostHeader = req.headers.host || `${fallbackHost}:${fallbackPort}`;
|
|
1835
|
+
return new URL(req.url || "/", `http://${hostHeader}`);
|
|
1836
|
+
}
|
|
1837
|
+
//#endregion
|
|
1838
|
+
//#region dev-middleware.ts
|
|
1839
|
+
function createProjectRequire(projectRoot) {
|
|
1840
|
+
return createRequire(`${resolve(projectRoot)}/package.json`);
|
|
1841
|
+
}
|
|
1842
|
+
function resolveDevMiddlewarePath(projectRoot) {
|
|
1843
|
+
const projectRequire = createProjectRequire(projectRoot),candidates = [() => {
|
|
1844
|
+
const expoPath = projectRequire.resolve("expo"),expoRequire = createRequire(expoPath),expoCliPath = expoRequire.resolve("@expo/cli"),expoCliRequire = createRequire(expoCliPath);
|
|
1845
|
+
return expoCliRequire.resolve("@react-native/dev-middleware");
|
|
1846
|
+
}, () => {
|
|
1847
|
+
const reactNativePath = projectRequire.resolve("react-native/package.json"),rnRequire = createRequire(reactNativePath),cliPluginPath = rnRequire.resolve("@react-native/community-cli-plugin/package.json"),cliPluginRequire = createRequire(cliPluginPath);
|
|
1848
|
+
return cliPluginRequire.resolve("@react-native/dev-middleware");
|
|
1849
|
+
}, () => projectRequire.resolve("@react-native/dev-middleware"), () => require.resolve("@react-native/dev-middleware")];
|
|
1850
|
+
for (const candidate of candidates) {
|
|
1851
|
+
try {
|
|
1852
|
+
return candidate();
|
|
1853
|
+
} catch {
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
return null;
|
|
1857
|
+
}
|
|
1858
|
+
async function loadDevMiddleware(options) {
|
|
1859
|
+
const path = resolveDevMiddlewarePath(options.projectRoot);
|
|
1860
|
+
if (!path)return null;
|
|
1861
|
+
try {
|
|
1862
|
+
const requireFromProject = createProjectRequire(options.projectRoot),mod = requireFromProject(path);
|
|
1863
|
+
return mod.createDevMiddleware({ serverBaseUrl: `http://localhost:${options.port}`, projectRoot: options.projectRoot, logger: { info: () => {
|
|
1864
|
+
}, warn: () => {
|
|
1865
|
+
}, error: (...args) => console.error("[zntc/rn dev-middleware]", ...args) } });
|
|
1866
|
+
} catch {
|
|
1867
|
+
return null;
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
const DEV_MIDDLEWARE_PATH_PREFIXES = ["/json", "/open-debugger", "/debugger-frontend", "/launch-js-devtools"];
|
|
1871
|
+
function isDevMiddlewareRoute(pathname) {
|
|
1872
|
+
return DEV_MIDDLEWARE_PATH_PREFIXES.some((p) => pathname === p || pathname.startsWith(`${p}/`));
|
|
1873
|
+
}
|
|
1874
|
+
//#endregion
|
|
1875
|
+
//#region assets.ts
|
|
1876
|
+
function isAssetRoute(pathname) {
|
|
1877
|
+
return pathname.startsWith("/assets/") || pathname.startsWith("/node_modules/");
|
|
1878
|
+
}
|
|
1879
|
+
const CONTENT_TYPE_MAP = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".bmp": "image/bmp", ".svg": "image/svg+xml", ".ico": "image/x-icon", ".json": "application/json" };
|
|
1880
|
+
function resolveSymlink(path,maxDepth=10) {
|
|
1881
|
+
if (maxDepth <= 0)return path;
|
|
1882
|
+
try {
|
|
1883
|
+
if (existsSync(path)) {
|
|
1884
|
+
const stats = lstatSync(path);
|
|
1885
|
+
if (stats.isSymbolicLink()) {
|
|
1886
|
+
return resolveSymlink(realpathSync(path), maxDepth - 1);
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
} catch {
|
|
1890
|
+
}
|
|
1891
|
+
return path;
|
|
1892
|
+
}
|
|
1893
|
+
function sanitizeRelativePath(input) {
|
|
1894
|
+
const segments = input.split("/"),out = [];
|
|
1895
|
+
for (const seg of segments) {
|
|
1896
|
+
if (seg === "..") {
|
|
1897
|
+
if (out.length > 0)out.pop();
|
|
1898
|
+
} else if (seg !== "." && seg !== "") {
|
|
1899
|
+
out.push(seg);
|
|
1900
|
+
}
|
|
1901
|
+
}
|
|
1902
|
+
return out.join("/");
|
|
1903
|
+
}
|
|
1904
|
+
function resolveAssetPath(urlPathname,opts) {
|
|
1905
|
+
let assetRelativePath;
|
|
1906
|
+
if (urlPathname.startsWith("/assets/")) {
|
|
1907
|
+
assetRelativePath = sanitizeRelativePath(urlPathname.slice("/assets/".length));
|
|
1908
|
+
} else if (urlPathname.startsWith("/node_modules/")) {
|
|
1909
|
+
assetRelativePath = `node_modules/${urlPathname.slice("/node_modules/".length)}`;
|
|
1910
|
+
} else {
|
|
1911
|
+
return null;
|
|
1912
|
+
}
|
|
1913
|
+
assetRelativePath = assetRelativePath.replace(/@\d+x\./, ".");
|
|
1914
|
+
assetRelativePath = assetRelativePath.replace(/\\/g, "/");
|
|
1915
|
+
const normalizedPath = assetRelativePath.replace(/\//g, sep);
|
|
1916
|
+
let resolved = resolve$1(opts.projectRoot, normalizedPath);
|
|
1917
|
+
if (existsSync(resolved))return resolveSymlink(resolved);
|
|
1918
|
+
for (const nmPath of opts.nodeModulesPaths) {
|
|
1919
|
+
const monorepoRoot = resolve$1(opts.projectRoot, nmPath),candidate = resolve$1(monorepoRoot, "..", normalizedPath);
|
|
1920
|
+
if (existsSync(candidate))return resolveSymlink(candidate);
|
|
1921
|
+
}
|
|
1922
|
+
const nmMatch = normalizedPath.match(/node_modules[/\\](?:\.(?:pnpm|bun)[/\\]([^/\\]+)[/\\]node_modules[/\\])?([^/\\]+)[/\\](.+)$/);
|
|
1923
|
+
if (!nmMatch)return null;
|
|
1924
|
+
const bunPackageDir = nmMatch[1];
|
|
1925
|
+
let packageNameOrPath = nmMatch[2],restPath = nmMatch[3];
|
|
1926
|
+
if (!packageNameOrPath || !restPath)return null;
|
|
1927
|
+
if (packageNameOrPath.startsWith("@")) {
|
|
1928
|
+
const slashIdx = restPath.indexOf(sep);
|
|
1929
|
+
if (slashIdx > 0) {
|
|
1930
|
+
packageNameOrPath = `${packageNameOrPath}/${restPath.slice(0, slashIdx)}`;
|
|
1931
|
+
restPath = restPath.slice(slashIdx + 1);
|
|
1932
|
+
}
|
|
1933
|
+
}
|
|
1934
|
+
if (!bunPackageDir && !packageNameOrPath.includes("@")) {
|
|
1935
|
+
const candidate = resolve$1(opts.projectRoot, "node_modules", packageNameOrPath, restPath);
|
|
1936
|
+
if (existsSync(candidate))return resolveSymlink(candidate);
|
|
1937
|
+
}
|
|
1938
|
+
if (packageNameOrPath.startsWith("@")) {
|
|
1939
|
+
const candidate = resolve$1(opts.projectRoot, "node_modules", packageNameOrPath, restPath);
|
|
1940
|
+
if (existsSync(candidate))return resolveSymlink(candidate);
|
|
1941
|
+
}
|
|
1942
|
+
const pnpmDir = resolve$1(opts.projectRoot, "node_modules", ".pnpm");
|
|
1943
|
+
if (existsSync(pnpmDir)) {
|
|
1944
|
+
try {
|
|
1945
|
+
const entries = readdirSync(pnpmDir),pnpmPkgName = packageNameOrPath.startsWith("@") ? packageNameOrPath.replace("/", "+") : packageNameOrPath;
|
|
1946
|
+
for (const entry of entries) {
|
|
1947
|
+
if (entry.startsWith(`${pnpmPkgName}@`) || entry === pnpmPkgName) {
|
|
1948
|
+
const candidate = resolve$1(pnpmDir, entry, "node_modules", packageNameOrPath, restPath);
|
|
1949
|
+
if (existsSync(candidate))return resolveSymlink(candidate);
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
} catch {
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1955
|
+
const bunDirCandidates = [resolve$1(opts.projectRoot, "node_modules", ".bun"), ...opts.nodeModulesPaths.map((p) => resolve$1(opts.projectRoot, p, ".bun"))];
|
|
1956
|
+
for (const bunDir of bunDirCandidates) {
|
|
1957
|
+
if (!existsSync(bunDir))continue;
|
|
1958
|
+
try {
|
|
1959
|
+
if (bunPackageDir) {
|
|
1960
|
+
const dir = resolveSymlink(resolve$1(bunDir, bunPackageDir)),candidate = resolve$1(dir, "node_modules", packageNameOrPath, restPath);
|
|
1961
|
+
if (existsSync(candidate))return resolveSymlink(candidate);
|
|
1962
|
+
} else {
|
|
1963
|
+
const bunPkgName = packageNameOrPath.startsWith("@") ? packageNameOrPath.replace("/", "+") : packageNameOrPath;
|
|
1964
|
+
for (const entry of readdirSync(bunDir)) {
|
|
1965
|
+
if (entry.startsWith(`${bunPkgName}@`) || entry === bunPkgName) {
|
|
1966
|
+
const dir = resolveSymlink(resolve$1(bunDir, entry)),candidate = resolve$1(dir, "node_modules", packageNameOrPath, restPath);
|
|
1967
|
+
if (existsSync(candidate))return resolveSymlink(candidate);
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
} catch {
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
const nonHoisted = resolve$1(opts.projectRoot, "node_modules", packageNameOrPath, "node_modules", restPath);
|
|
1975
|
+
if (existsSync(nonHoisted))return resolveSymlink(nonHoisted);
|
|
1976
|
+
for (const nmPath of opts.nodeModulesPaths) {
|
|
1977
|
+
const candidate = resolve$1(opts.projectRoot, nmPath, packageNameOrPath, restPath);
|
|
1978
|
+
if (existsSync(candidate))return resolveSymlink(candidate);
|
|
1979
|
+
}
|
|
1980
|
+
if (normalizedPath.startsWith("node_modules")) {
|
|
1981
|
+
try {
|
|
1982
|
+
const modulePath = normalizedPath.replace(/^node_modules[/\\]/, ""),packageName = modulePath.startsWith("@") ? (modulePath.match(/^(@[^/\\]+[/\\][^/\\]+)/)?.[1] ?? modulePath.split(sep)[0]) : modulePath.split(sep)[0];
|
|
1983
|
+
if (!packageName)return null;
|
|
1984
|
+
const packageRelativePath = modulePath.slice(packageName.length + 1);
|
|
1985
|
+
let packageJsonPath;
|
|
1986
|
+
try {
|
|
1987
|
+
packageJsonPath = require.resolve(`${packageName}/package.json`, { paths: [opts.projectRoot, ...opts.nodeModulesPaths] });
|
|
1988
|
+
} catch {
|
|
1989
|
+
const candidates = [resolve$1(opts.projectRoot, "node_modules", packageName, "package.json"), ...opts.nodeModulesPaths.map((p) => resolve$1(opts.projectRoot, p, packageName, "package.json"))],found = candidates.find((c) => existsSync(c));
|
|
1990
|
+
if (!found)return null;
|
|
1991
|
+
packageJsonPath = found;
|
|
1992
|
+
}
|
|
1993
|
+
const candidate = resolve$1(dirname(packageJsonPath), packageRelativePath);
|
|
1994
|
+
if (existsSync(candidate))return resolveSymlink(candidate);
|
|
1995
|
+
} catch {
|
|
1996
|
+
}
|
|
1997
|
+
}
|
|
1998
|
+
return null;
|
|
1999
|
+
}
|
|
2000
|
+
function isWithinRoot(path,root) {
|
|
2001
|
+
if (path === root)return true;
|
|
2002
|
+
return path.startsWith(root + sep);
|
|
2003
|
+
}
|
|
2004
|
+
function isAllowedPath(path,opts) {
|
|
2005
|
+
const normalized = resolve$1(path);
|
|
2006
|
+
if (isWithinRoot(normalized, resolve$1(opts.projectRoot)))return true;
|
|
2007
|
+
return opts.nodeModulesPaths.some((p) => isWithinRoot(normalized, resolve$1(opts.projectRoot, p)));
|
|
2008
|
+
}
|
|
2009
|
+
async function handleAssetRequest(_req,res,url,opts) {
|
|
2010
|
+
try {
|
|
2011
|
+
const resolved = resolveAssetPath(url.pathname, opts);
|
|
2012
|
+
if (!resolved) {
|
|
2013
|
+
sendText(res, 404, "Not Found");
|
|
2014
|
+
return;
|
|
2015
|
+
}
|
|
2016
|
+
if (!isAllowedPath(resolved, opts)) {
|
|
2017
|
+
sendText(res, 403, "Forbidden");
|
|
2018
|
+
return;
|
|
2019
|
+
}
|
|
2020
|
+
if (!existsSync(resolved)) {
|
|
2021
|
+
sendText(res, 404, "Not Found");
|
|
2022
|
+
return;
|
|
2023
|
+
}
|
|
2024
|
+
const ext = extname(resolved).toLowerCase();
|
|
2025
|
+
;
|
|
2026
|
+
const content = await readFile(resolved);
|
|
2027
|
+
res.writeHead(200, { "Content-Type": (CONTENT_TYPE_MAP[ext] ?? "application/octet-stream"), "Cache-Control": "public, max-age=31536000", "Content-Length": content.length });
|
|
2028
|
+
res.end(content);
|
|
2029
|
+
} catch {
|
|
2030
|
+
sendText(res, 500, "Internal Server Error");
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
//#endregion
|
|
2034
|
+
//#region runtime-loader.ts
|
|
2035
|
+
const RUNTIME_PATH = join(dirname$1(fileURLToPath(import.meta.url)), "..", "runtime", "zntc-hmr-client.cjs");
|
|
2036
|
+
const ZNTC_HMR_CLIENT_CODE = (() => {
|
|
2037
|
+
try {
|
|
2038
|
+
return readFileSync(RUNTIME_PATH, "utf-8");
|
|
2039
|
+
} catch {
|
|
2040
|
+
return "module.exports = { setup() {}, enable() {}, disable() {}, registerBundle() {}, log() {} }; module.exports.default = module.exports;";
|
|
2041
|
+
}
|
|
2042
|
+
})(),HMR_CLIENT_SUFFIX = "/Libraries/Utilities/HMRClient.js";
|
|
2043
|
+
//#endregion
|
|
2044
|
+
//#region escape-regex.ts
|
|
2045
|
+
const SPECIAL_CHARS_RE = /[.*+?^${}()|[\]\\]/g;
|
|
2046
|
+
function escapeRegex(s) {
|
|
2047
|
+
return s.replace(SPECIAL_CHARS_RE, "\\$&");
|
|
2048
|
+
}
|
|
2049
|
+
//#endregion
|
|
2050
|
+
//#region internal.ts
|
|
2051
|
+
const requireFromCli = createRequire$1(import.meta.url);
|
|
2052
|
+
function getErrorMessage(err,max=100) {
|
|
2053
|
+
const e = err;
|
|
2054
|
+
if (typeof e?.message == "string")return e.message.slice(0, max);
|
|
2055
|
+
return String(err).slice(0, max);
|
|
2056
|
+
}
|
|
2057
|
+
function normalizeExt(ext) {
|
|
2058
|
+
return ext.startsWith(".") ? ext : `.${ext}`;
|
|
2059
|
+
}
|
|
2060
|
+
//#endregion
|
|
2061
|
+
//#region asset.ts
|
|
2062
|
+
function svgComponentName(filePath) {
|
|
2063
|
+
const pascal = basename(filePath, extname$1(filePath)).split(/[^A-Za-z0-9_$]+/).filter(Boolean).map((part) => part[0].toUpperCase() + part.slice(1)).join("");
|
|
2064
|
+
return pascal ? `Svg${pascal}` : "SvgComponent";
|
|
2065
|
+
}
|
|
2066
|
+
function createSvgComponentModule(svg,filePath) {
|
|
2067
|
+
const componentName = svgComponentName(filePath);
|
|
2068
|
+
return [`import * as React from 'react';`, `import { SvgXml } from 'react-native-svg';`, ``, `const xml = ${JSON.stringify(svg)};`, ``, `function ${componentName}(props) {`, ` return React.createElement(SvgXml, Object.assign({ xml }, props));`, `}`, ``, `${componentName}.displayName = ${JSON.stringify(componentName)};`, ``, `export default ${componentName};`, ``].join("\n");
|
|
2069
|
+
}
|
|
2070
|
+
function createAssetPlugin(config) {
|
|
2071
|
+
return { name: "zntc:react-native:runtime", setup(build) {
|
|
2072
|
+
const hmrClientPattern = new RegExp(`${escapeRegex(HMR_CLIENT_SUFFIX)}$`);
|
|
2073
|
+
build.onLoad({ filter: hmrClientPattern }, () => ({ contents: ZNTC_HMR_CLIENT_CODE }));
|
|
2074
|
+
const hasSvgSource = config.sourceExts.some((e) => normalizeExt(e).toLowerCase() === ".svg");
|
|
2075
|
+
if (hasSvgSource) {
|
|
2076
|
+
build.onLoad({ filter: /\.svg$/i }, (args) => ({ contents: createSvgComponentModule(readFileSync$1(args.path, "utf8"), args.path) }));
|
|
2077
|
+
}
|
|
2078
|
+
if (config.babelTransformerPath) {
|
|
2079
|
+
let customTransformer = null;
|
|
2080
|
+
const transformerPath = config.babelTransformerPath,dev = config.dev ?? true,customExts = config.sourceExts.map((e) => normalizeExt(e).slice(1)).filter((e) => !/^(tsx?|jsx?|mjs|cjs|json|svg)$/.test(e)).join("|");
|
|
2081
|
+
if (customExts) {
|
|
2082
|
+
const customExtPattern = new RegExp(`\\.(${customExts})$`);
|
|
2083
|
+
build.onLoad({ filter: customExtPattern }, async (args) => {
|
|
2084
|
+
try {
|
|
2085
|
+
if (!customTransformer) {
|
|
2086
|
+
customTransformer = requireFromCli(requireFromCli.resolve(transformerPath, { paths: [config.projectRoot] }));
|
|
2087
|
+
}
|
|
2088
|
+
const src = readFileSync$1(args.path, "utf8"),result = await customTransformer.transform({ src, filename: args.path, options: { platform: config.rnPlatform, dev, hot: dev, projectRoot: config.projectRoot } });
|
|
2089
|
+
if (result?.code)return { contents: result.code };
|
|
2090
|
+
if (result?.ast) {
|
|
2091
|
+
throw new Error(`${transformerPath} returned a Babel AST for ${args.path}. ZNTC custom source transformers must return code; use a ZNTC native transformer for this extension.`);
|
|
2092
|
+
}
|
|
2093
|
+
} catch (err) {
|
|
2094
|
+
process.stderr.write(`[zntc:transformer] ${args.path.split("/").pop()}: ${getErrorMessage(err)}\n`);
|
|
2095
|
+
throw err;
|
|
2096
|
+
}
|
|
2097
|
+
return null;
|
|
2098
|
+
});
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
} };
|
|
2102
|
+
}
|
|
2103
|
+
//#endregion
|
|
2104
|
+
//#region metro-resolve-request.ts
|
|
2105
|
+
const DELEGATE_TO_DEFAULT_SENTINEL = "__ZNTC_RN_DELEGATE_TO_DEFAULT__",nodeRequire = createRequire$2(import.meta.url);
|
|
2106
|
+
function resolveFallbackRequest(moduleName,originModulePath) {
|
|
2107
|
+
if (isAbsolute(moduleName))return moduleName;
|
|
2108
|
+
const baseDir = originModulePath ? dirname$2(originModulePath) : process.cwd();
|
|
2109
|
+
if (moduleName.startsWith("."))return resolve$2(baseDir, moduleName);
|
|
2110
|
+
return nodeRequire.resolve(moduleName, { paths: [baseDir] });
|
|
2111
|
+
}
|
|
2112
|
+
function createMetroResolveRequestPlugin(opts) {
|
|
2113
|
+
const { resolveRequest:resolveRequest, platform:platform } = opts,metroPlatform = platform === "web" ? null : platform;
|
|
2114
|
+
return { name: "zntc:react-native:metro-resolve-request", setup(build) {
|
|
2115
|
+
build.onResolve({ filter: /.*/ }, (args) => {
|
|
2116
|
+
const fallbackResolver = (_context, moduleName) => {
|
|
2117
|
+
if (moduleName !== args.path) {
|
|
2118
|
+
return { type: "sourceFile", filePath: resolveFallbackRequest(moduleName, args.importer ?? "") };
|
|
2119
|
+
}
|
|
2120
|
+
throw new Error(DELEGATE_TO_DEFAULT_SENTINEL);
|
|
2121
|
+
};
|
|
2122
|
+
try {
|
|
2123
|
+
const result = resolveRequest({ originModulePath: args.importer ?? "", platform: metroPlatform, resolveRequest: fallbackResolver }, args.path, metroPlatform);
|
|
2124
|
+
if (result.type === "sourceFile")return { path: result.filePath };
|
|
2125
|
+
if (result.type === "assetFiles")return { path: result.filePaths[0] ?? args.path };
|
|
2126
|
+
if (result.type === "empty")return { disabled: true };
|
|
2127
|
+
} catch (err) {
|
|
2128
|
+
if (err.message === DELEGATE_TO_DEFAULT_SENTINEL)return null;
|
|
2129
|
+
throw err;
|
|
2130
|
+
}
|
|
2131
|
+
return null;
|
|
2132
|
+
});
|
|
2133
|
+
} };
|
|
2134
|
+
}
|
|
2135
|
+
//#endregion
|
|
2136
|
+
//#region require-context.ts
|
|
2137
|
+
function createRequireContextPlugin() {
|
|
2138
|
+
return { name: "zntc:react-native:require-context", setup(build) {
|
|
2139
|
+
build.onResolveContext({ filter: /.*/ }, (args) => {
|
|
2140
|
+
const { dir:dir, recursive:recursive, filter:filter, flags:flags, importer:importer } = args,absDir = resolve$3(dirname$3(importer), dir);
|
|
2141
|
+
let entries;
|
|
2142
|
+
try {
|
|
2143
|
+
if (recursive) {
|
|
2144
|
+
entries = readdirSync$1(absDir, { recursive: true, withFileTypes: true }).filter((d) => d.isFile()).map((d) => {
|
|
2145
|
+
const parent = d.parentPath ?? absDir;
|
|
2146
|
+
return relative(absDir, join$1(parent, d.name));
|
|
2147
|
+
});
|
|
2148
|
+
} else {
|
|
2149
|
+
entries = readdirSync$1(absDir, { withFileTypes: true }).filter((d) => d.isFile()).map((d) => d.name);
|
|
2150
|
+
}
|
|
2151
|
+
} catch {
|
|
2152
|
+
return { context: [] };
|
|
2153
|
+
}
|
|
2154
|
+
const re = filter ? new RegExp(filter, flags ?? "") : /^\.\/.*$/,matched = entries.map((f) => `./${f.replace(/\\/g, "/")}`).filter((p) => re.test(p)).sort();
|
|
2155
|
+
return { context: matched };
|
|
2156
|
+
});
|
|
2157
|
+
} };
|
|
2158
|
+
}
|
|
2159
|
+
//#endregion
|
|
2160
|
+
//#region rn-constants.ts
|
|
2161
|
+
const requireFromCli$1 = createRequire$3(import.meta.url);
|
|
2162
|
+
function tryResolve(specifier,fromDir) {
|
|
2163
|
+
try {
|
|
2164
|
+
return requireFromCli$1.resolve(specifier, { paths: [fromDir] });
|
|
2165
|
+
} catch {
|
|
2166
|
+
return null;
|
|
2167
|
+
}
|
|
2168
|
+
}
|
|
2169
|
+
function resolveRnPolyfills(projectRoot) {
|
|
2170
|
+
;
|
|
2171
|
+
for (const candidate of ["react-native/rn-get-polyfills", "@react-native/js-polyfills"]) {
|
|
2172
|
+
const resolved = tryResolve(candidate, projectRoot);
|
|
2173
|
+
if (resolved) {
|
|
2174
|
+
try {
|
|
2175
|
+
return requireFromCli$1(resolved)();
|
|
2176
|
+
} catch {
|
|
2177
|
+
continue;
|
|
2178
|
+
}
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
2181
|
+
console.warn("[zntc] Could not resolve RN polyfills, skipping");
|
|
2182
|
+
return [];
|
|
2183
|
+
}
|
|
2184
|
+
const RN_SINGLETON_PACKAGES = ["react", "react-native", "react-native-safe-area-context"],RN_GLOBAL_IDENTIFIERS = ["Promise", "regeneratorRuntime", "XMLHttpRequest", "FormData", "fetch", "Headers", "Request", "Response", "WebSocket", "Blob", "File", "FileReader", "URL", "URLSearchParams", "AbortController", "AbortSignal", "queueMicrotask", "setImmediate", "clearImmediate", "requestIdleCallback", "cancelIdleCallback", "setTimeout", "clearTimeout", "setInterval", "clearInterval", "requestAnimationFrame", "cancelAnimationFrame", "DOMRect", "DOMRectReadOnly", "DOMRectList", "HTMLCollection", "NodeList", "Node", "Document", "CharacterData", "Text", "Element", "HTMLElement", "IntersectionObserver", "MutationObserver", "MutationRecord", "EventCounts", "Performance", "PerformanceEntry", "PerformanceEventTiming", "PerformanceLongTaskTiming", "PerformanceMark", "PerformanceMeasure", "PerformanceObserver", "PerformanceObserverEntryList", "PerformanceResourceTiming", "TaskAttributionTiming"];
|
|
2185
|
+
//#endregion
|
|
2186
|
+
//#region preset.ts
|
|
2187
|
+
const DEFAULT_SOURCE_EXTS = [".js", ".jsx", ".json", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
2188
|
+
const DEFAULT_ASSET_EXTS = [".bmp", ".gif", ".jpg", ".jpeg", ".png", ".psd", ".svg", ".webp", ".tiff", ".tif", ".xml", ".avif", ".ico", ".m4v", ".mov", ".mp4", ".mpeg", ".mpg", ".webm", ".aac", ".aiff", ".caf", ".m4a", ".mp3", ".wav", ".html", ".pdf", ".yaml", ".yml", ".otf", ".ttf", ".woff", ".woff2"];
|
|
2189
|
+
function buildResolveExtensions(rnPlatform,sourceExts) {
|
|
2190
|
+
const platformPrefix = `.${rnPlatform}`,extensions = [],seen = new Set();
|
|
2191
|
+
for (const sourceExt of sourceExts) {
|
|
2192
|
+
const ext = normalizeExt(sourceExt);
|
|
2193
|
+
for (const candidate of [`${platformPrefix}${ext}`, `.native${ext}`, ext]) {
|
|
2194
|
+
if (!seen.has(candidate)) {
|
|
2195
|
+
seen.add(candidate);
|
|
2196
|
+
extensions.push(candidate);
|
|
2197
|
+
}
|
|
2198
|
+
}
|
|
2199
|
+
}
|
|
2200
|
+
return extensions;
|
|
2201
|
+
}
|
|
2202
|
+
function buildAssetLoaders(assetExts) {
|
|
2203
|
+
const loaders = {};
|
|
2204
|
+
for (const ext of assetExts) {
|
|
2205
|
+
loaders[normalizeExt(ext)] = "file";
|
|
2206
|
+
}
|
|
2207
|
+
return loaders;
|
|
2208
|
+
}
|
|
2209
|
+
function tryResolvePackageRoot(packageName,projectRoot) {
|
|
2210
|
+
const logicalRoot = resolve$4(projectRoot, "node_modules", packageName);
|
|
2211
|
+
if (existsSync$1(resolve$4(logicalRoot, "package.json")))return logicalRoot;
|
|
2212
|
+
const pkgJson = tryResolve(`${packageName}/package.json`, projectRoot);
|
|
2213
|
+
return pkgJson ? dirname$4(pkgJson) : null;
|
|
2214
|
+
}
|
|
2215
|
+
function tryResolvePackageFile(packageName,relativePath,projectRoot) {
|
|
2216
|
+
const packageRoot = tryResolvePackageRoot(packageName, projectRoot);
|
|
2217
|
+
if (packageRoot) {
|
|
2218
|
+
const file = resolve$4(packageRoot, relativePath);
|
|
2219
|
+
if (existsSync$1(file))return file;
|
|
2220
|
+
}
|
|
2221
|
+
return tryResolve(`${packageName}/${relativePath}`, projectRoot);
|
|
2222
|
+
}
|
|
2223
|
+
function buildRnSingletonAliases(projectRoot) {
|
|
2224
|
+
const aliases = {};
|
|
2225
|
+
for (const packageName of RN_SINGLETON_PACKAGES) {
|
|
2226
|
+
const packageRoot = tryResolvePackageRoot(packageName, projectRoot);
|
|
2227
|
+
if (packageRoot)aliases[packageName] = packageRoot;
|
|
2228
|
+
}
|
|
2229
|
+
return aliases;
|
|
2230
|
+
}
|
|
2231
|
+
const PRELUDE_RESERVED = new Set(["__BUNDLE_START_TIME__", "__DEV__", "__ZNTC_RN_GLOBAL__", "global", "process"]),RN_GLOBAL_EXPR = "(function(g,t,w,s){return g&&(typeof g==='object'||typeof g==='function')?g:t&&(typeof t==='object'||typeof t==='function')?t:w&&(typeof w==='object'||typeof w==='function')?w:s;})(typeof global!=='undefined'?global:void 0,typeof globalThis!=='undefined'?globalThis:void 0,typeof window!=='undefined'?window:void 0,this)";
|
|
2232
|
+
function formatExtraVars(extraVars) {
|
|
2233
|
+
const out = [];
|
|
2234
|
+
for (const [key, value] of Object.entries(extraVars)) {
|
|
2235
|
+
if (PRELUDE_RESERVED.has(key))continue;
|
|
2236
|
+
out.push(`var ${key}=${JSON.stringify(value)};`);
|
|
2237
|
+
}
|
|
2238
|
+
return out.join("");
|
|
2239
|
+
}
|
|
2240
|
+
function buildPrelude(input) {
|
|
2241
|
+
const { dev:dev, bannerExtras:bannerExtras, extra:extra } = input,lines = [`var __BUNDLE_START_TIME__=this.nativePerformanceNow?nativePerformanceNow():Date.now();`, `var __DEV__=${dev};`, `var __ZNTC_RN_GLOBAL__=${RN_GLOBAL_EXPR};`, `if(typeof global==='undefined')global=__ZNTC_RN_GLOBAL__;`, `if(typeof __ZNTC_RN_GLOBAL__.hasOwnProperty!=='function')try{Object.defineProperty(__ZNTC_RN_GLOBAL__,'hasOwnProperty',{value:Object.prototype.hasOwnProperty,configurable:true,writable:true});}catch(_e){try{__ZNTC_RN_GLOBAL__.hasOwnProperty=Object.prototype.hasOwnProperty;}catch(_e2){}}`, `var process=__ZNTC_RN_GLOBAL__.process||{};process.env=process.env||{};process.env.NODE_ENV=process.env.NODE_ENV||"${dev ? "development" : "production"}";`];
|
|
2242
|
+
if (extra?.extraVars && Object.keys(extra.extraVars).length > 0) {
|
|
2243
|
+
const formatted = formatExtraVars(extra.extraVars);
|
|
2244
|
+
if (formatted)lines.push(formatted);
|
|
2245
|
+
}
|
|
2246
|
+
if (bannerExtras)lines.push(bannerExtras);
|
|
2247
|
+
return lines.join("");
|
|
2248
|
+
}
|
|
2249
|
+
function buildFooter(dev) {
|
|
2250
|
+
const parts = [`(function(g){g.__ZNTC_RN_BUNDLER__=true;})(${RN_GLOBAL_EXPR});`];
|
|
2251
|
+
if (dev) {
|
|
2252
|
+
parts.push(`setTimeout(function(){try{NativeModules.DevLoadingView.hide()}catch(e){}},0);`);
|
|
2253
|
+
}
|
|
2254
|
+
return parts.join("");
|
|
2255
|
+
}
|
|
2256
|
+
function resolveWorkletPluginVersion(projectRoot,override) {
|
|
2257
|
+
if (override)return override;
|
|
2258
|
+
try {
|
|
2259
|
+
const pkgPath = requireFromCli.resolve("react-native-worklets/package.json", { paths: [projectRoot] }),pkg = requireFromCli(pkgPath);
|
|
2260
|
+
return pkg.version;
|
|
2261
|
+
} catch {
|
|
2262
|
+
return undefined;
|
|
2263
|
+
}
|
|
2264
|
+
}
|
|
2265
|
+
function deepMerge(base,override) {
|
|
2266
|
+
const result = { ...base };
|
|
2267
|
+
for (const [key, value] of Object.entries(override)) {
|
|
2268
|
+
if (value === undefined)continue;
|
|
2269
|
+
const existing = result[key];
|
|
2270
|
+
if (existing && typeof existing == "object" && !Array.isArray(existing) && value && typeof value == "object" && !Array.isArray(value)) {
|
|
2271
|
+
result[key] = deepMerge(existing, value);
|
|
2272
|
+
} else {
|
|
2273
|
+
result[key] = value;
|
|
2274
|
+
}
|
|
2275
|
+
}
|
|
2276
|
+
return result;
|
|
2277
|
+
}
|
|
2278
|
+
function buildRnBundleOptions(input) {
|
|
2279
|
+
const { entry:entry, projectRoot:projectRoot, rnPlatform:rnPlatform, dev:dev, sourcemap:sourcemap, minify:minify, dropConsole:dropConsole, dropDebugger:dropDebugger, extra:extra } = input;
|
|
2280
|
+
if (extra?.platforms && !extra.platforms.includes(rnPlatform)) {
|
|
2281
|
+
throw new Error(`extra.platforms (${JSON.stringify(extra.platforms)}) does not include the active rnPlatform '${rnPlatform}'`);
|
|
2282
|
+
}
|
|
2283
|
+
const sourceExts = extra?.sourceExts ?? DEFAULT_SOURCE_EXTS,assetExts = extra?.assetExts ?? DEFAULT_ASSET_EXTS,plugins = [];
|
|
2284
|
+
if (extra?.metroResolveRequest) {
|
|
2285
|
+
const opts = { resolveRequest: extra.metroResolveRequest, platform: rnPlatform };
|
|
2286
|
+
plugins.push(createMetroResolveRequestPlugin(opts));
|
|
2287
|
+
}
|
|
2288
|
+
plugins.push(createAssetPlugin({ projectRoot, assetExts, rnPlatform, dev, sourceExts, babelTransformerPath: extra?.babelTransformerPath }));
|
|
2289
|
+
plugins.push(createRequireContextPlugin());
|
|
2290
|
+
if (extra?.additionalPlugins) {
|
|
2291
|
+
plugins.push(...extra.additionalPlugins);
|
|
2292
|
+
}
|
|
2293
|
+
const polyfills = [...resolveRnPolyfills(projectRoot)];
|
|
2294
|
+
if (extra?.polyfills && extra.polyfills.length > 0) {
|
|
2295
|
+
for (const p of extra.polyfills)polyfills.push(resolve$4(projectRoot, p));
|
|
2296
|
+
}
|
|
2297
|
+
const runBeforeMain = [],initCore = tryResolvePackageFile("react-native", "Libraries/Core/InitializeCore.js", projectRoot);
|
|
2298
|
+
if (initCore)runBeforeMain.push(initCore);
|
|
2299
|
+
if (extra?.prelude && extra.prelude.length > 0) {
|
|
2300
|
+
for (const p of extra.prelude)runBeforeMain.push(resolve$4(projectRoot, p));
|
|
2301
|
+
}
|
|
2302
|
+
const define = { global: "__ZNTC_RN_GLOBAL__", __DEV__: String(dev), "process.env.NODE_ENV": `"${dev ? "development" : "production"}"`, "process.env.EXPO_ROUTER_APP_ROOT": JSON.stringify(resolve$4(projectRoot, "app")), "process.env.EXPO_ROUTER_IMPORT_MODE": "\"sync\"", "process.env.EXPO_OS": `"${rnPlatform}"` },baseLoader = buildAssetLoaders(assetExts),preset = { entryPoints: [resolve$4(projectRoot, entry)], platform: "react-native", sourcemap: sourcemap ?? dev, minify: minify ?? false, dropConsole: dropConsole ?? false, dropDebugger: dropDebugger ?? false, plugins, emitDiskSourcemap: !dev, target: "es5", flow: true, jsxInJs: true, configurableExports: true, strictExecutionOrder: true, inlineDynamicImports: true, workletTransform: true, codegenTransform: true, resolveExtensions: buildResolveExtensions(rnPlatform, sourceExts), mainFields: ["react-native", "browser", "main"], loader: baseLoader, alias: buildRnSingletonAliases(projectRoot), preserveSymlinks: true, resolveSymlinkSiblings: true, define, banner: buildPrelude(input), globalIdentifiers: [...RN_GLOBAL_IDENTIFIERS] };
|
|
2303
|
+
if (polyfills.length > 0)preset.polyfills = polyfills;
|
|
2304
|
+
if (runBeforeMain.length > 0)preset.runBeforeMain = runBeforeMain;
|
|
2305
|
+
const workletVersion = resolveWorkletPluginVersion(projectRoot, input.workletPluginVersion);
|
|
2306
|
+
if (workletVersion)preset.workletPluginVersion = workletVersion;
|
|
2307
|
+
preset.footer = buildFooter(dev);
|
|
2308
|
+
preset.jsx = dev ? "automatic-dev" : "automatic";
|
|
2309
|
+
if (dev) {
|
|
2310
|
+
preset.devMode = true;
|
|
2311
|
+
preset.reactRefresh = true;
|
|
2312
|
+
preset.collectModuleCodes = true;
|
|
2313
|
+
} else if (minify !== true) {
|
|
2314
|
+
preset.minifySyntax = true;
|
|
2315
|
+
}
|
|
2316
|
+
if (extra?.watchFolders && extra.watchFolders.length > 0) {
|
|
2317
|
+
preset.watchFolders = extra.watchFolders.map((p) => resolve$4(projectRoot, p));
|
|
2318
|
+
}
|
|
2319
|
+
if (extra?.nodeModulesPaths && extra.nodeModulesPaths.length > 0) {
|
|
2320
|
+
preset.nodePaths = extra.nodeModulesPaths.map((p) => resolve$4(projectRoot, p));
|
|
2321
|
+
}
|
|
2322
|
+
if (extra?.blockList && extra.blockList.length > 0) {
|
|
2323
|
+
preset.blockList = extra.blockList;
|
|
2324
|
+
}
|
|
2325
|
+
if (extra?.fallback && Object.keys(extra.fallback).length > 0) {
|
|
2326
|
+
preset.fallback = { ...extra.fallback };
|
|
2327
|
+
}
|
|
2328
|
+
if (extra?.inlineSourceMap === true) {
|
|
2329
|
+
preset.sourcemapMode = "inline";
|
|
2330
|
+
}
|
|
2331
|
+
if (extra?.sourceRoot) {
|
|
2332
|
+
preset.sourceRoot = extra.sourceRoot;
|
|
2333
|
+
}
|
|
2334
|
+
if (extra?.silentConsoleErrorPatterns && extra.silentConsoleErrorPatterns.length > 0) {
|
|
2335
|
+
preset.silentConsoleErrorPatterns = [...extra.silentConsoleErrorPatterns];
|
|
2336
|
+
}
|
|
2337
|
+
if (extra?.disableHierarchicalLookup === true) {
|
|
2338
|
+
preset.disableHierarchicalLookup = true;
|
|
2339
|
+
}
|
|
2340
|
+
if (input.override) {
|
|
2341
|
+
return deepMerge(preset, input.override);
|
|
2342
|
+
}
|
|
2343
|
+
return preset;
|
|
2344
|
+
}
|
|
2345
|
+
async function bundleRn(input) {
|
|
2346
|
+
init();
|
|
2347
|
+
return build(buildRnBundleOptions(input));
|
|
2348
|
+
}
|
|
2349
|
+
function watchRn(input) {
|
|
2350
|
+
init();
|
|
2351
|
+
const opts = buildRnBundleOptions(input);
|
|
2352
|
+
opts.outfile = input.outfile;
|
|
2353
|
+
opts.write = true;
|
|
2354
|
+
if (input.onReady)opts.onReady = input.onReady;
|
|
2355
|
+
if (input.onRebuild)opts.onRebuild = input.onRebuild;
|
|
2356
|
+
return watch(opts);
|
|
2357
|
+
}
|
|
2358
|
+
//#endregion
|
|
2359
|
+
//#region sourcemap.ts
|
|
2360
|
+
function stripVirtualPrefix(src) {
|
|
2361
|
+
return src.replace(/^[\u0000-\u0020]+/, "");
|
|
2362
|
+
}
|
|
2363
|
+
function isVirtualSource(stripped) {
|
|
2364
|
+
return /^[a-z][a-z0-9+.-]*:/i.test(stripped);
|
|
2365
|
+
}
|
|
2366
|
+
function isFrameworkSource(src) {
|
|
2367
|
+
if (typeof src != "string")return false;
|
|
2368
|
+
const stripped = stripVirtualPrefix(src);
|
|
2369
|
+
return (stripped === "__prelude__" || stripped.includes("?ctx=") || /(?:^|[/\\])node_modules[/\\]/.test(stripped) || stripped.startsWith("zntc:"));
|
|
2370
|
+
}
|
|
2371
|
+
function postProcessSourceMap(rawJson,pathOpts) {
|
|
2372
|
+
try {
|
|
2373
|
+
const map = JSON.parse(rawJson);
|
|
2374
|
+
if (map.version !== 3 || !map.sources)return rawJson;
|
|
2375
|
+
delete map.file;
|
|
2376
|
+
if (pathOpts?.sourceRoot === undefined && map.sourceRoot === "") {
|
|
2377
|
+
delete map.sourceRoot;
|
|
2378
|
+
}
|
|
2379
|
+
const existing = new Set([...(Array.isArray(map.x_google_ignoreList) ? map.x_google_ignoreList : []), ...(Array.isArray(map.ignoreList) ? map.ignoreList : [])].filter((v) => Number.isInteger(v) && v >= 0));
|
|
2380
|
+
for (let i = 0; i < map.sources.length; i++) {
|
|
2381
|
+
if (isFrameworkSource(map.sources[i]))existing.add(i);
|
|
2382
|
+
}
|
|
2383
|
+
if (existing.size > 0) {
|
|
2384
|
+
const ignoreList = [...existing].sort((a, b) => a - b);
|
|
2385
|
+
map.x_google_ignoreList = ignoreList;
|
|
2386
|
+
} else {
|
|
2387
|
+
delete map.x_google_ignoreList;
|
|
2388
|
+
}
|
|
2389
|
+
delete map.ignoreList;
|
|
2390
|
+
if (pathOpts) {
|
|
2391
|
+
if (pathOpts.sourceRoot !== undefined) {
|
|
2392
|
+
map.sourceRoot = pathOpts.sourceRoot;
|
|
2393
|
+
}
|
|
2394
|
+
if (pathOpts.useAbsolutePath && Array.isArray(map.sources)) {
|
|
2395
|
+
const projectRoot = pathOpts.projectRoot ?? process.cwd();
|
|
2396
|
+
map.sources = map.sources.map((s) => {
|
|
2397
|
+
if (typeof s != "string")return s;
|
|
2398
|
+
const stripped = stripVirtualPrefix(s);
|
|
2399
|
+
if (isVirtualSource(stripped) || isAbsolute$1(stripped))return s;
|
|
2400
|
+
return resolve$5(projectRoot, s);
|
|
2401
|
+
});
|
|
2402
|
+
}
|
|
2403
|
+
}
|
|
2404
|
+
return JSON.stringify(map);
|
|
2405
|
+
} catch {
|
|
2406
|
+
return rawJson;
|
|
2407
|
+
}
|
|
2408
|
+
}
|
|
2409
|
+
//#endregion
|
|
2410
|
+
//#region platform-state.ts
|
|
2411
|
+
const SOURCE_MAPPING_URL_RE = /\/\/# sourceMappingURL=[^\n]*/g;
|
|
2412
|
+
function getCachedSourceMap(state) {
|
|
2413
|
+
if (state.sourceMapCache)return state.sourceMapCache;
|
|
2414
|
+
const raw = state.handle.getBundleSourceMap();
|
|
2415
|
+
if (process.env.ZNTC_DEBUG_TERMINAL === "1") {
|
|
2416
|
+
process.stderr.write(`[zntc:rn-dev:debug] getBundleSourceMap[${state.platform}]: ${raw ? `len=${raw.length}` : "null"}\n`);
|
|
2417
|
+
}
|
|
2418
|
+
if (!raw)return null;
|
|
2419
|
+
state.sourceMapCache = postProcessSourceMap(raw);
|
|
2420
|
+
return state.sourceMapCache;
|
|
2421
|
+
}
|
|
2422
|
+
function getBundleText(result) {
|
|
2423
|
+
const jsFile = result.outputFiles.find((file) => file.path.endsWith(".js")) ?? result.outputFiles[0];
|
|
2424
|
+
if (!jsFile)throw new Error("Build produced no output");
|
|
2425
|
+
return jsFile.text.replace(SOURCE_MAPPING_URL_RE, "");
|
|
2426
|
+
}
|
|
2427
|
+
function getBundleSourceMapText(result) {
|
|
2428
|
+
return result.outputFiles.find((file) => file.path.endsWith(".map"))?.text ?? null;
|
|
2429
|
+
}
|
|
2430
|
+
function createPlatformState(options,platform,callbacks) {
|
|
2431
|
+
const outputDir = mkdtempSync(join$2(tmpdir(), `zntc-rn-${platform}-`)),outputPath = join$2(outputDir, "bundle.js"),platformBundle = { ...options.bundle, rnPlatform: platform };
|
|
2432
|
+
let refreshPromise = null;
|
|
2433
|
+
const state = { platform, outputDir, outputPath, handle: undefined, bundle: null, bundleStale: false, refreshBundle: () => refreshPlatformBundle(), sourceMapCache: null, buildError: null, fileCount: 1, lastRebuildTime: Date.now() };
|
|
2434
|
+
function refreshPlatformBundle() {
|
|
2435
|
+
if (!state.bundleStale && state.bundle !== null)return Promise.resolve();
|
|
2436
|
+
if (refreshPromise)return refreshPromise;
|
|
2437
|
+
refreshPromise = bundleRn(platformBundle).then((result) => {
|
|
2438
|
+
state.bundle = getBundleText(result);
|
|
2439
|
+
const sourceMap = getBundleSourceMapText(result);
|
|
2440
|
+
state.sourceMapCache = sourceMap ? postProcessSourceMap(sourceMap) : null;
|
|
2441
|
+
state.buildError = null;
|
|
2442
|
+
state.bundleStale = false;
|
|
2443
|
+
}).catch((err) => {
|
|
2444
|
+
state.bundle = null;
|
|
2445
|
+
state.buildError = err instanceof Error ? err.message : String(err);
|
|
2446
|
+
state.bundleStale = false;
|
|
2447
|
+
}).finally(() => {
|
|
2448
|
+
refreshPromise = null;
|
|
2449
|
+
});
|
|
2450
|
+
return refreshPromise;
|
|
2451
|
+
}
|
|
2452
|
+
if (process.env.ZNTC_DEBUG_TERMINAL === "1") {
|
|
2453
|
+
process.stderr.write(`[zntc:rn-dev:debug] watchRn[${platform}] sourcemap=${platformBundle.sourcemap} dev=${platformBundle.dev} outfile=${outputPath}\n`);
|
|
2454
|
+
}
|
|
2455
|
+
state.handle = watchRn({ ...platformBundle, outfile: outputPath, onReady(event) {
|
|
2456
|
+
if (event.files)state.fileCount = event.files;
|
|
2457
|
+
if (existsSync$2(outputPath)) {
|
|
2458
|
+
state.bundle = readFileSync$2(outputPath, "utf-8").replace(SOURCE_MAPPING_URL_RE, "");
|
|
2459
|
+
state.bundleStale = false;
|
|
2460
|
+
} else {
|
|
2461
|
+
state.buildError = "Build produced no output";
|
|
2462
|
+
}
|
|
2463
|
+
callbacks?.onReady?.(state, event);
|
|
2464
|
+
}, onRebuild(event) {
|
|
2465
|
+
state.lastRebuildTime = Date.now();
|
|
2466
|
+
if (!event.success) {
|
|
2467
|
+
state.buildError = event.error ?? "Unknown build error";
|
|
2468
|
+
callbacks?.onRebuild?.(state, event);
|
|
2469
|
+
return;
|
|
2470
|
+
}
|
|
2471
|
+
state.buildError = null;
|
|
2472
|
+
state.sourceMapCache = null;
|
|
2473
|
+
if (platformBundle.dev) {
|
|
2474
|
+
if (event.graphChanged) {
|
|
2475
|
+
state.bundleStale = true;
|
|
2476
|
+
return state.refreshBundle().then(() => {
|
|
2477
|
+
if (state.buildError) {
|
|
2478
|
+
callbacks?.onRebuild?.(state, { ...event, success: false, error: state.buildError });
|
|
2479
|
+
return;
|
|
2480
|
+
}
|
|
2481
|
+
callbacks?.onRebuild?.(state, event);
|
|
2482
|
+
});
|
|
2483
|
+
}
|
|
2484
|
+
if (event.updates && event.updates.length > 0) {
|
|
2485
|
+
state.bundleStale = true;
|
|
2486
|
+
}
|
|
2487
|
+
callbacks?.onRebuild?.(state, event);
|
|
2488
|
+
return;
|
|
2489
|
+
}
|
|
2490
|
+
if (existsSync$2(outputPath)) {
|
|
2491
|
+
state.bundle = readFileSync$2(outputPath, "utf-8").replace(SOURCE_MAPPING_URL_RE, "");
|
|
2492
|
+
state.bundleStale = false;
|
|
2493
|
+
}
|
|
2494
|
+
callbacks?.onRebuild?.(state, event);
|
|
2495
|
+
} });
|
|
2496
|
+
return state;
|
|
2497
|
+
}
|
|
2498
|
+
function waitForBuild(state,pollIntervalMs=50) {
|
|
2499
|
+
return new Promise((resolve) => {
|
|
2500
|
+
const check = () => {
|
|
2501
|
+
if (state.bundle !== null || state.buildError !== null)resolve(); else setTimeout(check, pollIntervalMs);
|
|
2502
|
+
};
|
|
2503
|
+
check();
|
|
2504
|
+
});
|
|
2505
|
+
}
|
|
2506
|
+
function createPlatformStateRegistry(options,callbacks) {
|
|
2507
|
+
const platforms = new Map();
|
|
2508
|
+
return { platforms, getOrCreate(platform) {
|
|
2509
|
+
let state = platforms.get(platform);
|
|
2510
|
+
if (state)return state;
|
|
2511
|
+
state = createPlatformState(options, platform, callbacks);
|
|
2512
|
+
platforms.set(platform, state);
|
|
2513
|
+
return state;
|
|
2514
|
+
}, async stopAll() {
|
|
2515
|
+
const handles = [...platforms.values()];
|
|
2516
|
+
platforms.clear();
|
|
2517
|
+
for (const s of handles) {
|
|
2518
|
+
try {
|
|
2519
|
+
s.handle.stop();
|
|
2520
|
+
} catch {
|
|
2521
|
+
}
|
|
2522
|
+
}
|
|
2523
|
+
} };
|
|
2524
|
+
}
|
|
2525
|
+
//#endregion
|
|
2526
|
+
//#region _shared.ts
|
|
2527
|
+
function resolvePlatform(url,registry,defaultPlatform) {
|
|
2528
|
+
const param = url.searchParams.get("platform");
|
|
2529
|
+
;
|
|
2530
|
+
return registry.getOrCreate((param === "ios" || param === "android" ? param : defaultPlatform));
|
|
2531
|
+
}
|
|
2532
|
+
//#endregion
|
|
2533
|
+
//#region bundle.ts
|
|
2534
|
+
var jscSafeUrl = __toESM(require_jsc_safe_url_index());
|
|
2535
|
+
const HMR_MAP_PREFIX = "/__zntc_hmr_map/",MULTIPART_BOUNDARY = "3beqjf3apnqeu3h5jqorms4i",CRLF = "\r\n",METRO_NO_STORE_HEADERS = { "Surrogate-Control": "no-store", "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate", Pragma: "no-cache", Expires: "0" };
|
|
2536
|
+
function isBundleRoute(pathname) {
|
|
2537
|
+
return pathname.endsWith(".bundle") || pathname.endsWith(".bundle.js");
|
|
2538
|
+
}
|
|
2539
|
+
function isMapRoute(pathname) {
|
|
2540
|
+
return pathname.endsWith(".map") || pathname.endsWith(".bundle.map");
|
|
2541
|
+
}
|
|
2542
|
+
function isHmrMapRoute(pathname) {
|
|
2543
|
+
return pathname.startsWith(HMR_MAP_PREFIX);
|
|
2544
|
+
}
|
|
2545
|
+
async function handleBundleRequest(req,res,url,registry,defaultPlatform,projectRoot,port) {
|
|
2546
|
+
const state = resolvePlatform(url, registry, defaultPlatform);
|
|
2547
|
+
if (state.bundle === null && state.buildError === null) {
|
|
2548
|
+
await waitForBuild(state);
|
|
2549
|
+
}
|
|
2550
|
+
if (state.bundleStale && state.buildError === null) {
|
|
2551
|
+
await state.refreshBundle();
|
|
2552
|
+
}
|
|
2553
|
+
if (state.buildError) {
|
|
2554
|
+
sendText(res, 200, `throw new Error(${JSON.stringify(state.buildError)});`, "application/javascript");
|
|
2555
|
+
return;
|
|
2556
|
+
}
|
|
2557
|
+
if (!state.bundle) {
|
|
2558
|
+
sendText(res, 503, "Bundle not ready yet. Build may have failed - check server logs.");
|
|
2559
|
+
return;
|
|
2560
|
+
}
|
|
2561
|
+
const host = req.headers.host || `localhost:${port}`,fullUrl = `http://${host}${url.pathname}${url.search}${url.hash || ""}`,bundleUrl = jscSafeUrl.toJscSafeUrl(fullUrl),mapPathname = url.pathname.replace(/\.bundle(\.js)?$/, ".map"),mapUrl = `http://${host}${mapPathname}${url.search}`,bundle = `${state.bundle}\n//# sourceMappingURL=${mapUrl}\n//# sourceURL=${bundleUrl}`;
|
|
2562
|
+
if (req.headers.accept === "multipart/mixed") {
|
|
2563
|
+
res.writeHead(200, { "Content-Type": `multipart/mixed; boundary="${MULTIPART_BOUNDARY}"`, ...METRO_NO_STORE_HEADERS, "X-React-Native-Project-Root": projectRoot });
|
|
2564
|
+
res.write("If you are seeing this, your client does not support multipart response");
|
|
2565
|
+
res.write(`${CRLF}--${MULTIPART_BOUNDARY}${CRLF}` + `Content-Type: application/json${CRLF}${CRLF}` + JSON.stringify({ done: state.fileCount, total: state.fileCount }));
|
|
2566
|
+
const bundleBytes = Buffer.byteLength(bundle),revisionId = `${Date.now()}-${Math.random().toString(36).substring(7)}`;
|
|
2567
|
+
res.end(`${CRLF}--${MULTIPART_BOUNDARY}${CRLF}` + `X-Metro-Files-Changed-Count: ${state.fileCount}${CRLF}` + `X-Metro-Delta-ID: ${revisionId}${CRLF}` + `Content-Type: application/javascript; charset=UTF-8${CRLF}` + `Content-Length: ${bundleBytes}${CRLF}` + `Last-Modified: ${new Date().toUTCString()}${CRLF}${CRLF}` + bundle + `${CRLF}--${MULTIPART_BOUNDARY}--${CRLF}`);
|
|
2568
|
+
return;
|
|
2569
|
+
}
|
|
2570
|
+
res.writeHead(200, { "X-Content-Type-Options": "nosniff", ...METRO_NO_STORE_HEADERS, "Content-Type": "application/javascript; charset=UTF-8", "Content-Length": Buffer.byteLength(bundle), "X-React-Native-Project-Root": projectRoot, "Content-Location": bundleUrl });
|
|
2571
|
+
res.end(bundle);
|
|
2572
|
+
}
|
|
2573
|
+
function handleMapRequest(_req,res,url,registry,defaultPlatform) {
|
|
2574
|
+
const state = resolvePlatform(url, registry, defaultPlatform),json = getCachedSourceMap(state);
|
|
2575
|
+
if (!json) {
|
|
2576
|
+
sendText(res, 404, "Source map not available");
|
|
2577
|
+
return;
|
|
2578
|
+
}
|
|
2579
|
+
res.writeHead(200, { "X-Content-Type-Options": "nosniff", ...METRO_NO_STORE_HEADERS, "Content-Type": "application/json", "Content-Length": Buffer.byteLength(json), "Access-Control-Allow-Origin": "devtools://devtools" });
|
|
2580
|
+
res.end(json);
|
|
2581
|
+
}
|
|
2582
|
+
function handleHmrMapRequest(_req,res,url,registry,defaultPlatform) {
|
|
2583
|
+
const state = resolvePlatform(url, registry, defaultPlatform),moduleId = decodeURIComponent(url.pathname.slice(HMR_MAP_PREFIX.length)),rawJson = state.handle.getHmrSourceMap(moduleId);
|
|
2584
|
+
if (!rawJson) {
|
|
2585
|
+
sendText(res, 404, "HMR source map not found");
|
|
2586
|
+
return;
|
|
2587
|
+
}
|
|
2588
|
+
const json = postProcessSourceMap(rawJson);
|
|
2589
|
+
res.writeHead(200, { "X-Content-Type-Options": "nosniff", ...METRO_NO_STORE_HEADERS, "Content-Type": "application/json", "Content-Length": Buffer.byteLength(json), "Access-Control-Allow-Origin": "devtools://devtools" });
|
|
2590
|
+
res.end(json);
|
|
2591
|
+
}
|
|
2592
|
+
//#endregion
|
|
2593
|
+
//#region devmenu.ts
|
|
2594
|
+
function isDevMenuRoute(pathname) {
|
|
2595
|
+
return pathname === "/devmenu";
|
|
2596
|
+
}
|
|
2597
|
+
function handleDevMenu(_req,res,broadcast) {
|
|
2598
|
+
broadcast("devMenu");
|
|
2599
|
+
sendText(res, 200, "OK");
|
|
2600
|
+
}
|
|
2601
|
+
//#endregion
|
|
2602
|
+
//#region index-page.ts
|
|
2603
|
+
function isIndexRoute(pathname) {
|
|
2604
|
+
return pathname === "/" || pathname === "/index.html";
|
|
2605
|
+
}
|
|
2606
|
+
function handleIndexPage(_req,res,port) {
|
|
2607
|
+
const html = `<!DOCTYPE html>
|
|
2608
|
+
<html lang="en">
|
|
2609
|
+
<head>
|
|
2610
|
+
<meta charset="UTF-8">
|
|
2611
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
2612
|
+
<title>ZNTC RN Dev Server</title>
|
|
2613
|
+
<style>
|
|
2614
|
+
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; font-size: 14px; line-height: 1.6; color: #333; margin: 0; padding: 30px; background: #fafafa; }
|
|
2615
|
+
h1 { font-size: 28px; margin-bottom: 8px; font-weight: 600; color: #222; }
|
|
2616
|
+
h2 { font-size: 18px; margin: 30px 0 15px; font-weight: 600; color: #444; padding-bottom: 8px; border-bottom: 2px solid #e0e0e0; }
|
|
2617
|
+
p { margin: 8px 0; color: #666; }
|
|
2618
|
+
a { color: #007aff; text-decoration: none; }
|
|
2619
|
+
a:hover { text-decoration: underline; }
|
|
2620
|
+
ul { list-style: none; padding: 0; margin: 15px 0; }
|
|
2621
|
+
li { margin: 10px 0; padding: 8px 0; }
|
|
2622
|
+
code { background: #f0f0f0; padding: 4px 8px; border-radius: 4px; font-family: Monaco, Menlo, monospace; font-size: 13px; color: #333; border: 1px solid #e0e0e0; }
|
|
2623
|
+
a code { background: #e8f4fd; border-color: #007aff; color: #007aff; }
|
|
2624
|
+
a:hover code { background: #d0e9fc; }
|
|
2625
|
+
</style>
|
|
2626
|
+
</head>
|
|
2627
|
+
<body>
|
|
2628
|
+
<h1>ZNTC RN Dev Server</h1>
|
|
2629
|
+
<p>Metro-compatible React Native dev server (port ${port})</p>
|
|
2630
|
+
<h2>Bundles</h2>
|
|
2631
|
+
<ul>
|
|
2632
|
+
<li><a href="/index.bundle?platform=ios&dev=true"><code>/index.bundle?platform=ios&dev=true</code></a></li>
|
|
2633
|
+
<li><a href="/index.bundle?platform=android&dev=true"><code>/index.bundle?platform=android&dev=true</code></a></li>
|
|
2634
|
+
</ul>
|
|
2635
|
+
<h2>Source Maps</h2>
|
|
2636
|
+
<ul>
|
|
2637
|
+
<li><a href="/index.bundle.map?platform=ios"><code>/index.bundle.map?platform=ios</code></a></li>
|
|
2638
|
+
<li><a href="/index.bundle.map?platform=android"><code>/index.bundle.map?platform=android</code></a></li>
|
|
2639
|
+
</ul>
|
|
2640
|
+
<h2>HMR</h2>
|
|
2641
|
+
<ul>
|
|
2642
|
+
<li><code>ws://localhost:${port}/hot</code></li>
|
|
2643
|
+
</ul>
|
|
2644
|
+
</body>
|
|
2645
|
+
</html>`;
|
|
2646
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Length": Buffer.byteLength(html) });
|
|
2647
|
+
res.end(html);
|
|
2648
|
+
}
|
|
2649
|
+
//#endregion
|
|
2650
|
+
//#region open-url.ts
|
|
2651
|
+
function isOpenUrlRoute(pathname,method) {
|
|
2652
|
+
return pathname === "/open-url" && method === "POST";
|
|
2653
|
+
}
|
|
2654
|
+
function resolveOpener(platform=process.platform) {
|
|
2655
|
+
if (platform === "darwin")return { command: "open", args: (t) => [t] };
|
|
2656
|
+
if (platform === "win32")return { command: "cmd", args: (t) => ["/c", "start", "", t] };
|
|
2657
|
+
return { command: "xdg-open", args: (t) => [t] };
|
|
2658
|
+
}
|
|
2659
|
+
async function handleOpenUrl(req,res,spawner=spawn,platform=process.platform) {
|
|
2660
|
+
let body = {};
|
|
2661
|
+
try {
|
|
2662
|
+
body = await readJsonBody(req);
|
|
2663
|
+
} catch {
|
|
2664
|
+
sendJson(res, 400, { error: "Invalid JSON body" });
|
|
2665
|
+
return;
|
|
2666
|
+
}
|
|
2667
|
+
const target = body.url;
|
|
2668
|
+
if (typeof target != "string" || target.length === 0) {
|
|
2669
|
+
sendJson(res, 400, { error: "Invalid URL" });
|
|
2670
|
+
return;
|
|
2671
|
+
}
|
|
2672
|
+
try {
|
|
2673
|
+
const { command:command, args:args } = resolveOpener(platform),child = spawner(command, args(target), { detached: true, stdio: "ignore" });
|
|
2674
|
+
child.unref();
|
|
2675
|
+
sendJson(res, 200, { success: true });
|
|
2676
|
+
} catch {
|
|
2677
|
+
sendJson(res, 500, { error: "Failed to open URL" });
|
|
2678
|
+
}
|
|
2679
|
+
}
|
|
2680
|
+
//#endregion
|
|
2681
|
+
//#region reload.ts
|
|
2682
|
+
function isReloadRoute(pathname) {
|
|
2683
|
+
return pathname === "/reload";
|
|
2684
|
+
}
|
|
2685
|
+
function handleReload(_req,res,broadcast) {
|
|
2686
|
+
broadcast("reload");
|
|
2687
|
+
sendText(res, 200, "OK");
|
|
2688
|
+
}
|
|
2689
|
+
//#endregion
|
|
2690
|
+
//#region status.ts
|
|
2691
|
+
const STATUS_BODY = "packager-status:running";
|
|
2692
|
+
function isStatusRoute(pathname) {
|
|
2693
|
+
return pathname === "/status" || pathname === "/status.txt";
|
|
2694
|
+
}
|
|
2695
|
+
function handleStatus(_req,res,projectRoot) {
|
|
2696
|
+
res.setHeader("X-React-Native-Project-Root", projectRoot);
|
|
2697
|
+
sendText(res, 200, STATUS_BODY);
|
|
2698
|
+
}
|
|
2699
|
+
//#endregion
|
|
2700
|
+
//#region symbolicate-source.ts
|
|
2701
|
+
async function createSourceMapConsumer(sourceMapJson) {
|
|
2702
|
+
let parsed;
|
|
2703
|
+
try {
|
|
2704
|
+
parsed = JSON.parse(sourceMapJson);
|
|
2705
|
+
} catch {
|
|
2706
|
+
return null;
|
|
2707
|
+
}
|
|
2708
|
+
try {
|
|
2709
|
+
const mod = (await Promise.resolve().then(()=>require_source_map_source_map()));
|
|
2710
|
+
return await new mod.SourceMapConsumer(parsed);
|
|
2711
|
+
} catch {
|
|
2712
|
+
return null;
|
|
2713
|
+
}
|
|
2714
|
+
}
|
|
2715
|
+
function normalizeFrame(frame) {
|
|
2716
|
+
return { file: frame.file ?? null, methodName: frame.methodName ?? null, lineNumber: frame.lineNumber ?? null, column: frame.column ?? null };
|
|
2717
|
+
}
|
|
2718
|
+
function symbolicateFrame(consumer,frame,projectRoot) {
|
|
2719
|
+
if (!frame.file || frame.lineNumber == null)return normalizeFrame(frame);
|
|
2720
|
+
try {
|
|
2721
|
+
const pos = consumer.originalPositionFor({ line: frame.lineNumber, column: frame.column ?? 0 });
|
|
2722
|
+
if (pos.source == null || pos.line == null)return normalizeFrame(frame);
|
|
2723
|
+
const sourcePath = pos.source.startsWith("/") ? pos.source : pathResolve(projectRoot, pos.source);
|
|
2724
|
+
return { file: sourcePath, methodName: pos.name ?? frame.methodName ?? null, lineNumber: pos.line, column: pos.column ?? 0 };
|
|
2725
|
+
} catch {
|
|
2726
|
+
return normalizeFrame(frame);
|
|
2727
|
+
}
|
|
2728
|
+
}
|
|
2729
|
+
async function extractCodeFrame(frames) {
|
|
2730
|
+
for (const frame of frames) {
|
|
2731
|
+
if (!frame.file || frame.lineNumber == null)continue;
|
|
2732
|
+
if (frame.file.includes(".bundle"))continue;
|
|
2733
|
+
try {
|
|
2734
|
+
const source = await readFile$1(frame.file, "utf-8"),lines = source.split("\n"),targetLine = frame.lineNumber - 1;
|
|
2735
|
+
if (targetLine < 0 || targetLine >= lines.length)continue;
|
|
2736
|
+
const startLine = Math.max(0, targetLine - 2),endLine = Math.min(lines.length - 1, targetLine + 2);
|
|
2737
|
+
return { content: lines.slice(startLine, endLine + 1).join("\n"), location: { row: frame.lineNumber, column: frame.column ?? 0 }, fileName: frame.file };
|
|
2738
|
+
} catch {
|
|
2739
|
+
}
|
|
2740
|
+
}
|
|
2741
|
+
return null;
|
|
2742
|
+
}
|
|
2743
|
+
async function applyCustomizeFrame(frame,customizeFrame) {
|
|
2744
|
+
if (!customizeFrame)return frame;
|
|
2745
|
+
try {
|
|
2746
|
+
const result = await customizeFrame(frame);
|
|
2747
|
+
if (result?.collapse)return { ...frame, collapse: true };
|
|
2748
|
+
} catch {
|
|
2749
|
+
}
|
|
2750
|
+
return frame;
|
|
2751
|
+
}
|
|
2752
|
+
//#endregion
|
|
2753
|
+
//#region symbolicate.ts
|
|
2754
|
+
function isSymbolicateRoute(pathname,method) {
|
|
2755
|
+
return pathname === "/symbolicate" && method === "POST";
|
|
2756
|
+
}
|
|
2757
|
+
async function handleSymbolicateRequest(req,res,url,registry,defaultPlatform,projectRoot,customizeFrame) {
|
|
2758
|
+
let body;
|
|
2759
|
+
try {
|
|
2760
|
+
body = await readJsonBody(req);
|
|
2761
|
+
} catch {
|
|
2762
|
+
sendJson(res, 400, { error: "Invalid JSON body" });
|
|
2763
|
+
return;
|
|
2764
|
+
}
|
|
2765
|
+
const stack = body.stack ?? [],state = resolvePlatform(url, registry, defaultPlatform),sourceMap = getCachedSourceMap(state),debug = process.env.ZNTC_DEBUG_SYMBOLICATE === "1";
|
|
2766
|
+
if (debug) {
|
|
2767
|
+
process.stderr.write(`[zntc:rn-dev:debug] /symbolicate stack[${stack.length}] sourceMap=${sourceMap ? `len=${sourceMap.length}` : "null"}\n`);
|
|
2768
|
+
for (const f of stack.slice(0, 5)) {
|
|
2769
|
+
process.stderr.write(`[zntc:rn-dev:debug] in: file=${f.file} line=${f.lineNumber} col=${f.column} method=${f.methodName}\n`);
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
const fallback = { stack: stack.map(normalizeFrame), codeFrame: null };
|
|
2773
|
+
if (!sourceMap) {
|
|
2774
|
+
if (debug)process.stderr.write("[zntc:rn-dev:debug] sourceMap miss → fallback\n");
|
|
2775
|
+
sendJson(res, 200, fallback);
|
|
2776
|
+
return;
|
|
2777
|
+
}
|
|
2778
|
+
const consumer = await createSourceMapConsumer(sourceMap);
|
|
2779
|
+
if (!consumer) {
|
|
2780
|
+
if (debug)process.stderr.write("[zntc:rn-dev:debug] consumer create fail → fallback\n");
|
|
2781
|
+
sendJson(res, 200, fallback);
|
|
2782
|
+
return;
|
|
2783
|
+
}
|
|
2784
|
+
try {
|
|
2785
|
+
const symbolicated = await Promise.all(stack.map(async (frame) => {
|
|
2786
|
+
const resolved = symbolicateFrame(consumer, frame, projectRoot);
|
|
2787
|
+
return applyCustomizeFrame(resolved, customizeFrame);
|
|
2788
|
+
})),codeFrame = await extractCodeFrame(symbolicated);
|
|
2789
|
+
if (debug) {
|
|
2790
|
+
for (const f of symbolicated.slice(0, 5)) {
|
|
2791
|
+
process.stderr.write(`[zntc:rn-dev:debug] out: file=${f.file} line=${f.lineNumber} col=${f.column} method=${f.methodName}${f.collapse ? " collapse=true" : ""}\n`);
|
|
2792
|
+
}
|
|
2793
|
+
process.stderr.write(`[zntc:rn-dev:debug] codeFrame: ${codeFrame ? `${codeFrame.fileName}:${codeFrame.location.row}` : "null"}\n`);
|
|
2794
|
+
}
|
|
2795
|
+
sendJson(res, 200, { stack: symbolicated, codeFrame });
|
|
2796
|
+
} finally {
|
|
2797
|
+
consumer.destroy?.();
|
|
2798
|
+
}
|
|
2799
|
+
}
|
|
2800
|
+
//#endregion
|
|
2801
|
+
//#region http-server.ts
|
|
2802
|
+
var jscSafeUrl$1 = __toESM(require_jsc_safe_url_index());
|
|
2803
|
+
function createBaseMiddleware(options,deps) {
|
|
2804
|
+
return (req, res, next) => {
|
|
2805
|
+
if (req.url) {
|
|
2806
|
+
const normalized = jscSafeUrl$1.toNormalUrl(req.url),rewritten = options.rewriteRequestUrl ? options.rewriteRequestUrl(normalized) : normalized;
|
|
2807
|
+
req.url = jscSafeUrl$1.toNormalUrl(rewritten);
|
|
2808
|
+
}
|
|
2809
|
+
const url = parseRequestUrl(req, options.host, options.port),pathname = url.pathname,method = req.method;
|
|
2810
|
+
if (isIndexRoute(pathname)) {
|
|
2811
|
+
handleIndexPage(req, res, options.port);
|
|
2812
|
+
return;
|
|
2813
|
+
}
|
|
2814
|
+
if (isStatusRoute(pathname)) {
|
|
2815
|
+
handleStatus(req, res, options.bundle.projectRoot);
|
|
2816
|
+
return;
|
|
2817
|
+
}
|
|
2818
|
+
if (isReloadRoute(pathname)) {
|
|
2819
|
+
handleReload(req, res, deps.broadcast);
|
|
2820
|
+
return;
|
|
2821
|
+
}
|
|
2822
|
+
if (isDevMenuRoute(pathname)) {
|
|
2823
|
+
handleDevMenu(req, res, deps.broadcast);
|
|
2824
|
+
return;
|
|
2825
|
+
}
|
|
2826
|
+
if (isOpenUrlRoute(pathname, method)) {
|
|
2827
|
+
handleOpenUrl(req, res).catch(next);
|
|
2828
|
+
return;
|
|
2829
|
+
}
|
|
2830
|
+
if (isAssetRoute(pathname)) {
|
|
2831
|
+
handleAssetRequest(req, res, url, { projectRoot: options.bundle.projectRoot, nodeModulesPaths: options.nodeModulesPaths }).catch(next);
|
|
2832
|
+
return;
|
|
2833
|
+
}
|
|
2834
|
+
if (isBundleRoute(pathname)) {
|
|
2835
|
+
handleBundleRequest(req, res, url, deps.platforms, options.bundle.rnPlatform, options.bundle.projectRoot, options.port).catch(next);
|
|
2836
|
+
return;
|
|
2837
|
+
}
|
|
2838
|
+
if (isHmrMapRoute(pathname)) {
|
|
2839
|
+
handleHmrMapRequest(req, res, url, deps.platforms, options.bundle.rnPlatform);
|
|
2840
|
+
return;
|
|
2841
|
+
}
|
|
2842
|
+
if (isMapRoute(pathname)) {
|
|
2843
|
+
handleMapRequest(req, res, url, deps.platforms, options.bundle.rnPlatform);
|
|
2844
|
+
return;
|
|
2845
|
+
}
|
|
2846
|
+
if (isSymbolicateRoute(pathname, method)) {
|
|
2847
|
+
handleSymbolicateRequest(req, res, url, deps.platforms, options.bundle.rnPlatform, options.bundle.projectRoot, options.symbolicator?.customizeFrame).catch(next);
|
|
2848
|
+
return;
|
|
2849
|
+
}
|
|
2850
|
+
if (deps.devMiddleware && isDevMiddlewareRoute(pathname)) {
|
|
2851
|
+
deps.devMiddleware.middleware(req, res, next);
|
|
2852
|
+
return;
|
|
2853
|
+
}
|
|
2854
|
+
next();
|
|
2855
|
+
};
|
|
2856
|
+
}
|
|
2857
|
+
function chainToHandler(middleware) {
|
|
2858
|
+
return (req, res) => {
|
|
2859
|
+
middleware(req, res, (err) => {
|
|
2860
|
+
if (err) {
|
|
2861
|
+
sendText(res, 500, `Internal Server Error: ${err.message ?? err}`);
|
|
2862
|
+
return;
|
|
2863
|
+
}
|
|
2864
|
+
if (!res.headersSent && !res.writableEnded)sendText(res, 404, "Not Found");
|
|
2865
|
+
});
|
|
2866
|
+
};
|
|
2867
|
+
}
|
|
2868
|
+
function attachWebSocketEndpoints(server,deps,options) {
|
|
2869
|
+
const hmr = deps.hmrBridge,cli = deps.cliServerApi?.websocketEndpoints,dev = deps.devMiddleware?.websocketEndpoints;
|
|
2870
|
+
if (!hmr && !cli && !dev)return null;
|
|
2871
|
+
const listener = (req, socket, head) => {
|
|
2872
|
+
const url = parseRequestUrl(req, options.host, options.port);
|
|
2873
|
+
if (hmr && (url.pathname === hmr.path || url.pathname.startsWith(`${hmr.path}?`))) {
|
|
2874
|
+
hmr.acceptUpgrade(req, socket);
|
|
2875
|
+
return;
|
|
2876
|
+
}
|
|
2877
|
+
if (cli) {
|
|
2878
|
+
for (const [path, ep] of Object.entries(cli)) {
|
|
2879
|
+
if (url.pathname === path || url.pathname.startsWith(`${path}?`)) {
|
|
2880
|
+
ep.handleUpgrade(req, socket, head, (ws) => ep.emit("connection", ws, req));
|
|
2881
|
+
return;
|
|
2882
|
+
}
|
|
2883
|
+
}
|
|
2884
|
+
}
|
|
2885
|
+
if (dev) {
|
|
2886
|
+
for (const [path, ep] of Object.entries(dev)) {
|
|
2887
|
+
if (url.pathname === path || url.pathname.startsWith(`${path}/`)) {
|
|
2888
|
+
ep.handleUpgrade(req, socket, head, (ws) => ep.emit("connection", ws, req));
|
|
2889
|
+
return;
|
|
2890
|
+
}
|
|
2891
|
+
}
|
|
2892
|
+
}
|
|
2893
|
+
socket.destroy();
|
|
2894
|
+
};
|
|
2895
|
+
server.on("upgrade", listener);
|
|
2896
|
+
return listener;
|
|
2897
|
+
}
|
|
2898
|
+
async function createDevHttpServer(options,deps) {
|
|
2899
|
+
const server = createServer(),baseMiddleware = createBaseMiddleware(options, deps),enhanced = options.enhanceMiddleware ? options.enhanceMiddleware(baseMiddleware, { httpServer: server }) : baseMiddleware,requestHandler = chainToHandler(enhanced);
|
|
2900
|
+
server.on("request", requestHandler);
|
|
2901
|
+
const upgradeHandler = attachWebSocketEndpoints(server, deps, options);
|
|
2902
|
+
await new Promise((resolve, reject) => {
|
|
2903
|
+
const onError = (err) => {
|
|
2904
|
+
server.removeListener("listening", onListening);
|
|
2905
|
+
reject(err);
|
|
2906
|
+
},onListening = () => {
|
|
2907
|
+
server.removeListener("error", onError);
|
|
2908
|
+
resolve();
|
|
2909
|
+
};
|
|
2910
|
+
server.once("error", onError);
|
|
2911
|
+
server.once("listening", onListening);
|
|
2912
|
+
server.listen(options.port, options.host);
|
|
2913
|
+
});
|
|
2914
|
+
return { server, url: `http://${options.host}:${options.port}`, port: options.port, stop: () => new Promise((resolve, reject) => {
|
|
2915
|
+
server.removeListener("request", requestHandler);
|
|
2916
|
+
if (upgradeHandler)server.removeListener("upgrade", upgradeHandler);
|
|
2917
|
+
server.close((err) => (err ? reject(err) : resolve()));
|
|
2918
|
+
}) };
|
|
2919
|
+
}
|
|
2920
|
+
//#endregion
|
|
2921
|
+
//#region cli-server-api.ts
|
|
2922
|
+
function resolveCliServerApiPath(projectRoot) {
|
|
2923
|
+
const candidates = [];
|
|
2924
|
+
if (projectRoot) {
|
|
2925
|
+
const projectRequire = createRequire$4(`${projectRoot}/package.json`);
|
|
2926
|
+
candidates.push(() => projectRequire.resolve("@react-native-community/cli-server-api"));
|
|
2927
|
+
}
|
|
2928
|
+
const selfRequire = createRequire$4(import.meta.url);
|
|
2929
|
+
candidates.push(() => selfRequire.resolve("@react-native-community/cli-server-api"));
|
|
2930
|
+
for (const c of candidates) {
|
|
2931
|
+
try {
|
|
2932
|
+
return c();
|
|
2933
|
+
} catch {
|
|
2934
|
+
}
|
|
2935
|
+
}
|
|
2936
|
+
return "@react-native-community/cli-server-api";
|
|
2937
|
+
}
|
|
2938
|
+
async function loadCliServerApi(options) {
|
|
2939
|
+
try {
|
|
2940
|
+
const resolvedPath = resolveCliServerApiPath(options.projectRoot),mod = (await import(resolvedPath)),result = mod.createDevServerMiddleware({ port: options.port, host: options.host, watchFolders: [] });
|
|
2941
|
+
return { websocketEndpoints: result.websocketEndpoints, broadcast: result.messageSocketEndpoint.broadcast };
|
|
2942
|
+
} catch (err) {
|
|
2943
|
+
if (process.env.ZNTC_DEBUG_TERMINAL === "1") {
|
|
2944
|
+
process.stderr.write(`[zntc:rn-dev:debug] cli-server-api load failed: ${err?.message ?? err}\n`);
|
|
2945
|
+
}
|
|
2946
|
+
return null;
|
|
2947
|
+
}
|
|
2948
|
+
}
|
|
2949
|
+
//#endregion
|
|
2950
|
+
//#region terminal-actions.ts
|
|
2951
|
+
function printDefaultShortcuts() {
|
|
2952
|
+
console.log("");
|
|
2953
|
+
logInfo("Available shortcuts:");
|
|
2954
|
+
console.log(` ${colors.bold}r${colors.reset} - Reload ${colors.bold}d${colors.reset} - Dev Menu ${colors.bold}j${colors.reset} - DevTools`);
|
|
2955
|
+
console.log(` ${colors.bold}i${colors.reset} - iOS Sim ${colors.bold}a${colors.reset} - Android ${colors.bold}c${colors.reset} - Clear cache`);
|
|
2956
|
+
console.log(` ${colors.bold}v${colors.reset} - Toggle console logs ${colors.bold}?${colors.reset} - Show this help`);
|
|
2957
|
+
console.log("");
|
|
2958
|
+
}
|
|
2959
|
+
function openIOSSimulator() {
|
|
2960
|
+
if (process.platform !== "darwin") {
|
|
2961
|
+
logWarn("iOS Simulator is only available on macOS");
|
|
2962
|
+
return;
|
|
2963
|
+
}
|
|
2964
|
+
if (!existsSync$3("/usr/bin/xcrun")) {
|
|
2965
|
+
logWarn("xcrun not found. Install Xcode Command Line Tools.");
|
|
2966
|
+
return;
|
|
2967
|
+
}
|
|
2968
|
+
logInfo("Opening iOS Simulator...");
|
|
2969
|
+
const child = spawn$1("open", ["-a", "Simulator"], { detached: true, stdio: ["ignore", "ignore", "ignore"] });
|
|
2970
|
+
child.on("error", () => {
|
|
2971
|
+
});
|
|
2972
|
+
child.unref();
|
|
2973
|
+
}
|
|
2974
|
+
const AVD_NAME_RE = /^[a-zA-Z0-9._-]+$/;
|
|
2975
|
+
function openAndroidEmulator() {
|
|
2976
|
+
const androidHome = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT;
|
|
2977
|
+
if (!androidHome) {
|
|
2978
|
+
logWarn("ANDROID_HOME or ANDROID_SDK_ROOT not set");
|
|
2979
|
+
return;
|
|
2980
|
+
}
|
|
2981
|
+
const emulatorPath = join$3(androidHome, "emulator", "emulator");
|
|
2982
|
+
if (!existsSync$3(emulatorPath)) {
|
|
2983
|
+
logWarn("Android emulator not found. Check your Android SDK installation.");
|
|
2984
|
+
return;
|
|
2985
|
+
}
|
|
2986
|
+
const list = spawn$1(emulatorPath, ["-list-avds"], { stdio: ["ignore", "pipe", "ignore"] });
|
|
2987
|
+
list.on("error", () => {
|
|
2988
|
+
});
|
|
2989
|
+
let buf = "";
|
|
2990
|
+
list.stdout?.on("data", (chunk) => {
|
|
2991
|
+
buf += chunk.toString();
|
|
2992
|
+
});
|
|
2993
|
+
list.on("close", () => {
|
|
2994
|
+
const first = buf.split("\n").find((line) => line.trim().length > 0);
|
|
2995
|
+
if (!first) {
|
|
2996
|
+
logWarn("No Android AVDs found. Create an AVD first.");
|
|
2997
|
+
return;
|
|
2998
|
+
}
|
|
2999
|
+
const avdName = first.trim();
|
|
3000
|
+
if (!AVD_NAME_RE.test(avdName)) {
|
|
3001
|
+
logWarn("Invalid AVD name");
|
|
3002
|
+
return;
|
|
3003
|
+
}
|
|
3004
|
+
logInfo(`Opening Android Emulator: ${avdName}`);
|
|
3005
|
+
const child = spawn$1(emulatorPath, ["@" + avdName], { detached: true, stdio: ["ignore", "ignore", "ignore"] });
|
|
3006
|
+
child.on("error", () => {
|
|
3007
|
+
});
|
|
3008
|
+
child.unref();
|
|
3009
|
+
});
|
|
3010
|
+
}
|
|
3011
|
+
function setupTerminalActions(callbacks,options={ enabled: true }) {
|
|
3012
|
+
const stdin = options.stdin ?? process.stdin;
|
|
3013
|
+
if (!options.enabled)return () => {
|
|
3014
|
+
};
|
|
3015
|
+
if (!stdin.isTTY) {
|
|
3016
|
+
process.stderr.write("[zntc:rn-dev] stdin is not a TTY — keyboard shortcuts (r/d/j/i/a/c/?) disabled\n");
|
|
3017
|
+
return () => {
|
|
3018
|
+
};
|
|
3019
|
+
}
|
|
3020
|
+
const wasRaw = stdin.isRaw;
|
|
3021
|
+
let rawModeOk = true;
|
|
3022
|
+
if (!wasRaw) {
|
|
3023
|
+
try {
|
|
3024
|
+
stdin.setRawMode(true);
|
|
3025
|
+
} catch (err) {
|
|
3026
|
+
rawModeOk = false;
|
|
3027
|
+
process.stderr.write(`[zntc:rn-dev] setRawMode failed (${err.message ?? err}) — keyboard shortcuts disabled\n`);
|
|
3028
|
+
return () => {
|
|
3029
|
+
};
|
|
3030
|
+
}
|
|
3031
|
+
}
|
|
3032
|
+
if (process.env.ZNTC_DEBUG_TERMINAL === "1") {
|
|
3033
|
+
process.stderr.write(`[zntc:rn-dev:debug] terminal-actions: isTTY=${stdin.isTTY} isRaw=${stdin.isRaw} rawModeOk=${rawModeOk} runtime=${process.versions.bun ? `bun-${process.versions.bun}` : `node-${process.versions.node}`}\n`);
|
|
3034
|
+
}
|
|
3035
|
+
stdin.resume();
|
|
3036
|
+
stdin.setEncoding("utf8");
|
|
3037
|
+
const printShortcuts = options.printShortcuts ?? printDefaultShortcuts,handleKey = (chunk) => {
|
|
3038
|
+
const key = typeof chunk == "string" ? chunk : chunk.toString("utf8");
|
|
3039
|
+
if (process.env.ZNTC_DEBUG_TERMINAL === "1") {
|
|
3040
|
+
const hex = typeof chunk == "string" ? Buffer.from(chunk, "utf8").toString("hex") : chunk.toString("hex");
|
|
3041
|
+
process.stderr.write(`[zntc:rn-dev:debug] key received: hex=${hex} len=${key.length} type=${typeof chunk}\n`);
|
|
3042
|
+
}
|
|
3043
|
+
if (stdin.isTTY && !stdin.isRaw) {
|
|
3044
|
+
try {
|
|
3045
|
+
stdin.setRawMode(true);
|
|
3046
|
+
} catch {
|
|
3047
|
+
}
|
|
3048
|
+
}
|
|
3049
|
+
if (key === "\u0003") {
|
|
3050
|
+
cleanup();
|
|
3051
|
+
process.kill(process.pid, "SIGINT");
|
|
3052
|
+
return;
|
|
3053
|
+
}
|
|
3054
|
+
if (key === "\u0004") {
|
|
3055
|
+
cleanup();
|
|
3056
|
+
process.kill(process.pid, "SIGTERM");
|
|
3057
|
+
return;
|
|
3058
|
+
}
|
|
3059
|
+
switch (key.toLowerCase()) {
|
|
3060
|
+
case "r":
|
|
3061
|
+
logInfo("Reloading app...");
|
|
3062
|
+
callbacks.onReload();
|
|
3063
|
+
break;
|
|
3064
|
+
case "d":
|
|
3065
|
+
logInfo("Opening Dev Menu...");
|
|
3066
|
+
callbacks.onDevMenu();
|
|
3067
|
+
break;
|
|
3068
|
+
case "j":
|
|
3069
|
+
logInfo("Opening DevTools...");
|
|
3070
|
+
callbacks.onOpenDevTools();
|
|
3071
|
+
break;
|
|
3072
|
+
case "i":
|
|
3073
|
+
openIOSSimulator();
|
|
3074
|
+
break;
|
|
3075
|
+
case "a":
|
|
3076
|
+
openAndroidEmulator();
|
|
3077
|
+
break;
|
|
3078
|
+
case "c":
|
|
3079
|
+
callbacks.onClearCache();
|
|
3080
|
+
logInfo("Cache cleared");
|
|
3081
|
+
break;
|
|
3082
|
+
case "v":
|
|
3083
|
+
{
|
|
3084
|
+
const enabled = callbacks.onToggleLogs();
|
|
3085
|
+
logInfo(`Console logs: ${enabled ? "ON" : "OFF"}`);
|
|
3086
|
+
break;
|
|
3087
|
+
}
|
|
3088
|
+
case "?":
|
|
3089
|
+
printShortcuts();
|
|
3090
|
+
break;
|
|
3091
|
+
default:
|
|
3092
|
+
break;
|
|
3093
|
+
}
|
|
3094
|
+
};
|
|
3095
|
+
stdin.on("data", handleKey);
|
|
3096
|
+
let cleanedUp = false;
|
|
3097
|
+
function cleanup() {
|
|
3098
|
+
if (cleanedUp)return;
|
|
3099
|
+
cleanedUp = true;
|
|
3100
|
+
stdin.removeListener("data", handleKey);
|
|
3101
|
+
if (!wasRaw && stdin.isTTY) {
|
|
3102
|
+
try {
|
|
3103
|
+
stdin.setRawMode(false);
|
|
3104
|
+
} catch {
|
|
3105
|
+
}
|
|
3106
|
+
}
|
|
3107
|
+
try {
|
|
3108
|
+
stdin.pause();
|
|
3109
|
+
} catch {
|
|
3110
|
+
}
|
|
3111
|
+
}
|
|
3112
|
+
return cleanup;
|
|
3113
|
+
}
|
|
3114
|
+
//#endregion
|
|
3115
|
+
//#region serve.ts
|
|
3116
|
+
const HMR_PATH = "/hot";
|
|
3117
|
+
function makeNoopBroadcast() {
|
|
3118
|
+
let warned = false;
|
|
3119
|
+
return (method) => {
|
|
3120
|
+
if (!warned) {
|
|
3121
|
+
warned = true;
|
|
3122
|
+
process.stderr.write(`[zntc:rn-dev] broadcast('${method}') skipped — '@react-native-community/cli-server-api' 미설치 또는 load 실패. ` + `RN runtime 의 reload/devMenu 메시지 안 감. peer dependency 설치 필요.\n`);
|
|
3123
|
+
}
|
|
3124
|
+
};
|
|
3125
|
+
}
|
|
3126
|
+
async function serveRn(options,extras={}) {
|
|
3127
|
+
if (!extras.silent)printZntcRnBanner(extras.version);
|
|
3128
|
+
const [cliServerApi, devMiddleware] = await Promise.all([loadCliServerApi({ port: options.port, host: options.host, projectRoot: options.bundle.projectRoot }), loadDevMiddleware({ port: options.port, projectRoot: options.bundle.projectRoot })]),broadcast = cliServerApi?.broadcast ?? makeNoopBroadcast();
|
|
3129
|
+
if (process.env.ZNTC_DEBUG_TERMINAL === "1") {
|
|
3130
|
+
process.stderr.write(`[zntc:rn-dev:debug] cli-server-api: ${cliServerApi ? "loaded" : "null (peer 미설치 또는 load 실패)"}\n`);
|
|
3131
|
+
process.stderr.write(`[zntc:rn-dev:debug] dev-middleware: ${devMiddleware ? "loaded" : "null (peer 미설치)"}\n`);
|
|
3132
|
+
}
|
|
3133
|
+
const hmrBridge = options.hmr ? createHmrBridge({ path: HMR_PATH, silent: extras.silent, forwardClientLogs: options.bundle.extra?.forwardClientLogs }) : undefined,platforms = createPlatformStateRegistry(options, hmrBridge?.callbacks),httpHandle = await createDevHttpServer(options, { broadcast, platforms, hmrBridge, devMiddleware: devMiddleware ?? undefined, cliServerApi: cliServerApi ?? undefined }),buildStart = Date.now(),firstState = platforms.getOrCreate(options.bundle.rnPlatform);
|
|
3134
|
+
await waitForBuild(firstState);
|
|
3135
|
+
if (!extras.silent) {
|
|
3136
|
+
if (firstState.buildError) {
|
|
3137
|
+
logBundle("failed", options.bundle.rnPlatform, options.bundle.entry, firstState.buildError);
|
|
3138
|
+
} else if (firstState.bundle !== null) {
|
|
3139
|
+
const sizeKB = (Buffer.byteLength(firstState.bundle) / 1024).toFixed(1),buildMs = Date.now() - buildStart;
|
|
3140
|
+
logBundle("done", options.bundle.rnPlatform, options.bundle.entry, `(${firstState.fileCount} files, ${sizeKB} KB, ${buildMs}ms)`);
|
|
3141
|
+
}
|
|
3142
|
+
}
|
|
3143
|
+
const terminalCleanup = setupTerminalActions({ onReload: () => broadcast("reload"), onDevMenu: () => broadcast("devMenu"), onOpenDevTools: () => {
|
|
3144
|
+
fetch(`${httpHandle.url}/open-debugger`, { method: "POST", signal: AbortSignal.timeout(5000) }).catch((err) => {
|
|
3145
|
+
logError(`Failed to open DevTools: ${err.message ?? err}. ` + `'@react-native/dev-middleware' peer dependency 설치 확인.`);
|
|
3146
|
+
});
|
|
3147
|
+
}, onClearCache: () => {
|
|
3148
|
+
for (const state of platforms.platforms.values()) {
|
|
3149
|
+
state.bundle = null;
|
|
3150
|
+
state.buildError = null;
|
|
3151
|
+
state.sourceMapCache = null;
|
|
3152
|
+
}
|
|
3153
|
+
}, onToggleLogs: () => hmrBridge?.toggleLogs() ?? true }, { enabled: options.terminalActions });
|
|
3154
|
+
if (!extras.silent) {
|
|
3155
|
+
logInfo(`Dev server listening on ${httpHandle.url} (platform=${options.bundle.rnPlatform})`);
|
|
3156
|
+
if (options.terminalActions)printDefaultShortcuts();
|
|
3157
|
+
}
|
|
3158
|
+
let signalCleanup = null;
|
|
3159
|
+
if (extras.installSignalHandlers !== false) {
|
|
3160
|
+
let shuttingDown = false;
|
|
3161
|
+
const handleSignal = (signal) => {
|
|
3162
|
+
if (shuttingDown)return;
|
|
3163
|
+
shuttingDown = true;
|
|
3164
|
+
if (!extras.silent)logInfo(`${signal} received, shutting down...`);
|
|
3165
|
+
void (async () => {
|
|
3166
|
+
try {
|
|
3167
|
+
terminalCleanup();
|
|
3168
|
+
await httpHandle.stop();
|
|
3169
|
+
await platforms.stopAll();
|
|
3170
|
+
} catch (err) {
|
|
3171
|
+
logError(`Shutdown error: ${err.message ?? err}`);
|
|
3172
|
+
process.exit(1);
|
|
3173
|
+
}
|
|
3174
|
+
if (!extras.silent)logInfo("Server stopped");
|
|
3175
|
+
process.exit(0);
|
|
3176
|
+
})();
|
|
3177
|
+
};
|
|
3178
|
+
process.on("SIGINT", handleSignal);
|
|
3179
|
+
process.on("SIGTERM", handleSignal);
|
|
3180
|
+
signalCleanup = () => {
|
|
3181
|
+
process.off("SIGINT", handleSignal);
|
|
3182
|
+
process.off("SIGTERM", handleSignal);
|
|
3183
|
+
};
|
|
3184
|
+
}
|
|
3185
|
+
return { url: httpHandle.url, port: httpHandle.port, hmrBridge, platforms, async stop() {
|
|
3186
|
+
signalCleanup?.();
|
|
3187
|
+
terminalCleanup();
|
|
3188
|
+
await httpHandle.stop();
|
|
3189
|
+
await platforms.stopAll();
|
|
3190
|
+
} };
|
|
3191
|
+
}
|
|
3192
|
+
//#endregion
|
|
3193
|
+
//#region options.ts
|
|
3194
|
+
function buildRnDevServerOptions(input) {
|
|
3195
|
+
return { bundle: input.bundle, port: input.port ?? 8081, host: input.host ?? "localhost", nodeModulesPaths: input.nodeModulesPaths ?? [], enhanceMiddleware: input.enhanceMiddleware, rewriteRequestUrl: input.rewriteRequestUrl, symbolicator: input.symbolicator?.customizeFrame ? { customizeFrame: input.symbolicator.customizeFrame } : undefined, terminalActions: input.terminalActions ?? true, hmr: input.hmr ?? true };
|
|
3196
|
+
}
|
|
3197
|
+
//#endregion
|
|
3198
|
+
//#region babel.ts
|
|
3199
|
+
const ZNTC_NATIVE_PLUGIN_PATTERNS = ["optional-chaining", "nullish-coalescing", "class-properties", "private-methods", "private-property-in-object", "flow-strip-types", "transform-flow", "transform-typescript", "transform-react-jsx", "transform-arrow-functions", "transform-block-scoping", "transform-shorthand-properties", "transform-template-literals", "transform-modules-commonjs", "react-native-worklets", "react-native-reanimated/plugin", "react-native-reanimated", "@react-native/babel-preset"];
|
|
3200
|
+
function isZntcNativePlugin(name) {
|
|
3201
|
+
return ZNTC_NATIVE_PLUGIN_PATTERNS.some((pattern) => name.includes(pattern));
|
|
3202
|
+
}
|
|
3203
|
+
function applyBabelPluginPrefix(name) {
|
|
3204
|
+
if (name.startsWith("./") || name.startsWith("/") || name.startsWith("module:"))return name;
|
|
3205
|
+
if (name.startsWith("@babel/")) {
|
|
3206
|
+
const rest = name.slice("@babel/".length);
|
|
3207
|
+
if (rest.startsWith("plugin-") || rest.startsWith("preset-"))return name;
|
|
3208
|
+
return `@babel/plugin-${rest}`;
|
|
3209
|
+
}
|
|
3210
|
+
if (name.startsWith("@")) {
|
|
3211
|
+
const slashIdx = name.indexOf("/");
|
|
3212
|
+
if (slashIdx > 0) {
|
|
3213
|
+
const scope = name.slice(0, slashIdx),rest = name.slice(slashIdx + 1);
|
|
3214
|
+
if (rest.startsWith("babel-plugin-") || rest.startsWith("babel-preset-"))return name;
|
|
3215
|
+
return `${scope}/babel-plugin-${rest}`;
|
|
3216
|
+
}
|
|
3217
|
+
return name;
|
|
3218
|
+
}
|
|
3219
|
+
if (name.startsWith("babel-plugin-") || name.startsWith("babel-preset-"))return name;
|
|
3220
|
+
return `babel-plugin-${name}`;
|
|
3221
|
+
}
|
|
3222
|
+
function entryName(p) {
|
|
3223
|
+
return typeof p == "string" ? p : Array.isArray(p) ? p[0] : "";
|
|
3224
|
+
}
|
|
3225
|
+
function hasNonNative(plugins) {
|
|
3226
|
+
return plugins.some((p) => {
|
|
3227
|
+
const name = entryName(p);
|
|
3228
|
+
return typeof name == "string" && name !== "" && !isZntcNativePlugin(name);
|
|
3229
|
+
});
|
|
3230
|
+
}
|
|
3231
|
+
function parserPluginsFor(filename) {
|
|
3232
|
+
const ext = extname$2(filename);
|
|
3233
|
+
if (ext === ".ts" || ext === ".tsx")return ["typescript", "jsx"];
|
|
3234
|
+
if (ext === ".js" || ext === ".jsx" || ext === ".mjs" || ext === ".cjs") {
|
|
3235
|
+
return ["jsx", "flow"];
|
|
3236
|
+
}
|
|
3237
|
+
return ["jsx"];
|
|
3238
|
+
}
|
|
3239
|
+
function isRootImportPluginName(name) {
|
|
3240
|
+
const normalized = name.replace(/\\/g, "/");
|
|
3241
|
+
return (normalized === "root-import" || normalized === "babel-plugin-root-import" || normalized.endsWith("/babel-plugin-root-import") || normalized.includes("/babel-plugin-root-import/"));
|
|
3242
|
+
}
|
|
3243
|
+
function injectRootImportRootOption(options,projectRoot) {
|
|
3244
|
+
const next = options ? { ...options } : {},paths = next.paths;
|
|
3245
|
+
if (Array.isArray(paths)) {
|
|
3246
|
+
next.paths = paths.map((pathOption) => {
|
|
3247
|
+
if (!pathOption || typeof pathOption != "object" || Array.isArray(pathOption)) {
|
|
3248
|
+
return pathOption;
|
|
3249
|
+
}
|
|
3250
|
+
const record = pathOption;
|
|
3251
|
+
return "root" in record ? record : { ...record, root: projectRoot };
|
|
3252
|
+
});
|
|
3253
|
+
} else if (paths && typeof paths == "object") {
|
|
3254
|
+
const record = paths;
|
|
3255
|
+
next.paths = "root" in record ? record : { ...record, root: projectRoot };
|
|
3256
|
+
}
|
|
3257
|
+
if (!("root" in next))next.root = projectRoot;
|
|
3258
|
+
return next;
|
|
3259
|
+
}
|
|
3260
|
+
function detectCustomPlugins(projectRoot,inline) {
|
|
3261
|
+
if (inline?.presets && hasNonNative(inline.presets))return true;
|
|
3262
|
+
if (inline?.plugins && hasNonNative(inline.plugins))return true;
|
|
3263
|
+
try {
|
|
3264
|
+
const configPath = join$4(projectRoot, "babel.config.js");
|
|
3265
|
+
if (!existsSync$4(configPath))return false;
|
|
3266
|
+
const projectRequire = createRequire$5(`${projectRoot}/package.json`),config = projectRequire(configPath),plugins = config?.plugins ?? [];
|
|
3267
|
+
return hasNonNative(plugins);
|
|
3268
|
+
} catch {
|
|
3269
|
+
return false;
|
|
3270
|
+
}
|
|
3271
|
+
}
|
|
3272
|
+
function createBabelTransformer(projectRoot,inline) {
|
|
3273
|
+
let babel = null,babelOptions = null;
|
|
3274
|
+
function ensureBabel() {
|
|
3275
|
+
if (babel)return;
|
|
3276
|
+
const projectRequire = createRequire$5(`${projectRoot}/package.json`);
|
|
3277
|
+
function resolvePluginPath(name) {
|
|
3278
|
+
const prefixed = applyBabelPluginPrefix(name);
|
|
3279
|
+
if (prefixed !== name) {
|
|
3280
|
+
try {
|
|
3281
|
+
return projectRequire.resolve(prefixed);
|
|
3282
|
+
} catch {
|
|
3283
|
+
try {
|
|
3284
|
+
return requireFromCli.resolve(prefixed);
|
|
3285
|
+
} catch {
|
|
3286
|
+
}
|
|
3287
|
+
}
|
|
3288
|
+
}
|
|
3289
|
+
try {
|
|
3290
|
+
return projectRequire.resolve(name);
|
|
3291
|
+
} catch {
|
|
3292
|
+
return requireFromCli.resolve(name);
|
|
3293
|
+
}
|
|
3294
|
+
}
|
|
3295
|
+
function resolveEntry(entry) {
|
|
3296
|
+
if (Array.isArray(entry)) {
|
|
3297
|
+
try {
|
|
3298
|
+
const resolvedPath = resolvePluginPath(entry[0]),shouldInjectRoot = isRootImportPluginName(entry[0]) || isRootImportPluginName(applyBabelPluginPrefix(entry[0])) || isRootImportPluginName(resolvedPath);
|
|
3299
|
+
if (shouldInjectRoot) {
|
|
3300
|
+
return [resolvedPath, injectRootImportRootOption(entry[1], projectRoot), ...entry.slice(2)];
|
|
3301
|
+
}
|
|
3302
|
+
return [resolvedPath, ...entry.slice(1)];
|
|
3303
|
+
} catch {
|
|
3304
|
+
return entry;
|
|
3305
|
+
}
|
|
3306
|
+
}
|
|
3307
|
+
try {
|
|
3308
|
+
const resolvedPath = resolvePluginPath(entry),shouldInjectRoot = isRootImportPluginName(entry) || isRootImportPluginName(applyBabelPluginPrefix(entry)) || isRootImportPluginName(resolvedPath);
|
|
3309
|
+
return shouldInjectRoot ? [resolvedPath, injectRootImportRootOption(undefined, projectRoot)] : resolvedPath;
|
|
3310
|
+
} catch {
|
|
3311
|
+
return entry;
|
|
3312
|
+
}
|
|
3313
|
+
}
|
|
3314
|
+
babel = (() => {
|
|
3315
|
+
try {
|
|
3316
|
+
return projectRequire("@babel/core");
|
|
3317
|
+
} catch {
|
|
3318
|
+
return requireFromCli("@babel/core");
|
|
3319
|
+
}
|
|
3320
|
+
})();
|
|
3321
|
+
const configPath = join$4(projectRoot, "babel.config.js"),fileConfig = existsSync$4(configPath) ? projectRequire(configPath) : { plugins: [] },filePlugins = fileConfig?.plugins ?? [],inlinePlugins = inline?.plugins ?? [],customPlugins = [];
|
|
3322
|
+
for (const plugin of [...filePlugins, ...inlinePlugins]) {
|
|
3323
|
+
const name = entryName(plugin);
|
|
3324
|
+
if (typeof name == "string" && name !== "" && !isZntcNativePlugin(name)) {
|
|
3325
|
+
customPlugins.push(resolveEntry(plugin));
|
|
3326
|
+
}
|
|
3327
|
+
}
|
|
3328
|
+
const customPresets = [];
|
|
3329
|
+
if (inline?.presets) {
|
|
3330
|
+
for (const preset of inline.presets) {
|
|
3331
|
+
const name = entryName(preset);
|
|
3332
|
+
if (typeof name == "string" && name !== "" && !isZntcNativePlugin(name)) {
|
|
3333
|
+
customPresets.push(resolveEntry(preset));
|
|
3334
|
+
}
|
|
3335
|
+
}
|
|
3336
|
+
}
|
|
3337
|
+
babelOptions = { presets: customPresets, plugins: customPlugins, cwd: projectRoot, root: projectRoot, babelrc: false, configFile: false, compact: false, retainLines: true, sourceMaps: false };
|
|
3338
|
+
const pluginNames = customPlugins.map((p) => Array.isArray(p) ? p[0].split("/").pop() : String(p).split("/").pop());
|
|
3339
|
+
process.stderr.write(`[zntc:babel] loaded: ${pluginNames.join(", ")}\n`);
|
|
3340
|
+
}
|
|
3341
|
+
return (code, filename) => {
|
|
3342
|
+
try {
|
|
3343
|
+
ensureBabel();
|
|
3344
|
+
const result = babel.transformSync(code, { ...babelOptions, filename, parserOpts: { plugins: parserPluginsFor(filename) } });
|
|
3345
|
+
if (result?.code && result.code !== code) {
|
|
3346
|
+
process.stderr.write(`[zntc:babel] ${filename.split("/").pop()}: ${code.length} -> ${result.code.length}\n`);
|
|
3347
|
+
return result.code;
|
|
3348
|
+
}
|
|
3349
|
+
return null;
|
|
3350
|
+
} catch (err) {
|
|
3351
|
+
process.stderr.write(`[zntc:babel] error: ${getErrorMessage(err)}\n`);
|
|
3352
|
+
throw err;
|
|
3353
|
+
}
|
|
3354
|
+
};
|
|
3355
|
+
}
|
|
3356
|
+
function createBabelPlugin(config) {
|
|
3357
|
+
return { name: "zntc:react-native:babel-transform", setup(build) {
|
|
3358
|
+
const transformer = createBabelTransformer(config.projectRoot, config.inlineBabel),extPatterns = config.sourceExts.map((e) => normalizeExt(e).slice(1)).join("|"),sourcePattern = new RegExp(`\\.(${extPatterns})$`);
|
|
3359
|
+
build.onTransform({ filter: sourcePattern }, (args) => {
|
|
3360
|
+
if (args.path.includes("node_modules"))return null;
|
|
3361
|
+
try {
|
|
3362
|
+
const result = transformer(args.code, args.path);
|
|
3363
|
+
return result ? { code: result } : null;
|
|
3364
|
+
} catch {
|
|
3365
|
+
return null;
|
|
3366
|
+
}
|
|
3367
|
+
});
|
|
3368
|
+
} };
|
|
3369
|
+
}
|
|
3370
|
+
//#endregion
|
|
3371
|
+
//#region codegen.ts
|
|
3372
|
+
const CODEGEN_NATIVE_COMPONENT_MARKER = "codegenNativeComponent";
|
|
3373
|
+
const CODEGEN_FILENAME_PATTERN = /\.(js|ts)$/;
|
|
3374
|
+
function createCodegenTransformer(projectRoot) {
|
|
3375
|
+
let babel = null,codegenPlugin = null,babelOptions = null;
|
|
3376
|
+
function ensureBabel() {
|
|
3377
|
+
if (babel)return;
|
|
3378
|
+
babel = requireFromCli("@babel/core");
|
|
3379
|
+
try {
|
|
3380
|
+
const codegenPath = (() => {
|
|
3381
|
+
try {
|
|
3382
|
+
return requireFromCli.resolve("@react-native/babel-plugin-codegen", { paths: [projectRoot] });
|
|
3383
|
+
} catch {
|
|
3384
|
+
return requireFromCli.resolve("@react-native/babel-plugin-codegen");
|
|
3385
|
+
}
|
|
3386
|
+
})();
|
|
3387
|
+
codegenPlugin = requireFromCli(codegenPath);
|
|
3388
|
+
} catch (err) {
|
|
3389
|
+
process.stderr.write(`[zntc:codegen] @react-native/babel-plugin-codegen not found (${getErrorMessage(err, 80)}) — view config inlining disabled\n`);
|
|
3390
|
+
throw err;
|
|
3391
|
+
}
|
|
3392
|
+
babelOptions = { babelrc: false, configFile: false, compact: false, sourceMaps: false, plugins: [codegenPlugin] };
|
|
3393
|
+
}
|
|
3394
|
+
return (code, filename) => {
|
|
3395
|
+
if (!CODEGEN_FILENAME_PATTERN.test(filename))return null;
|
|
3396
|
+
if (!code.includes(CODEGEN_NATIVE_COMPONENT_MARKER))return null;
|
|
3397
|
+
const parserPlugins = filename.endsWith(".ts") ? ["typescript"] : ["flow"];
|
|
3398
|
+
try {
|
|
3399
|
+
ensureBabel();
|
|
3400
|
+
const result = babel.transformSync(code, { ...babelOptions, filename, parserOpts: { plugins: parserPlugins } });
|
|
3401
|
+
if (result?.code && result.code !== code) {
|
|
3402
|
+
process.stderr.write(`[zntc:codegen] ${filename.split("/").pop()}: view config inlined\n`);
|
|
3403
|
+
return result.code;
|
|
3404
|
+
}
|
|
3405
|
+
return null;
|
|
3406
|
+
} catch (err) {
|
|
3407
|
+
process.stderr.write(`[zntc:codegen] ${filename.split("/").pop()} failed: ${getErrorMessage(err, 120)}\n`);
|
|
3408
|
+
return null;
|
|
3409
|
+
}
|
|
3410
|
+
};
|
|
3411
|
+
}
|
|
3412
|
+
function createCodegenPlugin(config) {
|
|
3413
|
+
return { name: "zntc:react-native:codegen-view-config", setup(build) {
|
|
3414
|
+
const transformer = createCodegenTransformer(config.projectRoot);
|
|
3415
|
+
build.onTransform({ filter: /\.(js|ts)$/ }, (args) => {
|
|
3416
|
+
try {
|
|
3417
|
+
const result = transformer(args.code, args.path);
|
|
3418
|
+
return result ? { code: result } : null;
|
|
3419
|
+
} catch {
|
|
3420
|
+
return null;
|
|
3421
|
+
}
|
|
3422
|
+
});
|
|
3423
|
+
} };
|
|
3424
|
+
}
|
|
3425
|
+
//#endregion
|
|
3426
|
+
//#region styled-components-native.ts
|
|
3427
|
+
const STYLED_COMPONENTS_NATIVE_PATH_RE = /(?:^|[/\\])styled-components[/\\]native[/\\]dist[/\\]styled-components\.native\.(?:cjs|esm)\.js$/;
|
|
3428
|
+
const DOM_PROBE_PATTERNS = [/(['"])undefined\1\s*!=\s*typeof\s+window\s*&&\s*(['"])HTMLElement\2\s*in\s+window/g, /typeof\s+window\s*!==?\s*(['"])undefined\1\s*&&\s*(['"])HTMLElement\2\s*in\s+window/g];
|
|
3429
|
+
function disableStyledComponentsNativeDomProbe(code) {
|
|
3430
|
+
let next = code;
|
|
3431
|
+
for (const pattern of DOM_PROBE_PATTERNS) {
|
|
3432
|
+
next = next.replace(pattern, "false");
|
|
3433
|
+
}
|
|
3434
|
+
return next === code ? null : next;
|
|
3435
|
+
}
|
|
3436
|
+
function createStyledComponentsNativePlugin() {
|
|
3437
|
+
return { name: "zntc:react-native:styled-components-native", setup(build) {
|
|
3438
|
+
build.onTransform({ filter: STYLED_COMPONENTS_NATIVE_PATH_RE }, (args) => {
|
|
3439
|
+
const code = disableStyledComponentsNativeDomProbe(args.code);
|
|
3440
|
+
return code ? { code } : null;
|
|
3441
|
+
});
|
|
3442
|
+
} };
|
|
3443
|
+
}
|
|
3444
|
+
//#endregion
|
|
3445
|
+
//#region withExpo.ts
|
|
3446
|
+
function detectExpo(projectRoot) {
|
|
3447
|
+
try {
|
|
3448
|
+
const pkg = JSON.parse(readFileSync$3(join$5(projectRoot, "package.json"), "utf8")),deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
3449
|
+
if (deps.expo)return { name: "expo", version: deps.expo };
|
|
3450
|
+
if (deps["expo-router"])return { name: "expo-router", version: deps["expo-router"] };
|
|
3451
|
+
} catch {
|
|
3452
|
+
}
|
|
3453
|
+
return undefined;
|
|
3454
|
+
}
|
|
3455
|
+
const EXPO_ASSET_EXTS = [".heic", ".avif", ".db"],EXPO_BLOCK_LIST = [/\.expo[\\/]types/];
|
|
3456
|
+
const WINTER_POLYFILL_WARNING_PATTERN = "^Failed to set polyfill\\.\\s+\\w+\\s+is not configurable\\.?$";
|
|
3457
|
+
function resolveExpoModules(root) {
|
|
3458
|
+
const winter = tryResolve("expo/src/winter/index.ts", root) ?? tryResolve("expo/src/winter/index", root) ?? tryResolve("expo/build/winter/index.js", root) ?? undefined,expoRouterPkg = tryResolve("expo-router/package.json", root),metroRuntimeBase = expoRouterPkg ? dirname$5(expoRouterPkg) : root,metroRuntime = tryResolve("@expo/metro-runtime", metroRuntimeBase) ?? undefined;
|
|
3459
|
+
return { winter, metroRuntime };
|
|
3460
|
+
}
|
|
3461
|
+
function withExpo(config) {
|
|
3462
|
+
const root = config.root ?? process.cwd(),{ winter:winter, metroRuntime:metroRuntime } = resolveExpoModules(root),expoModules = [];
|
|
3463
|
+
if (winter)expoModules.push(winter);
|
|
3464
|
+
if (metroRuntime)expoModules.push(metroRuntime);
|
|
3465
|
+
const existingAssetExts = config.resolver?.assetExts ?? [],existingNormalized = new Set(existingAssetExts.map(normalizeExt));
|
|
3466
|
+
return { ...config, resolver: { ...config.resolver, assetExts: [...existingAssetExts, ...EXPO_ASSET_EXTS.filter((ext) => !existingNormalized.has(ext))], blockList: [...(config.resolver?.blockList ?? []), ...EXPO_BLOCK_LIST] }, serializer: { ...config.serializer, prelude: [...(config.serializer?.prelude ?? []), ...expoModules] }, server: { ...config.server, silentConsoleErrorPatterns: [...(config.server?.silentConsoleErrorPatterns ?? []), WINTER_POLYFILL_WARNING_PATTERN] } };
|
|
3467
|
+
}
|
|
3468
|
+
//#endregion
|
|
3469
|
+
//#region index.ts
|
|
3470
|
+
export { HMR_RN_MSG, buildRnDevServerOptions, createBaseMiddleware, createDevHttpServer, createHmrBridge, createPlatformState, loadCliServerApi, loadDevMiddleware, createPlatformStateRegistry, getCachedSourceMap, applyCustomizeFrame, createSourceMapConsumer, extractCodeFrame, handleAssetRequest, handleBundleRequest, handleHmrMapRequest, handleIndexPage, handleMapRequest, handleSymbolicateRequest, isIndexRoute, isAssetRoute, isBundleRoute, isHmrMapRoute, isMapRoute, isSymbolicateRoute, normalizeFrame, symbolicateFrame, colors, formatLogBadge, logBundle, logError, logInfo, logWarn, postProcessSourceMap, printZntcRnBanner, resolveAssetPath, serveRn, setupTerminalActions, waitForBuild, createMetroHmrAdapter, createAssetPlugin, createBabelPlugin, createBabelTransformer, detectCustomPlugins, isZntcNativePlugin, ZNTC_NATIVE_PLUGIN_PATTERNS, CODEGEN_NATIVE_COMPONENT_MARKER, createCodegenPlugin, createCodegenTransformer, escapeRegex, createMetroResolveRequestPlugin, createRequireContextPlugin, createStyledComponentsNativePlugin, disableStyledComponentsNativeDomProbe, STYLED_COMPONENTS_NATIVE_PATH_RE, buildRnBundleOptions, bundleRn, DEFAULT_ASSET_EXTS, watchRn, resolveRnPolyfills, RN_GLOBAL_IDENTIFIERS, tryResolve, HMR_CLIENT_SUFFIX, ZNTC_HMR_CLIENT_CODE, detectExpo, WINTER_POLYFILL_WARNING_PATTERN, withExpo };
|
|
3471
|
+
//#endregion
|