@absolutejs/absolute 0.19.0-beta.942 → 0.19.0-beta.943

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -527,6 +527,15 @@ ${contents}` : contents, normalizePostcssModule = (mod) => {
527
527
  url: new URL(`file://${filePath}`)
528
528
  });
529
529
  const css = await runPostcss(result.css, filePath, config);
530
+ const loadedUrls = result.loadedUrls ?? [];
531
+ for (const url of loadedUrls) {
532
+ if (url.protocol !== "file:")
533
+ continue;
534
+ const dep = fileURLToPath(url);
535
+ if (resolve2(dep) === resolve2(filePath))
536
+ continue;
537
+ deps.add(dep);
538
+ }
530
539
  recordStyleDeps(filePath, deps);
531
540
  return css;
532
541
  } catch (error) {
@@ -695,7 +704,7 @@ ${contents}` : contents, normalizePostcssModule = (mod) => {
695
704
  }
696
705
  const contents = withAdditionalData(rawContents, options.additionalData);
697
706
  const loadPaths = normalizeLoadPaths(filePath, options.loadPaths);
698
- const compiled = sass.compileString(contents, {
707
+ const result = sass.compileString(contents, {
699
708
  importers: [
700
709
  createSassImporter(filePath, loadPaths, language, config)
701
710
  ],
@@ -703,8 +712,17 @@ ${contents}` : contents, normalizePostcssModule = (mod) => {
703
712
  style: "expanded",
704
713
  syntax: language === "sass" ? "indented" : "scss",
705
714
  url: new URL(`file://${filePath}`)
706
- }).css;
707
- return resolveCssImportsSync(compiled, dirname2(filePath), new Set([filePath]));
715
+ });
716
+ const loadedUrls = result.loadedUrls ?? [];
717
+ for (const url of loadedUrls) {
718
+ if (url.protocol !== "file:")
719
+ continue;
720
+ const dep = fileURLToPath(url);
721
+ if (resolve2(dep) === resolve2(filePath))
722
+ continue;
723
+ addStyleImporter(filePath, dep);
724
+ }
725
+ return resolveCssImportsSync(result.css, dirname2(filePath), new Set([filePath]));
708
726
  }
709
727
  if (language === "less") {
710
728
  throw new Error(`Unable to compile ${filePath}: Less styleUrl preprocessing is async-only. Import the Less file from a bundled entrypoint or use SCSS/CSS for Angular styleUrl.`);
@@ -13841,6 +13859,10 @@ var fail = (reason, detail, location) => ({
13841
13859
  return false;
13842
13860
  if (a.decoratorOutputsArraySig !== b2.decoratorOutputsArraySig)
13843
13861
  return false;
13862
+ if (a.hostBindingsSig !== b2.hostBindingsSig)
13863
+ return false;
13864
+ if (a.pageExportsSig !== b2.pageExportsSig)
13865
+ return false;
13844
13866
  return true;
13845
13867
  }, recordFingerprint = (id, fp) => {
13846
13868
  fingerprintCache.set(id, fp);
@@ -13864,25 +13886,47 @@ var fail = (reason, detail, location) => ({
13864
13886
  if (!className)
13865
13887
  continue;
13866
13888
  const decorators = ts6.getDecorators(stmt) ?? [];
13867
- const componentDecorator = decorators.find((d2) => {
13868
- if (!ts6.isCallExpression(d2.expression))
13869
- return false;
13870
- const expr = d2.expression.expression;
13871
- return ts6.isIdentifier(expr) && expr.text === "Component";
13872
- });
13873
- if (!componentDecorator)
13874
- continue;
13875
- const decoratorCall = componentDecorator.expression;
13876
- const args = decoratorCall.arguments[0];
13877
- if (!args || !ts6.isObjectLiteralExpression(args))
13889
+ const decoratorName = (() => {
13890
+ for (const d2 of decorators) {
13891
+ if (!ts6.isCallExpression(d2.expression))
13892
+ continue;
13893
+ const expr = d2.expression.expression;
13894
+ if (!ts6.isIdentifier(expr))
13895
+ continue;
13896
+ if (expr.text === "Component" || expr.text === "Directive" || expr.text === "Pipe" || expr.text === "Injectable") {
13897
+ return expr.text;
13898
+ }
13899
+ }
13900
+ return null;
13901
+ })();
13902
+ if (!decoratorName)
13878
13903
  continue;
13879
- const decoratorMeta = readDecoratorMeta(args);
13880
- const { inputs, outputs } = extractInputsAndOutputs(stmt, null);
13881
- const componentDir = dirname15(componentFilePath);
13882
- const fingerprint = extractFingerprint(stmt, className, decoratorMeta, inputs, outputs, sourceFile, componentDir);
13883
13904
  const projectRel = relative12(process.cwd(), componentFilePath).replace(/\\/g, "/");
13884
13905
  const id = encodeURIComponent(`${projectRel}@${className}`);
13885
- fingerprintCache.set(id, fingerprint);
13906
+ if (decoratorName === "Component") {
13907
+ const componentDecorator = decorators.find((d2) => {
13908
+ if (!ts6.isCallExpression(d2.expression))
13909
+ return false;
13910
+ const expr = d2.expression.expression;
13911
+ return ts6.isIdentifier(expr) && expr.text === "Component";
13912
+ });
13913
+ if (!componentDecorator)
13914
+ continue;
13915
+ const decoratorCall = componentDecorator.expression;
13916
+ const args = decoratorCall.arguments[0];
13917
+ if (!args || !ts6.isObjectLiteralExpression(args))
13918
+ continue;
13919
+ const decoratorMeta = readDecoratorMeta(args);
13920
+ const { inputs, outputs } = extractInputsAndOutputs(stmt, null);
13921
+ const componentDir = dirname15(componentFilePath);
13922
+ const fingerprint = extractFingerprint(stmt, className, decoratorMeta, inputs, outputs, sourceFile, componentDir);
13923
+ fingerprintCache.set(id, fingerprint);
13924
+ } else {
13925
+ try {
13926
+ const entityFingerprint = extractEntityFingerprint(stmt, className, sourceFile);
13927
+ entityFingerprintCache.set(id, entityFingerprint);
13928
+ } catch {}
13929
+ }
13886
13930
  }
13887
13931
  }, invalidateFingerprintCache = () => {
13888
13932
  fingerprintCache.clear();
@@ -14137,6 +14181,7 @@ var fail = (reason, detail, location) => ({
14137
14181
  const viewProvidersExpr = getProperty(args, "viewProviders");
14138
14182
  const inputsArrayExpr = getProperty(args, "inputs");
14139
14183
  const outputsArrayExpr = getProperty(args, "outputs");
14184
+ const hostExpr = getProperty(args, "host");
14140
14185
  const styleUrls = [];
14141
14186
  if (styleUrlsExpr && ts6.isArrayLiteralExpression(styleUrlsExpr)) {
14142
14187
  for (const el of styleUrlsExpr.elements) {
@@ -14172,6 +14217,7 @@ var fail = (reason, detail, location) => ({
14172
14217
  viewProvidersExpr: viewProvidersExpr && ts6.isArrayLiteralExpression(viewProvidersExpr) ? viewProvidersExpr : null,
14173
14218
  inputsArrayExpr: inputsArrayExpr && ts6.isArrayLiteralExpression(inputsArrayExpr) ? inputsArrayExpr : null,
14174
14219
  outputsArrayExpr: outputsArrayExpr && ts6.isArrayLiteralExpression(outputsArrayExpr) ? outputsArrayExpr : null,
14220
+ hostExpr: hostExpr && ts6.isObjectLiteralExpression(hostExpr) ? hostExpr : null,
14175
14221
  preserveWhitespaces: getBooleanProperty(args, "preserveWhitespaces") ?? projectDefaults.preserveWhitespaces ?? false,
14176
14222
  selector: getStringProperty(args, "selector"),
14177
14223
  standalone: getBooleanProperty(args, "standalone") ?? true,
@@ -15187,6 +15233,27 @@ var fail = (reason, detail, location) => ({
15187
15233
  const viewProvidersArraySig = decoratorMeta.viewProvidersExpr ? djb2Hash(decoratorMeta.viewProvidersExpr.getText()) : "";
15188
15234
  const decoratorInputsArraySig = decoratorMeta.inputsArrayExpr ? djb2Hash(decoratorMeta.inputsArrayExpr.getText()) : "";
15189
15235
  const decoratorOutputsArraySig = decoratorMeta.outputsArrayExpr ? djb2Hash(decoratorMeta.outputsArrayExpr.getText()) : "";
15236
+ const hostBindingsSig = decoratorMeta.hostExpr ? djb2Hash(decoratorMeta.hostExpr.getText()) : "";
15237
+ const PAGE_EXPORT_NAMES = new Set(["providers", "routes"]);
15238
+ const pageExportEntries = [];
15239
+ for (const stmt of sourceFile.statements) {
15240
+ if (!ts6.isVariableStatement(stmt))
15241
+ continue;
15242
+ const isExported = stmt.modifiers?.some((m) => m.kind === ts6.SyntaxKind.ExportKeyword);
15243
+ if (!isExported)
15244
+ continue;
15245
+ for (const decl of stmt.declarationList.declarations) {
15246
+ if (!ts6.isIdentifier(decl.name))
15247
+ continue;
15248
+ if (!PAGE_EXPORT_NAMES.has(decl.name.text))
15249
+ continue;
15250
+ if (!decl.initializer)
15251
+ continue;
15252
+ pageExportEntries.push(`${decl.name.text}=${djb2Hash(decl.initializer.getText())}`);
15253
+ }
15254
+ }
15255
+ pageExportEntries.sort();
15256
+ const pageExportsSig = pageExportEntries.length > 0 ? pageExportEntries.join("|") : "";
15190
15257
  return {
15191
15258
  animationsArraySig,
15192
15259
  arrowFieldSig,
@@ -15198,11 +15265,13 @@ var fail = (reason, detail, location) => ({
15198
15265
  encapsulation: decoratorMeta.encapsulation,
15199
15266
  hasProviders: decoratorMeta.hasProviders,
15200
15267
  hasViewProviders: decoratorMeta.hasViewProviders,
15268
+ hostBindingsSig,
15201
15269
  hostDirectivesSig,
15202
15270
  importsArraySig,
15203
15271
  inputs: inputNames,
15204
15272
  memberDecoratorSig,
15205
15273
  outputs: outputNames,
15274
+ pageExportsSig,
15206
15275
  propertyFieldNames,
15207
15276
  providerImportSig,
15208
15277
  providersArraySig,
@@ -15461,7 +15530,7 @@ ${block}
15461
15530
  const currentFingerprint = extractFingerprint(classNode, className, decoratorMeta, inputs, outputs, sourceFile, componentDir);
15462
15531
  const cachedFingerprint = fingerprintCache.get(fingerprintId);
15463
15532
  const fingerprintChanged = cachedFingerprint !== undefined && !fingerprintsEqual(cachedFingerprint, currentFingerprint);
15464
- const rebootstrapRequired = !currentFingerprint.standalone || cachedFingerprint !== undefined && (cachedFingerprint.importsArraySig !== currentFingerprint.importsArraySig || cachedFingerprint.hostDirectivesSig !== currentFingerprint.hostDirectivesSig || cachedFingerprint.providersArraySig !== currentFingerprint.providersArraySig || cachedFingerprint.viewProvidersArraySig !== currentFingerprint.viewProvidersArraySig || cachedFingerprint.selector !== currentFingerprint.selector || cachedFingerprint.standalone !== currentFingerprint.standalone);
15533
+ const rebootstrapRequired = !currentFingerprint.standalone || cachedFingerprint !== undefined && (cachedFingerprint.importsArraySig !== currentFingerprint.importsArraySig || cachedFingerprint.hostDirectivesSig !== currentFingerprint.hostDirectivesSig || cachedFingerprint.providersArraySig !== currentFingerprint.providersArraySig || cachedFingerprint.viewProvidersArraySig !== currentFingerprint.viewProvidersArraySig || cachedFingerprint.selector !== currentFingerprint.selector || cachedFingerprint.pageExportsSig !== currentFingerprint.pageExportsSig || cachedFingerprint.standalone !== currentFingerprint.standalone);
15465
15534
  const sourceFileObj = new compiler.ParseSourceFile(tsSource, componentFilePath);
15466
15535
  const zeroLoc = new compiler.ParseLocation(sourceFileObj, 0, 0, 0);
15467
15536
  const typeSourceSpan = new compiler.ParseSourceSpan(zeroLoc, zeroLoc);
@@ -19733,1252 +19802,1252 @@ var init_moduleMapper = __esm(() => {
19733
19802
  init_reactComponentClassifier();
19734
19803
  });
19735
19804
 
19736
- // src/dev/webSocket.ts
19737
- var trySendMessage = (client2, messageStr) => {
19738
- try {
19739
- client2.send(messageStr);
19740
- return true;
19741
- } catch {
19742
- return false;
19743
- }
19744
- }, broadcastToClients = (state, message) => {
19745
- const messageStr = JSON.stringify({
19746
- ...message,
19747
- timestamp: Date.now()
19748
- });
19749
- const shouldRemove = (client2) => {
19750
- return !trySendMessage(client2, messageStr);
19805
+ // src/dev/angular/resolveOwningComponents.ts
19806
+ var exports_resolveOwningComponents = {};
19807
+ __export(exports_resolveOwningComponents, {
19808
+ resolveOwningComponents: () => resolveOwningComponents,
19809
+ resolveDescendantsOfParent: () => resolveDescendantsOfParent,
19810
+ invalidateResourceIndex: () => invalidateResourceIndex
19811
+ });
19812
+ import { readdirSync as readdirSync2, readFileSync as readFileSync19, statSync as statSync3 } from "fs";
19813
+ import { dirname as dirname19, extname as extname9, join as join29, resolve as resolve34 } from "path";
19814
+ import ts7 from "typescript";
19815
+ var ENTITY_DECORATORS, isAngularSourceFile = (file5) => file5.endsWith(".ts") || file5.endsWith(".tsx"), walkAngularSourceFiles = (root) => {
19816
+ const out = [];
19817
+ const visit = (dir) => {
19818
+ let entries;
19819
+ try {
19820
+ entries = readdirSync2(dir, { withFileTypes: true });
19821
+ } catch {
19822
+ return;
19823
+ }
19824
+ for (const entry of entries) {
19825
+ if (entry.name.startsWith(".") || entry.name === "node_modules") {
19826
+ continue;
19827
+ }
19828
+ const full = join29(dir, entry.name);
19829
+ if (entry.isDirectory()) {
19830
+ visit(full);
19831
+ } else if (entry.isFile() && isAngularSourceFile(entry.name)) {
19832
+ out.push(full);
19833
+ }
19834
+ }
19751
19835
  };
19752
- const clientsToRemove = [];
19753
- state.connectedClients.forEach((client2) => {
19754
- if (shouldRemove(client2))
19755
- clientsToRemove.push(client2);
19756
- });
19757
- clientsToRemove.forEach((client2) => {
19758
- state.connectedClients.delete(client2);
19759
- });
19760
- }, handleClientConnect = (state, client2, manifest) => {
19761
- state.connectedClients.add(client2);
19762
- const serverVersions = serializeModuleVersions(state.moduleVersions);
19763
- client2.send(JSON.stringify({
19764
- data: {
19765
- manifest,
19766
- serverVersions
19767
- },
19768
- timestamp: Date.now(),
19769
- type: "manifest"
19770
- }));
19771
- client2.send(JSON.stringify({
19772
- message: "HMR client connected successfully",
19773
- timestamp: Date.now(),
19774
- type: "connected"
19775
- }));
19776
- }, handleClientDisconnect = (state, client2) => {
19777
- state.connectedClients.delete(client2);
19778
- }, parseJsonSafe = (raw) => JSON.parse(raw), parseMessage = (message) => {
19779
- if (typeof message === "string") {
19780
- return parseJsonSafe(message);
19781
- }
19782
- if (message instanceof Buffer) {
19783
- return parseJsonSafe(message.toString());
19784
- }
19785
- if (message instanceof ArrayBuffer) {
19786
- return parseJsonSafe(new TextDecoder().decode(new Uint8Array(message)));
19787
- }
19788
- if (ArrayBuffer.isView(message)) {
19789
- const view = new Uint8Array(message.buffer, message.byteOffset, message.byteLength);
19790
- return parseJsonSafe(new TextDecoder().decode(view));
19791
- }
19792
- if (typeof message === "object" && message !== null) {
19793
- return message;
19836
+ visit(root);
19837
+ return out;
19838
+ }, getStringPropertyValue = (obj, name) => {
19839
+ for (const prop of obj.properties) {
19840
+ if (!ts7.isPropertyAssignment(prop))
19841
+ continue;
19842
+ const propName = ts7.isIdentifier(prop.name) ? prop.name.text : ts7.isStringLiteral(prop.name) ? prop.name.text : null;
19843
+ if (propName !== name)
19844
+ continue;
19845
+ const init = prop.initializer;
19846
+ if (ts7.isStringLiteral(init) || ts7.isNoSubstitutionTemplateLiteral(init)) {
19847
+ return init.text;
19848
+ }
19794
19849
  }
19795
19850
  return null;
19796
- }, handleParsedMessage = (state, client2, data) => {
19797
- switch (data.type) {
19798
- case "ping":
19799
- client2.send(JSON.stringify({
19800
- timestamp: Date.now(),
19801
- type: "pong"
19802
- }));
19803
- break;
19804
- case "request-rebuild":
19805
- break;
19806
- case "ready":
19807
- if (data.framework) {
19808
- state.activeFrameworks.add(data.framework);
19851
+ }, getStringArrayProperty = (obj, name) => {
19852
+ const out = [];
19853
+ for (const prop of obj.properties) {
19854
+ if (!ts7.isPropertyAssignment(prop))
19855
+ continue;
19856
+ const propName = ts7.isIdentifier(prop.name) ? prop.name.text : ts7.isStringLiteral(prop.name) ? prop.name.text : null;
19857
+ if (propName !== name)
19858
+ continue;
19859
+ const init = prop.initializer;
19860
+ if (!ts7.isArrayLiteralExpression(init))
19861
+ continue;
19862
+ for (const element of init.elements) {
19863
+ if (ts7.isStringLiteral(element) || ts7.isNoSubstitutionTemplateLiteral(element)) {
19864
+ out.push(element.text);
19809
19865
  }
19810
- break;
19811
- case "hmr-timing":
19812
- logHmrUpdate(state.lastHmrPath ?? "", state.lastHmrFramework, data.duration);
19813
- break;
19814
- case "angular:hmr-ack": {
19815
- const tag = data.tier === "tier-0" ? "tier-0" : "tier-1a";
19816
- const suffix = data.error ? ` FAILED \u2014 ${data.error}` : ` applied in ${data.applyMs.toFixed(0)}ms`;
19817
- logInfo(`[ng-hmr] ${tag} ${data.className}${suffix}`);
19818
- break;
19819
- }
19820
- }
19821
- }, handleHMRMessage = (state, client2, message) => {
19822
- try {
19823
- const parsedData = parseMessage(message);
19824
- if (parsedData === null) {
19825
- return;
19826
- }
19827
- if (!isValidHMRClientMessage(parsedData)) {
19828
- return;
19829
19866
  }
19830
- handleParsedMessage(state, client2, parsedData);
19831
- } catch {}
19832
- };
19833
- var init_webSocket = __esm(() => {
19834
- init_logger();
19835
- });
19836
-
19837
- // src/core/ssrCache.ts
19838
- var dirtyFrameworks, isSsrCacheDirty = (framework) => dirtyFrameworks.has(framework), markSsrCacheDirty = (framework) => {
19839
- dirtyFrameworks.add(framework);
19840
- };
19841
- var init_ssrCache = __esm(() => {
19842
- dirtyFrameworks = new Set;
19843
- });
19844
-
19845
- // src/dev/moduleServer.ts
19846
- var exports_moduleServer = {};
19847
- __export(exports_moduleServer, {
19848
- warnIfReactFastRefreshUnsupported: () => warnIfReactFastRefreshUnsupported,
19849
- warmCompilers: () => warmCompilers,
19850
- warmCache: () => warmCache,
19851
- setGlobalModuleServer: () => setGlobalModuleServer,
19852
- invalidateModule: () => invalidateModule,
19853
- createModuleServer: () => createModuleServer,
19854
- SRC_URL_PREFIX: () => SRC_URL_PREFIX
19855
- });
19856
- import { existsSync as existsSync26, readFileSync as readFileSync19, statSync as statSync3 } from "fs";
19857
- import { basename as basename11, dirname as dirname19, extname as extname9, join as join29, resolve as resolve34, relative as relative14 } from "path";
19858
- var SRC_PREFIX = "/@src/", jsTranspiler2, tsTranspiler2, tsxTranspiler, TRANSPILABLE, ALL_EXPORTS_RE, STRING_CONTENTS_RE, preserveTypeExports = (originalSource, transpiled, valueExports) => {
19859
- const codeOnly = originalSource.replace(STRING_CONTENTS_RE, '""');
19860
- const allExports = [];
19861
- let match;
19862
- ALL_EXPORTS_RE.lastIndex = 0;
19863
- while ((match = ALL_EXPORTS_RE.exec(codeOnly)) !== null) {
19864
- if (match[1])
19865
- allExports.push(match[1]);
19866
19867
  }
19867
- const valueSet = new Set(valueExports);
19868
- const typeExports = allExports.filter((exp) => !valueSet.has(exp));
19869
- if (typeExports.length === 0)
19870
- return transpiled;
19871
- const stubs = typeExports.map((name) => `export const ${name} = undefined;`).join(`
19872
- `);
19873
- return `${transpiled}
19874
- ${stubs}
19875
- `;
19876
- }, resolveRelativeExtension = (srcPath, projectRoot, extensions) => {
19877
- const found = extensions.find((ext) => existsSync26(resolve34(projectRoot, srcPath + ext)));
19878
- return found ? srcPath + found : srcPath;
19879
- }, IMPORT_EXTENSIONS, SIDE_EFFECT_EXTENSIONS, MODULE_EXTENSIONS, RESOLVED_MODULE_EXTENSIONS, REACT_EXTENSIONS, escapeRegex3 = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), buildImportRewriter = (vendorPaths) => {
19880
- const entries = Object.entries(vendorPaths).sort(([a], [b2]) => b2.length - a.length);
19881
- if (entries.length === 0)
19882
- return null;
19883
- const alt = entries.map(([spec]) => escapeRegex3(spec)).join("|");
19884
- const lookup = new Map(entries);
19885
- const vendorRegex = new RegExp(`((?:from|import)\\s*["']|import\\s*\\(\\s*["'])(${alt})(["'](?:\\s*[;)]?)?)`, "g");
19886
- return { lookup, vendorRegex };
19887
- }, mtimeCache, buildVersion = (mtime, absPath) => {
19888
- const invalidationVersion = getInvalidationVersion(absPath);
19889
- return invalidationVersion > 0 ? `${mtime}.${invalidationVersion}` : `${mtime}`;
19890
- }, srcUrl = (relPath, projectRoot) => {
19891
- const base = `${SRC_PREFIX}${relPath.replace(/\\/g, "/")}`;
19892
- const absPath = resolve34(projectRoot, relPath);
19893
- const cached = mtimeCache.get(absPath);
19894
- if (cached !== undefined)
19895
- return `${base}?v=${buildVersion(cached, absPath)}`;
19868
+ return out;
19869
+ }, parseDecoratedClasses = (filePath) => {
19870
+ let source;
19896
19871
  try {
19897
- const mtime = Math.round(statSync3(absPath).mtimeMs);
19898
- mtimeCache.set(absPath, mtime);
19899
- return `${base}?v=${buildVersion(mtime, absPath)}`;
19872
+ source = readFileSync19(filePath, "utf8");
19900
19873
  } catch {
19901
- return base;
19902
- }
19903
- }, resolveRelativeImport = (relPath, fileDir, projectRoot, extensions) => {
19904
- const absPath = resolve34(fileDir, relPath);
19905
- const rel = relative14(projectRoot, absPath);
19906
- const extension = extname9(rel);
19907
- let srcPath = RESOLVED_MODULE_EXTENSIONS.has(extension) ? rel : resolveRelativeExtension(rel, projectRoot, extensions);
19908
- if (extname9(srcPath) === ".svelte") {
19909
- srcPath = relative14(projectRoot, resolveSvelteModulePath(resolve34(projectRoot, srcPath)));
19874
+ return [];
19910
19875
  }
19911
- return srcUrl(srcPath, projectRoot);
19912
- }, NODE_BUILTIN_RE, resolveAbsoluteSpecifier = (specifier, projectRoot) => {
19913
- if (NODE_BUILTIN_RE.test(specifier))
19914
- return;
19915
- try {
19916
- const fromExports = resolvePackageImport(specifier, [
19917
- "browser",
19918
- "import"
19919
- ]);
19920
- if (fromExports)
19921
- return relative14(projectRoot, fromExports);
19922
- try {
19923
- const isScoped = specifier.startsWith("@");
19924
- const parts = specifier.split("/");
19925
- const packageName = isScoped ? `${parts[0]}/${parts[1]}` : parts[0];
19926
- const subpath = isScoped ? parts.slice(2).join("/") : parts.slice(1).join("/");
19927
- if (!subpath) {
19928
- const pkgDir = resolve34(projectRoot, "node_modules", packageName ?? "");
19929
- const pkgJsonPath = join29(pkgDir, "package.json");
19930
- if (existsSync26(pkgJsonPath)) {
19931
- const pkg = JSON.parse(readFileSync19(pkgJsonPath, "utf-8"));
19932
- const esmEntry = typeof pkg.module === "string" && pkg.module || typeof pkg.browser === "string" && pkg.browser;
19933
- if (esmEntry) {
19934
- const resolved = resolve34(pkgDir, esmEntry);
19935
- if (existsSync26(resolved))
19936
- return relative14(projectRoot, resolved);
19876
+ const sourceFile = ts7.createSourceFile(filePath, source, ts7.ScriptTarget.ES2022, true, ts7.ScriptKind.TS);
19877
+ const out = [];
19878
+ const visit = (node) => {
19879
+ if (ts7.isClassDeclaration(node) && node.name) {
19880
+ for (const decorator of ts7.getDecorators(node) ?? []) {
19881
+ const expr = decorator.expression;
19882
+ if (!ts7.isCallExpression(expr))
19883
+ continue;
19884
+ const fn2 = expr.expression;
19885
+ if (!ts7.isIdentifier(fn2))
19886
+ continue;
19887
+ const kind = ENTITY_DECORATORS[fn2.text];
19888
+ if (!kind)
19889
+ continue;
19890
+ let extendsName = null;
19891
+ for (const heritage of node.heritageClauses ?? []) {
19892
+ if (heritage.token !== ts7.SyntaxKind.ExtendsKeyword) {
19893
+ continue;
19894
+ }
19895
+ const first = heritage.types[0];
19896
+ if (first && ts7.isIdentifier(first.expression)) {
19897
+ extendsName = first.expression.text;
19937
19898
  }
19899
+ break;
19900
+ }
19901
+ const entry = {
19902
+ className: node.name.text,
19903
+ kind,
19904
+ styleUrls: [],
19905
+ templateUrls: [],
19906
+ extendsName
19907
+ };
19908
+ const arg = expr.arguments[0];
19909
+ if (arg && ts7.isObjectLiteralExpression(arg) && kind === "component") {
19910
+ const tplUrl = getStringPropertyValue(arg, "templateUrl");
19911
+ if (tplUrl)
19912
+ entry.templateUrls.push(tplUrl);
19913
+ const styleUrl = getStringPropertyValue(arg, "styleUrl");
19914
+ if (styleUrl)
19915
+ entry.styleUrls.push(styleUrl);
19916
+ entry.styleUrls.push(...getStringArrayProperty(arg, "styleUrls"));
19938
19917
  }
19918
+ out.push(entry);
19919
+ break;
19939
19920
  }
19940
- } catch {}
19941
- return relative14(projectRoot, Bun.resolveSync(specifier, projectRoot));
19942
- } catch {
19943
- return;
19944
- }
19945
- }, rewriteImports = (code, filePath, projectRoot, rewriter) => {
19946
- let result = code;
19947
- const vendorReplace = (_match, prefix, specifier, suffix) => {
19948
- const webPath = rewriter?.lookup.get(specifier);
19949
- return webPath ? `${prefix}${webPath}${suffix}` : _match;
19950
- };
19951
- if (rewriter) {
19952
- rewriter.vendorRegex.lastIndex = 0;
19953
- result = result.replace(rewriter.vendorRegex, vendorReplace);
19954
- }
19955
- const stubReplace = (_match, prefix, specifier, suffix) => {
19956
- if (specifier.startsWith("/") || specifier.startsWith("."))
19957
- return _match;
19958
- const resolved = resolveAbsoluteSpecifier(specifier, projectRoot);
19959
- if (resolved) {
19960
- return `${prefix}${srcUrl(resolved, projectRoot)}${suffix}`;
19961
19921
  }
19962
- return `${prefix}/@stub/${encodeURIComponent(specifier)}${suffix}`;
19922
+ ts7.forEachChild(node, visit);
19963
19923
  };
19964
- result = result.replace(/^((?:import\s+[\s\S]+?\s+from|export\s+[\s\S]+?\s+from|import)\s*["'])([^"'./][^"']*)(["'])/gm, stubReplace);
19965
- result = result.replace(/(import\s*\(\s*["'])([^"'./][^"']*)(["']\s*\))/g, stubReplace);
19966
- const fileDir = dirname19(filePath);
19967
- result = result.replace(/(from\s*["'])(\.\.?\/[^"']+)(["'])/g, (_match, prefix, relPath, suffix) => `${prefix}${resolveRelativeImport(relPath, fileDir, projectRoot, IMPORT_EXTENSIONS)}${suffix}`);
19968
- result = result.replace(/(import\s*\(\s*["'])(\.\.?\/[^"']+)(["']\s*\))/g, (_match, prefix, relPath, suffix) => `${prefix}${resolveRelativeImport(relPath, fileDir, projectRoot, IMPORT_EXTENSIONS)}${suffix}`);
19969
- result = result.replace(/(import\s*["'])(\.\.?\/[^"']+)(["']\s*;?)/g, (_match, prefix, relPath, suffix) => `${prefix}${resolveRelativeImport(relPath, fileDir, projectRoot, SIDE_EFFECT_EXTENSIONS)}${suffix}`);
19970
- const rewriteAbsoluteToSrc = (_match, prefix, absPath, _ext, suffix) => {
19971
- if (absPath.startsWith(projectRoot)) {
19972
- const rel2 = relative14(projectRoot, absPath).replace(/\\/g, "/");
19973
- return `${prefix}${srcUrl(rel2, projectRoot)}${suffix}`;
19924
+ visit(sourceFile);
19925
+ return out;
19926
+ }, safeNormalize = (path) => resolve34(path).replace(/\\/g, "/"), resolveOwningComponents = (params) => {
19927
+ const { changedFilePath, userAngularRoot } = params;
19928
+ const changedAbs = safeNormalize(changedFilePath);
19929
+ const out = [];
19930
+ const ext = extname9(changedAbs).toLowerCase();
19931
+ if (ext === ".ts" || ext === ".tsx") {
19932
+ const classes = parseDecoratedClasses(changedAbs);
19933
+ for (const cls of classes) {
19934
+ out.push({
19935
+ className: cls.className,
19936
+ componentFilePath: changedAbs,
19937
+ kind: cls.kind
19938
+ });
19974
19939
  }
19975
- const rel = relative14(projectRoot, absPath).replace(/\\/g, "/");
19976
- return `${prefix}${srcUrl(rel, projectRoot)}${suffix}`;
19977
- };
19978
- result = result.replace(/((?:from|import)\s*["'])(\/[^"']+\.(tsx?|jsx?|ts))(["'])/g, rewriteAbsoluteToSrc);
19979
- result = result.replace(/(import\s*\(\s*["'])(\/[^"']+\.(tsx?|jsx?|ts))(["']\s*\))/g, rewriteAbsoluteToSrc);
19980
- result = result.replace(/new\s+URL\(\s*["'](\.\.?\/[^"']+)["']\s*,\s*import\.meta\.url\s*\)/g, (_match, relPath) => {
19981
- const absPath = resolve34(fileDir, relPath);
19982
- const rel = relative14(projectRoot, absPath);
19983
- return `new URL('${srcUrl(rel, projectRoot)}', import.meta.url)`;
19984
- });
19985
- result = result.replace(/import\.meta\.resolve\(\s*["'](\.\.?\/[^"']+)["']\s*\)/g, (_match, relPath) => {
19986
- const absPath = resolve34(fileDir, relPath);
19987
- const rel = relative14(projectRoot, absPath);
19988
- return `'${srcUrl(rel, projectRoot)}'`;
19989
- });
19990
- return result;
19991
- }, JSX_AUTO_RE, JSXS_AUTO_RE, JSX_PROD_RE, FRAGMENT_RE, addJsxImport = (code) => {
19992
- const imports = [];
19993
- const jsxDevMatch = JSX_AUTO_RE.exec(code);
19994
- if (jsxDevMatch) {
19995
- imports.push(`import { jsxDEV as ${jsxDevMatch[1]} } from "react/jsx-dev-runtime";`);
19996
- }
19997
- const jsxsMatch = JSXS_AUTO_RE.exec(code);
19998
- if (jsxsMatch && (!jsxDevMatch || jsxsMatch[1] !== jsxDevMatch[1])) {
19999
- imports.push(`import { jsxs as ${jsxsMatch[1]} } from "react/jsx-runtime";`);
20000
- }
20001
- const jsxProdMatch = JSX_PROD_RE.exec(code);
20002
- if (jsxProdMatch) {
20003
- imports.push(`import { jsx as ${jsxProdMatch[1]} } from "react/jsx-runtime";`);
19940
+ return out;
20004
19941
  }
20005
- const fragmentMatch = FRAGMENT_RE.exec(code);
20006
- if (fragmentMatch) {
20007
- imports.push(`import { Fragment as ${fragmentMatch[1]} } from "react";`);
19942
+ if (ext !== ".html" && ext !== ".css" && ext !== ".scss" && ext !== ".sass") {
19943
+ return out;
20008
19944
  }
20009
- if (imports.length === 0)
20010
- return code;
20011
- return `${imports.join(`
20012
- `)}
20013
- ${code}`;
20014
- }, reactTranspilerOptions, reactTranspiler, probeReactFastRefresh = () => {
19945
+ let rootStat;
20015
19946
  try {
20016
- const probeOptions = {
20017
- loader: "tsx",
20018
- reactFastRefresh: true
20019
- };
20020
- const probe = new Bun.Transpiler(probeOptions);
20021
- const out = probe.transformSync("export function __AbsoluteRefreshProbe(){return null;}");
20022
- return out.includes("$RefreshReg$");
19947
+ rootStat = statSync3(userAngularRoot);
20023
19948
  } catch {
20024
- return false;
19949
+ return out;
20025
19950
  }
20026
- }, reactFastRefreshSupported, reactFastRefreshWarningEmitted = false, warnIfReactFastRefreshUnsupported = () => {
20027
- if (reactFastRefreshSupported || reactFastRefreshWarningEmitted)
20028
- return;
20029
- reactFastRefreshWarningEmitted = true;
20030
- logWarn("React HMR is blocked: this Bun build ignores " + "`reactFastRefresh` on Bun.Transpiler, so component state " + "cannot be preserved across edits. Tracking " + "https://github.com/oven-sh/bun/pull/28312 \u2014 if it still has " + "not merged, leave a \uD83D\uDC4D on the PR so the Bun team knows it " + "is blocking you. Until then, React edits trigger a full " + "reload instead of a fast refresh.");
20031
- }, transformReactFile = (filePath, projectRoot, rewriter) => {
20032
- const raw = readFileSync19(filePath, "utf-8");
20033
- const valueExports = tsxTranspiler.scan(raw).exports;
20034
- let transpiled = reactTranspiler.transformSync(raw);
20035
- transpiled = preserveTypeExports(raw, transpiled, valueExports);
20036
- transpiled = addJsxImport(transpiled);
20037
- transpiled = transpiled.replace(/import\s*\{[^}]*\}\s*from\s*["']react-refresh\/runtime["'];?\n?/, "");
20038
- transpiled = transpiled.replace(/\$RefreshReg\$_[a-z0-9]+/g, "$RefreshReg$");
20039
- transpiled = transpiled.replace(/\$RefreshSig\$_[a-z0-9]+/g, "$RefreshSig$");
20040
- transpiled = `var $RefreshReg$ = window.$RefreshReg$ || function(){};
20041
- ` + `var $RefreshSig$ = window.$RefreshSig$ || function(){ return function(t){ return t; }; };
20042
- ${transpiled}`;
20043
- const relPath = relative14(projectRoot, filePath).replace(/\\/g, "/");
20044
- transpiled = transpiled.replace(/\binput\.tsx:/g, `${relPath}:`);
20045
- transpiled += buildIslandMetadataExports(raw);
20046
- return rewriteImports(transpiled, filePath, projectRoot, rewriter);
20047
- }, transformPlainFile = (filePath, projectRoot, rewriter, vueDir) => {
20048
- const raw = readFileSync19(filePath, "utf-8");
20049
- const ext = extname9(filePath);
20050
- const isTS = ext === ".ts" || ext === ".tsx";
20051
- const isTSX = ext === ".tsx" || ext === ".jsx";
20052
- let transpiler6 = jsTranspiler2;
20053
- if (isTSX)
20054
- transpiler6 = tsxTranspiler;
20055
- else if (isTS)
20056
- transpiler6 = tsTranspiler2;
20057
- const valueExports = isTS ? transpiler6.scan(raw).exports : [];
20058
- let transpiled = transpiler6.transformSync(raw);
20059
- if (isTS) {
20060
- transpiled = preserveTypeExports(raw, transpiled, valueExports);
19951
+ if (!rootStat.isDirectory())
19952
+ return out;
19953
+ const index = getOrBuildResourceIndex(userAngularRoot);
19954
+ const owners = index.get(changedAbs);
19955
+ if (owners) {
19956
+ out.push(...owners);
20061
19957
  }
20062
- transpiled = rewriteImports(transpiled, filePath, projectRoot, rewriter);
20063
- if (!vueDir || !filePath.startsWith(vueDir) || !isTS)
20064
- return transpiled;
20065
- const useExports = valueExports.filter((e) => e.startsWith("use"));
20066
- if (useExports.length === 0)
20067
- return transpiled;
20068
- return injectComposableTracking(transpiled, filePath, useExports);
20069
- }, classifyChar = (char, prevChar, inString) => {
20070
- if (inString) {
20071
- const closed = char === inString && prevChar !== "\\";
20072
- return { nextString: closed ? false : inString, skip: true };
19958
+ return out;
19959
+ }, indexByRoot, resolveParentClassFile = (parentName, childFilePath, angularRoot) => {
19960
+ let source;
19961
+ try {
19962
+ source = readFileSync19(childFilePath, "utf8");
19963
+ } catch {
19964
+ return null;
20073
19965
  }
20074
- if (char === '"' || char === "'" || char === "`")
20075
- return { nextString: char, skip: true };
20076
- return { nextString: false, skip: false };
20077
- }, findFunctionEnd = (source, startPos) => {
20078
- let depth = 0;
20079
- let inString = false;
20080
- for (let idx = startPos;idx < source.length; idx++) {
20081
- const char = source[idx] ?? "";
20082
- const classified = classifyChar(char, source[idx - 1] ?? "", inString);
20083
- inString = classified.nextString;
20084
- if (classified.skip)
19966
+ const sf = ts7.createSourceFile(childFilePath, source, ts7.ScriptTarget.ES2022, true, ts7.ScriptKind.TS);
19967
+ const childDir = dirname19(childFilePath);
19968
+ for (const stmt of sf.statements) {
19969
+ if (!ts7.isImportDeclaration(stmt))
20085
19970
  continue;
20086
- if (char === "{" || char === "(")
20087
- depth++;
20088
- if (char === "}" || char === ")")
20089
- depth--;
20090
- if (depth === 0 && char === ";")
20091
- return idx;
20092
- }
20093
- return startPos;
20094
- }, injectComposableTracking = (code, filePath, useExports) => {
20095
- const moduleId = JSON.stringify(filePath);
20096
- const runtime = [
20097
- `var __hmr_cs = (globalThis.__HMR_COMPOSABLE_STATE__ ??= {});`,
20098
- `var __hmr_mid = ${moduleId};`,
20099
- `var __hmr_prev_refs = __hmr_cs[__hmr_mid];`,
20100
- `var __hmr_idx = {};`,
20101
- `__hmr_cs[__hmr_mid] = {};`,
20102
- `function __hmr_wrap(name, fn) {`,
20103
- ` return function() {`,
20104
- ` var idx = (__hmr_idx[name] = (__hmr_idx[name] ?? -1) + 1);`,
20105
- ` var result = fn.apply(this, arguments);`,
20106
- ` if (result && typeof result === "object") {`,
20107
- ` var refs = {};`,
20108
- ` for (var k in result) {`,
20109
- ` var v = result[k];`,
20110
- ` if (v && typeof v === "object" && "value" in v && !v.effect && typeof v.value !== "function") {`,
20111
- ` refs[k] = v;`,
20112
- ` }`,
20113
- ` }`,
20114
- ` (__hmr_cs[__hmr_mid][name] ??= [])[idx] = refs;`,
20115
- ` if (__hmr_prev_refs && __hmr_prev_refs[name] && __hmr_prev_refs[name][idx]) {`,
20116
- ` var old = __hmr_prev_refs[name][idx];`,
20117
- ` for (var k in old) {`,
20118
- ` var nv = result[k];`,
20119
- ` var ov = old[k];`,
20120
- ` if (nv && ov && typeof nv === "object" && "value" in nv && !nv.effect && typeof nv.value === typeof ov.value) {`,
20121
- ` nv.value = ov.value;`,
20122
- ` }`,
20123
- ` }`,
20124
- ` }`,
20125
- ` }`,
20126
- ` return result;`,
20127
- ` };`,
20128
- `}`
20129
- ].join(`
20130
- `);
20131
- let result = `${runtime}
20132
- ${code}`;
20133
- for (const name of useExports) {
20134
- result = wrapComposableExport(result, name);
19971
+ if (!ts7.isStringLiteral(stmt.moduleSpecifier))
19972
+ continue;
19973
+ const clause = stmt.importClause;
19974
+ if (!clause || clause.isTypeOnly)
19975
+ continue;
19976
+ let matchesName = false;
19977
+ if (clause.name && clause.name.text === parentName)
19978
+ matchesName = true;
19979
+ if (!matchesName && clause.namedBindings && ts7.isNamedImports(clause.namedBindings)) {
19980
+ for (const el of clause.namedBindings.elements) {
19981
+ if (el.isTypeOnly)
19982
+ continue;
19983
+ if (el.name.text === parentName) {
19984
+ matchesName = true;
19985
+ break;
19986
+ }
19987
+ }
19988
+ }
19989
+ if (!matchesName)
19990
+ continue;
19991
+ const spec = stmt.moduleSpecifier.text;
19992
+ if (!spec.startsWith(".") && !spec.startsWith("/")) {
19993
+ return null;
19994
+ }
19995
+ const base = resolve34(childDir, spec);
19996
+ const candidates = [
19997
+ `${base}.ts`,
19998
+ `${base}.tsx`,
19999
+ `${base}/index.ts`,
20000
+ `${base}/index.tsx`
20001
+ ];
20002
+ const angularRootNorm = safeNormalize(angularRoot);
20003
+ for (const candidate of candidates) {
20004
+ try {
20005
+ if (statSync3(candidate).isFile()) {
20006
+ const norm = safeNormalize(candidate);
20007
+ if (!norm.startsWith(angularRootNorm))
20008
+ return null;
20009
+ return norm;
20010
+ }
20011
+ } catch {}
20012
+ }
20013
+ return null;
20135
20014
  }
20136
- return result;
20137
- }, wrapComposableExport = (source, name) => {
20138
- const marker = new RegExp(`export\\s+(?:const|var|let)\\s+${name}\\s*=\\s*`);
20139
- const match = marker.exec(source);
20140
- if (!match)
20141
- return source;
20142
- const insertPos = match.index + match[0].length;
20143
- const endPos = findFunctionEnd(source, insertPos);
20144
- const funcBody = source.slice(insertPos, endPos);
20145
- return `${source.slice(0, insertPos)}__hmr_wrap(${JSON.stringify(name)}, ${funcBody})${source.slice(endPos)}`;
20146
- }, svelteExternalCss, svelteCompiler = null, vueCompiler = null, getLoadedSvelteCompiler = () => {
20147
- if (!svelteCompiler)
20148
- throw new Error("Svelte compiler is not loaded.");
20149
- return svelteCompiler;
20150
- }, getLoadedVueCompiler = () => {
20151
- if (!vueCompiler)
20152
- throw new Error("Vue compiler is not loaded.");
20153
- return vueCompiler;
20154
- }, warmCompilers = async (frameworks2) => {
20155
- const [svelteModule, vueModule] = await Promise.all([
20156
- frameworks2.svelte ? import("svelte/compiler") : undefined,
20157
- frameworks2.vue ? import("@vue/compiler-sfc") : undefined
20158
- ]);
20159
- if (svelteModule) {
20160
- svelteCompiler = svelteModule;
20161
- svelteModule.compile("<script>let x=$state(0)</script>{x}", {
20162
- css: "external",
20163
- dev: true,
20164
- filename: "_warm.svelte",
20165
- generate: "client",
20166
- hmr: true
20167
- });
20015
+ return null;
20016
+ }, getOrBuildIndexes = (userAngularRoot) => {
20017
+ const cached = indexByRoot.get(userAngularRoot);
20018
+ if (cached)
20019
+ return cached;
20020
+ const resource = new Map;
20021
+ const parentFile = new Map;
20022
+ for (const tsPath of walkAngularSourceFiles(userAngularRoot)) {
20023
+ const classes = parseDecoratedClasses(tsPath);
20024
+ const componentDir = dirname19(tsPath);
20025
+ for (const cls of classes) {
20026
+ const entity = {
20027
+ className: cls.className,
20028
+ componentFilePath: tsPath,
20029
+ kind: cls.kind
20030
+ };
20031
+ if (cls.kind === "component") {
20032
+ for (const url of [...cls.templateUrls, ...cls.styleUrls]) {
20033
+ const abs = safeNormalize(resolve34(componentDir, url));
20034
+ const existing = resource.get(abs);
20035
+ if (existing)
20036
+ existing.push(entity);
20037
+ else
20038
+ resource.set(abs, [entity]);
20039
+ }
20040
+ }
20041
+ if (cls.extendsName !== null) {
20042
+ const parentPath = resolveParentClassFile(cls.extendsName, tsPath, userAngularRoot);
20043
+ if (parentPath !== null && parentPath !== safeNormalize(tsPath)) {
20044
+ const existing = parentFile.get(parentPath);
20045
+ if (existing)
20046
+ existing.push(entity);
20047
+ else
20048
+ parentFile.set(parentPath, [entity]);
20049
+ }
20050
+ }
20051
+ }
20168
20052
  }
20169
- if (!vueModule)
20170
- return;
20171
- vueCompiler = vueModule;
20172
- const { descriptor } = vueModule.parse("<script setup>const x=1</script><template>{{x}}</template>", { filename: "_warm.vue" });
20173
- vueModule.compileScript(descriptor, { id: "w", inlineTemplate: false });
20174
- if (!descriptor.template)
20175
- return;
20176
- vueModule.compileTemplate({
20177
- filename: "_warm.vue",
20178
- id: "w",
20179
- source: descriptor.template.content
20053
+ const bundle = { parentFile, resource };
20054
+ indexByRoot.set(userAngularRoot, bundle);
20055
+ return bundle;
20056
+ }, getOrBuildResourceIndex = (userAngularRoot) => getOrBuildIndexes(userAngularRoot).resource, resolveDescendantsOfParent = (params) => {
20057
+ const norm = safeNormalize(params.changedFilePath);
20058
+ let rootStat;
20059
+ try {
20060
+ rootStat = statSync3(params.userAngularRoot);
20061
+ } catch {
20062
+ return [];
20063
+ }
20064
+ if (!rootStat.isDirectory())
20065
+ return [];
20066
+ const bundle = getOrBuildIndexes(params.userAngularRoot);
20067
+ return bundle.parentFile.get(norm) ?? [];
20068
+ }, invalidateResourceIndex = () => {
20069
+ indexByRoot.clear();
20070
+ };
20071
+ var init_resolveOwningComponents = __esm(() => {
20072
+ ENTITY_DECORATORS = {
20073
+ Component: "component",
20074
+ Directive: "directive",
20075
+ Pipe: "pipe",
20076
+ Injectable: "service"
20077
+ };
20078
+ indexByRoot = new Map;
20079
+ });
20080
+
20081
+ // src/dev/webSocket.ts
20082
+ var trySendMessage = (client2, messageStr) => {
20083
+ try {
20084
+ client2.send(messageStr);
20085
+ return true;
20086
+ } catch {
20087
+ return false;
20088
+ }
20089
+ }, broadcastToClients = (state, message) => {
20090
+ const messageStr = JSON.stringify({
20091
+ ...message,
20092
+ timestamp: Date.now()
20180
20093
  });
20181
- }, compileSvelteModule = (raw, filePath) => {
20182
- const compiler = getLoadedSvelteCompiler();
20183
- const source = tsTranspiler2.transformSync(raw);
20184
- return compiler.compileModule(source, {
20185
- dev: true,
20186
- filename: filePath
20187
- }).js.code;
20188
- }, compileSvelteComponent = (raw, filePath, projectRoot, enableAsync = false) => {
20189
- const compiler = getLoadedSvelteCompiler();
20190
- const compiled = compiler.compile(raw, {
20191
- css: "external",
20192
- dev: true,
20193
- experimental: {
20194
- async: enableAsync
20195
- },
20196
- filename: filePath,
20197
- generate: "client",
20198
- hmr: true
20094
+ const shouldRemove = (client2) => {
20095
+ return !trySendMessage(client2, messageStr);
20096
+ };
20097
+ const clientsToRemove = [];
20098
+ state.connectedClients.forEach((client2) => {
20099
+ if (shouldRemove(client2))
20100
+ clientsToRemove.push(client2);
20199
20101
  });
20200
- let { code } = compiled.js;
20201
- if (compiled.css?.code) {
20202
- const cssPath = `${filePath}.css`;
20203
- svelteExternalCss.set(cssPath, compiled.css.code);
20204
- const cssUrl = srcUrl(relative14(projectRoot, cssPath), projectRoot);
20205
- code = `import "${cssUrl}";
20206
- ${code}`;
20102
+ clientsToRemove.forEach((client2) => {
20103
+ state.connectedClients.delete(client2);
20104
+ });
20105
+ }, handleClientConnect = (state, client2, manifest) => {
20106
+ state.connectedClients.add(client2);
20107
+ const serverVersions = serializeModuleVersions(state.moduleVersions);
20108
+ client2.send(JSON.stringify({
20109
+ data: {
20110
+ manifest,
20111
+ serverVersions
20112
+ },
20113
+ timestamp: Date.now(),
20114
+ type: "manifest"
20115
+ }));
20116
+ client2.send(JSON.stringify({
20117
+ message: "HMR client connected successfully",
20118
+ timestamp: Date.now(),
20119
+ type: "connected"
20120
+ }));
20121
+ }, handleClientDisconnect = (state, client2) => {
20122
+ state.connectedClients.delete(client2);
20123
+ }, parseJsonSafe = (raw) => JSON.parse(raw), parseMessage = (message) => {
20124
+ if (typeof message === "string") {
20125
+ return parseJsonSafe(message);
20207
20126
  }
20208
- const moduleUrl = `${SRC_PREFIX}${relative14(projectRoot, filePath).replace(/\\/g, "/")}`;
20209
- code = code.replace(/if\s*\(import\.meta\.hot\)\s*\{/, `if (typeof window !== "undefined") {
20210
- ` + ` if (!window.__SVELTE_HMR_ACCEPT__) window.__SVELTE_HMR_ACCEPT__ = {};
20211
- ` + ` var __hmr_accept = function(cb) { window.__SVELTE_HMR_ACCEPT__[${JSON.stringify(moduleUrl)}] = cb; };`);
20212
- return code.replace(/import\.meta\.hot\.accept\(/g, "__hmr_accept(");
20213
- }, transformSvelteFile = async (filePath, projectRoot, rewriter, stylePreprocessors) => {
20214
- const raw = readFileSync19(filePath, "utf-8");
20215
- if (!svelteCompiler) {
20216
- svelteCompiler = await import("svelte/compiler");
20127
+ if (message instanceof Buffer) {
20128
+ return parseJsonSafe(message.toString());
20217
20129
  }
20218
- const isModule = filePath.endsWith(".svelte.ts") || filePath.endsWith(".svelte.js");
20219
- const loweredAwaitSource = isModule ? { code: raw, transformed: false } : lowerSvelteAwaitSlotSyntax(raw);
20220
- const loweredSource = isModule ? loweredAwaitSource : lowerSvelteIslandSyntax(loweredAwaitSource.code, "client");
20221
- const source = isModule ? loweredSource.code : (await svelteCompiler.preprocess(loweredSource.code, createSvelteStylePreprocessor(stylePreprocessors))).code;
20222
- const enableAsync = loweredAwaitSource.transformed || loweredSource.transformed;
20223
- const code = isModule ? compileSvelteModule(source, filePath) : compileSvelteComponent(source, filePath, projectRoot, enableAsync);
20224
- return rewriteImports(code, filePath, projectRoot, rewriter);
20225
- }, compileVueTemplate = (descriptor, compiledScript, filePath, componentId) => {
20226
- const compiler = getLoadedVueCompiler();
20227
- const scriptContent = compiledScript.content;
20228
- if (!descriptor.template)
20229
- return scriptContent;
20230
- const isScoped = descriptor.styles.some((style) => style.scoped);
20231
- const templateResult = compiler.compileTemplate({
20232
- compilerOptions: {
20233
- bindingMetadata: compiledScript.bindings,
20234
- expressionPlugins: ["typescript"],
20235
- isCustomElement: (tag) => tag === "absolute-island",
20236
- prefixIdentifiers: true
20237
- },
20238
- filename: filePath,
20239
- id: componentId,
20240
- scoped: isScoped,
20241
- source: descriptor.template.content
20242
- });
20243
- let code = scriptContent.replace("export default", "const __script__ =");
20244
- code += `
20245
- ${templateResult.code}`;
20246
- code += `
20247
- __script__.render = render;`;
20248
- code += `
20249
- export default __script__;`;
20250
- return code;
20251
- }, compileVueStyles = async (descriptor, filePath, componentId, code, stylePreprocessors) => {
20252
- if (descriptor.styles.length === 0)
20253
- return code;
20254
- const compiler = getLoadedVueCompiler();
20255
- const cssCode = (await Promise.all(descriptor.styles.map(async (style) => compiler.compileStyle({
20256
- filename: filePath,
20257
- id: `data-v-${componentId}`,
20258
- scoped: Boolean(style.scoped),
20259
- source: style.lang ? await compileStyleSource(filePath, style.content, style.lang, stylePreprocessors) : style.content,
20260
- trim: true
20261
- }).code))).join(`
20262
- `);
20263
- const escaped = cssCode.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
20264
- const hmrId = JSON.stringify(filePath);
20265
- const cssInjection = [
20266
- `var __style=document.createElement('style');`,
20267
- `__style.textContent=\`${escaped}\`;`,
20268
- `__style.dataset.hmrId=${hmrId};`,
20269
- `var __prev=document.querySelector('style[data-hmr-id="${filePath}"]');`,
20270
- `if(__prev)__prev.remove();`,
20271
- `document.head.appendChild(__style);`
20272
- ].join("");
20273
- return `${cssInjection}
20274
- ${code}`;
20275
- }, transformVueFile = async (filePath, projectRoot, rewriter, vueDir, stylePreprocessors) => {
20276
- const rawSource = readFileSync19(filePath, "utf-8");
20277
- const raw = addAutoRouterSetupApp(rawSource);
20278
- if (!vueCompiler) {
20279
- vueCompiler = await import("@vue/compiler-sfc");
20130
+ if (message instanceof ArrayBuffer) {
20131
+ return parseJsonSafe(new TextDecoder().decode(new Uint8Array(message)));
20280
20132
  }
20281
- const fileName = basename11(filePath, ".vue");
20282
- const componentId = fileName.toLowerCase();
20283
- const { descriptor } = vueCompiler.parse(raw, { filename: filePath });
20284
- const hasScript = descriptor.script || descriptor.scriptSetup;
20285
- const compiledScript = hasScript ? vueCompiler.compileScript(descriptor, {
20286
- id: componentId,
20287
- inlineTemplate: false
20288
- }) : { bindings: {}, content: "export default {};" };
20289
- const compiledSfcScript = {
20290
- bindings: compiledScript.bindings ?? {},
20291
- content: compiledScript.content
20292
- };
20293
- let code = compileVueTemplate(descriptor, compiledSfcScript, filePath, componentId);
20294
- code = await compileVueStyles(descriptor, filePath, componentId, code, stylePreprocessors);
20295
- code = tsTranspiler2.transformSync(code);
20296
- code = injectVueHmr(code, filePath, projectRoot, vueDir);
20297
- return rewriteImports(code, filePath, projectRoot, rewriter);
20298
- }, injectVueHmr = (code, filePath, projectRoot, vueDir) => {
20299
- const hmrBase = vueDir ? resolve34(vueDir) : projectRoot;
20300
- const hmrId = relative14(hmrBase, filePath).replace(/\\/g, "/").replace(/\.vue$/, "");
20301
- let result = code.replace(/export\s+default\s+/, "var __hmr_comp__ = ");
20302
- result += [
20303
- "",
20304
- `__hmr_comp__.__hmrId = ${JSON.stringify(hmrId)};`,
20305
- `if (typeof __VUE_HMR_RUNTIME__ !== "undefined") {`,
20306
- ` __VUE_HMR_RUNTIME__.createRecord(${JSON.stringify(hmrId)}, __hmr_comp__);`,
20307
- ` __VUE_HMR_RUNTIME__.rerender(${JSON.stringify(hmrId)}, __hmr_comp__.render);`,
20308
- `}`,
20309
- "export default __hmr_comp__;"
20310
- ].join(`
20311
- `);
20312
- return result;
20313
- }, resolveSvelteModulePath = (path) => {
20314
- if (existsSync26(path))
20315
- return path;
20316
- if (existsSync26(`${path}.ts`))
20317
- return `${path}.ts`;
20318
- if (existsSync26(`${path}.js`))
20319
- return `${path}.js`;
20320
- return path;
20321
- }, jsResponse = (body) => {
20322
- const etag = `"${Bun.hash(body).toString(BASE_36_RADIX)}"`;
20323
- return new Response(body, {
20324
- headers: {
20325
- "Cache-Control": "no-cache",
20326
- "Content-Type": "application/javascript",
20327
- ETag: etag
20328
- }
20329
- });
20330
- }, handleCssRequest = (filePath) => {
20331
- const raw = readFileSync19(filePath, "utf-8");
20332
- const escaped = raw.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
20333
- return [
20334
- `const style = document.createElement('style');`,
20335
- `style.textContent = \`${escaped}\`;`,
20336
- `style.dataset.hmrId = ${JSON.stringify(filePath)};`,
20337
- `const existing = document.querySelector(\`style[data-hmr-id="${filePath}"]\`);`,
20338
- `if (existing) existing.remove();`,
20339
- `document.head.appendChild(style);`
20340
- ].join(`
20341
- `);
20342
- }, generateSvelteHmrBootstrap = (moduleUrl, vendorPaths, timestamp) => {
20343
- const sveltePath = vendorPaths["svelte"] || "/svelte/vendor/svelte.js";
20344
- return [
20345
- `import { mount, unmount } from "${sveltePath}";`,
20346
- `const { default: Component } = await import("${moduleUrl}?t=${timestamp}");`,
20347
- ``,
20348
- `// Extract count from DOM before unmount (survives across runtime instances)`,
20349
- `var countBtn = document.querySelector("button");`,
20350
- `var countMatch = countBtn && countBtn.textContent && countBtn.textContent.match(/(\\d+)/);`,
20351
- `var domCount = countMatch ? parseInt(countMatch[1], 10) : null;`,
20352
- ``,
20353
- `var preservedState = window.__HMR_PRESERVED_STATE__ || {};`,
20354
- `if (domCount !== null && preservedState.initialCount === undefined) {`,
20355
- ` preservedState.initialCount = domCount;`,
20356
- `}`,
20357
- `var initialProps = window.__INITIAL_PROPS__ || {};`,
20358
- `var mergedProps = Object.assign({}, initialProps, preservedState);`,
20359
- ``,
20360
- `// Update __INITIAL_PROPS__ so subsequent HMR cycles start with current state`,
20361
- `if (domCount !== null) window.__INITIAL_PROPS__ = Object.assign({}, initialProps, { initialCount: domCount });`,
20362
- ``,
20363
- `if (typeof window.__SVELTE_UNMOUNT__ === "function") {`,
20364
- ` try { window.__SVELTE_UNMOUNT__(); } catch (err) { /* ignore */ }`,
20365
- `}`,
20366
- ``,
20367
- `var target = document.getElementById("__absolute_svelte_root__") || document.body;`,
20368
- `var component = mount(Component, { target, props: mergedProps });`,
20369
- `window.__SVELTE_COMPONENT__ = component;`,
20370
- `window.__SVELTE_UNMOUNT__ = function() { unmount(component); };`,
20371
- `window.__HMR_PRESERVED_STATE__ = undefined;`
20372
- ].join(`
20373
- `);
20374
- }, generateVueHmrBootstrap = (moduleUrl, vendorPaths, timestamp) => {
20375
- const vuePath = vendorPaths["vue"] || "/vue/vendor/vue.js";
20376
- return [
20377
- `import { createApp } from "${vuePath}";`,
20378
- `const { default: Component } = await import("${moduleUrl}?t=${timestamp}");`,
20379
- ``,
20380
- `// Extract count from DOM before unmount (works across Vue instances)`,
20381
- `var countBtn = document.querySelector("button");`,
20382
- `var countMatch = countBtn && countBtn.textContent && countBtn.textContent.match(/(\\d+)/);`,
20383
- `var domCount = countMatch ? parseInt(countMatch[1], 10) : null;`,
20384
- ``,
20385
- `var preservedState = window.__HMR_PRESERVED_STATE__ || {};`,
20386
- `if (domCount !== null && preservedState.initialCount === undefined) {`,
20387
- ` preservedState.initialCount = domCount;`,
20388
- `}`,
20389
- `var initialProps = window.__INITIAL_PROPS__ || {};`,
20390
- `var mergedProps = Object.assign({}, initialProps, preservedState);`,
20391
- ``,
20392
- `// Update __INITIAL_PROPS__ so subsequent HMR cycles start with current state`,
20393
- `if (domCount !== null) window.__INITIAL_PROPS__ = Object.assign({}, initialProps, { initialCount: domCount });`,
20394
- ``,
20395
- `var root = document.getElementById("root");`,
20396
- `var savedHTML = root ? root.innerHTML : "";`,
20397
- `if (window.__VUE_APP__) {`,
20398
- ` window.__VUE_APP__.unmount();`,
20399
- ` window.__VUE_APP__ = null;`,
20400
- `}`,
20401
- `if (root) root.innerHTML = savedHTML;`,
20402
- ``,
20403
- `var app = createApp(Component, mergedProps);`,
20404
- `app.mount(root);`,
20405
- `window.__VUE_APP__ = app;`,
20406
- `window.__HMR_PRESERVED_STATE__ = undefined;`
20407
- ].join(`
20408
- `);
20409
- }, handleStubRequest = async (pathname) => {
20410
- const specifier = decodeURIComponent(pathname.slice("/@stub/".length));
20411
- const stubCode = await buildStubCode(specifier);
20412
- return new Response(stubCode, {
20413
- headers: {
20414
- "Cache-Control": "no-cache",
20415
- "Content-Type": "application/javascript"
20133
+ if (ArrayBuffer.isView(message)) {
20134
+ const view = new Uint8Array(message.buffer, message.byteOffset, message.byteLength);
20135
+ return parseJsonSafe(new TextDecoder().decode(view));
20136
+ }
20137
+ if (typeof message === "object" && message !== null) {
20138
+ return message;
20139
+ }
20140
+ return null;
20141
+ }, handleParsedMessage = (state, client2, data) => {
20142
+ switch (data.type) {
20143
+ case "ping":
20144
+ client2.send(JSON.stringify({
20145
+ timestamp: Date.now(),
20146
+ type: "pong"
20147
+ }));
20148
+ break;
20149
+ case "request-rebuild":
20150
+ break;
20151
+ case "ready":
20152
+ if (data.framework) {
20153
+ state.activeFrameworks.add(data.framework);
20154
+ }
20155
+ break;
20156
+ case "hmr-timing":
20157
+ logHmrUpdate(state.lastHmrPath ?? "", state.lastHmrFramework, data.duration);
20158
+ break;
20159
+ case "angular:hmr-ack": {
20160
+ const tag = data.tier === "tier-0" ? "tier-0" : "tier-1a";
20161
+ const suffix = data.error ? ` FAILED \u2014 ${data.error}` : ` applied in ${data.applyMs.toFixed(0)}ms`;
20162
+ logInfo(`[ng-hmr] ${tag} ${data.className}${suffix}`);
20163
+ break;
20416
20164
  }
20417
- });
20418
- }, BUN_WRAP_MODULE, handleBunWrapRequest = () => new Response(BUN_WRAP_MODULE, {
20419
- headers: {
20420
- "Cache-Control": "no-cache",
20421
- "Content-Type": "application/javascript"
20422
20165
  }
20423
- }), buildStubCode = async (specifier) => {
20166
+ }, handleHMRMessage = (state, client2, message) => {
20424
20167
  try {
20425
- const mod = await import(specifier);
20426
- const names = Object.keys(mod).filter((key) => key !== "default" && key !== "__esModule");
20427
- if (names.length === 0)
20428
- return `export default {};
20429
- `;
20430
- const noops = names.map((n) => `export const ${n} = () => {};`).join(`
20431
- `);
20432
- return `${noops}
20433
- export default {};
20434
- `;
20435
- } catch {
20436
- return `export default {};
20437
- `;
20438
- }
20439
- }, handleHmrBootstrap = (pathname, vendorPaths) => {
20440
- const rest = pathname.slice("/@hmr/".length);
20441
- const slashIdx = rest.indexOf("/");
20442
- if (slashIdx === UNFOUND_INDEX)
20443
- return;
20444
- const framework = rest.slice(0, slashIdx);
20445
- const componentRelPath = rest.slice(slashIdx + 1);
20446
- const url = `${SRC_PREFIX}${componentRelPath}`;
20447
- const timestamp = String(Date.now());
20448
- const generators = {
20449
- svelte: generateSvelteHmrBootstrap,
20450
- vue: generateVueHmrBootstrap
20451
- };
20452
- const generate = generators[framework];
20453
- if (!generate)
20454
- return;
20455
- return jsResponse(generate(url, vendorPaths, timestamp));
20456
- }, handleVirtualSvelteCss = (cssCheckPath) => {
20457
- const virtualCss = svelteExternalCss.get(cssCheckPath);
20458
- if (!virtualCss)
20459
- return;
20460
- const escaped = virtualCss.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
20461
- return jsResponse(`var s=document.createElement('style');s.textContent=\`${escaped}\`;s.dataset.svelteHmr=${JSON.stringify(cssCheckPath)};var p=document.querySelector('style[data-svelte-hmr="${cssCheckPath}"]');if(p)p.remove();document.head.appendChild(s);`);
20462
- }, resolveSourcePath = (relPath, projectRoot) => {
20463
- const filePath = resolve34(projectRoot, relPath);
20464
- const ext = extname9(filePath);
20465
- if (ext === ".svelte")
20466
- return { ext, filePath: resolveSvelteModulePath(filePath) };
20467
- if (ext)
20468
- return { ext, filePath };
20469
- const found = MODULE_EXTENSIONS.find((candidate) => existsSync26(filePath + candidate));
20470
- if (!found)
20471
- return { ext, filePath };
20472
- const resolved = filePath + found;
20473
- if (found === ".svelte")
20474
- return { ext: found, filePath: resolveSvelteModulePath(resolved) };
20475
- return { ext: found, filePath: resolved };
20476
- }, transformAndCache = async (filePath, ext, projectRoot, rewriter, vueDir, stylePreprocessors) => {
20477
- if (ext === ".css")
20478
- return jsResponse(handleCssRequest(filePath));
20479
- const isSvelte = ext === ".svelte" || filePath.endsWith(".svelte.ts") || filePath.endsWith(".svelte.js");
20480
- const cached = getTransformed(filePath);
20481
- if (cached)
20482
- return jsResponse(cached);
20483
- if (isSvelte)
20484
- return transformAndCacheSvelte(filePath, projectRoot, rewriter, stylePreprocessors);
20485
- if (ext === ".vue")
20486
- return transformAndCacheVue(filePath, projectRoot, rewriter, vueDir, stylePreprocessors);
20487
- if (!TRANSPILABLE.has(ext))
20488
- return;
20489
- const stat3 = statSync3(filePath);
20490
- const resolvedVueDir = vueDir ? resolve34(vueDir) : undefined;
20491
- let content = REACT_EXTENSIONS.has(ext) ? transformReactFile(filePath, projectRoot, rewriter) : transformPlainFile(filePath, projectRoot, rewriter, resolvedVueDir);
20492
- const isAngularGeneratedJs = ext === ".js" && filePath.replace(/\\/g, "/").includes("/.absolutejs/generated/angular/");
20493
- if (isAngularGeneratedJs) {
20494
- const userAngularRoot = await getAngularUserRoot(projectRoot);
20495
- if (userAngularRoot) {
20496
- const { applyAngularHmrInjection: applyAngularHmrInjection2 } = await Promise.resolve().then(() => (init_hmrInjectionPlugin(), exports_hmrInjectionPlugin));
20497
- const { getFrameworkGeneratedDir: getFrameworkGeneratedDir2 } = await Promise.resolve().then(() => (init_generatedDir(), exports_generatedDir));
20498
- const generatedAngularRoot = getFrameworkGeneratedDir2("angular");
20499
- const transformed = applyAngularHmrInjection2(content, filePath, {
20500
- generatedAngularRoot,
20501
- projectRoot,
20502
- userAngularRoot
20503
- });
20504
- if (transformed !== undefined) {
20505
- content = rewriter ? rewriteImports(transformed, filePath, projectRoot, rewriter) : transformed;
20506
- }
20168
+ const parsedData = parseMessage(message);
20169
+ if (parsedData === null) {
20170
+ return;
20507
20171
  }
20508
- }
20509
- setTransformed(filePath, content, stat3.mtimeMs, extractImportedFiles(content, projectRoot));
20510
- return jsResponse(content);
20511
- }, cachedAngularUserRoot, getAngularUserRoot = async (_projectRoot) => {
20512
- if (cachedAngularUserRoot !== undefined)
20513
- return cachedAngularUserRoot;
20514
- cachedAngularUserRoot = configuredAngularUserRoot ?? null;
20515
- return cachedAngularUserRoot;
20516
- }, configuredAngularUserRoot, transformAndCacheSvelte = async (filePath, projectRoot, rewriter, stylePreprocessors) => {
20517
- const stat3 = statSync3(filePath);
20518
- const content = await transformSvelteFile(filePath, projectRoot, rewriter, stylePreprocessors);
20519
- setTransformed(filePath, content, stat3.mtimeMs, extractImportedFiles(content, projectRoot));
20520
- return jsResponse(content);
20521
- }, transformAndCacheVue = async (filePath, projectRoot, rewriter, vueDir, stylePreprocessors) => {
20522
- const stat3 = statSync3(filePath);
20523
- const content = await transformVueFile(filePath, projectRoot, rewriter, vueDir, stylePreprocessors);
20524
- setTransformed(filePath, content, stat3.mtimeMs, extractImportedFiles(content, projectRoot));
20525
- return jsResponse(content);
20526
- }, transformErrorResponse = (err) => {
20527
- const errMsg = err instanceof Error ? err.message : String(err);
20528
- return new Response(`console.error('[ModuleServer] Transform error:', ${JSON.stringify(errMsg)});`, {
20529
- headers: { "Content-Type": "application/javascript" },
20530
- status: 500
20531
- });
20532
- }, createModuleServer = (config) => {
20533
- const { projectRoot, vendorPaths, frameworkDirs, stylePreprocessors } = config;
20534
- const rewriter = buildImportRewriter(vendorPaths);
20535
- if (frameworkDirs?.angular) {
20536
- configuredAngularUserRoot = frameworkDirs.angular;
20537
- cachedAngularUserRoot = undefined;
20538
- }
20539
- return async (pathname) => {
20540
- if (pathname.startsWith("/@stub/"))
20541
- return handleStubRequest(pathname);
20542
- if (pathname.startsWith("/@hmr/"))
20543
- return handleHmrBootstrap(pathname, vendorPaths);
20544
- if (!pathname.startsWith(SRC_PREFIX))
20172
+ if (!isValidHMRClientMessage(parsedData)) {
20545
20173
  return;
20546
- const relPath = pathname.slice(SRC_PREFIX.length);
20547
- if (relPath === "bun:wrap" || relPath.startsWith("bun:wrap?"))
20548
- return handleBunWrapRequest();
20549
- const virtualCssResponse = handleVirtualSvelteCss(resolve34(projectRoot, relPath));
20550
- if (virtualCssResponse)
20551
- return virtualCssResponse;
20552
- const { filePath, ext } = resolveSourcePath(relPath, projectRoot);
20553
- try {
20554
- return await transformAndCache(filePath, ext, projectRoot, rewriter, frameworkDirs?.vue, stylePreprocessors);
20555
- } catch (err) {
20556
- return transformErrorResponse(err);
20557
20174
  }
20558
- };
20559
- }, SRC_IMPORT_RE, extractImportedFiles = (content, projectRoot) => {
20560
- const files = [];
20561
- let match;
20562
- SRC_IMPORT_RE.lastIndex = 0;
20563
- while ((match = SRC_IMPORT_RE.exec(content)) !== null) {
20564
- if (match[1])
20565
- files.push(resolve34(projectRoot, match[1]));
20566
- }
20567
- return files;
20568
- }, invalidateModule = (filePath) => {
20569
- const resolved = resolve34(filePath);
20570
- invalidate(filePath);
20571
- if (resolved !== filePath)
20572
- invalidate(resolved);
20573
- mtimeCache.delete(filePath);
20574
- mtimeCache.delete(resolved);
20575
- }, warmCache = (pathname) => {
20576
- if (!pathname.startsWith(SRC_PREFIX))
20577
- return;
20578
- if (!globalModuleServer)
20579
- return;
20580
- globalModuleServer(pathname);
20581
- }, globalModuleServer = null, SRC_URL_PREFIX, setGlobalModuleServer = (handler) => {
20582
- globalModuleServer = handler;
20175
+ handleParsedMessage(state, client2, parsedData);
20176
+ } catch {}
20583
20177
  };
20584
- var init_moduleServer = __esm(() => {
20585
- init_constants();
20586
- init_resolvePackageImport();
20587
- init_vueAutoRouterTransform();
20588
- init_sourceMetadata();
20589
- init_stylePreprocessor();
20590
- init_lowerAwaitSlotSyntax();
20591
- init_lowerIslandSyntax();
20178
+ var init_webSocket = __esm(() => {
20592
20179
  init_logger();
20593
- init_transformCache();
20594
- jsTranspiler2 = new Bun.Transpiler({
20595
- loader: "js",
20596
- trimUnusedImports: true
20597
- });
20598
- tsTranspiler2 = new Bun.Transpiler({
20599
- loader: "ts",
20600
- trimUnusedImports: true
20601
- });
20602
- tsxTranspiler = new Bun.Transpiler({
20603
- loader: "tsx",
20604
- trimUnusedImports: true
20605
- });
20606
- TRANSPILABLE = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs"]);
20607
- ALL_EXPORTS_RE = /export\s+(?:type|interface|const|let|var|function|class|enum|abstract\s+class)\s+(\w+)/g;
20608
- STRING_CONTENTS_RE = /`(?:[^`\\]|\\.)*`|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/gs;
20609
- IMPORT_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js", ".svelte", ".vue"];
20610
- SIDE_EFFECT_EXTENSIONS = [
20611
- ".tsx",
20612
- ".ts",
20613
- ".jsx",
20614
- ".js",
20615
- ".css",
20616
- ".svelte",
20617
- ".vue"
20618
- ];
20619
- MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js", ".svelte", ".vue"];
20620
- RESOLVED_MODULE_EXTENSIONS = new Set([
20621
- ...IMPORT_EXTENSIONS,
20622
- ...SIDE_EFFECT_EXTENSIONS,
20623
- ".mjs",
20624
- ".css"
20625
- ]);
20626
- REACT_EXTENSIONS = new Set([".tsx", ".jsx"]);
20627
- mtimeCache = new Map;
20628
- NODE_BUILTIN_RE = /^(?:node:|(?:assert|async_hooks|buffer|child_process|cluster|console|constants|crypto|dgram|dns|domain|events|fs|http|http2|https|inspector|module|net|os|path|perf_hooks|process|punycode|querystring|readline|repl|stream|string_decoder|sys|timers|tls|trace_events|tty|url|util|v8|vm|wasi|worker_threads|zlib)(?:\/|$))/;
20629
- JSX_AUTO_RE = /\b(jsxDEV_[a-z0-9]+)\b/;
20630
- JSXS_AUTO_RE = /\b(jsxs_[a-z0-9]+)\b/;
20631
- JSX_PROD_RE = /\b(jsx_[a-z0-9]+)\b/;
20632
- FRAGMENT_RE = /\b(Fragment_[a-z0-9]+)\b/;
20633
- reactTranspilerOptions = {
20634
- loader: "tsx",
20635
- reactFastRefresh: true,
20636
- trimUnusedImports: true
20637
- };
20638
- reactTranspiler = new Bun.Transpiler(reactTranspilerOptions);
20639
- reactFastRefreshSupported = probeReactFastRefresh();
20640
- svelteExternalCss = new Map;
20641
- BUN_WRAP_MODULE = `
20642
- export function __legacyDecorateClassTS(decorators, target, key, desc) {
20643
- var c = arguments.length;
20644
- var r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc;
20645
- var d;
20646
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
20647
- r = Reflect.decorate(decorators, target, key, desc);
20648
- } else {
20649
- for (var i = decorators.length - 1; i >= 0; i--) {
20650
- if (d = decorators[i]) {
20651
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
20652
- }
20653
- }
20654
- }
20655
- if (c > 3 && r) Object.defineProperty(target, key, r);
20656
- return r;
20657
- }
20658
- export function __legacyMetadataTS(k, v) {
20659
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
20660
- return Reflect.metadata(k, v);
20661
- }
20662
- }
20663
- `.trim();
20664
- SRC_IMPORT_RE = /\/@src\/([^"'?\s]+)/g;
20665
- SRC_URL_PREFIX = SRC_PREFIX;
20666
20180
  });
20667
20181
 
20668
- // src/build/rewriteImports.ts
20669
- var exports_rewriteImports = {};
20670
- __export(exports_rewriteImports, {
20671
- rewriteVendorDirectories: () => rewriteVendorDirectories2,
20672
- rewriteImports: () => rewriteImports2
20673
- });
20674
- var rewriteImports2 = async (outputPaths, vendorPaths) => {
20675
- const jsFiles = outputPaths.filter((path) => path.endsWith(".js"));
20676
- if (jsFiles.length === 0)
20677
- return;
20678
- if (Object.keys(vendorPaths).length === 0)
20679
- return;
20680
- await Promise.all(jsFiles.map(async (filePath) => {
20681
- let original;
20682
- try {
20683
- original = await Bun.file(filePath).text();
20684
- } catch (err) {
20685
- const code = err.code;
20686
- if (code === "ENOENT")
20687
- return;
20688
- throw err;
20689
- }
20690
- const rewritten = rewriteImportsInContent(original, vendorPaths);
20691
- if (rewritten === original)
20692
- return;
20693
- try {
20694
- await Bun.write(filePath, rewritten);
20695
- } catch (err) {
20696
- const code = err.code;
20697
- if (code === "ENOENT")
20698
- return;
20699
- throw err;
20700
- }
20701
- }));
20702
- }, rewriteVendorDirectories2;
20703
- var init_rewriteImports = __esm(() => {
20704
- init_rewriteImportsPlugin();
20705
- rewriteVendorDirectories2 = rewriteVendorDirectories;
20182
+ // src/core/ssrCache.ts
20183
+ var dirtyFrameworks, isSsrCacheDirty = (framework) => dirtyFrameworks.has(framework), markSsrCacheDirty = (framework) => {
20184
+ dirtyFrameworks.add(framework);
20185
+ };
20186
+ var init_ssrCache = __esm(() => {
20187
+ dirtyFrameworks = new Set;
20706
20188
  });
20707
20189
 
20708
- // src/dev/angular/resolveOwningComponents.ts
20709
- var exports_resolveOwningComponents = {};
20710
- __export(exports_resolveOwningComponents, {
20711
- resolveOwningComponents: () => resolveOwningComponents,
20712
- resolveDescendantsOfParent: () => resolveDescendantsOfParent,
20713
- invalidateResourceIndex: () => invalidateResourceIndex
20190
+ // src/dev/moduleServer.ts
20191
+ var exports_moduleServer = {};
20192
+ __export(exports_moduleServer, {
20193
+ warnIfReactFastRefreshUnsupported: () => warnIfReactFastRefreshUnsupported,
20194
+ warmCompilers: () => warmCompilers,
20195
+ warmCache: () => warmCache,
20196
+ setGlobalModuleServer: () => setGlobalModuleServer,
20197
+ invalidateModule: () => invalidateModule,
20198
+ createModuleServer: () => createModuleServer,
20199
+ SRC_URL_PREFIX: () => SRC_URL_PREFIX
20714
20200
  });
20715
- import { readdirSync as readdirSync2, readFileSync as readFileSync20, statSync as statSync4 } from "fs";
20716
- import { dirname as dirname20, extname as extname10, join as join30, resolve as resolve35 } from "path";
20717
- import ts7 from "typescript";
20718
- var ENTITY_DECORATORS, isAngularSourceFile = (file5) => file5.endsWith(".ts") || file5.endsWith(".tsx"), walkAngularSourceFiles = (root) => {
20719
- const out = [];
20720
- const visit = (dir) => {
20721
- let entries;
20201
+ import { existsSync as existsSync26, readFileSync as readFileSync20, statSync as statSync4 } from "fs";
20202
+ import { basename as basename11, dirname as dirname20, extname as extname10, join as join30, resolve as resolve35, relative as relative14 } from "path";
20203
+ var SRC_PREFIX = "/@src/", jsTranspiler2, tsTranspiler2, tsxTranspiler, TRANSPILABLE, ALL_EXPORTS_RE, STRING_CONTENTS_RE, preserveTypeExports = (originalSource, transpiled, valueExports) => {
20204
+ const codeOnly = originalSource.replace(STRING_CONTENTS_RE, '""');
20205
+ const allExports = [];
20206
+ let match;
20207
+ ALL_EXPORTS_RE.lastIndex = 0;
20208
+ while ((match = ALL_EXPORTS_RE.exec(codeOnly)) !== null) {
20209
+ if (match[1])
20210
+ allExports.push(match[1]);
20211
+ }
20212
+ const valueSet = new Set(valueExports);
20213
+ const typeExports = allExports.filter((exp) => !valueSet.has(exp));
20214
+ if (typeExports.length === 0)
20215
+ return transpiled;
20216
+ const stubs = typeExports.map((name) => `export const ${name} = undefined;`).join(`
20217
+ `);
20218
+ return `${transpiled}
20219
+ ${stubs}
20220
+ `;
20221
+ }, resolveRelativeExtension = (srcPath, projectRoot, extensions) => {
20222
+ const found = extensions.find((ext) => existsSync26(resolve35(projectRoot, srcPath + ext)));
20223
+ return found ? srcPath + found : srcPath;
20224
+ }, IMPORT_EXTENSIONS, SIDE_EFFECT_EXTENSIONS, MODULE_EXTENSIONS, RESOLVED_MODULE_EXTENSIONS, REACT_EXTENSIONS, escapeRegex3 = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), buildImportRewriter = (vendorPaths) => {
20225
+ const entries = Object.entries(vendorPaths).sort(([a], [b2]) => b2.length - a.length);
20226
+ if (entries.length === 0)
20227
+ return null;
20228
+ const alt = entries.map(([spec]) => escapeRegex3(spec)).join("|");
20229
+ const lookup = new Map(entries);
20230
+ const vendorRegex = new RegExp(`((?:from|import)\\s*["']|import\\s*\\(\\s*["'])(${alt})(["'](?:\\s*[;)]?)?)`, "g");
20231
+ return { lookup, vendorRegex };
20232
+ }, mtimeCache, buildVersion = (mtime, absPath) => {
20233
+ const invalidationVersion = getInvalidationVersion(absPath);
20234
+ return invalidationVersion > 0 ? `${mtime}.${invalidationVersion}` : `${mtime}`;
20235
+ }, srcUrl = (relPath, projectRoot) => {
20236
+ const base = `${SRC_PREFIX}${relPath.replace(/\\/g, "/")}`;
20237
+ const absPath = resolve35(projectRoot, relPath);
20238
+ const cached = mtimeCache.get(absPath);
20239
+ if (cached !== undefined)
20240
+ return `${base}?v=${buildVersion(cached, absPath)}`;
20241
+ try {
20242
+ const mtime = Math.round(statSync4(absPath).mtimeMs);
20243
+ mtimeCache.set(absPath, mtime);
20244
+ return `${base}?v=${buildVersion(mtime, absPath)}`;
20245
+ } catch {
20246
+ return base;
20247
+ }
20248
+ }, resolveRelativeImport = (relPath, fileDir, projectRoot, extensions) => {
20249
+ const absPath = resolve35(fileDir, relPath);
20250
+ const rel = relative14(projectRoot, absPath);
20251
+ const extension = extname10(rel);
20252
+ let srcPath = RESOLVED_MODULE_EXTENSIONS.has(extension) ? rel : resolveRelativeExtension(rel, projectRoot, extensions);
20253
+ if (extname10(srcPath) === ".svelte") {
20254
+ srcPath = relative14(projectRoot, resolveSvelteModulePath(resolve35(projectRoot, srcPath)));
20255
+ }
20256
+ return srcUrl(srcPath, projectRoot);
20257
+ }, NODE_BUILTIN_RE, resolveAbsoluteSpecifier = (specifier, projectRoot) => {
20258
+ if (NODE_BUILTIN_RE.test(specifier))
20259
+ return;
20260
+ try {
20261
+ const fromExports = resolvePackageImport(specifier, [
20262
+ "browser",
20263
+ "import"
20264
+ ]);
20265
+ if (fromExports)
20266
+ return relative14(projectRoot, fromExports);
20722
20267
  try {
20723
- entries = readdirSync2(dir, { withFileTypes: true });
20724
- } catch {
20725
- return;
20726
- }
20727
- for (const entry of entries) {
20728
- if (entry.name.startsWith(".") || entry.name === "node_modules") {
20729
- continue;
20730
- }
20731
- const full = join30(dir, entry.name);
20732
- if (entry.isDirectory()) {
20733
- visit(full);
20734
- } else if (entry.isFile() && isAngularSourceFile(entry.name)) {
20735
- out.push(full);
20268
+ const isScoped = specifier.startsWith("@");
20269
+ const parts = specifier.split("/");
20270
+ const packageName = isScoped ? `${parts[0]}/${parts[1]}` : parts[0];
20271
+ const subpath = isScoped ? parts.slice(2).join("/") : parts.slice(1).join("/");
20272
+ if (!subpath) {
20273
+ const pkgDir = resolve35(projectRoot, "node_modules", packageName ?? "");
20274
+ const pkgJsonPath = join30(pkgDir, "package.json");
20275
+ if (existsSync26(pkgJsonPath)) {
20276
+ const pkg = JSON.parse(readFileSync20(pkgJsonPath, "utf-8"));
20277
+ const esmEntry = typeof pkg.module === "string" && pkg.module || typeof pkg.browser === "string" && pkg.browser;
20278
+ if (esmEntry) {
20279
+ const resolved = resolve35(pkgDir, esmEntry);
20280
+ if (existsSync26(resolved))
20281
+ return relative14(projectRoot, resolved);
20282
+ }
20283
+ }
20736
20284
  }
20285
+ } catch {}
20286
+ return relative14(projectRoot, Bun.resolveSync(specifier, projectRoot));
20287
+ } catch {
20288
+ return;
20289
+ }
20290
+ }, rewriteImports = (code, filePath, projectRoot, rewriter) => {
20291
+ let result = code;
20292
+ const vendorReplace = (_match, prefix, specifier, suffix) => {
20293
+ const webPath = rewriter?.lookup.get(specifier);
20294
+ return webPath ? `${prefix}${webPath}${suffix}` : _match;
20295
+ };
20296
+ if (rewriter) {
20297
+ rewriter.vendorRegex.lastIndex = 0;
20298
+ result = result.replace(rewriter.vendorRegex, vendorReplace);
20299
+ }
20300
+ const stubReplace = (_match, prefix, specifier, suffix) => {
20301
+ if (specifier.startsWith("/") || specifier.startsWith("."))
20302
+ return _match;
20303
+ const resolved = resolveAbsoluteSpecifier(specifier, projectRoot);
20304
+ if (resolved) {
20305
+ return `${prefix}${srcUrl(resolved, projectRoot)}${suffix}`;
20737
20306
  }
20307
+ return `${prefix}/@stub/${encodeURIComponent(specifier)}${suffix}`;
20738
20308
  };
20739
- visit(root);
20740
- return out;
20741
- }, getStringPropertyValue = (obj, name) => {
20742
- for (const prop of obj.properties) {
20743
- if (!ts7.isPropertyAssignment(prop))
20744
- continue;
20745
- const propName = ts7.isIdentifier(prop.name) ? prop.name.text : ts7.isStringLiteral(prop.name) ? prop.name.text : null;
20746
- if (propName !== name)
20747
- continue;
20748
- const init = prop.initializer;
20749
- if (ts7.isStringLiteral(init) || ts7.isNoSubstitutionTemplateLiteral(init)) {
20750
- return init.text;
20309
+ result = result.replace(/^((?:import\s+[\s\S]+?\s+from|export\s+[\s\S]+?\s+from|import)\s*["'])([^"'./][^"']*)(["'])/gm, stubReplace);
20310
+ result = result.replace(/(import\s*\(\s*["'])([^"'./][^"']*)(["']\s*\))/g, stubReplace);
20311
+ const fileDir = dirname20(filePath);
20312
+ result = result.replace(/(from\s*["'])(\.\.?\/[^"']+)(["'])/g, (_match, prefix, relPath, suffix) => `${prefix}${resolveRelativeImport(relPath, fileDir, projectRoot, IMPORT_EXTENSIONS)}${suffix}`);
20313
+ result = result.replace(/(import\s*\(\s*["'])(\.\.?\/[^"']+)(["']\s*\))/g, (_match, prefix, relPath, suffix) => `${prefix}${resolveRelativeImport(relPath, fileDir, projectRoot, IMPORT_EXTENSIONS)}${suffix}`);
20314
+ result = result.replace(/(import\s*["'])(\.\.?\/[^"']+)(["']\s*;?)/g, (_match, prefix, relPath, suffix) => `${prefix}${resolveRelativeImport(relPath, fileDir, projectRoot, SIDE_EFFECT_EXTENSIONS)}${suffix}`);
20315
+ const rewriteAbsoluteToSrc = (_match, prefix, absPath, _ext, suffix) => {
20316
+ if (absPath.startsWith(projectRoot)) {
20317
+ const rel2 = relative14(projectRoot, absPath).replace(/\\/g, "/");
20318
+ return `${prefix}${srcUrl(rel2, projectRoot)}${suffix}`;
20751
20319
  }
20320
+ const rel = relative14(projectRoot, absPath).replace(/\\/g, "/");
20321
+ return `${prefix}${srcUrl(rel, projectRoot)}${suffix}`;
20322
+ };
20323
+ result = result.replace(/((?:from|import)\s*["'])(\/[^"']+\.(tsx?|jsx?|ts))(["'])/g, rewriteAbsoluteToSrc);
20324
+ result = result.replace(/(import\s*\(\s*["'])(\/[^"']+\.(tsx?|jsx?|ts))(["']\s*\))/g, rewriteAbsoluteToSrc);
20325
+ result = result.replace(/new\s+URL\(\s*["'](\.\.?\/[^"']+)["']\s*,\s*import\.meta\.url\s*\)/g, (_match, relPath) => {
20326
+ const absPath = resolve35(fileDir, relPath);
20327
+ const rel = relative14(projectRoot, absPath);
20328
+ return `new URL('${srcUrl(rel, projectRoot)}', import.meta.url)`;
20329
+ });
20330
+ result = result.replace(/import\.meta\.resolve\(\s*["'](\.\.?\/[^"']+)["']\s*\)/g, (_match, relPath) => {
20331
+ const absPath = resolve35(fileDir, relPath);
20332
+ const rel = relative14(projectRoot, absPath);
20333
+ return `'${srcUrl(rel, projectRoot)}'`;
20334
+ });
20335
+ return result;
20336
+ }, JSX_AUTO_RE, JSXS_AUTO_RE, JSX_PROD_RE, FRAGMENT_RE, addJsxImport = (code) => {
20337
+ const imports = [];
20338
+ const jsxDevMatch = JSX_AUTO_RE.exec(code);
20339
+ if (jsxDevMatch) {
20340
+ imports.push(`import { jsxDEV as ${jsxDevMatch[1]} } from "react/jsx-dev-runtime";`);
20752
20341
  }
20753
- return null;
20754
- }, getStringArrayProperty = (obj, name) => {
20755
- const out = [];
20756
- for (const prop of obj.properties) {
20757
- if (!ts7.isPropertyAssignment(prop))
20758
- continue;
20759
- const propName = ts7.isIdentifier(prop.name) ? prop.name.text : ts7.isStringLiteral(prop.name) ? prop.name.text : null;
20760
- if (propName !== name)
20761
- continue;
20762
- const init = prop.initializer;
20763
- if (!ts7.isArrayLiteralExpression(init))
20764
- continue;
20765
- for (const element of init.elements) {
20766
- if (ts7.isStringLiteral(element) || ts7.isNoSubstitutionTemplateLiteral(element)) {
20767
- out.push(element.text);
20768
- }
20769
- }
20342
+ const jsxsMatch = JSXS_AUTO_RE.exec(code);
20343
+ if (jsxsMatch && (!jsxDevMatch || jsxsMatch[1] !== jsxDevMatch[1])) {
20344
+ imports.push(`import { jsxs as ${jsxsMatch[1]} } from "react/jsx-runtime";`);
20770
20345
  }
20771
- return out;
20772
- }, parseDecoratedClasses = (filePath) => {
20773
- let source;
20346
+ const jsxProdMatch = JSX_PROD_RE.exec(code);
20347
+ if (jsxProdMatch) {
20348
+ imports.push(`import { jsx as ${jsxProdMatch[1]} } from "react/jsx-runtime";`);
20349
+ }
20350
+ const fragmentMatch = FRAGMENT_RE.exec(code);
20351
+ if (fragmentMatch) {
20352
+ imports.push(`import { Fragment as ${fragmentMatch[1]} } from "react";`);
20353
+ }
20354
+ if (imports.length === 0)
20355
+ return code;
20356
+ return `${imports.join(`
20357
+ `)}
20358
+ ${code}`;
20359
+ }, reactTranspilerOptions, reactTranspiler, probeReactFastRefresh = () => {
20774
20360
  try {
20775
- source = readFileSync20(filePath, "utf8");
20361
+ const probeOptions = {
20362
+ loader: "tsx",
20363
+ reactFastRefresh: true
20364
+ };
20365
+ const probe = new Bun.Transpiler(probeOptions);
20366
+ const out = probe.transformSync("export function __AbsoluteRefreshProbe(){return null;}");
20367
+ return out.includes("$RefreshReg$");
20776
20368
  } catch {
20777
- return [];
20369
+ return false;
20778
20370
  }
20779
- const sourceFile = ts7.createSourceFile(filePath, source, ts7.ScriptTarget.ES2022, true, ts7.ScriptKind.TS);
20780
- const out = [];
20781
- const visit = (node) => {
20782
- if (ts7.isClassDeclaration(node) && node.name) {
20783
- for (const decorator of ts7.getDecorators(node) ?? []) {
20784
- const expr = decorator.expression;
20785
- if (!ts7.isCallExpression(expr))
20786
- continue;
20787
- const fn2 = expr.expression;
20788
- if (!ts7.isIdentifier(fn2))
20789
- continue;
20790
- const kind = ENTITY_DECORATORS[fn2.text];
20791
- if (!kind)
20792
- continue;
20793
- let extendsName = null;
20794
- for (const heritage of node.heritageClauses ?? []) {
20795
- if (heritage.token !== ts7.SyntaxKind.ExtendsKeyword) {
20796
- continue;
20797
- }
20798
- const first = heritage.types[0];
20799
- if (first && ts7.isIdentifier(first.expression)) {
20800
- extendsName = first.expression.text;
20801
- }
20802
- break;
20803
- }
20804
- const entry = {
20805
- className: node.name.text,
20806
- kind,
20807
- styleUrls: [],
20808
- templateUrls: [],
20809
- extendsName
20810
- };
20811
- const arg = expr.arguments[0];
20812
- if (arg && ts7.isObjectLiteralExpression(arg) && kind === "component") {
20813
- const tplUrl = getStringPropertyValue(arg, "templateUrl");
20814
- if (tplUrl)
20815
- entry.templateUrls.push(tplUrl);
20816
- const styleUrl = getStringPropertyValue(arg, "styleUrl");
20817
- if (styleUrl)
20818
- entry.styleUrls.push(styleUrl);
20819
- entry.styleUrls.push(...getStringArrayProperty(arg, "styleUrls"));
20820
- }
20821
- out.push(entry);
20822
- break;
20823
- }
20371
+ }, reactFastRefreshSupported, reactFastRefreshWarningEmitted = false, warnIfReactFastRefreshUnsupported = () => {
20372
+ if (reactFastRefreshSupported || reactFastRefreshWarningEmitted)
20373
+ return;
20374
+ reactFastRefreshWarningEmitted = true;
20375
+ logWarn("React HMR is blocked: this Bun build ignores " + "`reactFastRefresh` on Bun.Transpiler, so component state " + "cannot be preserved across edits. Tracking " + "https://github.com/oven-sh/bun/pull/28312 \u2014 if it still has " + "not merged, leave a \uD83D\uDC4D on the PR so the Bun team knows it " + "is blocking you. Until then, React edits trigger a full " + "reload instead of a fast refresh.");
20376
+ }, transformReactFile = (filePath, projectRoot, rewriter) => {
20377
+ const raw = readFileSync20(filePath, "utf-8");
20378
+ const valueExports = tsxTranspiler.scan(raw).exports;
20379
+ let transpiled = reactTranspiler.transformSync(raw);
20380
+ transpiled = preserveTypeExports(raw, transpiled, valueExports);
20381
+ transpiled = addJsxImport(transpiled);
20382
+ transpiled = transpiled.replace(/import\s*\{[^}]*\}\s*from\s*["']react-refresh\/runtime["'];?\n?/, "");
20383
+ transpiled = transpiled.replace(/\$RefreshReg\$_[a-z0-9]+/g, "$RefreshReg$");
20384
+ transpiled = transpiled.replace(/\$RefreshSig\$_[a-z0-9]+/g, "$RefreshSig$");
20385
+ transpiled = `var $RefreshReg$ = window.$RefreshReg$ || function(){};
20386
+ ` + `var $RefreshSig$ = window.$RefreshSig$ || function(){ return function(t){ return t; }; };
20387
+ ${transpiled}`;
20388
+ const relPath = relative14(projectRoot, filePath).replace(/\\/g, "/");
20389
+ transpiled = transpiled.replace(/\binput\.tsx:/g, `${relPath}:`);
20390
+ transpiled += buildIslandMetadataExports(raw);
20391
+ return rewriteImports(transpiled, filePath, projectRoot, rewriter);
20392
+ }, transformPlainFile = (filePath, projectRoot, rewriter, vueDir) => {
20393
+ const raw = readFileSync20(filePath, "utf-8");
20394
+ const ext = extname10(filePath);
20395
+ const isTS = ext === ".ts" || ext === ".tsx";
20396
+ const isTSX = ext === ".tsx" || ext === ".jsx";
20397
+ let transpiler6 = jsTranspiler2;
20398
+ if (isTSX)
20399
+ transpiler6 = tsxTranspiler;
20400
+ else if (isTS)
20401
+ transpiler6 = tsTranspiler2;
20402
+ const valueExports = isTS ? transpiler6.scan(raw).exports : [];
20403
+ let transpiled = transpiler6.transformSync(raw);
20404
+ if (isTS) {
20405
+ transpiled = preserveTypeExports(raw, transpiled, valueExports);
20406
+ }
20407
+ transpiled = rewriteImports(transpiled, filePath, projectRoot, rewriter);
20408
+ if (!vueDir || !filePath.startsWith(vueDir) || !isTS)
20409
+ return transpiled;
20410
+ const useExports = valueExports.filter((e) => e.startsWith("use"));
20411
+ if (useExports.length === 0)
20412
+ return transpiled;
20413
+ return injectComposableTracking(transpiled, filePath, useExports);
20414
+ }, classifyChar = (char, prevChar, inString) => {
20415
+ if (inString) {
20416
+ const closed = char === inString && prevChar !== "\\";
20417
+ return { nextString: closed ? false : inString, skip: true };
20418
+ }
20419
+ if (char === '"' || char === "'" || char === "`")
20420
+ return { nextString: char, skip: true };
20421
+ return { nextString: false, skip: false };
20422
+ }, findFunctionEnd = (source, startPos) => {
20423
+ let depth = 0;
20424
+ let inString = false;
20425
+ for (let idx = startPos;idx < source.length; idx++) {
20426
+ const char = source[idx] ?? "";
20427
+ const classified = classifyChar(char, source[idx - 1] ?? "", inString);
20428
+ inString = classified.nextString;
20429
+ if (classified.skip)
20430
+ continue;
20431
+ if (char === "{" || char === "(")
20432
+ depth++;
20433
+ if (char === "}" || char === ")")
20434
+ depth--;
20435
+ if (depth === 0 && char === ";")
20436
+ return idx;
20437
+ }
20438
+ return startPos;
20439
+ }, injectComposableTracking = (code, filePath, useExports) => {
20440
+ const moduleId = JSON.stringify(filePath);
20441
+ const runtime = [
20442
+ `var __hmr_cs = (globalThis.__HMR_COMPOSABLE_STATE__ ??= {});`,
20443
+ `var __hmr_mid = ${moduleId};`,
20444
+ `var __hmr_prev_refs = __hmr_cs[__hmr_mid];`,
20445
+ `var __hmr_idx = {};`,
20446
+ `__hmr_cs[__hmr_mid] = {};`,
20447
+ `function __hmr_wrap(name, fn) {`,
20448
+ ` return function() {`,
20449
+ ` var idx = (__hmr_idx[name] = (__hmr_idx[name] ?? -1) + 1);`,
20450
+ ` var result = fn.apply(this, arguments);`,
20451
+ ` if (result && typeof result === "object") {`,
20452
+ ` var refs = {};`,
20453
+ ` for (var k in result) {`,
20454
+ ` var v = result[k];`,
20455
+ ` if (v && typeof v === "object" && "value" in v && !v.effect && typeof v.value !== "function") {`,
20456
+ ` refs[k] = v;`,
20457
+ ` }`,
20458
+ ` }`,
20459
+ ` (__hmr_cs[__hmr_mid][name] ??= [])[idx] = refs;`,
20460
+ ` if (__hmr_prev_refs && __hmr_prev_refs[name] && __hmr_prev_refs[name][idx]) {`,
20461
+ ` var old = __hmr_prev_refs[name][idx];`,
20462
+ ` for (var k in old) {`,
20463
+ ` var nv = result[k];`,
20464
+ ` var ov = old[k];`,
20465
+ ` if (nv && ov && typeof nv === "object" && "value" in nv && !nv.effect && typeof nv.value === typeof ov.value) {`,
20466
+ ` nv.value = ov.value;`,
20467
+ ` }`,
20468
+ ` }`,
20469
+ ` }`,
20470
+ ` }`,
20471
+ ` return result;`,
20472
+ ` };`,
20473
+ `}`
20474
+ ].join(`
20475
+ `);
20476
+ let result = `${runtime}
20477
+ ${code}`;
20478
+ for (const name of useExports) {
20479
+ result = wrapComposableExport(result, name);
20480
+ }
20481
+ return result;
20482
+ }, wrapComposableExport = (source, name) => {
20483
+ const marker = new RegExp(`export\\s+(?:const|var|let)\\s+${name}\\s*=\\s*`);
20484
+ const match = marker.exec(source);
20485
+ if (!match)
20486
+ return source;
20487
+ const insertPos = match.index + match[0].length;
20488
+ const endPos = findFunctionEnd(source, insertPos);
20489
+ const funcBody = source.slice(insertPos, endPos);
20490
+ return `${source.slice(0, insertPos)}__hmr_wrap(${JSON.stringify(name)}, ${funcBody})${source.slice(endPos)}`;
20491
+ }, svelteExternalCss, svelteCompiler = null, vueCompiler = null, getLoadedSvelteCompiler = () => {
20492
+ if (!svelteCompiler)
20493
+ throw new Error("Svelte compiler is not loaded.");
20494
+ return svelteCompiler;
20495
+ }, getLoadedVueCompiler = () => {
20496
+ if (!vueCompiler)
20497
+ throw new Error("Vue compiler is not loaded.");
20498
+ return vueCompiler;
20499
+ }, warmCompilers = async (frameworks2) => {
20500
+ const [svelteModule, vueModule] = await Promise.all([
20501
+ frameworks2.svelte ? import("svelte/compiler") : undefined,
20502
+ frameworks2.vue ? import("@vue/compiler-sfc") : undefined
20503
+ ]);
20504
+ if (svelteModule) {
20505
+ svelteCompiler = svelteModule;
20506
+ svelteModule.compile("<script>let x=$state(0)</script>{x}", {
20507
+ css: "external",
20508
+ dev: true,
20509
+ filename: "_warm.svelte",
20510
+ generate: "client",
20511
+ hmr: true
20512
+ });
20513
+ }
20514
+ if (!vueModule)
20515
+ return;
20516
+ vueCompiler = vueModule;
20517
+ const { descriptor } = vueModule.parse("<script setup>const x=1</script><template>{{x}}</template>", { filename: "_warm.vue" });
20518
+ vueModule.compileScript(descriptor, { id: "w", inlineTemplate: false });
20519
+ if (!descriptor.template)
20520
+ return;
20521
+ vueModule.compileTemplate({
20522
+ filename: "_warm.vue",
20523
+ id: "w",
20524
+ source: descriptor.template.content
20525
+ });
20526
+ }, compileSvelteModule = (raw, filePath) => {
20527
+ const compiler = getLoadedSvelteCompiler();
20528
+ const source = tsTranspiler2.transformSync(raw);
20529
+ return compiler.compileModule(source, {
20530
+ dev: true,
20531
+ filename: filePath
20532
+ }).js.code;
20533
+ }, compileSvelteComponent = (raw, filePath, projectRoot, enableAsync = false) => {
20534
+ const compiler = getLoadedSvelteCompiler();
20535
+ const compiled = compiler.compile(raw, {
20536
+ css: "external",
20537
+ dev: true,
20538
+ experimental: {
20539
+ async: enableAsync
20540
+ },
20541
+ filename: filePath,
20542
+ generate: "client",
20543
+ hmr: true
20544
+ });
20545
+ let { code } = compiled.js;
20546
+ if (compiled.css?.code) {
20547
+ const cssPath = `${filePath}.css`;
20548
+ svelteExternalCss.set(cssPath, compiled.css.code);
20549
+ const cssUrl = srcUrl(relative14(projectRoot, cssPath), projectRoot);
20550
+ code = `import "${cssUrl}";
20551
+ ${code}`;
20552
+ }
20553
+ const moduleUrl = `${SRC_PREFIX}${relative14(projectRoot, filePath).replace(/\\/g, "/")}`;
20554
+ code = code.replace(/if\s*\(import\.meta\.hot\)\s*\{/, `if (typeof window !== "undefined") {
20555
+ ` + ` if (!window.__SVELTE_HMR_ACCEPT__) window.__SVELTE_HMR_ACCEPT__ = {};
20556
+ ` + ` var __hmr_accept = function(cb) { window.__SVELTE_HMR_ACCEPT__[${JSON.stringify(moduleUrl)}] = cb; };`);
20557
+ return code.replace(/import\.meta\.hot\.accept\(/g, "__hmr_accept(");
20558
+ }, transformSvelteFile = async (filePath, projectRoot, rewriter, stylePreprocessors) => {
20559
+ const raw = readFileSync20(filePath, "utf-8");
20560
+ if (!svelteCompiler) {
20561
+ svelteCompiler = await import("svelte/compiler");
20562
+ }
20563
+ const isModule = filePath.endsWith(".svelte.ts") || filePath.endsWith(".svelte.js");
20564
+ const loweredAwaitSource = isModule ? { code: raw, transformed: false } : lowerSvelteAwaitSlotSyntax(raw);
20565
+ const loweredSource = isModule ? loweredAwaitSource : lowerSvelteIslandSyntax(loweredAwaitSource.code, "client");
20566
+ const source = isModule ? loweredSource.code : (await svelteCompiler.preprocess(loweredSource.code, createSvelteStylePreprocessor(stylePreprocessors))).code;
20567
+ const enableAsync = loweredAwaitSource.transformed || loweredSource.transformed;
20568
+ const code = isModule ? compileSvelteModule(source, filePath) : compileSvelteComponent(source, filePath, projectRoot, enableAsync);
20569
+ return rewriteImports(code, filePath, projectRoot, rewriter);
20570
+ }, compileVueTemplate = (descriptor, compiledScript, filePath, componentId) => {
20571
+ const compiler = getLoadedVueCompiler();
20572
+ const scriptContent = compiledScript.content;
20573
+ if (!descriptor.template)
20574
+ return scriptContent;
20575
+ const isScoped = descriptor.styles.some((style) => style.scoped);
20576
+ const templateResult = compiler.compileTemplate({
20577
+ compilerOptions: {
20578
+ bindingMetadata: compiledScript.bindings,
20579
+ expressionPlugins: ["typescript"],
20580
+ isCustomElement: (tag) => tag === "absolute-island",
20581
+ prefixIdentifiers: true
20582
+ },
20583
+ filename: filePath,
20584
+ id: componentId,
20585
+ scoped: isScoped,
20586
+ source: descriptor.template.content
20587
+ });
20588
+ let code = scriptContent.replace("export default", "const __script__ =");
20589
+ code += `
20590
+ ${templateResult.code}`;
20591
+ code += `
20592
+ __script__.render = render;`;
20593
+ code += `
20594
+ export default __script__;`;
20595
+ return code;
20596
+ }, compileVueStyles = async (descriptor, filePath, componentId, code, stylePreprocessors) => {
20597
+ if (descriptor.styles.length === 0)
20598
+ return code;
20599
+ const compiler = getLoadedVueCompiler();
20600
+ const cssCode = (await Promise.all(descriptor.styles.map(async (style) => compiler.compileStyle({
20601
+ filename: filePath,
20602
+ id: `data-v-${componentId}`,
20603
+ scoped: Boolean(style.scoped),
20604
+ source: style.lang ? await compileStyleSource(filePath, style.content, style.lang, stylePreprocessors) : style.content,
20605
+ trim: true
20606
+ }).code))).join(`
20607
+ `);
20608
+ const escaped = cssCode.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
20609
+ const hmrId = JSON.stringify(filePath);
20610
+ const cssInjection = [
20611
+ `var __style=document.createElement('style');`,
20612
+ `__style.textContent=\`${escaped}\`;`,
20613
+ `__style.dataset.hmrId=${hmrId};`,
20614
+ `var __prev=document.querySelector('style[data-hmr-id="${filePath}"]');`,
20615
+ `if(__prev)__prev.remove();`,
20616
+ `document.head.appendChild(__style);`
20617
+ ].join("");
20618
+ return `${cssInjection}
20619
+ ${code}`;
20620
+ }, transformVueFile = async (filePath, projectRoot, rewriter, vueDir, stylePreprocessors) => {
20621
+ const rawSource = readFileSync20(filePath, "utf-8");
20622
+ const raw = addAutoRouterSetupApp(rawSource);
20623
+ if (!vueCompiler) {
20624
+ vueCompiler = await import("@vue/compiler-sfc");
20625
+ }
20626
+ const fileName = basename11(filePath, ".vue");
20627
+ const componentId = fileName.toLowerCase();
20628
+ const { descriptor } = vueCompiler.parse(raw, { filename: filePath });
20629
+ const hasScript = descriptor.script || descriptor.scriptSetup;
20630
+ const compiledScript = hasScript ? vueCompiler.compileScript(descriptor, {
20631
+ id: componentId,
20632
+ inlineTemplate: false
20633
+ }) : { bindings: {}, content: "export default {};" };
20634
+ const compiledSfcScript = {
20635
+ bindings: compiledScript.bindings ?? {},
20636
+ content: compiledScript.content
20637
+ };
20638
+ let code = compileVueTemplate(descriptor, compiledSfcScript, filePath, componentId);
20639
+ code = await compileVueStyles(descriptor, filePath, componentId, code, stylePreprocessors);
20640
+ code = tsTranspiler2.transformSync(code);
20641
+ code = injectVueHmr(code, filePath, projectRoot, vueDir);
20642
+ return rewriteImports(code, filePath, projectRoot, rewriter);
20643
+ }, injectVueHmr = (code, filePath, projectRoot, vueDir) => {
20644
+ const hmrBase = vueDir ? resolve35(vueDir) : projectRoot;
20645
+ const hmrId = relative14(hmrBase, filePath).replace(/\\/g, "/").replace(/\.vue$/, "");
20646
+ let result = code.replace(/export\s+default\s+/, "var __hmr_comp__ = ");
20647
+ result += [
20648
+ "",
20649
+ `__hmr_comp__.__hmrId = ${JSON.stringify(hmrId)};`,
20650
+ `if (typeof __VUE_HMR_RUNTIME__ !== "undefined") {`,
20651
+ ` __VUE_HMR_RUNTIME__.createRecord(${JSON.stringify(hmrId)}, __hmr_comp__);`,
20652
+ ` __VUE_HMR_RUNTIME__.rerender(${JSON.stringify(hmrId)}, __hmr_comp__.render);`,
20653
+ `}`,
20654
+ "export default __hmr_comp__;"
20655
+ ].join(`
20656
+ `);
20657
+ return result;
20658
+ }, resolveSvelteModulePath = (path) => {
20659
+ if (existsSync26(path))
20660
+ return path;
20661
+ if (existsSync26(`${path}.ts`))
20662
+ return `${path}.ts`;
20663
+ if (existsSync26(`${path}.js`))
20664
+ return `${path}.js`;
20665
+ return path;
20666
+ }, jsResponse = (body) => {
20667
+ const etag = `"${Bun.hash(body).toString(BASE_36_RADIX)}"`;
20668
+ return new Response(body, {
20669
+ headers: {
20670
+ "Cache-Control": "no-cache",
20671
+ "Content-Type": "application/javascript",
20672
+ ETag: etag
20824
20673
  }
20825
- ts7.forEachChild(node, visit);
20826
- };
20827
- visit(sourceFile);
20828
- return out;
20829
- }, safeNormalize = (path) => resolve35(path).replace(/\\/g, "/"), resolveOwningComponents = (params) => {
20830
- const { changedFilePath, userAngularRoot } = params;
20831
- const changedAbs = safeNormalize(changedFilePath);
20832
- const out = [];
20833
- const ext = extname10(changedAbs).toLowerCase();
20834
- if (ext === ".ts" || ext === ".tsx") {
20835
- const classes = parseDecoratedClasses(changedAbs);
20836
- for (const cls of classes) {
20837
- out.push({
20838
- className: cls.className,
20839
- componentFilePath: changedAbs,
20840
- kind: cls.kind
20841
- });
20674
+ });
20675
+ }, handleCssRequest = (filePath) => {
20676
+ const raw = readFileSync20(filePath, "utf-8");
20677
+ const escaped = raw.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
20678
+ return [
20679
+ `const style = document.createElement('style');`,
20680
+ `style.textContent = \`${escaped}\`;`,
20681
+ `style.dataset.hmrId = ${JSON.stringify(filePath)};`,
20682
+ `const existing = document.querySelector(\`style[data-hmr-id="${filePath}"]\`);`,
20683
+ `if (existing) existing.remove();`,
20684
+ `document.head.appendChild(style);`
20685
+ ].join(`
20686
+ `);
20687
+ }, generateSvelteHmrBootstrap = (moduleUrl, vendorPaths, timestamp) => {
20688
+ const sveltePath = vendorPaths["svelte"] || "/svelte/vendor/svelte.js";
20689
+ return [
20690
+ `import { mount, unmount } from "${sveltePath}";`,
20691
+ `const { default: Component } = await import("${moduleUrl}?t=${timestamp}");`,
20692
+ ``,
20693
+ `// Extract count from DOM before unmount (survives across runtime instances)`,
20694
+ `var countBtn = document.querySelector("button");`,
20695
+ `var countMatch = countBtn && countBtn.textContent && countBtn.textContent.match(/(\\d+)/);`,
20696
+ `var domCount = countMatch ? parseInt(countMatch[1], 10) : null;`,
20697
+ ``,
20698
+ `var preservedState = window.__HMR_PRESERVED_STATE__ || {};`,
20699
+ `if (domCount !== null && preservedState.initialCount === undefined) {`,
20700
+ ` preservedState.initialCount = domCount;`,
20701
+ `}`,
20702
+ `var initialProps = window.__INITIAL_PROPS__ || {};`,
20703
+ `var mergedProps = Object.assign({}, initialProps, preservedState);`,
20704
+ ``,
20705
+ `// Update __INITIAL_PROPS__ so subsequent HMR cycles start with current state`,
20706
+ `if (domCount !== null) window.__INITIAL_PROPS__ = Object.assign({}, initialProps, { initialCount: domCount });`,
20707
+ ``,
20708
+ `if (typeof window.__SVELTE_UNMOUNT__ === "function") {`,
20709
+ ` try { window.__SVELTE_UNMOUNT__(); } catch (err) { /* ignore */ }`,
20710
+ `}`,
20711
+ ``,
20712
+ `var target = document.getElementById("__absolute_svelte_root__") || document.body;`,
20713
+ `var component = mount(Component, { target, props: mergedProps });`,
20714
+ `window.__SVELTE_COMPONENT__ = component;`,
20715
+ `window.__SVELTE_UNMOUNT__ = function() { unmount(component); };`,
20716
+ `window.__HMR_PRESERVED_STATE__ = undefined;`
20717
+ ].join(`
20718
+ `);
20719
+ }, generateVueHmrBootstrap = (moduleUrl, vendorPaths, timestamp) => {
20720
+ const vuePath = vendorPaths["vue"] || "/vue/vendor/vue.js";
20721
+ return [
20722
+ `import { createApp } from "${vuePath}";`,
20723
+ `const { default: Component } = await import("${moduleUrl}?t=${timestamp}");`,
20724
+ ``,
20725
+ `// Extract count from DOM before unmount (works across Vue instances)`,
20726
+ `var countBtn = document.querySelector("button");`,
20727
+ `var countMatch = countBtn && countBtn.textContent && countBtn.textContent.match(/(\\d+)/);`,
20728
+ `var domCount = countMatch ? parseInt(countMatch[1], 10) : null;`,
20729
+ ``,
20730
+ `var preservedState = window.__HMR_PRESERVED_STATE__ || {};`,
20731
+ `if (domCount !== null && preservedState.initialCount === undefined) {`,
20732
+ ` preservedState.initialCount = domCount;`,
20733
+ `}`,
20734
+ `var initialProps = window.__INITIAL_PROPS__ || {};`,
20735
+ `var mergedProps = Object.assign({}, initialProps, preservedState);`,
20736
+ ``,
20737
+ `// Update __INITIAL_PROPS__ so subsequent HMR cycles start with current state`,
20738
+ `if (domCount !== null) window.__INITIAL_PROPS__ = Object.assign({}, initialProps, { initialCount: domCount });`,
20739
+ ``,
20740
+ `var root = document.getElementById("root");`,
20741
+ `var savedHTML = root ? root.innerHTML : "";`,
20742
+ `if (window.__VUE_APP__) {`,
20743
+ ` window.__VUE_APP__.unmount();`,
20744
+ ` window.__VUE_APP__ = null;`,
20745
+ `}`,
20746
+ `if (root) root.innerHTML = savedHTML;`,
20747
+ ``,
20748
+ `var app = createApp(Component, mergedProps);`,
20749
+ `app.mount(root);`,
20750
+ `window.__VUE_APP__ = app;`,
20751
+ `window.__HMR_PRESERVED_STATE__ = undefined;`
20752
+ ].join(`
20753
+ `);
20754
+ }, handleStubRequest = async (pathname) => {
20755
+ const specifier = decodeURIComponent(pathname.slice("/@stub/".length));
20756
+ const stubCode = await buildStubCode(specifier);
20757
+ return new Response(stubCode, {
20758
+ headers: {
20759
+ "Cache-Control": "no-cache",
20760
+ "Content-Type": "application/javascript"
20842
20761
  }
20843
- return out;
20844
- }
20845
- if (ext !== ".html" && ext !== ".css" && ext !== ".scss" && ext !== ".sass") {
20846
- return out;
20847
- }
20848
- let rootStat;
20849
- try {
20850
- rootStat = statSync4(userAngularRoot);
20851
- } catch {
20852
- return out;
20853
- }
20854
- if (!rootStat.isDirectory())
20855
- return out;
20856
- const index = getOrBuildResourceIndex(userAngularRoot);
20857
- const owners = index.get(changedAbs);
20858
- if (owners) {
20859
- out.push(...owners);
20762
+ });
20763
+ }, BUN_WRAP_MODULE, handleBunWrapRequest = () => new Response(BUN_WRAP_MODULE, {
20764
+ headers: {
20765
+ "Cache-Control": "no-cache",
20766
+ "Content-Type": "application/javascript"
20860
20767
  }
20861
- return out;
20862
- }, indexByRoot, resolveParentClassFile = (parentName, childFilePath, angularRoot) => {
20863
- let source;
20768
+ }), buildStubCode = async (specifier) => {
20864
20769
  try {
20865
- source = readFileSync20(childFilePath, "utf8");
20770
+ const mod = await import(specifier);
20771
+ const names = Object.keys(mod).filter((key) => key !== "default" && key !== "__esModule");
20772
+ if (names.length === 0)
20773
+ return `export default {};
20774
+ `;
20775
+ const noops = names.map((n) => `export const ${n} = () => {};`).join(`
20776
+ `);
20777
+ return `${noops}
20778
+ export default {};
20779
+ `;
20866
20780
  } catch {
20867
- return null;
20868
- }
20869
- const sf = ts7.createSourceFile(childFilePath, source, ts7.ScriptTarget.ES2022, true, ts7.ScriptKind.TS);
20870
- const childDir = dirname20(childFilePath);
20871
- for (const stmt of sf.statements) {
20872
- if (!ts7.isImportDeclaration(stmt))
20873
- continue;
20874
- if (!ts7.isStringLiteral(stmt.moduleSpecifier))
20875
- continue;
20876
- const clause = stmt.importClause;
20877
- if (!clause || clause.isTypeOnly)
20878
- continue;
20879
- let matchesName = false;
20880
- if (clause.name && clause.name.text === parentName)
20881
- matchesName = true;
20882
- if (!matchesName && clause.namedBindings && ts7.isNamedImports(clause.namedBindings)) {
20883
- for (const el of clause.namedBindings.elements) {
20884
- if (el.isTypeOnly)
20885
- continue;
20886
- if (el.name.text === parentName) {
20887
- matchesName = true;
20888
- break;
20889
- }
20890
- }
20891
- }
20892
- if (!matchesName)
20893
- continue;
20894
- const spec = stmt.moduleSpecifier.text;
20895
- if (!spec.startsWith(".") && !spec.startsWith("/")) {
20896
- return null;
20897
- }
20898
- const base = resolve35(childDir, spec);
20899
- const candidates = [
20900
- `${base}.ts`,
20901
- `${base}.tsx`,
20902
- `${base}/index.ts`,
20903
- `${base}/index.tsx`
20904
- ];
20905
- const angularRootNorm = safeNormalize(angularRoot);
20906
- for (const candidate of candidates) {
20907
- try {
20908
- if (statSync4(candidate).isFile()) {
20909
- const norm = safeNormalize(candidate);
20910
- if (!norm.startsWith(angularRootNorm))
20911
- return null;
20912
- return norm;
20913
- }
20914
- } catch {}
20915
- }
20916
- return null;
20781
+ return `export default {};
20782
+ `;
20917
20783
  }
20918
- return null;
20919
- }, getOrBuildIndexes = (userAngularRoot) => {
20920
- const cached = indexByRoot.get(userAngularRoot);
20921
- if (cached)
20922
- return cached;
20923
- const resource = new Map;
20924
- const parentFile = new Map;
20925
- for (const tsPath of walkAngularSourceFiles(userAngularRoot)) {
20926
- const classes = parseDecoratedClasses(tsPath);
20927
- const componentDir = dirname20(tsPath);
20928
- for (const cls of classes) {
20929
- const entity = {
20930
- className: cls.className,
20931
- componentFilePath: tsPath,
20932
- kind: cls.kind
20933
- };
20934
- if (cls.kind === "component") {
20935
- for (const url of [...cls.templateUrls, ...cls.styleUrls]) {
20936
- const abs = safeNormalize(resolve35(componentDir, url));
20937
- const existing = resource.get(abs);
20938
- if (existing)
20939
- existing.push(entity);
20940
- else
20941
- resource.set(abs, [entity]);
20942
- }
20943
- }
20944
- if (cls.extendsName !== null) {
20945
- const parentPath = resolveParentClassFile(cls.extendsName, tsPath, userAngularRoot);
20946
- if (parentPath !== null && parentPath !== safeNormalize(tsPath)) {
20947
- const existing = parentFile.get(parentPath);
20948
- if (existing)
20949
- existing.push(entity);
20950
- else
20951
- parentFile.set(parentPath, [entity]);
20952
- }
20784
+ }, handleHmrBootstrap = (pathname, vendorPaths) => {
20785
+ const rest = pathname.slice("/@hmr/".length);
20786
+ const slashIdx = rest.indexOf("/");
20787
+ if (slashIdx === UNFOUND_INDEX)
20788
+ return;
20789
+ const framework = rest.slice(0, slashIdx);
20790
+ const componentRelPath = rest.slice(slashIdx + 1);
20791
+ const url = `${SRC_PREFIX}${componentRelPath}`;
20792
+ const timestamp = String(Date.now());
20793
+ const generators = {
20794
+ svelte: generateSvelteHmrBootstrap,
20795
+ vue: generateVueHmrBootstrap
20796
+ };
20797
+ const generate = generators[framework];
20798
+ if (!generate)
20799
+ return;
20800
+ return jsResponse(generate(url, vendorPaths, timestamp));
20801
+ }, handleVirtualSvelteCss = (cssCheckPath) => {
20802
+ const virtualCss = svelteExternalCss.get(cssCheckPath);
20803
+ if (!virtualCss)
20804
+ return;
20805
+ const escaped = virtualCss.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
20806
+ return jsResponse(`var s=document.createElement('style');s.textContent=\`${escaped}\`;s.dataset.svelteHmr=${JSON.stringify(cssCheckPath)};var p=document.querySelector('style[data-svelte-hmr="${cssCheckPath}"]');if(p)p.remove();document.head.appendChild(s);`);
20807
+ }, resolveSourcePath = (relPath, projectRoot) => {
20808
+ const filePath = resolve35(projectRoot, relPath);
20809
+ const ext = extname10(filePath);
20810
+ if (ext === ".svelte")
20811
+ return { ext, filePath: resolveSvelteModulePath(filePath) };
20812
+ if (ext)
20813
+ return { ext, filePath };
20814
+ const found = MODULE_EXTENSIONS.find((candidate) => existsSync26(filePath + candidate));
20815
+ if (!found)
20816
+ return { ext, filePath };
20817
+ const resolved = filePath + found;
20818
+ if (found === ".svelte")
20819
+ return { ext: found, filePath: resolveSvelteModulePath(resolved) };
20820
+ return { ext: found, filePath: resolved };
20821
+ }, transformAndCache = async (filePath, ext, projectRoot, rewriter, vueDir, stylePreprocessors) => {
20822
+ if (ext === ".css")
20823
+ return jsResponse(handleCssRequest(filePath));
20824
+ const isSvelte = ext === ".svelte" || filePath.endsWith(".svelte.ts") || filePath.endsWith(".svelte.js");
20825
+ const cached = getTransformed(filePath);
20826
+ if (cached)
20827
+ return jsResponse(cached);
20828
+ if (isSvelte)
20829
+ return transformAndCacheSvelte(filePath, projectRoot, rewriter, stylePreprocessors);
20830
+ if (ext === ".vue")
20831
+ return transformAndCacheVue(filePath, projectRoot, rewriter, vueDir, stylePreprocessors);
20832
+ if (!TRANSPILABLE.has(ext))
20833
+ return;
20834
+ const stat3 = statSync4(filePath);
20835
+ const resolvedVueDir = vueDir ? resolve35(vueDir) : undefined;
20836
+ let content = REACT_EXTENSIONS.has(ext) ? transformReactFile(filePath, projectRoot, rewriter) : transformPlainFile(filePath, projectRoot, rewriter, resolvedVueDir);
20837
+ const isAngularGeneratedJs = ext === ".js" && filePath.replace(/\\/g, "/").includes("/.absolutejs/generated/angular/");
20838
+ if (isAngularGeneratedJs) {
20839
+ const userAngularRoot = await getAngularUserRoot(projectRoot);
20840
+ if (userAngularRoot) {
20841
+ const { applyAngularHmrInjection: applyAngularHmrInjection2 } = await Promise.resolve().then(() => (init_hmrInjectionPlugin(), exports_hmrInjectionPlugin));
20842
+ const { getFrameworkGeneratedDir: getFrameworkGeneratedDir2 } = await Promise.resolve().then(() => (init_generatedDir(), exports_generatedDir));
20843
+ const generatedAngularRoot = getFrameworkGeneratedDir2("angular");
20844
+ const transformed = applyAngularHmrInjection2(content, filePath, {
20845
+ generatedAngularRoot,
20846
+ projectRoot,
20847
+ userAngularRoot
20848
+ });
20849
+ if (transformed !== undefined) {
20850
+ content = rewriter ? rewriteImports(transformed, filePath, projectRoot, rewriter) : transformed;
20953
20851
  }
20954
20852
  }
20955
20853
  }
20956
- const bundle = { parentFile, resource };
20957
- indexByRoot.set(userAngularRoot, bundle);
20958
- return bundle;
20959
- }, getOrBuildResourceIndex = (userAngularRoot) => getOrBuildIndexes(userAngularRoot).resource, resolveDescendantsOfParent = (params) => {
20960
- const norm = safeNormalize(params.changedFilePath);
20961
- let rootStat;
20962
- try {
20963
- rootStat = statSync4(params.userAngularRoot);
20964
- } catch {
20965
- return [];
20854
+ setTransformed(filePath, content, stat3.mtimeMs, extractImportedFiles(content, projectRoot));
20855
+ return jsResponse(content);
20856
+ }, cachedAngularUserRoot, getAngularUserRoot = async (_projectRoot) => {
20857
+ if (cachedAngularUserRoot !== undefined)
20858
+ return cachedAngularUserRoot;
20859
+ cachedAngularUserRoot = configuredAngularUserRoot ?? null;
20860
+ return cachedAngularUserRoot;
20861
+ }, configuredAngularUserRoot, transformAndCacheSvelte = async (filePath, projectRoot, rewriter, stylePreprocessors) => {
20862
+ const stat3 = statSync4(filePath);
20863
+ const content = await transformSvelteFile(filePath, projectRoot, rewriter, stylePreprocessors);
20864
+ setTransformed(filePath, content, stat3.mtimeMs, extractImportedFiles(content, projectRoot));
20865
+ return jsResponse(content);
20866
+ }, transformAndCacheVue = async (filePath, projectRoot, rewriter, vueDir, stylePreprocessors) => {
20867
+ const stat3 = statSync4(filePath);
20868
+ const content = await transformVueFile(filePath, projectRoot, rewriter, vueDir, stylePreprocessors);
20869
+ setTransformed(filePath, content, stat3.mtimeMs, extractImportedFiles(content, projectRoot));
20870
+ return jsResponse(content);
20871
+ }, transformErrorResponse = (err) => {
20872
+ const errMsg = err instanceof Error ? err.message : String(err);
20873
+ return new Response(`console.error('[ModuleServer] Transform error:', ${JSON.stringify(errMsg)});`, {
20874
+ headers: { "Content-Type": "application/javascript" },
20875
+ status: 500
20876
+ });
20877
+ }, createModuleServer = (config) => {
20878
+ const { projectRoot, vendorPaths, frameworkDirs, stylePreprocessors } = config;
20879
+ const rewriter = buildImportRewriter(vendorPaths);
20880
+ if (frameworkDirs?.angular) {
20881
+ configuredAngularUserRoot = frameworkDirs.angular;
20882
+ cachedAngularUserRoot = undefined;
20966
20883
  }
20967
- if (!rootStat.isDirectory())
20968
- return [];
20969
- const bundle = getOrBuildIndexes(params.userAngularRoot);
20970
- return bundle.parentFile.get(norm) ?? [];
20971
- }, invalidateResourceIndex = () => {
20972
- indexByRoot.clear();
20884
+ return async (pathname) => {
20885
+ if (pathname.startsWith("/@stub/"))
20886
+ return handleStubRequest(pathname);
20887
+ if (pathname.startsWith("/@hmr/"))
20888
+ return handleHmrBootstrap(pathname, vendorPaths);
20889
+ if (!pathname.startsWith(SRC_PREFIX))
20890
+ return;
20891
+ const relPath = pathname.slice(SRC_PREFIX.length);
20892
+ if (relPath === "bun:wrap" || relPath.startsWith("bun:wrap?"))
20893
+ return handleBunWrapRequest();
20894
+ const virtualCssResponse = handleVirtualSvelteCss(resolve35(projectRoot, relPath));
20895
+ if (virtualCssResponse)
20896
+ return virtualCssResponse;
20897
+ const { filePath, ext } = resolveSourcePath(relPath, projectRoot);
20898
+ try {
20899
+ return await transformAndCache(filePath, ext, projectRoot, rewriter, frameworkDirs?.vue, stylePreprocessors);
20900
+ } catch (err) {
20901
+ return transformErrorResponse(err);
20902
+ }
20903
+ };
20904
+ }, SRC_IMPORT_RE, extractImportedFiles = (content, projectRoot) => {
20905
+ const files = [];
20906
+ let match;
20907
+ SRC_IMPORT_RE.lastIndex = 0;
20908
+ while ((match = SRC_IMPORT_RE.exec(content)) !== null) {
20909
+ if (match[1])
20910
+ files.push(resolve35(projectRoot, match[1]));
20911
+ }
20912
+ return files;
20913
+ }, invalidateModule = (filePath) => {
20914
+ const resolved = resolve35(filePath);
20915
+ invalidate(filePath);
20916
+ if (resolved !== filePath)
20917
+ invalidate(resolved);
20918
+ mtimeCache.delete(filePath);
20919
+ mtimeCache.delete(resolved);
20920
+ }, warmCache = (pathname) => {
20921
+ if (!pathname.startsWith(SRC_PREFIX))
20922
+ return;
20923
+ if (!globalModuleServer)
20924
+ return;
20925
+ globalModuleServer(pathname);
20926
+ }, globalModuleServer = null, SRC_URL_PREFIX, setGlobalModuleServer = (handler) => {
20927
+ globalModuleServer = handler;
20973
20928
  };
20974
- var init_resolveOwningComponents = __esm(() => {
20975
- ENTITY_DECORATORS = {
20976
- Component: "component",
20977
- Directive: "directive",
20978
- Pipe: "pipe",
20979
- Injectable: "service"
20929
+ var init_moduleServer = __esm(() => {
20930
+ init_constants();
20931
+ init_resolvePackageImport();
20932
+ init_vueAutoRouterTransform();
20933
+ init_sourceMetadata();
20934
+ init_stylePreprocessor();
20935
+ init_lowerAwaitSlotSyntax();
20936
+ init_lowerIslandSyntax();
20937
+ init_logger();
20938
+ init_transformCache();
20939
+ jsTranspiler2 = new Bun.Transpiler({
20940
+ loader: "js",
20941
+ trimUnusedImports: true
20942
+ });
20943
+ tsTranspiler2 = new Bun.Transpiler({
20944
+ loader: "ts",
20945
+ trimUnusedImports: true
20946
+ });
20947
+ tsxTranspiler = new Bun.Transpiler({
20948
+ loader: "tsx",
20949
+ trimUnusedImports: true
20950
+ });
20951
+ TRANSPILABLE = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs"]);
20952
+ ALL_EXPORTS_RE = /export\s+(?:type|interface|const|let|var|function|class|enum|abstract\s+class)\s+(\w+)/g;
20953
+ STRING_CONTENTS_RE = /`(?:[^`\\]|\\.)*`|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/gs;
20954
+ IMPORT_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js", ".svelte", ".vue"];
20955
+ SIDE_EFFECT_EXTENSIONS = [
20956
+ ".tsx",
20957
+ ".ts",
20958
+ ".jsx",
20959
+ ".js",
20960
+ ".css",
20961
+ ".svelte",
20962
+ ".vue"
20963
+ ];
20964
+ MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js", ".svelte", ".vue"];
20965
+ RESOLVED_MODULE_EXTENSIONS = new Set([
20966
+ ...IMPORT_EXTENSIONS,
20967
+ ...SIDE_EFFECT_EXTENSIONS,
20968
+ ".mjs",
20969
+ ".css"
20970
+ ]);
20971
+ REACT_EXTENSIONS = new Set([".tsx", ".jsx"]);
20972
+ mtimeCache = new Map;
20973
+ NODE_BUILTIN_RE = /^(?:node:|(?:assert|async_hooks|buffer|child_process|cluster|console|constants|crypto|dgram|dns|domain|events|fs|http|http2|https|inspector|module|net|os|path|perf_hooks|process|punycode|querystring|readline|repl|stream|string_decoder|sys|timers|tls|trace_events|tty|url|util|v8|vm|wasi|worker_threads|zlib)(?:\/|$))/;
20974
+ JSX_AUTO_RE = /\b(jsxDEV_[a-z0-9]+)\b/;
20975
+ JSXS_AUTO_RE = /\b(jsxs_[a-z0-9]+)\b/;
20976
+ JSX_PROD_RE = /\b(jsx_[a-z0-9]+)\b/;
20977
+ FRAGMENT_RE = /\b(Fragment_[a-z0-9]+)\b/;
20978
+ reactTranspilerOptions = {
20979
+ loader: "tsx",
20980
+ reactFastRefresh: true,
20981
+ trimUnusedImports: true
20980
20982
  };
20981
- indexByRoot = new Map;
20983
+ reactTranspiler = new Bun.Transpiler(reactTranspilerOptions);
20984
+ reactFastRefreshSupported = probeReactFastRefresh();
20985
+ svelteExternalCss = new Map;
20986
+ BUN_WRAP_MODULE = `
20987
+ export function __legacyDecorateClassTS(decorators, target, key, desc) {
20988
+ var c = arguments.length;
20989
+ var r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc;
20990
+ var d;
20991
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
20992
+ r = Reflect.decorate(decorators, target, key, desc);
20993
+ } else {
20994
+ for (var i = decorators.length - 1; i >= 0; i--) {
20995
+ if (d = decorators[i]) {
20996
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
20997
+ }
20998
+ }
20999
+ }
21000
+ if (c > 3 && r) Object.defineProperty(target, key, r);
21001
+ return r;
21002
+ }
21003
+ export function __legacyMetadataTS(k, v) {
21004
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") {
21005
+ return Reflect.metadata(k, v);
21006
+ }
21007
+ }
21008
+ `.trim();
21009
+ SRC_IMPORT_RE = /\/@src\/([^"'?\s]+)/g;
21010
+ SRC_URL_PREFIX = SRC_PREFIX;
21011
+ });
21012
+
21013
+ // src/build/rewriteImports.ts
21014
+ var exports_rewriteImports = {};
21015
+ __export(exports_rewriteImports, {
21016
+ rewriteVendorDirectories: () => rewriteVendorDirectories2,
21017
+ rewriteImports: () => rewriteImports2
21018
+ });
21019
+ var rewriteImports2 = async (outputPaths, vendorPaths) => {
21020
+ const jsFiles = outputPaths.filter((path) => path.endsWith(".js"));
21021
+ if (jsFiles.length === 0)
21022
+ return;
21023
+ if (Object.keys(vendorPaths).length === 0)
21024
+ return;
21025
+ await Promise.all(jsFiles.map(async (filePath) => {
21026
+ let original;
21027
+ try {
21028
+ original = await Bun.file(filePath).text();
21029
+ } catch (err) {
21030
+ const code = err.code;
21031
+ if (code === "ENOENT")
21032
+ return;
21033
+ throw err;
21034
+ }
21035
+ const rewritten = rewriteImportsInContent(original, vendorPaths);
21036
+ if (rewritten === original)
21037
+ return;
21038
+ try {
21039
+ await Bun.write(filePath, rewritten);
21040
+ } catch (err) {
21041
+ const code = err.code;
21042
+ if (code === "ENOENT")
21043
+ return;
21044
+ throw err;
21045
+ }
21046
+ }));
21047
+ }, rewriteVendorDirectories2;
21048
+ var init_rewriteImports = __esm(() => {
21049
+ init_rewriteImportsPlugin();
21050
+ rewriteVendorDirectories2 = rewriteVendorDirectories;
20982
21051
  });
20983
21052
 
20984
21053
  // src/dev/angular/hmrCompiler.ts
@@ -21445,6 +21514,35 @@ var moduleServerPromise, getModuleServer = () => moduleServerPromise, runSequent
21445
21514
  for (const importer of findStyleEntriesImporting(changedStylePath)) {
21446
21515
  enqueueImporter(state, importer);
21447
21516
  }
21517
+ enqueueAngularOwningComponentForStyle(state, changedStylePath);
21518
+ }, enqueueAngularOwningComponentForStyle = (state, changedStylePath) => {
21519
+ const angularDir = state.resolvedPaths.angularDir;
21520
+ if (!angularDir)
21521
+ return;
21522
+ const visited = new Set;
21523
+ const stack = [
21524
+ changedStylePath,
21525
+ ...findStyleEntriesImporting(changedStylePath)
21526
+ ];
21527
+ while (stack.length > 0) {
21528
+ const stylePath = stack.pop();
21529
+ if (!stylePath || visited.has(stylePath))
21530
+ continue;
21531
+ visited.add(stylePath);
21532
+ for (const upstream of findStyleEntriesImporting(stylePath)) {
21533
+ if (!visited.has(upstream))
21534
+ stack.push(upstream);
21535
+ }
21536
+ try {
21537
+ const owners = resolveOwningComponents({
21538
+ changedFilePath: stylePath,
21539
+ userAngularRoot: angularDir
21540
+ });
21541
+ for (const owner of owners) {
21542
+ enqueueImporter(state, owner.componentFilePath);
21543
+ }
21544
+ } catch {}
21545
+ }
21448
21546
  }, queueFileChange = async (state, filePath, config, onRebuildComplete) => {
21449
21547
  const framework = detectFramework(filePath, state.resolvedPaths);
21450
21548
  if (framework === "ignored") {
@@ -23079,6 +23177,7 @@ var init_rebuildTrigger = __esm(() => {
23079
23177
  init_telemetryEvent();
23080
23178
  init_assetStore();
23081
23179
  init_pathUtils();
23180
+ init_resolveOwningComponents();
23082
23181
  init_webSocket();
23083
23182
  init_stylePreprocessor();
23084
23183
  init_compileTailwind();
@@ -32352,5 +32451,5 @@ export {
32352
32451
  ANGULAR_INIT_TIMEOUT_MS
32353
32452
  };
32354
32453
 
32355
- //# debugId=F77D088B9EDAE99064756E2164756E21
32454
+ //# debugId=6FEE58AB0632470164756E2164756E21
32356
32455
  //# sourceMappingURL=index.js.map