@utoo/pack 1.3.2-alpha.0 → 1.3.3-alpha.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.
@@ -1,442 +0,0 @@
1
- import fs from "fs";
2
- import http from "http";
3
- import https from "https";
4
- import { isIPv6 } from "net";
5
- import path from "path";
6
- import send from "send";
7
- import url from "url";
8
- import { resolveBundleOptions } from "../config/webpackCompat.js";
9
- import { createHotReloader } from "../core/hmr.js";
10
- import { blockStdout, getPackPath } from "../utils/common.js";
11
- import { findRootDir } from "../utils/findRoot.js";
12
- import { createSelfSignedCertificate } from "../utils/mkcert.js";
13
- import { printServerInfo } from "../utils/printServerInfo.js";
14
- import { xcodeProfilingReady } from "../utils/xcodeProfile.js";
15
- function parsePath(pathStr) {
16
- const hashIndex = pathStr.indexOf("#");
17
- const queryIndex = pathStr.indexOf("?");
18
- const hasQuery = queryIndex > -1 && (hashIndex < 0 || queryIndex < hashIndex);
19
- if (hasQuery || hashIndex > -1) {
20
- return {
21
- pathname: pathStr.substring(0, hasQuery ? queryIndex : hashIndex),
22
- query: hasQuery
23
- ? pathStr.substring(queryIndex, hashIndex > -1 ? hashIndex : undefined)
24
- : "",
25
- hash: hashIndex > -1 ? pathStr.slice(hashIndex) : "",
26
- };
27
- }
28
- return { pathname: pathStr, query: "", hash: "" };
29
- }
30
- function pathHasPrefix(pathStr, prefix) {
31
- if (typeof pathStr !== "string") {
32
- return false;
33
- }
34
- const { pathname } = parsePath(pathStr);
35
- return pathname === prefix || pathname.startsWith(prefix + "/");
36
- }
37
- function removePathPrefix(pathStr, prefix) {
38
- // If the path doesn't start with the prefix we can return it as is.
39
- if (!pathHasPrefix(pathStr, prefix)) {
40
- return pathStr;
41
- }
42
- // Remove the prefix from the path via slicing.
43
- const withoutPrefix = pathStr.slice(prefix.length);
44
- // If the path without the prefix starts with a `/` we can return it as is.
45
- if (withoutPrefix.startsWith("/")) {
46
- return withoutPrefix;
47
- }
48
- // If the path without the prefix doesn't start with a `/` we need to add it
49
- // back to the path to make sure it's a valid path.
50
- return `/${withoutPrefix}`;
51
- }
52
- function normalizedPublicPath(publicPath) {
53
- const escapedPublicPath = (publicPath === null || publicPath === void 0 ? void 0 : publicPath.replace(/^\/+|\/+$/g, "")) || false;
54
- if (!escapedPublicPath) {
55
- return "";
56
- }
57
- try {
58
- if (URL.canParse(escapedPublicPath)) {
59
- const url = new URL(escapedPublicPath).toString();
60
- return url.endsWith("/") ? url.slice(0, -1) : url;
61
- }
62
- }
63
- catch (_a) { }
64
- return `/${escapedPublicPath}`;
65
- }
66
- export function serve(options, projectPath, rootPath, serverOptions) {
67
- const bundleOptions = resolveBundleOptions(options, projectPath, rootPath);
68
- if (!rootPath) {
69
- rootPath = findRootDir(projectPath || process.cwd());
70
- }
71
- return serveInternal(bundleOptions, projectPath, rootPath, serverOptions);
72
- }
73
- async function serveInternal(options, projectPath, rootPath, serverOptions) {
74
- var _a;
75
- blockStdout();
76
- if (process.env.XCODE_PROFILE) {
77
- await xcodeProfilingReady();
78
- }
79
- // FIXME: fix any type
80
- const cfgDevServer = (((_a = options.config) === null || _a === void 0 ? void 0 : _a.devServer) || {});
81
- const serverOpts = {
82
- hostname: (serverOptions === null || serverOptions === void 0 ? void 0 : serverOptions.hostname) || cfgDevServer.host || "localhost",
83
- port: typeof (serverOptions === null || serverOptions === void 0 ? void 0 : serverOptions.port) !== "undefined"
84
- ? serverOptions.port
85
- : cfgDevServer.port || 3000,
86
- https: typeof (serverOptions === null || serverOptions === void 0 ? void 0 : serverOptions.https) !== "undefined"
87
- ? serverOptions.https
88
- : cfgDevServer.https,
89
- logServerInfo: serverOptions === null || serverOptions === void 0 ? void 0 : serverOptions.logServerInfo,
90
- selfSignedCertificate: serverOptions === null || serverOptions === void 0 ? void 0 : serverOptions.selfSignedCertificate,
91
- };
92
- // If HTTPS is requested and no certificate provided, attempt to generate one.
93
- if (serverOpts.https && !serverOpts.selfSignedCertificate) {
94
- try {
95
- // createSelfSignedCertificate may return undefined on failure
96
- const cert = await createSelfSignedCertificate(serverOpts.hostname);
97
- if (cert)
98
- serverOpts.selfSignedCertificate = cert;
99
- }
100
- catch (e) {
101
- // ignore and fall back to http if certificate generation fails
102
- }
103
- }
104
- await startServer(serverOpts, {
105
- ...options,
106
- config: {
107
- ...options.config,
108
- devServer: {
109
- hot: true,
110
- ...(options.config.devServer || {}),
111
- },
112
- },
113
- packPath: getPackPath(),
114
- }, projectPath || process.cwd(), rootPath);
115
- }
116
- export async function startServer(serverOptions, bundleOptions, projectPath, rootPath) {
117
- let { port, hostname, selfSignedCertificate } = serverOptions;
118
- process.title = "utoopack-dev-server";
119
- let handlersReady = () => { };
120
- let handlersError = () => { };
121
- let handlersPromise = new Promise((resolve, reject) => {
122
- handlersReady = resolve;
123
- handlersError = reject;
124
- });
125
- let requestHandler = async (req, res) => {
126
- if (handlersPromise) {
127
- await handlersPromise;
128
- return requestHandler(req, res);
129
- }
130
- throw new Error("Invariant request handler was not setup");
131
- };
132
- let upgradeHandler = async (req, socket, head) => {
133
- if (handlersPromise) {
134
- await handlersPromise;
135
- return upgradeHandler(req, socket, head);
136
- }
137
- throw new Error("Invariant upgrade handler was not setup");
138
- };
139
- async function requestListener(req, res) {
140
- try {
141
- if (handlersPromise) {
142
- await handlersPromise;
143
- handlersPromise = undefined;
144
- }
145
- await requestHandler(req, res);
146
- }
147
- catch (err) {
148
- res.statusCode = 500;
149
- res.end("Internal Server Error");
150
- console.error(`Failed to handle request for ${req.url}`);
151
- console.error(err);
152
- }
153
- }
154
- const server = selfSignedCertificate
155
- ? https.createServer({
156
- key: fs.readFileSync(selfSignedCertificate.key),
157
- cert: fs.readFileSync(selfSignedCertificate.cert),
158
- }, requestListener)
159
- : http.createServer(requestListener);
160
- server.on("upgrade", async (req, socket, head) => {
161
- try {
162
- await upgradeHandler(req, socket, head);
163
- }
164
- catch (err) {
165
- socket.destroy();
166
- console.error(`Failed to handle request for ${req.url}`);
167
- console.error(err);
168
- }
169
- });
170
- let portRetryCount = 0;
171
- const originalPort = port;
172
- server.on("error", (err) => {
173
- if (port && err.code === "EADDRINUSE" && portRetryCount < 10) {
174
- port += 1;
175
- portRetryCount += 1;
176
- server.listen(port, hostname);
177
- }
178
- else {
179
- console.error(`Failed to start server`);
180
- console.error(err);
181
- process.exit(1);
182
- }
183
- });
184
- await new Promise((resolve) => {
185
- server.on("listening", async () => {
186
- const addr = server.address();
187
- const actualHostname = formatHostname(typeof addr === "object"
188
- ? (addr === null || addr === void 0 ? void 0 : addr.address) || hostname || "localhost"
189
- : addr);
190
- const formattedHostname = !hostname || actualHostname === "0.0.0.0"
191
- ? "localhost"
192
- : actualHostname === "[::]"
193
- ? "[::1]"
194
- : formatHostname(hostname);
195
- port = typeof addr === "object" ? (addr === null || addr === void 0 ? void 0 : addr.port) || port : port;
196
- if (portRetryCount) {
197
- console.warn(`Port ${originalPort} is in use, using available port ${port} instead.`);
198
- }
199
- if (serverOptions.logServerInfo !== false) {
200
- printServerInfo(serverOptions.https ? "https" : "http", formattedHostname, port);
201
- }
202
- try {
203
- let cleanupStarted = false;
204
- let closeUpgraded = null;
205
- const cleanup = () => {
206
- if (cleanupStarted) {
207
- return;
208
- }
209
- cleanupStarted = true;
210
- (async () => {
211
- console.debug("start-server process cleanup");
212
- await new Promise((res) => {
213
- server.close((err) => {
214
- if (err)
215
- console.error(err);
216
- res();
217
- });
218
- server.closeAllConnections();
219
- closeUpgraded === null || closeUpgraded === void 0 ? void 0 : closeUpgraded();
220
- });
221
- console.debug("start-server process cleanup finished");
222
- process.exit(0);
223
- })();
224
- };
225
- const exception = (err) => {
226
- console.error(err);
227
- };
228
- process.on("SIGINT", cleanup);
229
- process.on("SIGTERM", cleanup);
230
- process.on("rejectionHandled", () => { });
231
- process.on("uncaughtException", exception);
232
- process.on("unhandledRejection", exception);
233
- const initResult = await initialize(bundleOptions, projectPath, rootPath);
234
- requestHandler = initResult.requestHandler;
235
- upgradeHandler = initResult.upgradeHandler;
236
- closeUpgraded = initResult.closeUpgraded;
237
- handlersReady();
238
- }
239
- catch (err) {
240
- handlersError();
241
- console.error(err);
242
- process.exit(1);
243
- }
244
- resolve();
245
- });
246
- server.listen(port, hostname);
247
- });
248
- }
249
- export async function initialize(bundleOptions, projectPath, rootPath) {
250
- process.env.NODE_ENV = "development";
251
- const hotReloader = await createHotReloader(bundleOptions, projectPath, rootPath);
252
- await hotReloader.start();
253
- const requestHandlerImpl = async (req, res) => {
254
- req.on("error", console.error);
255
- res.on("error", console.error);
256
- const handleRequest = async () => {
257
- var _a, _b;
258
- if (!(req.method === "GET" || req.method === "HEAD")) {
259
- res.setHeader("Allow", ["GET", "HEAD"]);
260
- res.statusCode = 405;
261
- res.end();
262
- }
263
- const distRoot = path.resolve(projectPath, ((_a = bundleOptions.config.output) === null || _a === void 0 ? void 0 : _a.path) || "./dist");
264
- const publicPath = (_b = bundleOptions.config.output) === null || _b === void 0 ? void 0 : _b.publicPath;
265
- try {
266
- const reqUrl = req.url || "";
267
- let requestPath = url.parse(reqUrl).pathname || "";
268
- if (publicPath && publicPath !== "runtime") {
269
- const normalizedPrefix = normalizedPublicPath(publicPath);
270
- const isAbsoluteUrl = normalizedPrefix.startsWith("http://") ||
271
- normalizedPrefix.startsWith("https://");
272
- if (!isAbsoluteUrl && normalizedPrefix) {
273
- if (pathHasPrefix(requestPath, normalizedPrefix)) {
274
- requestPath = removePathPrefix(requestPath, normalizedPrefix);
275
- }
276
- }
277
- }
278
- return await serveStatic(req, res, requestPath, { root: distRoot });
279
- }
280
- catch (err) {
281
- res.setHeader("Cache-Control", "private, no-cache, no-store, max-age=0, must-revalidate");
282
- res.statusCode = 404;
283
- res.end();
284
- }
285
- };
286
- try {
287
- await handleRequest();
288
- }
289
- catch (err) {
290
- res.statusCode = 500;
291
- res.end("Internal Server Error");
292
- }
293
- };
294
- let requestHandler = requestHandlerImpl;
295
- const logError = async (type, err) => {
296
- if (type === "unhandledRejection") {
297
- console.error("unhandledRejection: ", err);
298
- }
299
- else if (type === "uncaughtException") {
300
- console.error("uncaughtException: ", err);
301
- }
302
- };
303
- process.on("uncaughtException", logError.bind(null, "uncaughtException"));
304
- process.on("unhandledRejection", logError.bind(null, "unhandledRejection"));
305
- const upgradeHandler = async (req, socket, head) => {
306
- var _a;
307
- try {
308
- const isHMRRequest = (_a = req.url) === null || _a === void 0 ? void 0 : _a.includes("turbopack-hmr");
309
- if (isHMRRequest) {
310
- hotReloader.onHMR(req, socket, head);
311
- }
312
- else {
313
- socket.end();
314
- }
315
- }
316
- catch (err) {
317
- console.error("Error handling upgrade request", err);
318
- socket.end();
319
- }
320
- };
321
- return {
322
- requestHandler,
323
- upgradeHandler,
324
- closeUpgraded() {
325
- hotReloader.close();
326
- },
327
- };
328
- }
329
- export async function pipeToNodeResponse(readable, res, waitUntilForEnd) {
330
- try {
331
- const { errored, destroyed } = res;
332
- if (errored || destroyed)
333
- return;
334
- const controller = createAbortController(res);
335
- const writer = createWriterFromResponse(res, waitUntilForEnd);
336
- await readable.pipeTo(writer, { signal: controller.signal });
337
- }
338
- catch (err) {
339
- if (isAbortError(err))
340
- return;
341
- throw new Error("failed to pipe response", { cause: err });
342
- }
343
- }
344
- export function createAbortController(response) {
345
- const controller = new AbortController();
346
- response.once("close", () => {
347
- if (response.writableFinished)
348
- return;
349
- controller.abort(new ResponseAborted());
350
- });
351
- return controller;
352
- }
353
- export function isAbortError(e) {
354
- return (e === null || e === void 0 ? void 0 : e.name) === "AbortError" || (e === null || e === void 0 ? void 0 : e.name) === ResponseAbortedName;
355
- }
356
- export const ResponseAbortedName = "ResponseAborted";
357
- export class ResponseAborted extends Error {
358
- constructor() {
359
- super(...arguments);
360
- this.name = ResponseAbortedName;
361
- }
362
- }
363
- function createWriterFromResponse(res, waitUntilForEnd) {
364
- let started = false;
365
- let drained = new DetachedPromise();
366
- function onDrain() {
367
- drained.resolve();
368
- }
369
- res.on("drain", onDrain);
370
- res.once("close", () => {
371
- res.off("drain", onDrain);
372
- drained.resolve();
373
- });
374
- const finished = new DetachedPromise();
375
- res.once("finish", () => {
376
- finished.resolve();
377
- });
378
- return new WritableStream({
379
- write: async (chunk) => {
380
- if (!started) {
381
- started = true;
382
- res.flushHeaders();
383
- }
384
- try {
385
- const ok = res.write(chunk);
386
- if ("flush" in res && typeof res.flush === "function") {
387
- res.flush();
388
- }
389
- if (!ok) {
390
- await drained.promise;
391
- drained = new DetachedPromise();
392
- }
393
- }
394
- catch (err) {
395
- res.end();
396
- throw new Error("failed to write chunk to response", { cause: err });
397
- }
398
- },
399
- abort: (err) => {
400
- if (res.writableFinished)
401
- return;
402
- res.destroy(err);
403
- },
404
- close: async () => {
405
- if (waitUntilForEnd) {
406
- await waitUntilForEnd;
407
- }
408
- if (res.writableFinished)
409
- return;
410
- res.end();
411
- return finished.promise;
412
- },
413
- });
414
- }
415
- export class DetachedPromise {
416
- constructor() {
417
- let resolve;
418
- let reject;
419
- this.promise = new Promise((res, rej) => {
420
- resolve = res;
421
- reject = rej;
422
- });
423
- this.resolve = resolve;
424
- this.reject = reject;
425
- }
426
- }
427
- export function serveStatic(req, res, path, opts) {
428
- return new Promise((resolve, reject) => {
429
- send(req, path, opts)
430
- .on("directory", () => {
431
- const err = new Error("No directory access");
432
- err.code = "ENOENT";
433
- reject(err);
434
- })
435
- .on("error", reject)
436
- .pipe(res)
437
- .on("finish", resolve);
438
- });
439
- }
440
- export function formatHostname(hostname) {
441
- return isIPv6(hostname) ? `[${hostname}]` : hostname;
442
- }
@@ -1,29 +0,0 @@
1
- /**
2
- * HTTP proxy middleware for Hono dev server.
3
- * Matches ProxyRule by path, applies pathRewrite, and forwards via Hono proxy().
4
- * No generic WS proxying in this module.
5
- */
6
- import type { DevServerProxy, PathRewrite, ProxyRule } from "@utoo/pack-shared";
7
- import type { Context, Next } from "hono";
8
- /** Path prefix or ^-prefixed regex match (regex tests full path). */
9
- export declare function doesContextMatchUrl(context: string, pathOrUrl: string): boolean;
10
- export declare function ruleMatchesUrl(rule: ProxyRule, pathOrUrl: string): boolean;
11
- /**
12
- * Apply pathRewrite (http-proxy-middleware style).
13
- * Object: first matching regex → replace, then stop. Function: (path) => new path.
14
- */
15
- export declare function applyPathRewrite(path: string, pathRewrite?: PathRewrite): string;
16
- export interface PreparedProxyRequest {
17
- url: URL;
18
- headers: Headers;
19
- }
20
- /**
21
- * Build target URL and headers for the proxy request from current context and rule.
22
- */
23
- export declare function prepareProxyRequest(c: Context, rule: ProxyRule): PreparedProxyRequest;
24
- /**
25
- * Hono middleware: on match, proxy to rule.target with pathRewrite and changeOrigin;
26
- * on error return 502; otherwise next().
27
- * Caller (e.g. dev.ts) must pass a non-empty array; empty array means no rule matches.
28
- */
29
- export declare function createHttpProxyMiddleware(rules: DevServerProxy): (c: Context, next: Next) => Promise<void | Response>;
@@ -1,89 +0,0 @@
1
- /**
2
- * HTTP proxy middleware for Hono dev server.
3
- * Matches ProxyRule by path, applies pathRewrite, and forwards via Hono proxy().
4
- * No generic WS proxying in this module.
5
- */
6
- import { proxy } from "hono/proxy";
7
- /** Path prefix or ^-prefixed regex match (regex tests full path). */
8
- export function doesContextMatchUrl(context, pathOrUrl) {
9
- if (context[0] === "^") {
10
- try {
11
- return new RegExp(context).test(pathOrUrl);
12
- }
13
- catch (_a) {
14
- return false;
15
- }
16
- }
17
- return pathOrUrl === context || pathOrUrl.startsWith(context + "/");
18
- }
19
- export function ruleMatchesUrl(rule, pathOrUrl) {
20
- const contexts = Array.isArray(rule.context) ? rule.context : [rule.context];
21
- return contexts.some((ctx) => doesContextMatchUrl(ctx, pathOrUrl));
22
- }
23
- /**
24
- * Apply pathRewrite (http-proxy-middleware style).
25
- * Object: first matching regex → replace, then stop. Function: (path) => new path.
26
- */
27
- export function applyPathRewrite(path, pathRewrite) {
28
- if (!pathRewrite)
29
- return path;
30
- if (typeof pathRewrite === "function") {
31
- return pathRewrite(path);
32
- }
33
- for (const [pattern, value] of Object.entries(pathRewrite)) {
34
- try {
35
- const regex = new RegExp(pattern);
36
- if (regex.test(path)) {
37
- return path.replace(regex, value);
38
- }
39
- }
40
- catch (_a) {
41
- // invalid regex, skip
42
- }
43
- }
44
- return path;
45
- }
46
- /**
47
- * Build target URL and headers for the proxy request from current context and rule.
48
- */
49
- export function prepareProxyRequest(c, rule) {
50
- const origUrl = new URL(c.req.url);
51
- const targetUrl = new URL(rule.target);
52
- const origPath = c.req.path;
53
- const rewrittenPath = applyPathRewrite(origPath, rule.pathRewrite);
54
- targetUrl.pathname = rewrittenPath;
55
- targetUrl.search = origUrl.search;
56
- const headers = new Headers(c.req.header());
57
- if (rule.changeOrigin !== false) {
58
- headers.set("host", targetUrl.host);
59
- }
60
- return { url: targetUrl, headers };
61
- }
62
- /**
63
- * Hono middleware: on match, proxy to rule.target with pathRewrite and changeOrigin;
64
- * on error return 502; otherwise next().
65
- * Caller (e.g. dev.ts) must pass a non-empty array; empty array means no rule matches.
66
- */
67
- export function createHttpProxyMiddleware(rules) {
68
- return async (c, next) => {
69
- const rule = rules.find((r) => ruleMatchesUrl(r, c.req.path));
70
- if (!rule) {
71
- return next();
72
- }
73
- try {
74
- const prepared = prepareProxyRequest(c, rule);
75
- const init = {
76
- method: c.req.method,
77
- headers: prepared.headers,
78
- };
79
- if (c.req.method !== "GET" && c.req.method !== "HEAD") {
80
- init.body = c.req.raw.body;
81
- }
82
- return proxy(prepared.url.toString(), init);
83
- }
84
- catch (err) {
85
- console.error("[dev proxy] error", c.req.method, c.req.url, err);
86
- return c.text("Bad Gateway", 502);
87
- }
88
- };
89
- }