rsbuild-plugin-react-router 0.7.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +14 -2
  2. package/dist/468.js +48 -0
  3. package/dist/511.js +60 -86
  4. package/dist/819.js +64 -0
  5. package/dist/build-output-transforms.d.ts +3 -1
  6. package/dist/constants.d.ts +1 -0
  7. package/dist/dev-hdr-channel.d.ts +9 -0
  8. package/dist/dev-hmr.d.ts +1 -22
  9. package/dist/dev-runtime-controller.d.ts +1 -6
  10. package/dist/dev-server.d.ts +3 -1
  11. package/dist/index.cjs +5417 -5080
  12. package/dist/index.js +1701 -1441
  13. package/dist/manifest-assets.d.ts +34 -0
  14. package/dist/manifest-snapshot.d.ts +17 -0
  15. package/dist/manifest-state.d.ts +12 -0
  16. package/dist/manifest.d.ts +2 -22
  17. package/dist/modify-browser-manifest.d.ts +2 -0
  18. package/dist/node-only-manifest.d.ts +8 -0
  19. package/dist/plugin-utils.d.ts +1 -1
  20. package/dist/rsc-prerender.d.ts +3 -2
  21. package/dist/server-build-worker-client.d.ts +20 -0
  22. package/dist/server-build-worker-protocol.d.ts +84 -0
  23. package/dist/server-build-worker.d.ts +1 -0
  24. package/dist/server-build-worker.js +123 -0
  25. package/dist/server-utils.d.ts +1 -2
  26. package/dist/types.d.ts +6 -0
  27. package/package.json +4 -4
  28. package/src/build-output-transforms.ts +22 -1
  29. package/src/classic-mode.ts +0 -1
  30. package/src/constants.ts +3 -0
  31. package/src/dev-hdr-channel.ts +38 -0
  32. package/src/dev-hmr.ts +57 -100
  33. package/src/dev-runtime-controller.ts +23 -18
  34. package/src/dev-server.ts +24 -4
  35. package/src/index.ts +229 -144
  36. package/src/lazy-compilation.ts +7 -2
  37. package/src/manifest-assets.ts +228 -0
  38. package/src/manifest-snapshot.ts +80 -0
  39. package/src/manifest-state.ts +71 -0
  40. package/src/manifest.ts +23 -161
  41. package/src/mode-plan.ts +12 -4
  42. package/src/modify-browser-manifest.ts +47 -18
  43. package/src/node-only-manifest.ts +52 -0
  44. package/src/plugin-utils.ts +6 -2
  45. package/src/prerender-build.ts +76 -86
  46. package/src/route-chunks.ts +152 -63
  47. package/src/rsc-prerender.ts +7 -35
  48. package/src/server-build-resolution.ts +1 -2
  49. package/src/server-build-worker-client.ts +221 -0
  50. package/src/server-build-worker-protocol.ts +69 -0
  51. package/src/server-build-worker.ts +192 -0
  52. package/src/server-utils.ts +0 -2
  53. package/src/types.ts +7 -0
package/dist/index.js CHANGED
@@ -1,23 +1,69 @@
1
1
  let globalStore, previousPrepareStackTrace, o, origin, bigint1e6, characters, charactersLength, O, quoteValue, options, f, fiber, scoped;
2
- import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, watch, writeFileSync } from "node:fs";
3
- import fs_extra from "fs-extra";
4
2
  import { rspack } from "@rsbuild/core";
5
- import { dirname, isAbsolute, join as external_pathe_join, relative, resolve as external_pathe_resolve } from "pathe";
3
+ import { dirname, isAbsolute, join, relative, resolve as external_pathe_resolve } from "pathe";
4
+ import { createHash, randomUUID } from "node:crypto";
5
+ import { existsSync, readFileSync, realpathSync, statSync, watch } from "node:fs";
6
+ import fs_extra from "fs-extra";
6
7
  import { availableParallelism, cpus } from "node:os";
7
- import { createRequestHandler as external_react_router_createRequestHandler, matchRoutes } from "react-router";
8
+ import { SourceMap, createRequire } from "node:module";
9
+ import { matchRoutes } from "react-router";
8
10
  import { access, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
9
11
  import { fileURLToPath, pathToFileURL, fileURLToPath as __rspack_fileURLToPath } from "node:url";
10
- import { createHash } from "node:crypto";
12
+ import { Worker } from "node:worker_threads";
11
13
  import jsesc from "jsesc";
12
- import { SourceMap, createRequire } from "node:module";
13
14
  import { dirname as external_node_path_dirname, isAbsolute as external_node_path_isAbsolute, join as external_node_path_join, relative as external_node_path_relative, resolve as external_node_path_resolve, sep as external_node_path_sep, dirname as __rspack_dirname } from "node:path";
14
15
  import { createJiti } from "jiti";
15
16
  import { createRequestListener as node_fetch_server_createRequestListener } from "@remix-run/node-fetch-server";
16
- import { analyzeRouteModuleCode, yuku_parse, collectReferencedNames, createReactRouterPerformanceProfiler, combineURLs, JS_EXTENSIONS, generate as yuku_generate, executeRouteTransformTask, generateWithProps, resolveAppPackagePath, validateRouteChunks, roundMs, BUILD_CLIENT_ROUTE_QUERY_STRING, resolveEffectiveAssetPrefix, removeUnusedImports, getProgram, detectRouteChunks, getPatternIdentifierNames, getExportedName, SERVER_ONLY_ROUTE_EXPORTS, createRouteId, removeExports, SERVER_EXPORTS, getExportNames, HMR_PATCHABLE_ROUTE_FLAGS, escapeHtml, PLUGIN_NAME, getRouteModuleAnalysis, parseVersionMajorMinor, getRouteChunkNameFromModuleId, createEmptyRouteChunkByExportName, findEntryFile, routeChunkExportNames, buildManifestChunkValidity, CLIENT_NON_COMPONENT_EXPORTS, CLIENT_EXPORTS, SPA_FALLBACK_HTML_FILE, getRouteChunkEntryName, getRouteChunkModuleId, normalizeAssetPrefix, detectRouteChunksIfEnabled, validateSpaModeRouteExports, DEFAULT_JS_DIST_PATH, getRouteEntryBaseName, getPackageVersion, createBundlerRouteExportResolver } from "./511.js";
17
+ import { SERVER_ONLY_ROUTE_EXPORTS, BROWSER_MANIFEST_ENTRY_NAME, SPA_FALLBACK_HTML_FILE, JS_EXTENSIONS, SERVER_EXPORTS, BUILD_CLIENT_ROUTE_QUERY_STRING, CLIENT_EXPORTS, CLIENT_NON_COMPONENT_EXPORTS, PLUGIN_NAME, DEFAULT_JS_DIST_PATH } from "./468.js";
18
+ import { analyzeRouteModuleCode, combineURLs, generate as yuku_generate, executeRouteTransformTask, generateWithProps, resolveAppPackagePath, validateRouteChunks, roundMs, resolveEffectiveAssetPrefix, removeUnusedImports, getProgram, detectRouteChunks, getPatternIdentifierNames, getExportedName, createRouteId, removeExports, HMR_PATCHABLE_ROUTE_FLAGS, getExportNames, escapeHtml, getRouteModuleAnalysis, parseVersionMajorMinor, getRouteChunkNameFromModuleId, createEmptyRouteChunkByExportName, findEntryFile, yuku_parse, routeChunkExportNames, buildManifestChunkValidity, createReactRouterPerformanceProfiler, getRouteChunkEntryName, getRouteChunkModuleId, normalizeAssetPrefix, detectRouteChunksIfEnabled, validateSpaModeRouteExports, createBundlerRouteExportResolver, getPackageVersion, getRouteEntryBaseName, collectReferencedNames } from "./511.js";
19
+ import { resolveServerBuildModule, headerEntries } from "./819.js";
17
20
  var effect, description, __rspack_import_meta_dirname__ = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
18
- let getAvailableCpuCount = ()=>'function' == typeof availableParallelism ? availableParallelism() : cpus().length, getDefaultConcurrency = (cpuCount = getAvailableCpuCount())=>Math.max(0, Math.floor(cpuCount) - 2), getCappedPluginConcurrency = (cap = 16)=>Math.max(1, Math.min(cap, getDefaultConcurrency() || 1)), createReactRouterHydrationModuleTest = (entryClientPath)=>{
21
+ let createReactRouterManifestSnapshot = ({ manifest, sri, moduleExportsByRouteId, serverBuildPlan, routesByServerBundleId })=>{
22
+ let { server, moduleExportsByRouteId: detachedModuleExports } = structuredClone({
23
+ server: {
24
+ ...manifest,
25
+ sri
26
+ },
27
+ moduleExportsByRouteId
28
+ }), browser = {
29
+ ...server,
30
+ sri: void 0
31
+ }, bundles = serverBuildPlan.serverBundleEntries.flatMap(({ bundleId, entryName })=>{
32
+ let bundleRoutes = routesByServerBundleId[bundleId];
33
+ return bundleRoutes ? [
34
+ {
35
+ bundleId,
36
+ entryName,
37
+ manifest: {
38
+ ...server,
39
+ routes: Object.fromEntries(Object.entries(server.routes).filter(([routeId])=>Object.hasOwn(bundleRoutes, routeId)))
40
+ }
41
+ }
42
+ ] : [];
43
+ });
44
+ return {
45
+ browser,
46
+ moduleExportsByRouteId: detachedModuleExports,
47
+ server,
48
+ serverByBundleId: Object.fromEntries(bundles.map(({ bundleId, manifest })=>[
49
+ bundleId,
50
+ manifest
51
+ ])),
52
+ serverByEntryName: Object.fromEntries([
53
+ [
54
+ serverBuildPlan.defaultEntryName,
55
+ server
56
+ ],
57
+ ...bundles.map(({ entryName, manifest })=>[
58
+ entryName,
59
+ manifest
60
+ ])
61
+ ])
62
+ };
63
+ }, getAvailableCpuCount = ()=>'function' == typeof availableParallelism ? availableParallelism() : cpus().length, getDefaultConcurrency = (cpuCount = getAvailableCpuCount())=>Math.max(0, Math.floor(cpuCount) - 2), getCappedPluginConcurrency = (cap = 16)=>Math.max(1, Math.min(cap, getDefaultConcurrency() || 1)), DEV_HDR_UPDATE_EVENT = 'react-router:hdr-update', DEV_HMR_RUNTIME_MODULE_ID = 'virtual/react-router/hmr-runtime', DEV_MANIFEST_UPDATE_EVENT = 'react-router:manifest-update', dev_hmr_isObject = (value)=>null !== value && 'object' == typeof value, isSwcLoader = (loader)=>'string' == typeof loader && loader.includes('builtin:swc-loader'), readSwcLoaderRefresh = (value)=>Array.isArray(value) ? value.some(readSwcLoaderRefresh) : !!dev_hmr_isObject(value) && (isSwcLoader(value.loader) ? value.options?.jsc?.transform?.react?.refresh === !0 : Object.values(value).some(readSwcLoaderRefresh)), readRuleSwcRefresh = (rule)=>!!dev_hmr_isObject(rule) && (isSwcLoader(rule.loader) ? readSwcLoaderRefresh(rule) : readSwcLoaderRefresh(rule.use) || readRuleSetSwcRefresh(rule.oneOf) || readRuleSetSwcRefresh(rule.rules)), readRuleSetSwcRefresh = (rules)=>Array.isArray(rules) && rules.some(readRuleSwcRefresh), isRspackSwcReactRefreshEnabled = (rspackConfig)=>readRuleSetSwcRefresh(rspackConfig.module?.rules), createReactRouterHydrationModuleTest = (entryClientPath)=>{
19
64
  let eagerPatterns = [
20
- 'virtual/react-router/browser-manifest',
65
+ BROWSER_MANIFEST_ENTRY_NAME,
66
+ DEV_HMR_RUNTIME_MODULE_ID,
21
67
  ...entryClientPath ? [
22
68
  entryClientPath.replace(/\\/g, '/'),
23
69
  BUILD_CLIENT_ROUTE_QUERY_STRING,
@@ -40,7 +86,108 @@ let getAvailableCpuCount = ()=>'function' == typeof availableParallelism ? avail
40
86
  return existsSync(userEntryPath) ? userEntryPath : external_pathe_resolve(templatesDirectory, templateName);
41
87
  }, getModuleFederationOptions = (plugin)=>{
42
88
  if (plugin && 'object' == typeof plugin && ('ModuleFederationPlugin' === plugin.name || 'RspackModuleFederationPlugin' === plugin.name)) return plugin._options ?? plugin.options;
43
- }, Function_dual = function(arity, body) {
89
+ };
90
+ function generateServerBuild(routes, options) {
91
+ let manifestId = options.serverManifestId ?? 'virtual/react-router/server-manifest', routeEntries = Object.entries(routes);
92
+ return `
93
+ import * as entryServer from ${JSON.stringify(options.entryServerPath)};
94
+ ${routeEntries.map(([, route], index)=>options.isSpaMode && 'root' !== route.id ? `const route${index} = { default: () => null };` : `import * as route${index} from ${JSON.stringify(external_pathe_resolve(options.appDirectory, route.file))};`).join('\n')}
95
+
96
+ export { default as assets } from ${JSON.stringify(manifestId)};
97
+ export const assetsBuildDirectory = ${JSON.stringify(options.assetsBuildDirectory)};
98
+ export const basename = ${JSON.stringify(options.basename)};
99
+ export const future = ${JSON.stringify(options.future ?? {})};
100
+ export const isSpaMode = ${options.isSpaMode};
101
+ export const ssr = ${options.ssr};
102
+ export const routeDiscovery = ${JSON.stringify(options.routeDiscovery)};
103
+ export const prerender = ${JSON.stringify(options.prerender ?? [])};
104
+ export const publicPath = ${JSON.stringify(options.publicPath ?? '/')};
105
+ export const entry = { module: entryServer };
106
+ export const allowedActionOrigins = ${JSON.stringify(options.allowedActionOrigins)};
107
+ export var routes = {};
108
+ ${routeEntries.map(([key, route], index)=>`routes[${JSON.stringify(key)}] = {
109
+ id: ${JSON.stringify(route.id)},
110
+ parentId: ${JSON.stringify(route.parentId)},
111
+ path: ${JSON.stringify(route.path)},
112
+ index: ${JSON.stringify(route.index)},
113
+ caseSensitive: ${JSON.stringify(route.caseSensitive)},
114
+ module: route${index}
115
+ };`).join('\n ')}
116
+ `;
117
+ }
118
+ function resolveReactRouterServerBuild(buildModule) {
119
+ return resolveServerBuildModule(buildModule, 'Imported module');
120
+ }
121
+ let normalizePath = (value)=>value.replace(/\/\/+/g, '/').replace(/(.+)\/$/, '$1'), groupRoutesByParentId = (manifest)=>{
122
+ let grouped = {};
123
+ return Object.values(manifest).forEach((route)=>{
124
+ if (!route) return;
125
+ let parentId = route.parentId || '';
126
+ grouped[parentId] ??= [], grouped[parentId].push(route);
127
+ }), grouped;
128
+ }, createPrerenderRoutes = (manifest, parentId = '', grouped = groupRoutesByParentId(manifest))=>(grouped[parentId] || []).map((route)=>{
129
+ let common = {
130
+ id: route.id,
131
+ path: route.path,
132
+ caseSensitive: route.caseSensitive
133
+ };
134
+ return route.index ? {
135
+ index: !0,
136
+ ...common
137
+ } : {
138
+ ...common,
139
+ children: createPrerenderRoutes(manifest, route.id, grouped)
140
+ };
141
+ }), normalizePrerenderMatchPath = (path)=>`/${path}/`.replace(/^\/\/+/, '/'), resolvePrerenderPaths = async (prerender, ssr, routes, options = {})=>{
142
+ let pathsConfig, paths, paramRoutes, recurse;
143
+ if (null == prerender || !1 === prerender || !1 === (pathsConfig = 'object' == typeof prerender && null !== prerender && 'paths' in prerender ? prerender?.paths : prerender)) return [];
144
+ let { paths: paths1, paramRoutes: paramRoutes1 } = (paths = [
145
+ '/'
146
+ ], paramRoutes = [], (recurse = (entries, prefix = '', hasDynamicParent = !1)=>{
147
+ for (let route of entries){
148
+ let routePath = route.path ?? '', hasDynamicSegment = routePath.split('/').filter(Boolean).some((segment)=>segment.startsWith(':') || '*' === segment) || '*' === routePath, nextHasDynamic = hasDynamicParent || hasDynamicSegment;
149
+ if (routePath) {
150
+ let fullPath = normalizePath([
151
+ prefix,
152
+ routePath
153
+ ].join('/'));
154
+ nextHasDynamic ? paramRoutes.push(fullPath) : paths.push(fullPath);
155
+ }
156
+ if (route.children) {
157
+ let newPrefix = routePath ? normalizePath([
158
+ prefix,
159
+ routePath
160
+ ].join('/')) : prefix;
161
+ recurse(route.children, newPrefix, nextHasDynamic);
162
+ }
163
+ }
164
+ })(routes), {
165
+ paths: paths.map(normalizePath),
166
+ paramRoutes: paramRoutes.map(normalizePath)
167
+ });
168
+ if (!0 === pathsConfig) return options.logWarning && !ssr && paramRoutes1.length > 0 && (options.warn ?? ((message)=>{
169
+ console.warn(message);
170
+ }))([
171
+ "⚠️ Paths with dynamic/splat params cannot be prerendered when using `prerender: true`. You may want to use the `prerender()` API to prerender the following paths:",
172
+ ...paramRoutes1.map((path)=>` - ${path.replace(/^\/(?=[:*])/, '')}`)
173
+ ].join('\n')), paths1;
174
+ if ('function' == typeof pathsConfig) {
175
+ let resolved = await pathsConfig({
176
+ getStaticPaths: ()=>paths1
177
+ });
178
+ return !0 === resolved ? paths1 : !1 === resolved || null == resolved ? [] : resolved;
179
+ }
180
+ return pathsConfig ?? [];
181
+ }, getPrerenderConcurrency = (prerender, _cpuCount)=>{
182
+ let config = getPrerenderConfigObject(prerender), value = getPrerenderConcurrencyConfig(config)?.value;
183
+ return 'number' == typeof value && Number.isInteger(value) && value > 0 ? value : 1;
184
+ }, getPrerenderConfigObject = (prerender)=>'object' != typeof prerender || null === prerender || Array.isArray(prerender) ? null : prerender, getPrerenderConcurrencyConfig = (config)=>config?.concurrency !== void 0 ? {
185
+ key: 'prerender.concurrency',
186
+ value: config.concurrency
187
+ } : config?.unstable_concurrency !== void 0 ? {
188
+ key: 'prerender.unstable_concurrency',
189
+ value: config.unstable_concurrency
190
+ } : void 0, Function_dual = function(arity, body) {
44
191
  if ("function" == typeof arity) return function() {
45
192
  return arity(arguments) ? body.apply(this, arguments) : (self)=>body(self, ...arguments);
46
193
  };
@@ -434,7 +581,120 @@ let isEqual = (u)=>Predicate_hasProperty(u, Equal_symbol), Inspectable_NodeInspe
434
581
  }), isOption = (input)=>Predicate_hasProperty(input, TypeId), isNone = (fa)=>"None" === fa._tag, isSome = (fa)=>"Some" === fa._tag, option_none = Object.create(NoneProto), option_some = (value)=>{
435
582
  let a = Object.create(SomeProto);
436
583
  return a.value = value, a;
437
- }, either_TypeId = Symbol.for("effect/Either"), either_CommonProto = {
584
+ }, TagTypeId = Symbol.for("effect/Context/Tag"), ReferenceTypeId = Symbol.for("effect/Context/Reference"), STMTypeId = Symbol.for("effect/STM"), context_TagProto = {
585
+ ...EffectPrototype,
586
+ _op: "Tag",
587
+ [STMTypeId]: effectVariance,
588
+ [TagTypeId]: {
589
+ _Service: (_)=>_,
590
+ _Identifier: (_)=>_
591
+ },
592
+ toString () {
593
+ return JSON.stringify(this.toJSON(), null, 2);
594
+ },
595
+ toJSON () {
596
+ return {
597
+ _id: "Tag",
598
+ key: this.key,
599
+ stack: this.stack
600
+ };
601
+ },
602
+ [Inspectable_NodeInspectSymbol] () {
603
+ return this.toJSON();
604
+ },
605
+ of: (self)=>self,
606
+ context (self) {
607
+ return make(this, self);
608
+ }
609
+ }, ReferenceProto = {
610
+ ...context_TagProto,
611
+ [ReferenceTypeId]: ReferenceTypeId
612
+ }, context_TypeId = Symbol.for("effect/Context"), ContextProto = {
613
+ [context_TypeId]: {
614
+ _Services: (_)=>_
615
+ },
616
+ [Equal_symbol] (that) {
617
+ if (isContext(that) && this.unsafeMap.size === that.unsafeMap.size) {
618
+ for (let k of this.unsafeMap.keys())if (!that.unsafeMap.has(k) || !equals(this.unsafeMap.get(k), that.unsafeMap.get(k))) return !1;
619
+ return !0;
620
+ }
621
+ return !1;
622
+ },
623
+ [Hash_symbol] () {
624
+ return Hash_cached(this, number(this.unsafeMap.size));
625
+ },
626
+ pipe () {
627
+ return Pipeable_pipeArguments(this, arguments);
628
+ },
629
+ toString () {
630
+ return JSON.stringify(this.toJSON(), null, 2);
631
+ },
632
+ toJSON () {
633
+ return {
634
+ _id: "Context",
635
+ services: Array.from(this.unsafeMap).map(toJSON)
636
+ };
637
+ },
638
+ [Inspectable_NodeInspectSymbol] () {
639
+ return this.toJSON();
640
+ }
641
+ }, makeContext = (unsafeMap)=>{
642
+ let context = Object.create(ContextProto);
643
+ return context.unsafeMap = unsafeMap, context;
644
+ }, isContext = (u)=>Predicate_hasProperty(u, context_TypeId), _empty = makeContext(new Map()), make = (tag, service)=>makeContext(new Map([
645
+ [
646
+ tag.key,
647
+ service
648
+ ]
649
+ ])), add = Function_dual(3, (self, tag, service)=>{
650
+ let map = new Map(self.unsafeMap);
651
+ return map.set(tag.key, service), makeContext(map);
652
+ }), defaultValueCache = GlobalValue_globalValue("effect/Context/defaultValueCache", ()=>new Map()), getDefaultValue = (tag)=>{
653
+ if (defaultValueCache.has(tag.key)) return defaultValueCache.get(tag.key);
654
+ let value = tag.defaultValue();
655
+ return defaultValueCache.set(tag.key, value), value;
656
+ }, unsafeGet = Function_dual(2, (self, tag)=>{
657
+ if (!self.unsafeMap.has(tag.key)) {
658
+ if (ReferenceTypeId in tag) return getDefaultValue(tag);
659
+ throw ((tag)=>{
660
+ let error = Error(`Service not found${tag.key ? `: ${String(tag.key)}` : ""}`);
661
+ if (tag.stack) {
662
+ let lines = tag.stack.split("\n");
663
+ if (lines.length > 2) {
664
+ let afterAt = lines[2].match(/at (.*)/);
665
+ afterAt && (error.message = error.message + ` (defined at ${afterAt[1]})`);
666
+ }
667
+ }
668
+ if (error.stack) {
669
+ let lines = error.stack.split("\n");
670
+ lines.splice(1, 3), error.stack = lines.join("\n");
671
+ }
672
+ return error;
673
+ })(tag);
674
+ }
675
+ return self.unsafeMap.get(tag.key);
676
+ }), getOption = Function_dual(2, (self, tag)=>self.unsafeMap.has(tag.key) ? option_some(self.unsafeMap.get(tag.key)) : Predicate_hasProperty(tag, ReferenceTypeId) ? option_some(getDefaultValue(tag)) : option_none), merge = Function_dual(2, (self, that)=>{
677
+ let map = new Map(self.unsafeMap);
678
+ for (let [tag, s] of that.unsafeMap)map.set(tag, s);
679
+ return makeContext(map);
680
+ }), GenericTag = (key)=>{
681
+ let limit = Error.stackTraceLimit;
682
+ Error.stackTraceLimit = 2;
683
+ let creationError = Error();
684
+ Error.stackTraceLimit = limit;
685
+ let tag = Object.create(context_TagProto);
686
+ return Object.defineProperty(tag, "stack", {
687
+ get: ()=>creationError.stack
688
+ }), tag.key = key, tag;
689
+ }, Context_Reference = ()=>(id, options)=>{
690
+ let limit = Error.stackTraceLimit;
691
+ Error.stackTraceLimit = 2;
692
+ let creationError = Error();
693
+ function ReferenceClass() {}
694
+ return Error.stackTraceLimit = limit, Object.setPrototypeOf(ReferenceClass, ReferenceProto), ReferenceClass.key = id, ReferenceClass.defaultValue = options.defaultValue, Object.defineProperty(ReferenceClass, "stack", {
695
+ get: ()=>creationError.stack
696
+ }), ReferenceClass;
697
+ }, either_TypeId = Symbol.for("effect/Either"), either_CommonProto = {
438
698
  ...EffectPrototype,
439
699
  [either_TypeId]: {
440
700
  _R: (_)=>_
@@ -483,10 +743,10 @@ let isEqual = (u)=>Predicate_hasProperty(u, Equal_symbol), Inspectable_NodeInspe
483
743
  }, either_right = (right)=>{
484
744
  let a = Object.create(RightProto);
485
745
  return a.right = right, a;
486
- }, merge = (Function_dual(2, (self, { onLeft, onRight })=>isLeft(self) ? onLeft(self.left) : onRight(self.right)))({
746
+ }, Either_merge = (Function_dual(2, (self, { onLeft, onRight })=>isLeft(self) ? onLeft(self.left) : onRight(self.right)))({
487
747
  onLeft: Function_identity,
488
748
  onRight: Function_identity
489
- }), make = (isEquivalent)=>(self, that)=>self === that || isEquivalent(self, that), Equivalence_mapInput = Function_dual(2, (self, f)=>make((x, y)=>self(f(x), f(y)))), isNonEmptyArray = (self)=>self.length > 0, Option_none = ()=>option_none, Option_match = Function_dual(2, (self, { onNone, onSome })=>isNone(self) ? onNone() : onSome(self.value)), Option_getOrElse = Function_dual(2, (self, onNone)=>isNone(self) ? onNone() : self.value), orElseSome = Function_dual(2, (self, onNone)=>isNone(self) ? option_some(onNone()) : self), Option_fromNullable = (nullableValue)=>null == nullableValue ? Option_none() : option_some(nullableValue), Option_getOrUndefined = Option_getOrElse(Function_constUndefined), Option_getOrThrow = (Function_dual(2, (self, onNone)=>{
749
+ }), Equivalence_make = (isEquivalent)=>(self, that)=>self === that || isEquivalent(self, that), Equivalence_mapInput = Function_dual(2, (self, f)=>Equivalence_make((x, y)=>self(f(x), f(y)))), isNonEmptyArray = (self)=>self.length > 0, Option_none = ()=>option_none, Option_match = Function_dual(2, (self, { onNone, onSome })=>isNone(self) ? onNone() : onSome(self.value)), Option_getOrElse = Function_dual(2, (self, onNone)=>isNone(self) ? onNone() : self.value), orElseSome = Function_dual(2, (self, onNone)=>isNone(self) ? option_some(onNone()) : self), Option_fromNullable = (nullableValue)=>null == nullableValue ? Option_none() : option_some(nullableValue), Option_getOrUndefined = Option_getOrElse(Function_constUndefined), Option_getOrThrow = (Function_dual(2, (self, onNone)=>{
490
750
  if (isSome(self)) return self.value;
491
751
  throw onNone();
492
752
  }))(()=>Error("getOrThrow called on a None")), Option_map = Function_dual(2, (self, f)=>isNone(self) ? Option_none() : option_some(f(self.value))), Option_flatMap = Function_dual(2, (self, f)=>isNone(self) ? Option_none() : f(self.value)), contains = Function_dual(2, (self, a)=>!isNone(self) && equals(self.value, a)), mergeWith = (f)=>(o1, o2)=>isNone(o1) ? o2 : isNone(o2) ? o1 : option_some(f(o1.value, o2.value)), constEmpty = {
@@ -511,11 +771,11 @@ let isEqual = (u)=>Predicate_hasProperty(u, Equal_symbol), Inspectable_NodeInspe
511
771
  ]), Array_appendAll = Function_dual(2, (self, that)=>Array_fromIterable(self).concat(Array_fromIterable(that))), isOutOfBounds = (i, as)=>i < 0 || i >= as.length, Array_get = Function_dual(2, (self, index)=>{
512
772
  let i = Math.floor(index);
513
773
  return isOutOfBounds(i, self) ? Option_none() : option_some(self[i]);
514
- }), unsafeGet = Function_dual(2, (self, index)=>{
774
+ }), Array_unsafeGet = Function_dual(2, (self, index)=>{
515
775
  let i = Math.floor(index);
516
776
  if (isOutOfBounds(i, self)) throw Error(`Index ${i} out of bounds`);
517
777
  return self[i];
518
- }), Array_head = Array_get(0), headNonEmpty = unsafeGet(0), lastNonEmpty = (self)=>self[self.length - 1], tailNonEmpty = (self)=>self.slice(1), Array_span = Function_dual(2, (self, predicate)=>splitAt(self, ((self, predicate)=>{
778
+ }), Array_head = Array_get(0), headNonEmpty = Array_unsafeGet(0), lastNonEmpty = (self)=>self[self.length - 1], tailNonEmpty = (self)=>self.slice(1), Array_span = Function_dual(2, (self, predicate)=>splitAt(self, ((self, predicate)=>{
519
779
  let i = 0;
520
780
  for (let a of self){
521
781
  if (!predicate(a, i)) break;
@@ -593,7 +853,7 @@ let isEqual = (u)=>Predicate_hasProperty(u, Equal_symbol), Inspectable_NodeInspe
593
853
  out.push(a), next = b;
594
854
  }
595
855
  return out;
596
- }, Array_getEquivalence = (item)=>make((self, that)=>{
856
+ }, Array_getEquivalence = (item)=>Equivalence_make((self, that)=>{
597
857
  if (self.length !== that.length) return !1;
598
858
  for(let i = 0; i < self.length; i++)if (!item(self[i], that[i])) return !1;
599
859
  return !0;
@@ -607,7 +867,7 @@ let isEqual = (u)=>Predicate_hasProperty(u, Equal_symbol), Inspectable_NodeInspe
607
867
  return out;
608
868
  }
609
869
  return [];
610
- }), Array_dedupe = (self)=>dedupeWith(self, equals), join = Function_dual(2, (self, sep)=>Array_fromIterable(self).join(sep)), Chunk_TypeId = Symbol.for("effect/Chunk"), emptyArray = [], Chunk_equivalence = make((self, that)=>self.length === that.length && toReadonlyArray(self).every((value, i)=>equals(value, Chunk_unsafeGet(that, i)))), ChunkProto = {
870
+ }), Array_dedupe = (self)=>dedupeWith(self, equals), Array_join = Function_dual(2, (self, sep)=>Array_fromIterable(self).join(sep)), Chunk_TypeId = Symbol.for("effect/Chunk"), emptyArray = [], Chunk_equivalence = Equivalence_make((self, that)=>self.length === that.length && toReadonlyArray(self).every((value, i)=>equals(value, Chunk_unsafeGet(that, i)))), ChunkProto = {
611
871
  [Chunk_TypeId]: {
612
872
  _A: (_)=>_
613
873
  },
@@ -652,18 +912,18 @@ let isEqual = (u)=>Predicate_hasProperty(u, Equal_symbol), Inspectable_NodeInspe
652
912
  chunk.length = backing.left.length + backing.right.length, chunk.depth = 1 + Math.max(backing.left.depth, backing.right.depth), chunk.left = backing.left, chunk.right = backing.right;
653
913
  break;
654
914
  case "IArray":
655
- chunk.length = backing.array.length, chunk.depth = 0, chunk.left = _empty, chunk.right = _empty;
915
+ chunk.length = backing.array.length, chunk.depth = 0, chunk.left = Chunk_empty, chunk.right = Chunk_empty;
656
916
  break;
657
917
  case "ISingleton":
658
- chunk.length = 1, chunk.depth = 0, chunk.left = _empty, chunk.right = _empty;
918
+ chunk.length = 1, chunk.depth = 0, chunk.left = Chunk_empty, chunk.right = Chunk_empty;
659
919
  break;
660
920
  case "ISlice":
661
- chunk.length = backing.length, chunk.depth = backing.chunk.depth + 1, chunk.left = _empty, chunk.right = _empty;
921
+ chunk.length = backing.length, chunk.depth = backing.chunk.depth + 1, chunk.left = Chunk_empty, chunk.right = Chunk_empty;
662
922
  }
663
923
  return chunk;
664
- }, isChunk = (u)=>Predicate_hasProperty(u, Chunk_TypeId), _empty = makeChunk({
924
+ }, isChunk = (u)=>Predicate_hasProperty(u, Chunk_TypeId), Chunk_empty = makeChunk({
665
925
  _tag: "IEmpty"
666
- }), Chunk_empty = ()=>_empty, Chunk_make = (...as)=>unsafeFromNonEmptyArray(as), Chunk_of = (a)=>makeChunk({
926
+ }), esm_Chunk_empty = ()=>Chunk_empty, Chunk_make = (...as)=>unsafeFromNonEmptyArray(as), Chunk_of = (a)=>makeChunk({
667
927
  _tag: "ISingleton",
668
928
  a
669
929
  }), Chunk_fromIterable = (self)=>isChunk(self) ? self : unsafeFromArray(Array_fromIterable(self)), copyToArray = (self, array, initial)=>{
@@ -697,7 +957,7 @@ let isEqual = (u)=>Predicate_hasProperty(u, Equal_symbol), Inspectable_NodeInspe
697
957
  return copyToArray(self, arr, 0), self.backing = {
698
958
  _tag: "IArray",
699
959
  array: arr
700
- }, self.left = _empty, self.right = _empty, self.depth = 0, arr;
960
+ }, self.left = Chunk_empty, self.right = Chunk_empty, self.depth = 0, arr;
701
961
  }
702
962
  }
703
963
  }, Chunk_reverse = (self)=>{
@@ -719,7 +979,7 @@ let isEqual = (u)=>Predicate_hasProperty(u, Equal_symbol), Inspectable_NodeInspe
719
979
  case "ISlice":
720
980
  return unsafeFromArray(Array_reverse(toReadonlyArray(self)));
721
981
  }
722
- }, Chunk_get = Function_dual(2, (self, index)=>index < 0 || index >= self.length ? Option_none() : option_some(Chunk_unsafeGet(self, index))), unsafeFromArray = (self)=>0 === self.length ? Chunk_empty() : 1 === self.length ? Chunk_of(self[0]) : makeChunk({
982
+ }, Chunk_get = Function_dual(2, (self, index)=>index < 0 || index >= self.length ? Option_none() : option_some(Chunk_unsafeGet(self, index))), unsafeFromArray = (self)=>0 === self.length ? esm_Chunk_empty() : 1 === self.length ? Chunk_of(self[0]) : makeChunk({
723
983
  _tag: "IArray",
724
984
  array: self
725
985
  }), unsafeFromNonEmptyArray = (self)=>unsafeFromArray(self), Chunk_unsafeGet = Function_dual(2, (self, index)=>{
@@ -739,7 +999,7 @@ let isEqual = (u)=>Predicate_hasProperty(u, Equal_symbol), Inspectable_NodeInspe
739
999
  }
740
1000
  }), Chunk_append = Function_dual(2, (self, a)=>Chunk_appendAll(self, Chunk_of(a))), Chunk_prepend = Function_dual(2, (self, elem)=>Chunk_appendAll(Chunk_of(elem), self)), Chunk_drop = Function_dual(2, (self, n)=>{
741
1001
  if (n <= 0) return self;
742
- if (n >= self.length) return _empty;
1002
+ if (n >= self.length) return Chunk_empty;
743
1003
  switch(self.backing._tag){
744
1004
  case "ISlice":
745
1005
  return makeChunk({
@@ -838,39 +1098,225 @@ let isEqual = (u)=>Predicate_hasProperty(u, Equal_symbol), Inspectable_NodeInspe
838
1098
  });
839
1099
  }
840
1100
  }
841
- }), Chunk_isEmpty = (self)=>0 === self.length, isNonEmpty = (self)=>self.length > 0, Chunk_head = Chunk_get(0), Chunk_unsafeHead = (self)=>Chunk_unsafeGet(self, 0), Chunk_tailNonEmpty = (self)=>Chunk_drop(self, 1);
842
- function fromBitmap(bitmap, bit) {
843
- var x;
844
- return x = bitmap & bit - 1, x -= x >> 1 & 0x55555555, x = (x = (0x33333333 & x) + (x >> 2 & 0x33333333)) + (x >> 4) & 0x0f0f0f0f, x += x >> 8, 0x7f & (x += x >> 16);
845
- }
846
- let stack_make = (value, previous)=>({
847
- value,
848
- previous
849
- });
850
- function arrayUpdate(mutate, at, v, arr) {
851
- let out = arr;
852
- if (!mutate) {
853
- let len = arr.length;
854
- out = Array(len);
855
- for(let i = 0; i < len; ++i)out[i] = arr[i];
856
- }
857
- return out[at] = v, out;
858
- }
859
- function arraySpliceOut(mutate, at, arr) {
860
- let newLen = arr.length - 1, i = 0, g = 0, out = arr;
861
- if (mutate) i = g = at;
862
- else for(out = Array(newLen); i < at;)out[g++] = arr[i++];
863
- for(++i; i <= newLen;)out[g++] = arr[i++];
864
- return mutate && (out.length = newLen), out;
865
- }
866
- class EmptyNode {
867
- _tag = "EmptyNode";
868
- modify(edit, _shift, f, hash, key, size) {
869
- let v = f(Option_none());
870
- return isNone(v) ? new EmptyNode() : (++size.value, new LeafNode(edit, hash, key, v));
871
- }
872
- }
873
- function isEmptyNode(a) {
1101
+ }), Chunk_isEmpty = (self)=>0 === self.length, isNonEmpty = (self)=>self.length > 0, Chunk_head = Chunk_get(0), Chunk_unsafeHead = (self)=>Chunk_unsafeGet(self, 0), Chunk_tailNonEmpty = (self)=>Chunk_drop(self, 1), Duration_TypeId = Symbol.for("effect/Duration"), bigint0 = BigInt(0), bigint24 = BigInt(24), bigint60 = BigInt(60), bigint1e3 = BigInt(1000), Duration_bigint1e6 = BigInt(1000000), bigint1e9 = BigInt(1000000000), DURATION_REGEX = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/, decode = (input)=>{
1102
+ if (isDuration(input)) return input;
1103
+ if (isNumber(input)) return Duration_millis(input);
1104
+ if ("bigint" == typeof input) return Duration_nanos(input);
1105
+ if (Array.isArray(input) && 2 === input.length && input.every(isNumber)) return -1 / 0 === input[0] || -1 / 0 === input[1] || Number.isNaN(input[0]) || Number.isNaN(input[1]) ? Duration_zero : 1 / 0 === input[0] || 1 / 0 === input[1] ? infinity : Duration_nanos(BigInt(Math.round(1000000000 * input[0])) + BigInt(Math.round(input[1])));
1106
+ if ("string" == typeof input) {
1107
+ let match = DURATION_REGEX.exec(input);
1108
+ if (match) {
1109
+ let [_, valueStr, unit] = match, value = Number(valueStr);
1110
+ switch(unit){
1111
+ case "nano":
1112
+ case "nanos":
1113
+ return Duration_nanos(BigInt(valueStr));
1114
+ case "micro":
1115
+ case "micros":
1116
+ return Duration_micros(BigInt(valueStr));
1117
+ case "milli":
1118
+ case "millis":
1119
+ return Duration_millis(value);
1120
+ case "second":
1121
+ case "seconds":
1122
+ return Duration_seconds(value);
1123
+ case "minute":
1124
+ case "minutes":
1125
+ return Duration_minutes(value);
1126
+ case "hour":
1127
+ case "hours":
1128
+ return Duration_hours(value);
1129
+ case "day":
1130
+ case "days":
1131
+ return Duration_days(value);
1132
+ case "week":
1133
+ case "weeks":
1134
+ return Duration_weeks(value);
1135
+ }
1136
+ }
1137
+ }
1138
+ throw Error("Invalid DurationInput");
1139
+ }, zeroValue = {
1140
+ _tag: "Millis",
1141
+ millis: 0
1142
+ }, infinityValue = {
1143
+ _tag: "Infinity"
1144
+ }, DurationProto = {
1145
+ [Duration_TypeId]: Duration_TypeId,
1146
+ [Hash_symbol] () {
1147
+ return Hash_cached(this, structure(this.value));
1148
+ },
1149
+ [Equal_symbol] (that) {
1150
+ return isDuration(that) && Duration_equals(this, that);
1151
+ },
1152
+ toString () {
1153
+ return `Duration(${Duration_format(this)})`;
1154
+ },
1155
+ toJSON () {
1156
+ switch(this.value._tag){
1157
+ case "Millis":
1158
+ return {
1159
+ _id: "Duration",
1160
+ _tag: "Millis",
1161
+ millis: this.value.millis
1162
+ };
1163
+ case "Nanos":
1164
+ return {
1165
+ _id: "Duration",
1166
+ _tag: "Nanos",
1167
+ hrtime: toHrTime(this)
1168
+ };
1169
+ case "Infinity":
1170
+ return {
1171
+ _id: "Duration",
1172
+ _tag: "Infinity"
1173
+ };
1174
+ }
1175
+ },
1176
+ [Inspectable_NodeInspectSymbol] () {
1177
+ return this.toJSON();
1178
+ },
1179
+ pipe () {
1180
+ return Pipeable_pipeArguments(this, arguments);
1181
+ }
1182
+ }, Duration_make = (input)=>{
1183
+ let duration = Object.create(DurationProto);
1184
+ return isNumber(input) ? isNaN(input) || input <= 0 ? duration.value = zeroValue : Number.isFinite(input) ? Number.isInteger(input) ? duration.value = {
1185
+ _tag: "Millis",
1186
+ millis: input
1187
+ } : duration.value = {
1188
+ _tag: "Nanos",
1189
+ nanos: BigInt(Math.round(1000000 * input))
1190
+ } : duration.value = infinityValue : input <= bigint0 ? duration.value = zeroValue : duration.value = {
1191
+ _tag: "Nanos",
1192
+ nanos: input
1193
+ }, duration;
1194
+ }, isDuration = (u)=>Predicate_hasProperty(u, Duration_TypeId), Duration_zero = Duration_make(0), infinity = Duration_make(1 / 0), Duration_nanos = (nanos)=>Duration_make(nanos), Duration_micros = (micros)=>Duration_make(micros * bigint1e3), Duration_millis = (millis)=>Duration_make(millis), Duration_seconds = (seconds)=>Duration_make(1000 * seconds), Duration_minutes = (minutes)=>Duration_make(60000 * minutes), Duration_hours = (hours)=>Duration_make(3600000 * hours), Duration_days = (days)=>Duration_make(86400000 * days), Duration_weeks = (weeks)=>Duration_make(604800000 * weeks), toMillis = (self)=>Duration_match(self, {
1195
+ onMillis: (millis)=>millis,
1196
+ onNanos: (nanos)=>Number(nanos) / 1000000
1197
+ }), toHrTime = (self)=>{
1198
+ let _self = decode(self);
1199
+ switch(_self.value._tag){
1200
+ case "Infinity":
1201
+ return [
1202
+ 1 / 0,
1203
+ 0
1204
+ ];
1205
+ case "Nanos":
1206
+ return [
1207
+ Number(_self.value.nanos / bigint1e9),
1208
+ Number(_self.value.nanos % bigint1e9)
1209
+ ];
1210
+ case "Millis":
1211
+ return [
1212
+ Math.floor(_self.value.millis / 1000),
1213
+ Math.round(_self.value.millis % 1000 * 1000000)
1214
+ ];
1215
+ }
1216
+ }, Duration_match = Function_dual(2, (self, options)=>{
1217
+ let _self = decode(self);
1218
+ switch(_self.value._tag){
1219
+ case "Nanos":
1220
+ return options.onNanos(_self.value.nanos);
1221
+ case "Infinity":
1222
+ return options.onMillis(1 / 0);
1223
+ case "Millis":
1224
+ return options.onMillis(_self.value.millis);
1225
+ }
1226
+ }), matchWith = Function_dual(3, (self, that, options)=>{
1227
+ let _self = decode(self), _that = decode(that);
1228
+ if ("Infinity" === _self.value._tag || "Infinity" === _that.value._tag) return options.onMillis(toMillis(_self), toMillis(_that));
1229
+ if ("Nanos" === _self.value._tag || "Nanos" === _that.value._tag) {
1230
+ let selfNanos = "Nanos" === _self.value._tag ? _self.value.nanos : BigInt(Math.round(1000000 * _self.value.millis)), thatNanos = "Nanos" === _that.value._tag ? _that.value.nanos : BigInt(Math.round(1000000 * _that.value.millis));
1231
+ return options.onNanos(selfNanos, thatNanos);
1232
+ }
1233
+ return options.onMillis(_self.value.millis, _that.value.millis);
1234
+ }), Duration_lessThanOrEqualTo = Function_dual(2, (self, that)=>matchWith(self, that, {
1235
+ onMillis: (self, that)=>self <= that,
1236
+ onNanos: (self, that)=>self <= that
1237
+ })), Duration_greaterThanOrEqualTo = Function_dual(2, (self, that)=>matchWith(self, that, {
1238
+ onMillis: (self, that)=>self >= that,
1239
+ onNanos: (self, that)=>self >= that
1240
+ })), Duration_equals = Function_dual(2, (self, that)=>matchWith(decode(self), decode(that), {
1241
+ onMillis: (self, that)=>self === that,
1242
+ onNanos: (self, that)=>self === that
1243
+ })), Duration_format = (self)=>{
1244
+ let duration = decode(self);
1245
+ if ("Infinity" === duration.value._tag) return "Infinity";
1246
+ if (((self)=>{
1247
+ switch(self.value._tag){
1248
+ case "Millis":
1249
+ return 0 === self.value.millis;
1250
+ case "Nanos":
1251
+ return self.value.nanos === bigint0;
1252
+ case "Infinity":
1253
+ return !1;
1254
+ }
1255
+ })(duration)) return "0";
1256
+ let fragments = ((self)=>{
1257
+ let duration = decode(self);
1258
+ if ("Infinity" === duration.value._tag) return {
1259
+ days: 1 / 0,
1260
+ hours: 1 / 0,
1261
+ minutes: 1 / 0,
1262
+ seconds: 1 / 0,
1263
+ millis: 1 / 0,
1264
+ nanos: 1 / 0
1265
+ };
1266
+ let nanos = ((self)=>{
1267
+ let _self = decode(self);
1268
+ switch(_self.value._tag){
1269
+ case "Infinity":
1270
+ throw Error("Cannot convert infinite duration to nanos");
1271
+ case "Nanos":
1272
+ return _self.value.nanos;
1273
+ case "Millis":
1274
+ return BigInt(Math.round(1000000 * _self.value.millis));
1275
+ }
1276
+ })(duration), ms = nanos / Duration_bigint1e6, sec = ms / bigint1e3, min = sec / bigint60, hr = min / bigint60;
1277
+ return {
1278
+ days: Number(hr / bigint24),
1279
+ hours: Number(hr % bigint24),
1280
+ minutes: Number(min % bigint60),
1281
+ seconds: Number(sec % bigint60),
1282
+ millis: Number(ms % bigint1e3),
1283
+ nanos: Number(nanos % Duration_bigint1e6)
1284
+ };
1285
+ })(duration), pieces = [];
1286
+ return 0 !== fragments.days && pieces.push(`${fragments.days}d`), 0 !== fragments.hours && pieces.push(`${fragments.hours}h`), 0 !== fragments.minutes && pieces.push(`${fragments.minutes}m`), 0 !== fragments.seconds && pieces.push(`${fragments.seconds}s`), 0 !== fragments.millis && pieces.push(`${fragments.millis}ms`), 0 !== fragments.nanos && pieces.push(`${fragments.nanos}ns`), pieces.join(" ");
1287
+ };
1288
+ function fromBitmap(bitmap, bit) {
1289
+ var x;
1290
+ return x = bitmap & bit - 1, x -= x >> 1 & 0x55555555, x = (x = (0x33333333 & x) + (x >> 2 & 0x33333333)) + (x >> 4) & 0x0f0f0f0f, x += x >> 8, 0x7f & (x += x >> 16);
1291
+ }
1292
+ let stack_make = (value, previous)=>({
1293
+ value,
1294
+ previous
1295
+ });
1296
+ function arrayUpdate(mutate, at, v, arr) {
1297
+ let out = arr;
1298
+ if (!mutate) {
1299
+ let len = arr.length;
1300
+ out = Array(len);
1301
+ for(let i = 0; i < len; ++i)out[i] = arr[i];
1302
+ }
1303
+ return out[at] = v, out;
1304
+ }
1305
+ function arraySpliceOut(mutate, at, arr) {
1306
+ let newLen = arr.length - 1, i = 0, g = 0, out = arr;
1307
+ if (mutate) i = g = at;
1308
+ else for(out = Array(newLen); i < at;)out[g++] = arr[i++];
1309
+ for(++i; i <= newLen;)out[g++] = arr[i++];
1310
+ return mutate && (out.length = newLen), out;
1311
+ }
1312
+ class EmptyNode {
1313
+ _tag = "EmptyNode";
1314
+ modify(edit, _shift, f, hash, key, size) {
1315
+ let v = f(Option_none());
1316
+ return isNone(v) ? new EmptyNode() : (++size.value, new LeafNode(edit, hash, key, v));
1317
+ }
1318
+ }
1319
+ function isEmptyNode(a) {
874
1320
  return Predicate_isTagged(a, "EmptyNode");
875
1321
  }
876
1322
  function canEditNode(node, edit) {
@@ -1206,691 +1652,27 @@ let applyCont = (cont)=>cont ? visitLazyChildren(cont[0], cont[1], cont[2], cont
1206
1652
  }), hashSet_every = Function_dual(2, (self, refinement)=>!hashSet_some(self, (a)=>!refinement(a))), hashSet_beginMutation = (self)=>hashSet_makeImpl(beginMutation(self._keyMap)), hashSet_endMutation = (self)=>(self._keyMap._editable = !1, self), hashSet_mutate = Function_dual(2, (self, f)=>{
1207
1653
  let transient = hashSet_beginMutation(self);
1208
1654
  return f(transient), hashSet_endMutation(transient);
1209
- }), add = Function_dual(2, (self, value)=>self._keyMap._editable ? (hashMap_set(value, !0)(self._keyMap), self) : hashSet_makeImpl(hashMap_set(value, !0)(self._keyMap))), hashSet_remove = Function_dual(2, (self, value)=>self._keyMap._editable ? (hashMap_remove(value)(self._keyMap), self) : hashSet_makeImpl(hashMap_remove(value)(self._keyMap))), hashSet_difference = Function_dual(2, (self, that)=>hashSet_mutate(self, (set)=>{
1655
+ }), hashSet_add = Function_dual(2, (self, value)=>self._keyMap._editable ? (hashMap_set(value, !0)(self._keyMap), self) : hashSet_makeImpl(hashMap_set(value, !0)(self._keyMap))), hashSet_remove = Function_dual(2, (self, value)=>self._keyMap._editable ? (hashMap_remove(value)(self._keyMap), self) : hashSet_makeImpl(hashMap_remove(value)(self._keyMap))), hashSet_difference = Function_dual(2, (self, that)=>hashSet_mutate(self, (set)=>{
1210
1656
  for (let value of that)hashSet_remove(set, value);
1211
1657
  })), hashSet_union = Function_dual(2, (self, that)=>hashSet_mutate(internal_hashSet_empty(), (set)=>{
1212
- for (let value of (hashSet_forEach(self, (value)=>add(set, value)), that))add(set, value);
1658
+ for (let value of (hashSet_forEach(self, (value)=>hashSet_add(set, value)), that))hashSet_add(set, value);
1213
1659
  })), hashSet_forEach = Function_dual(2, (self, f)=>hashMap_forEach(self._keyMap, (_, k)=>f(k))), hashSet_reduce = Function_dual(3, (self, zero, f)=>hashMap_reduce(self._keyMap, zero, (z, _, a)=>f(z, a))), HashSet_make = (...elements)=>{
1214
1660
  let set = hashSet_beginMutation(internal_hashSet_empty());
1215
- for (let value of elements)add(set, value);
1661
+ for (let value of elements)hashSet_add(set, value);
1216
1662
  return hashSet_endMutation(set);
1217
- }, HashSet_size = (self)=>self._keyMap._size, OP_INTERRUPT = "Interrupt", OP_PARALLEL = "Parallel", OP_SEQUENTIAL = "Sequential", CauseSymbolKey = "effect/Cause", CauseTypeId = Symbol.for(CauseSymbolKey), cause_proto = {
1218
- [CauseTypeId]: {
1219
- _E: (_)=>_
1663
+ }, HashSet_size = (self)=>self._keyMap._size, MutableRef_TypeId = Symbol.for("effect/MutableRef"), MutableRefProto = {
1664
+ [MutableRef_TypeId]: MutableRef_TypeId,
1665
+ toString () {
1666
+ return JSON.stringify(this.toJSON(), null, 2);
1220
1667
  },
1221
- [Hash_symbol] () {
1222
- return Function_pipe(Hash_hash(CauseSymbolKey), Hash_combine(Hash_hash(flattenCause(this))), Hash_cached(this));
1668
+ toJSON () {
1669
+ return {
1670
+ _id: "MutableRef",
1671
+ current: toJSON(this.current)
1672
+ };
1223
1673
  },
1224
- [Equal_symbol] (that) {
1225
- return isCause(that) && causeEquals(this, that);
1226
- },
1227
- pipe () {
1228
- return Pipeable_pipeArguments(this, arguments);
1229
- },
1230
- toJSON () {
1231
- switch(this._tag){
1232
- case "Empty":
1233
- return {
1234
- _id: "Cause",
1235
- _tag: this._tag
1236
- };
1237
- case "Die":
1238
- return {
1239
- _id: "Cause",
1240
- _tag: this._tag,
1241
- defect: toJSON(this.defect)
1242
- };
1243
- case "Interrupt":
1244
- return {
1245
- _id: "Cause",
1246
- _tag: this._tag,
1247
- fiberId: this.fiberId.toJSON()
1248
- };
1249
- case "Fail":
1250
- return {
1251
- _id: "Cause",
1252
- _tag: this._tag,
1253
- failure: toJSON(this.error)
1254
- };
1255
- case "Sequential":
1256
- case "Parallel":
1257
- return {
1258
- _id: "Cause",
1259
- _tag: this._tag,
1260
- left: toJSON(this.left),
1261
- right: toJSON(this.right)
1262
- };
1263
- }
1264
- },
1265
- toString () {
1266
- return pretty(this);
1267
- },
1268
- [Inspectable_NodeInspectSymbol] () {
1269
- return this.toJSON();
1270
- }
1271
- }, cause_empty = ((o = Object.create(cause_proto))._tag = "Empty", o), cause_fail = (error)=>{
1272
- let o = Object.create(cause_proto);
1273
- return o._tag = "Fail", o.error = error, o;
1274
- }, cause_die = (defect)=>{
1275
- let o = Object.create(cause_proto);
1276
- return o._tag = "Die", o.defect = defect, o;
1277
- }, interrupt = (fiberId)=>{
1278
- let o = Object.create(cause_proto);
1279
- return o._tag = OP_INTERRUPT, o.fiberId = fiberId, o;
1280
- }, cause_parallel = (left, right)=>{
1281
- let o = Object.create(cause_proto);
1282
- return o._tag = OP_PARALLEL, o.left = left, o.right = right, o;
1283
- }, cause_sequential = (left, right)=>{
1284
- let o = Object.create(cause_proto);
1285
- return o._tag = OP_SEQUENTIAL, o.left = left, o.right = right, o;
1286
- }, isCause = (u)=>Predicate_hasProperty(u, CauseTypeId), cause_isEmpty = (self)=>"Empty" === self._tag || cause_reduce(self, !0, (acc, cause)=>{
1287
- switch(cause._tag){
1288
- case "Empty":
1289
- return option_some(acc);
1290
- case "Die":
1291
- case "Fail":
1292
- case OP_INTERRUPT:
1293
- return option_some(!1);
1294
- default:
1295
- return Option_none();
1296
- }
1297
- }), isInterruptedOnly = (self)=>reduceWithContext(void 0, IsInterruptedOnlyCauseReducer)(self), cause_defects = (self)=>Chunk_reverse(cause_reduce(self, Chunk_empty(), (list, cause)=>"Die" === cause._tag ? option_some(Function_pipe(list, Chunk_prepend(cause.defect))) : Option_none())), interruptors = (self)=>cause_reduce(self, internal_hashSet_empty(), (set, cause)=>cause._tag === OP_INTERRUPT ? option_some(Function_pipe(set, add(cause.fiberId))) : Option_none()), failureOption = (self)=>find(self, (cause)=>"Fail" === cause._tag ? option_some(cause.error) : Option_none()), cause_failureOrCause = (self)=>{
1298
- let option = failureOption(self);
1299
- switch(option._tag){
1300
- case "None":
1301
- return either_right(self);
1302
- case "Some":
1303
- return either_left(option.value);
1304
- }
1305
- }, stripFailures = (self)=>cause_match(self, {
1306
- onEmpty: cause_empty,
1307
- onFail: ()=>cause_empty,
1308
- onDie: cause_die,
1309
- onInterrupt: interrupt,
1310
- onSequential: cause_sequential,
1311
- onParallel: cause_parallel
1312
- }), cause_flatMap = ((self, f)=>cause_flatMap(self, (e)=>cause_fail(f(e))), Function_dual(2, (self, f)=>cause_match(self, {
1313
- onEmpty: cause_empty,
1314
- onFail: (error)=>f(error),
1315
- onDie: (defect)=>cause_die(defect),
1316
- onInterrupt: (fiberId)=>interrupt(fiberId),
1317
- onSequential: (left, right)=>cause_sequential(left, right),
1318
- onParallel: (left, right)=>cause_parallel(left, right)
1319
- }))), causeEquals = (left, right)=>{
1320
- let leftStack = Chunk_of(left), rightStack = Chunk_of(right);
1321
- for(; isNonEmpty(leftStack) && isNonEmpty(rightStack);){
1322
- let [leftParallel, leftSequential] = Function_pipe(Chunk_unsafeHead(leftStack), cause_reduce([
1323
- internal_hashSet_empty(),
1324
- Chunk_empty()
1325
- ], ([parallel, sequential], cause)=>{
1326
- let [par, seq] = evaluateCause(cause);
1327
- return option_some([
1328
- Function_pipe(parallel, hashSet_union(par)),
1329
- Function_pipe(sequential, Chunk_appendAll(seq))
1330
- ]);
1331
- })), [rightParallel, rightSequential] = Function_pipe(Chunk_unsafeHead(rightStack), cause_reduce([
1332
- internal_hashSet_empty(),
1333
- Chunk_empty()
1334
- ], ([parallel, sequential], cause)=>{
1335
- let [par, seq] = evaluateCause(cause);
1336
- return option_some([
1337
- Function_pipe(parallel, hashSet_union(par)),
1338
- Function_pipe(sequential, Chunk_appendAll(seq))
1339
- ]);
1340
- }));
1341
- if (!equals(leftParallel, rightParallel)) return !1;
1342
- leftStack = leftSequential, rightStack = rightSequential;
1343
- }
1344
- return !0;
1345
- }, flattenCause = (cause)=>flattenCauseLoop(Chunk_of(cause), Chunk_empty()), flattenCauseLoop = (causes, flattened)=>{
1346
- for(;;){
1347
- let [parallel, sequential] = Function_pipe(causes, Array_reduce([
1348
- internal_hashSet_empty(),
1349
- Chunk_empty()
1350
- ], ([parallel, sequential], cause)=>{
1351
- let [par, seq] = evaluateCause(cause);
1352
- return [
1353
- Function_pipe(parallel, hashSet_union(par)),
1354
- Function_pipe(sequential, Chunk_appendAll(seq))
1355
- ];
1356
- })), updated = HashSet_size(parallel) > 0 ? Function_pipe(flattened, Chunk_prepend(parallel)) : flattened;
1357
- if (Chunk_isEmpty(sequential)) return Chunk_reverse(updated);
1358
- causes = sequential, flattened = updated;
1359
- }
1360
- throw Error(getBugErrorMessage("Cause.flattenCauseLoop"));
1361
- }, find = Function_dual(2, (self, pf)=>{
1362
- let stack = [
1363
- self
1364
- ];
1365
- for(; stack.length > 0;){
1366
- let item = stack.pop(), option = pf(item);
1367
- switch(option._tag){
1368
- case "None":
1369
- switch(item._tag){
1370
- case OP_SEQUENTIAL:
1371
- case OP_PARALLEL:
1372
- stack.push(item.right), stack.push(item.left);
1373
- }
1374
- break;
1375
- case "Some":
1376
- return option;
1377
- }
1378
- }
1379
- return Option_none();
1380
- }), evaluateCause = (self)=>{
1381
- let cause = self, stack = [], _parallel = internal_hashSet_empty(), _sequential = Chunk_empty();
1382
- for(; void 0 !== cause;)switch(cause._tag){
1383
- case "Empty":
1384
- if (0 === stack.length) return [
1385
- _parallel,
1386
- _sequential
1387
- ];
1388
- cause = stack.pop();
1389
- break;
1390
- case "Fail":
1391
- if (_parallel = add(_parallel, Chunk_make(cause._tag, cause.error)), 0 === stack.length) return [
1392
- _parallel,
1393
- _sequential
1394
- ];
1395
- cause = stack.pop();
1396
- break;
1397
- case "Die":
1398
- if (_parallel = add(_parallel, Chunk_make(cause._tag, cause.defect)), 0 === stack.length) return [
1399
- _parallel,
1400
- _sequential
1401
- ];
1402
- cause = stack.pop();
1403
- break;
1404
- case OP_INTERRUPT:
1405
- if (_parallel = add(_parallel, Chunk_make(cause._tag, cause.fiberId)), 0 === stack.length) return [
1406
- _parallel,
1407
- _sequential
1408
- ];
1409
- cause = stack.pop();
1410
- break;
1411
- case OP_SEQUENTIAL:
1412
- switch(cause.left._tag){
1413
- case "Empty":
1414
- cause = cause.right;
1415
- break;
1416
- case OP_SEQUENTIAL:
1417
- cause = cause_sequential(cause.left.left, cause_sequential(cause.left.right, cause.right));
1418
- break;
1419
- case OP_PARALLEL:
1420
- cause = cause_parallel(cause_sequential(cause.left.left, cause.right), cause_sequential(cause.left.right, cause.right));
1421
- break;
1422
- default:
1423
- _sequential = Chunk_prepend(_sequential, cause.right), cause = cause.left;
1424
- }
1425
- break;
1426
- case OP_PARALLEL:
1427
- stack.push(cause.right), cause = cause.left;
1428
- }
1429
- throw Error(getBugErrorMessage("Cause.evaluateCauseLoop"));
1430
- }, IsInterruptedOnlyCauseReducer = {
1431
- emptyCase: Function_constTrue,
1432
- failCase: Function_constFalse,
1433
- dieCase: Function_constFalse,
1434
- interruptCase: Function_constTrue,
1435
- sequentialCase: (_, left, right)=>left && right,
1436
- parallelCase: (_, left, right)=>left && right
1437
- }, OP_SEQUENTIAL_CASE = "SequentialCase", OP_PARALLEL_CASE = "ParallelCase", cause_match = Function_dual(2, (self, { onDie, onEmpty, onFail, onInterrupt, onParallel, onSequential })=>reduceWithContext(self, void 0, {
1438
- emptyCase: ()=>onEmpty,
1439
- failCase: (_, error)=>onFail(error),
1440
- dieCase: (_, defect)=>onDie(defect),
1441
- interruptCase: (_, fiberId)=>onInterrupt(fiberId),
1442
- sequentialCase: (_, left, right)=>onSequential(left, right),
1443
- parallelCase: (_, left, right)=>onParallel(left, right)
1444
- })), cause_reduce = Function_dual(3, (self, zero, pf)=>{
1445
- let accumulator = zero, cause = self, causes = [];
1446
- for(; void 0 !== cause;){
1447
- let option = pf(accumulator, cause);
1448
- switch(accumulator = isSome(option) ? option.value : accumulator, cause._tag){
1449
- case OP_SEQUENTIAL:
1450
- case OP_PARALLEL:
1451
- causes.push(cause.right), cause = cause.left;
1452
- break;
1453
- default:
1454
- cause = void 0;
1455
- }
1456
- void 0 === cause && causes.length > 0 && (cause = causes.pop());
1457
- }
1458
- return accumulator;
1459
- }), reduceWithContext = Function_dual(3, (self, context, reducer)=>{
1460
- let input = [
1461
- self
1462
- ], output = [];
1463
- for(; input.length > 0;){
1464
- let cause = input.pop();
1465
- switch(cause._tag){
1466
- case "Empty":
1467
- output.push(either_right(reducer.emptyCase(context)));
1468
- break;
1469
- case "Fail":
1470
- output.push(either_right(reducer.failCase(context, cause.error)));
1471
- break;
1472
- case "Die":
1473
- output.push(either_right(reducer.dieCase(context, cause.defect)));
1474
- break;
1475
- case OP_INTERRUPT:
1476
- output.push(either_right(reducer.interruptCase(context, cause.fiberId)));
1477
- break;
1478
- case OP_SEQUENTIAL:
1479
- input.push(cause.right), input.push(cause.left), output.push(either_left({
1480
- _tag: OP_SEQUENTIAL_CASE
1481
- }));
1482
- break;
1483
- case OP_PARALLEL:
1484
- input.push(cause.right), input.push(cause.left), output.push(either_left({
1485
- _tag: OP_PARALLEL_CASE
1486
- }));
1487
- }
1488
- }
1489
- let accumulator = [];
1490
- for(; output.length > 0;){
1491
- let either = output.pop();
1492
- switch(either._tag){
1493
- case "Left":
1494
- switch(either.left._tag){
1495
- case OP_SEQUENTIAL_CASE:
1496
- {
1497
- let left = accumulator.pop(), right = accumulator.pop(), value = reducer.sequentialCase(context, left, right);
1498
- accumulator.push(value);
1499
- break;
1500
- }
1501
- case OP_PARALLEL_CASE:
1502
- {
1503
- let left = accumulator.pop(), right = accumulator.pop(), value = reducer.parallelCase(context, left, right);
1504
- accumulator.push(value);
1505
- }
1506
- }
1507
- break;
1508
- case "Right":
1509
- accumulator.push(either.right);
1510
- }
1511
- }
1512
- if (0 === accumulator.length) throw Error("BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");
1513
- return accumulator.pop();
1514
- }), pretty = (cause, options)=>isInterruptedOnly(cause) ? "All fibers interrupted without errors." : prettyErrors(cause).map(function(e) {
1515
- return options?.renderErrorCause !== !0 || void 0 === e.cause ? e.stack : `${e.stack} {\n${renderErrorCause(e.cause, " ")}\n}`;
1516
- }).join("\n"), renderErrorCause = (cause, prefix)=>{
1517
- let lines = cause.stack.split("\n"), stack = `${prefix}[cause]: ${lines[0]}`;
1518
- for(let i = 1, len = lines.length; i < len; i++)stack += `\n${prefix}${lines[i]}`;
1519
- return cause.cause && (stack += ` {\n${renderErrorCause(cause.cause, `${prefix} `)}\n${prefix}}`), stack;
1520
- }, makePrettyError = (originalError)=>{
1521
- let originalErrorIsObject = "object" == typeof originalError && null !== originalError, prevLimit = Error.stackTraceLimit;
1522
- Error.stackTraceLimit = 1;
1523
- let error = Error(prettyErrorMessage(originalError), originalErrorIsObject && "cause" in originalError && void 0 !== originalError.cause ? {
1524
- cause: makePrettyError(originalError.cause)
1525
- } : void 0);
1526
- return Error.stackTraceLimit = prevLimit, "" === error.message && (error.message = "An error has occurred"), Error.stackTraceLimit = prevLimit, error.name = originalError instanceof Error ? originalError.name : "Error", originalErrorIsObject && (spanSymbol in originalError && (error.span = originalError[spanSymbol]), Object.keys(originalError).forEach((key)=>{
1527
- key in error || (error[key] = originalError[key]);
1528
- })), error.stack = prettyErrorStack(`${error.name}: ${error.message}`, originalError instanceof Error && originalError.stack ? originalError.stack : "", error.span), error;
1529
- }, prettyErrorMessage = (u)=>{
1530
- if ("string" == typeof u) return u;
1531
- if ("object" == typeof u && null !== u && u instanceof Error) return u.message;
1532
- try {
1533
- let input;
1534
- if (Predicate_hasProperty(u, "toString") && (input = u.toString, "function" == typeof input) && u.toString !== Object.prototype.toString && u.toString !== globalThis.Array.prototype.toString) return u.toString();
1535
- } catch {}
1536
- return stringifyCircular(u);
1537
- }, locationRegex = /\((.*)\)/g, spanToTrace = GlobalValue_globalValue("effect/Tracer/spanToTrace", ()=>new WeakMap()), prettyErrorStack = (message, stack, span)=>{
1538
- let out = [
1539
- message
1540
- ], lines = stack.startsWith(message) ? stack.slice(message.length).split("\n") : stack.split("\n");
1541
- for(let i = 1; i < lines.length; i++){
1542
- if (lines[i].includes(" at new BaseEffectError") || lines[i].includes(" at new YieldableError")) {
1543
- i++;
1544
- continue;
1545
- }
1546
- if (lines[i].includes("Generator.next") || lines[i].includes("effect_internal_function")) break;
1547
- out.push(lines[i].replace(/at .*effect_instruction_i.*\((.*)\)/, "at $1").replace(/EffectPrimitive\.\w+/, "<anonymous>"));
1548
- }
1549
- if (span) {
1550
- let current = span, i = 0;
1551
- for(; current && "Span" === current._tag && i < 10;){
1552
- let stackFn = spanToTrace.get(current);
1553
- if ("function" == typeof stackFn) {
1554
- let stack = stackFn();
1555
- if ("string" == typeof stack) {
1556
- let locationMatchAll = stack.matchAll(locationRegex), match = !1;
1557
- for (let [, location] of locationMatchAll)match = !0, out.push(` at ${current.name} (${location})`);
1558
- match || out.push(` at ${current.name} (${stack.replace(/^at /, "")})`);
1559
- } else out.push(` at ${current.name}`);
1560
- } else out.push(` at ${current.name}`);
1561
- current = Option_getOrUndefined(current.parent), i++;
1562
- }
1563
- }
1564
- return out.join("\n");
1565
- }, spanSymbol = Symbol.for("effect/SpanAnnotation"), prettyErrors = (cause)=>reduceWithContext(cause, void 0, {
1566
- emptyCase: ()=>[],
1567
- dieCase: (_, unknownError)=>[
1568
- makePrettyError(unknownError)
1569
- ],
1570
- failCase: (_, error)=>[
1571
- makePrettyError(error)
1572
- ],
1573
- interruptCase: ()=>[],
1574
- parallelCase: (_, l, r)=>[
1575
- ...l,
1576
- ...r
1577
- ],
1578
- sequentialCase: (_, l, r)=>[
1579
- ...l,
1580
- ...r
1581
- ]
1582
- }), TagTypeId = Symbol.for("effect/Context/Tag"), ReferenceTypeId = Symbol.for("effect/Context/Reference"), STMTypeId = Symbol.for("effect/STM"), context_TagProto = {
1583
- ...EffectPrototype,
1584
- _op: "Tag",
1585
- [STMTypeId]: effectVariance,
1586
- [TagTypeId]: {
1587
- _Service: (_)=>_,
1588
- _Identifier: (_)=>_
1589
- },
1590
- toString () {
1591
- return JSON.stringify(this.toJSON(), null, 2);
1592
- },
1593
- toJSON () {
1594
- return {
1595
- _id: "Tag",
1596
- key: this.key,
1597
- stack: this.stack
1598
- };
1599
- },
1600
- [Inspectable_NodeInspectSymbol] () {
1601
- return this.toJSON();
1602
- },
1603
- of: (self)=>self,
1604
- context (self) {
1605
- return context_make(this, self);
1606
- }
1607
- }, ReferenceProto = {
1608
- ...context_TagProto,
1609
- [ReferenceTypeId]: ReferenceTypeId
1610
- }, context_TypeId = Symbol.for("effect/Context"), ContextProto = {
1611
- [context_TypeId]: {
1612
- _Services: (_)=>_
1613
- },
1614
- [Equal_symbol] (that) {
1615
- if (isContext(that) && this.unsafeMap.size === that.unsafeMap.size) {
1616
- for (let k of this.unsafeMap.keys())if (!that.unsafeMap.has(k) || !equals(this.unsafeMap.get(k), that.unsafeMap.get(k))) return !1;
1617
- return !0;
1618
- }
1619
- return !1;
1620
- },
1621
- [Hash_symbol] () {
1622
- return Hash_cached(this, number(this.unsafeMap.size));
1623
- },
1624
- pipe () {
1625
- return Pipeable_pipeArguments(this, arguments);
1626
- },
1627
- toString () {
1628
- return JSON.stringify(this.toJSON(), null, 2);
1629
- },
1630
- toJSON () {
1631
- return {
1632
- _id: "Context",
1633
- services: Array.from(this.unsafeMap).map(toJSON)
1634
- };
1635
- },
1636
- [Inspectable_NodeInspectSymbol] () {
1637
- return this.toJSON();
1638
- }
1639
- }, makeContext = (unsafeMap)=>{
1640
- let context = Object.create(ContextProto);
1641
- return context.unsafeMap = unsafeMap, context;
1642
- }, isContext = (u)=>Predicate_hasProperty(u, context_TypeId), context_empty = makeContext(new Map()), context_make = (tag, service)=>makeContext(new Map([
1643
- [
1644
- tag.key,
1645
- service
1646
- ]
1647
- ])), context_add = Function_dual(3, (self, tag, service)=>{
1648
- let map = new Map(self.unsafeMap);
1649
- return map.set(tag.key, service), makeContext(map);
1650
- }), defaultValueCache = GlobalValue_globalValue("effect/Context/defaultValueCache", ()=>new Map()), getDefaultValue = (tag)=>{
1651
- if (defaultValueCache.has(tag.key)) return defaultValueCache.get(tag.key);
1652
- let value = tag.defaultValue();
1653
- return defaultValueCache.set(tag.key, value), value;
1654
- }, context_unsafeGet = Function_dual(2, (self, tag)=>{
1655
- if (!self.unsafeMap.has(tag.key)) {
1656
- if (ReferenceTypeId in tag) return getDefaultValue(tag);
1657
- throw ((tag)=>{
1658
- let error = Error(`Service not found${tag.key ? `: ${String(tag.key)}` : ""}`);
1659
- if (tag.stack) {
1660
- let lines = tag.stack.split("\n");
1661
- if (lines.length > 2) {
1662
- let afterAt = lines[2].match(/at (.*)/);
1663
- afterAt && (error.message = error.message + ` (defined at ${afterAt[1]})`);
1664
- }
1665
- }
1666
- if (error.stack) {
1667
- let lines = error.stack.split("\n");
1668
- lines.splice(1, 3), error.stack = lines.join("\n");
1669
- }
1670
- return error;
1671
- })(tag);
1672
- }
1673
- return self.unsafeMap.get(tag.key);
1674
- }), getOption = Function_dual(2, (self, tag)=>self.unsafeMap.has(tag.key) ? option_some(self.unsafeMap.get(tag.key)) : Predicate_hasProperty(tag, ReferenceTypeId) ? option_some(getDefaultValue(tag)) : option_none), context_merge = Function_dual(2, (self, that)=>{
1675
- let map = new Map(self.unsafeMap);
1676
- for (let [tag, s] of that.unsafeMap)map.set(tag, s);
1677
- return makeContext(map);
1678
- }), GenericTag = (key)=>{
1679
- let limit = Error.stackTraceLimit;
1680
- Error.stackTraceLimit = 2;
1681
- let creationError = Error();
1682
- Error.stackTraceLimit = limit;
1683
- let tag = Object.create(context_TagProto);
1684
- return Object.defineProperty(tag, "stack", {
1685
- get: ()=>creationError.stack
1686
- }), tag.key = key, tag;
1687
- }, Context_Reference = ()=>(id, options)=>{
1688
- let limit = Error.stackTraceLimit;
1689
- Error.stackTraceLimit = 2;
1690
- let creationError = Error();
1691
- function ReferenceClass() {}
1692
- return Error.stackTraceLimit = limit, Object.setPrototypeOf(ReferenceClass, ReferenceProto), ReferenceClass.key = id, ReferenceClass.defaultValue = options.defaultValue, Object.defineProperty(ReferenceClass, "stack", {
1693
- get: ()=>creationError.stack
1694
- }), ReferenceClass;
1695
- }, Duration_TypeId = Symbol.for("effect/Duration"), bigint0 = BigInt(0), bigint24 = BigInt(24), bigint60 = BigInt(60), bigint1e3 = BigInt(1000), Duration_bigint1e6 = BigInt(1000000), bigint1e9 = BigInt(1000000000), DURATION_REGEX = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/, decode = (input)=>{
1696
- if (isDuration(input)) return input;
1697
- if (isNumber(input)) return Duration_millis(input);
1698
- if ("bigint" == typeof input) return Duration_nanos(input);
1699
- if (Array.isArray(input) && 2 === input.length && input.every(isNumber)) return -1 / 0 === input[0] || -1 / 0 === input[1] || Number.isNaN(input[0]) || Number.isNaN(input[1]) ? Duration_zero : 1 / 0 === input[0] || 1 / 0 === input[1] ? infinity : Duration_nanos(BigInt(Math.round(1000000000 * input[0])) + BigInt(Math.round(input[1])));
1700
- if ("string" == typeof input) {
1701
- let match = DURATION_REGEX.exec(input);
1702
- if (match) {
1703
- let [_, valueStr, unit] = match, value = Number(valueStr);
1704
- switch(unit){
1705
- case "nano":
1706
- case "nanos":
1707
- return Duration_nanos(BigInt(valueStr));
1708
- case "micro":
1709
- case "micros":
1710
- return Duration_micros(BigInt(valueStr));
1711
- case "milli":
1712
- case "millis":
1713
- return Duration_millis(value);
1714
- case "second":
1715
- case "seconds":
1716
- return Duration_seconds(value);
1717
- case "minute":
1718
- case "minutes":
1719
- return Duration_minutes(value);
1720
- case "hour":
1721
- case "hours":
1722
- return Duration_hours(value);
1723
- case "day":
1724
- case "days":
1725
- return Duration_days(value);
1726
- case "week":
1727
- case "weeks":
1728
- return Duration_weeks(value);
1729
- }
1730
- }
1731
- }
1732
- throw Error("Invalid DurationInput");
1733
- }, zeroValue = {
1734
- _tag: "Millis",
1735
- millis: 0
1736
- }, infinityValue = {
1737
- _tag: "Infinity"
1738
- }, DurationProto = {
1739
- [Duration_TypeId]: Duration_TypeId,
1740
- [Hash_symbol] () {
1741
- return Hash_cached(this, structure(this.value));
1742
- },
1743
- [Equal_symbol] (that) {
1744
- return isDuration(that) && Duration_equals(this, that);
1745
- },
1746
- toString () {
1747
- return `Duration(${Duration_format(this)})`;
1748
- },
1749
- toJSON () {
1750
- switch(this.value._tag){
1751
- case "Millis":
1752
- return {
1753
- _id: "Duration",
1754
- _tag: "Millis",
1755
- millis: this.value.millis
1756
- };
1757
- case "Nanos":
1758
- return {
1759
- _id: "Duration",
1760
- _tag: "Nanos",
1761
- hrtime: toHrTime(this)
1762
- };
1763
- case "Infinity":
1764
- return {
1765
- _id: "Duration",
1766
- _tag: "Infinity"
1767
- };
1768
- }
1769
- },
1770
- [Inspectable_NodeInspectSymbol] () {
1771
- return this.toJSON();
1772
- },
1773
- pipe () {
1774
- return Pipeable_pipeArguments(this, arguments);
1775
- }
1776
- }, Duration_make = (input)=>{
1777
- let duration = Object.create(DurationProto);
1778
- return isNumber(input) ? isNaN(input) || input <= 0 ? duration.value = zeroValue : Number.isFinite(input) ? Number.isInteger(input) ? duration.value = {
1779
- _tag: "Millis",
1780
- millis: input
1781
- } : duration.value = {
1782
- _tag: "Nanos",
1783
- nanos: BigInt(Math.round(1000000 * input))
1784
- } : duration.value = infinityValue : input <= bigint0 ? duration.value = zeroValue : duration.value = {
1785
- _tag: "Nanos",
1786
- nanos: input
1787
- }, duration;
1788
- }, isDuration = (u)=>Predicate_hasProperty(u, Duration_TypeId), Duration_zero = Duration_make(0), infinity = Duration_make(1 / 0), Duration_nanos = (nanos)=>Duration_make(nanos), Duration_micros = (micros)=>Duration_make(micros * bigint1e3), Duration_millis = (millis)=>Duration_make(millis), Duration_seconds = (seconds)=>Duration_make(1000 * seconds), Duration_minutes = (minutes)=>Duration_make(60000 * minutes), Duration_hours = (hours)=>Duration_make(3600000 * hours), Duration_days = (days)=>Duration_make(86400000 * days), Duration_weeks = (weeks)=>Duration_make(604800000 * weeks), toMillis = (self)=>Duration_match(self, {
1789
- onMillis: (millis)=>millis,
1790
- onNanos: (nanos)=>Number(nanos) / 1000000
1791
- }), toHrTime = (self)=>{
1792
- let _self = decode(self);
1793
- switch(_self.value._tag){
1794
- case "Infinity":
1795
- return [
1796
- 1 / 0,
1797
- 0
1798
- ];
1799
- case "Nanos":
1800
- return [
1801
- Number(_self.value.nanos / bigint1e9),
1802
- Number(_self.value.nanos % bigint1e9)
1803
- ];
1804
- case "Millis":
1805
- return [
1806
- Math.floor(_self.value.millis / 1000),
1807
- Math.round(_self.value.millis % 1000 * 1000000)
1808
- ];
1809
- }
1810
- }, Duration_match = Function_dual(2, (self, options)=>{
1811
- let _self = decode(self);
1812
- switch(_self.value._tag){
1813
- case "Nanos":
1814
- return options.onNanos(_self.value.nanos);
1815
- case "Infinity":
1816
- return options.onMillis(1 / 0);
1817
- case "Millis":
1818
- return options.onMillis(_self.value.millis);
1819
- }
1820
- }), matchWith = Function_dual(3, (self, that, options)=>{
1821
- let _self = decode(self), _that = decode(that);
1822
- if ("Infinity" === _self.value._tag || "Infinity" === _that.value._tag) return options.onMillis(toMillis(_self), toMillis(_that));
1823
- if ("Nanos" === _self.value._tag || "Nanos" === _that.value._tag) {
1824
- let selfNanos = "Nanos" === _self.value._tag ? _self.value.nanos : BigInt(Math.round(1000000 * _self.value.millis)), thatNanos = "Nanos" === _that.value._tag ? _that.value.nanos : BigInt(Math.round(1000000 * _that.value.millis));
1825
- return options.onNanos(selfNanos, thatNanos);
1826
- }
1827
- return options.onMillis(_self.value.millis, _that.value.millis);
1828
- }), Duration_lessThanOrEqualTo = Function_dual(2, (self, that)=>matchWith(self, that, {
1829
- onMillis: (self, that)=>self <= that,
1830
- onNanos: (self, that)=>self <= that
1831
- })), Duration_greaterThanOrEqualTo = Function_dual(2, (self, that)=>matchWith(self, that, {
1832
- onMillis: (self, that)=>self >= that,
1833
- onNanos: (self, that)=>self >= that
1834
- })), Duration_equals = Function_dual(2, (self, that)=>matchWith(decode(self), decode(that), {
1835
- onMillis: (self, that)=>self === that,
1836
- onNanos: (self, that)=>self === that
1837
- })), Duration_format = (self)=>{
1838
- let duration = decode(self);
1839
- if ("Infinity" === duration.value._tag) return "Infinity";
1840
- if (((self)=>{
1841
- switch(self.value._tag){
1842
- case "Millis":
1843
- return 0 === self.value.millis;
1844
- case "Nanos":
1845
- return self.value.nanos === bigint0;
1846
- case "Infinity":
1847
- return !1;
1848
- }
1849
- })(duration)) return "0";
1850
- let fragments = ((self)=>{
1851
- let duration = decode(self);
1852
- if ("Infinity" === duration.value._tag) return {
1853
- days: 1 / 0,
1854
- hours: 1 / 0,
1855
- minutes: 1 / 0,
1856
- seconds: 1 / 0,
1857
- millis: 1 / 0,
1858
- nanos: 1 / 0
1859
- };
1860
- let nanos = ((self)=>{
1861
- let _self = decode(self);
1862
- switch(_self.value._tag){
1863
- case "Infinity":
1864
- throw Error("Cannot convert infinite duration to nanos");
1865
- case "Nanos":
1866
- return _self.value.nanos;
1867
- case "Millis":
1868
- return BigInt(Math.round(1000000 * _self.value.millis));
1869
- }
1870
- })(duration), ms = nanos / Duration_bigint1e6, sec = ms / bigint1e3, min = sec / bigint60, hr = min / bigint60;
1871
- return {
1872
- days: Number(hr / bigint24),
1873
- hours: Number(hr % bigint24),
1874
- minutes: Number(min % bigint60),
1875
- seconds: Number(sec % bigint60),
1876
- millis: Number(ms % bigint1e3),
1877
- nanos: Number(nanos % Duration_bigint1e6)
1878
- };
1879
- })(duration), pieces = [];
1880
- return 0 !== fragments.days && pieces.push(`${fragments.days}d`), 0 !== fragments.hours && pieces.push(`${fragments.hours}h`), 0 !== fragments.minutes && pieces.push(`${fragments.minutes}m`), 0 !== fragments.seconds && pieces.push(`${fragments.seconds}s`), 0 !== fragments.millis && pieces.push(`${fragments.millis}ms`), 0 !== fragments.nanos && pieces.push(`${fragments.nanos}ns`), pieces.join(" ");
1881
- }, MutableRef_TypeId = Symbol.for("effect/MutableRef"), MutableRefProto = {
1882
- [MutableRef_TypeId]: MutableRef_TypeId,
1883
- toString () {
1884
- return JSON.stringify(this.toJSON(), null, 2);
1885
- },
1886
- toJSON () {
1887
- return {
1888
- _id: "MutableRef",
1889
- current: toJSON(this.current)
1890
- };
1891
- },
1892
- [Inspectable_NodeInspectSymbol] () {
1893
- return this.toJSON();
1674
+ [Inspectable_NodeInspectSymbol] () {
1675
+ return this.toJSON();
1894
1676
  },
1895
1677
  pipe () {
1896
1678
  return Pipeable_pipeArguments(this, arguments);
@@ -2099,14 +1881,14 @@ let fiberId_none = new class {
2099
1881
  }
2100
1882
  return Structural.prototype = effectable_StructuralPrototype, Structural;
2101
1883
  }(), data_struct = (as)=>Object.assign(Object.create(effectable_StructuralPrototype), as), ChunkPatchTypeId = Symbol.for("effect/DifferChunkPatch");
2102
- function chunkPatch_variance(a) {
1884
+ function variance(a) {
2103
1885
  return a;
2104
1886
  }
2105
1887
  ({
2106
1888
  ...data_Structural.prototype,
2107
1889
  [ChunkPatchTypeId]: {
2108
- _Value: chunkPatch_variance,
2109
- _Patch: chunkPatch_variance
1890
+ _Value: variance,
1891
+ _Patch: variance
2110
1892
  }
2111
1893
  });
2112
1894
  let ContextPatchTypeId = Symbol.for("effect/DifferContextPatch");
@@ -2179,137 +1961,502 @@ function hashMapPatch_variance(a) {
2179
1961
  _Key: hashMapPatch_variance,
2180
1962
  _Patch: hashMapPatch_variance
2181
1963
  }
2182
- });
2183
- let HashSetPatchTypeId = Symbol.for("effect/DifferHashSetPatch");
2184
- function hashSetPatch_variance(a) {
2185
- return a;
2186
- }
2187
- let hashSetPatch_PatchProto = {
2188
- ...data_Structural.prototype,
2189
- [HashSetPatchTypeId]: {
2190
- _Value: hashSetPatch_variance,
2191
- _Key: hashSetPatch_variance,
2192
- _Patch: hashSetPatch_variance
1964
+ });
1965
+ let HashSetPatchTypeId = Symbol.for("effect/DifferHashSetPatch");
1966
+ function hashSetPatch_variance(a) {
1967
+ return a;
1968
+ }
1969
+ let hashSetPatch_PatchProto = {
1970
+ ...data_Structural.prototype,
1971
+ [HashSetPatchTypeId]: {
1972
+ _Value: hashSetPatch_variance,
1973
+ _Key: hashSetPatch_variance,
1974
+ _Patch: hashSetPatch_variance
1975
+ }
1976
+ }, hashSetPatch_empty = Object.create(Object.assign(Object.create(hashSetPatch_PatchProto), {
1977
+ _tag: "Empty"
1978
+ })), hashSetPatch_AndThenProto = Object.assign(Object.create(hashSetPatch_PatchProto), {
1979
+ _tag: "AndThen"
1980
+ }), hashSetPatch_AddProto = Object.assign(Object.create(hashSetPatch_PatchProto), {
1981
+ _tag: "Add"
1982
+ }), hashSetPatch_RemoveProto = Object.assign(Object.create(hashSetPatch_PatchProto), {
1983
+ _tag: "Remove"
1984
+ }), hashSetPatch_combine = Function_dual(2, (self, that)=>{
1985
+ let o;
1986
+ return (o = Object.create(hashSetPatch_AndThenProto)).first = self, o.second = that, o;
1987
+ }), hashSetPatch_patch = Function_dual(2, (self, oldValue)=>{
1988
+ if ("Empty" === self._tag) return oldValue;
1989
+ let set = oldValue, patches = Chunk_of(self);
1990
+ for(; isNonEmpty(patches);){
1991
+ let head = Chunk_unsafeHead(patches), tail = Chunk_tailNonEmpty(patches);
1992
+ switch(head._tag){
1993
+ case "Empty":
1994
+ patches = tail;
1995
+ break;
1996
+ case "AndThen":
1997
+ patches = Chunk_prepend(head.first)(Chunk_prepend(head.second)(tail));
1998
+ break;
1999
+ case "Add":
2000
+ set = hashSet_add(head.value)(set), patches = tail;
2001
+ break;
2002
+ case "Remove":
2003
+ set = hashSet_remove(head.value)(set), patches = tail;
2004
+ }
2005
+ }
2006
+ return set;
2007
+ }), OrPatchTypeId = Symbol.for("effect/DifferOrPatch");
2008
+ function orPatch_variance(a) {
2009
+ return a;
2010
+ }
2011
+ let orPatch_PatchProto = {
2012
+ ...data_Structural.prototype,
2013
+ [OrPatchTypeId]: {
2014
+ _Value: orPatch_variance,
2015
+ _Key: orPatch_variance,
2016
+ _Patch: orPatch_variance
2017
+ }
2018
+ }, orPatch_AndThenProto = Object.assign(Object.create(orPatch_PatchProto), {
2019
+ _tag: "AndThen"
2020
+ }), ReadonlyArrayPatchTypeId = ((self, that)=>{
2021
+ let o;
2022
+ return (o = Object.create(orPatch_AndThenProto)).first = self, o.second = that, o;
2023
+ }, Symbol.for("effect/DifferReadonlyArrayPatch"));
2024
+ function readonlyArrayPatch_variance(a) {
2025
+ return a;
2026
+ }
2027
+ let readonlyArrayPatch_PatchProto = {
2028
+ ...data_Structural.prototype,
2029
+ [ReadonlyArrayPatchTypeId]: {
2030
+ _Value: readonlyArrayPatch_variance,
2031
+ _Patch: readonlyArrayPatch_variance
2032
+ }
2033
+ }, readonlyArrayPatch_empty = Object.create(Object.assign(Object.create(readonlyArrayPatch_PatchProto), {
2034
+ _tag: "Empty"
2035
+ })), readonlyArrayPatch_AndThenProto = Object.assign(Object.create(readonlyArrayPatch_PatchProto), {
2036
+ _tag: "AndThen"
2037
+ }), readonlyArrayPatch_AppendProto = Object.assign(Object.create(readonlyArrayPatch_PatchProto), {
2038
+ _tag: "Append"
2039
+ }), readonlyArrayPatch_SliceProto = Object.assign(Object.create(readonlyArrayPatch_PatchProto), {
2040
+ _tag: "Slice"
2041
+ }), readonlyArrayPatch_UpdateProto = Object.assign(Object.create(readonlyArrayPatch_PatchProto), {
2042
+ _tag: "Update"
2043
+ }), readonlyArrayPatch_makeUpdate = (index, patch)=>{
2044
+ let o = Object.create(readonlyArrayPatch_UpdateProto);
2045
+ return o.index = index, o.patch = patch, o;
2046
+ }, readonlyArrayPatch_combine = Function_dual(2, (self, that)=>{
2047
+ let o;
2048
+ return (o = Object.create(readonlyArrayPatch_AndThenProto)).first = self, o.second = that, o;
2049
+ }), readonlyArrayPatch_patch = Function_dual(3, (self, oldValue, differ)=>{
2050
+ if ("Empty" === self._tag) return oldValue;
2051
+ let readonlyArray = oldValue.slice(), patches = Array_of(self);
2052
+ for(; isNonEmptyArray(patches);){
2053
+ let head = headNonEmpty(patches), tail = tailNonEmpty(patches);
2054
+ switch(head._tag){
2055
+ case "Empty":
2056
+ patches = tail;
2057
+ break;
2058
+ case "AndThen":
2059
+ tail.unshift(head.first, head.second), patches = tail;
2060
+ break;
2061
+ case "Append":
2062
+ for (let value of head.values)readonlyArray.push(value);
2063
+ patches = tail;
2064
+ break;
2065
+ case "Slice":
2066
+ readonlyArray = readonlyArray.slice(head.from, head.until), patches = tail;
2067
+ break;
2068
+ case "Update":
2069
+ readonlyArray[head.index] = differ.patch(head.patch, readonlyArray[head.index]), patches = tail;
2070
+ }
2071
+ }
2072
+ return readonlyArray;
2073
+ }), DifferProto = {
2074
+ [Symbol.for("effect/Differ")]: {
2075
+ _P: Function_identity,
2076
+ _V: Function_identity
2077
+ },
2078
+ pipe () {
2079
+ return Pipeable_pipeArguments(this, arguments);
2080
+ }
2081
+ }, differ_make = (params)=>{
2082
+ let differ = Object.create(DifferProto);
2083
+ return differ.empty = params.empty, differ.diff = params.diff, differ.combine = params.combine, differ.patch = params.patch, differ;
2084
+ }, differ_update = ()=>updateWith((_, a)=>a), updateWith = (f)=>differ_make({
2085
+ empty: Function_identity,
2086
+ combine: (first, second)=>first === Function_identity ? second : second === Function_identity ? first : (a)=>second(first(a)),
2087
+ diff: (oldValue, newValue)=>equals(oldValue, newValue) ? Function_identity : constant(newValue),
2088
+ patch: (patch, oldValue)=>f(oldValue, patch(oldValue))
2089
+ }), runtimeFlagsPatch_make = (active, enabled)=>(0xff & active) + ((enabled & active & 0xff) << 0x08), runtimeFlagsPatch_empty = runtimeFlagsPatch_make(0, 0), exclude = Function_dual(2, (self, flag)=>runtimeFlagsPatch_make(0xff & self & ~flag, self >> 0x08 & 0xff)), runtimeFlagsPatch_andThen = Function_dual(2, (self, that)=>self | that), cooperativeYielding = (self)=>runtimeFlags_isEnabled(self, 32), runtimeFlags_disable = Function_dual(2, (self, flag)=>self & ~flag), runtimeFlags_enable = Function_dual(2, (self, flag)=>self | flag), runtimeFlags_interruptible = (self)=>runtimeFlags_interruption(self) && !windDown(self), runtimeFlags_interruption = (self)=>runtimeFlags_isEnabled(self, 1), runtimeFlags_isEnabled = Function_dual(2, (self, flag)=>(self & flag) != 0), runtimeFlags_make = (...flags)=>flags.reduce((a, b)=>a | b, 0), runtimeFlags_none = runtimeFlags_make(0), windDown = (self)=>runtimeFlags_isEnabled(self, 16), runtimeFlags_diff = Function_dual(2, (self, that)=>runtimeFlagsPatch_make(self ^ that, that)), runtimeFlags_patch = Function_dual(2, (self, patch)=>self & (~(0xff & patch) >>> 0 & 0xff | patch >> 0x08 & 0xff) | 0xff & patch & (patch >> 0x08 & 0xff)), runtimeFlags_differ = differ_make({
2090
+ empty: runtimeFlagsPatch_empty,
2091
+ diff: (oldValue, newValue)=>runtimeFlags_diff(oldValue, newValue),
2092
+ combine: (first, second)=>runtimeFlagsPatch_andThen(second)(first),
2093
+ patch: (_patch, oldValue)=>runtimeFlags_patch(oldValue, _patch)
2094
+ }), OP_INTERRUPT = "Interrupt", OP_PARALLEL = "Parallel", OP_SEQUENTIAL = "Sequential", CauseSymbolKey = "effect/Cause", CauseTypeId = Symbol.for(CauseSymbolKey), cause_proto = {
2095
+ [CauseTypeId]: {
2096
+ _E: (_)=>_
2097
+ },
2098
+ [Hash_symbol] () {
2099
+ return Function_pipe(Hash_hash(CauseSymbolKey), Hash_combine(Hash_hash(flattenCause(this))), Hash_cached(this));
2100
+ },
2101
+ [Equal_symbol] (that) {
2102
+ return isCause(that) && causeEquals(this, that);
2103
+ },
2104
+ pipe () {
2105
+ return Pipeable_pipeArguments(this, arguments);
2106
+ },
2107
+ toJSON () {
2108
+ switch(this._tag){
2109
+ case "Empty":
2110
+ return {
2111
+ _id: "Cause",
2112
+ _tag: this._tag
2113
+ };
2114
+ case "Die":
2115
+ return {
2116
+ _id: "Cause",
2117
+ _tag: this._tag,
2118
+ defect: toJSON(this.defect)
2119
+ };
2120
+ case "Interrupt":
2121
+ return {
2122
+ _id: "Cause",
2123
+ _tag: this._tag,
2124
+ fiberId: this.fiberId.toJSON()
2125
+ };
2126
+ case "Fail":
2127
+ return {
2128
+ _id: "Cause",
2129
+ _tag: this._tag,
2130
+ failure: toJSON(this.error)
2131
+ };
2132
+ case "Sequential":
2133
+ case "Parallel":
2134
+ return {
2135
+ _id: "Cause",
2136
+ _tag: this._tag,
2137
+ left: toJSON(this.left),
2138
+ right: toJSON(this.right)
2139
+ };
2140
+ }
2141
+ },
2142
+ toString () {
2143
+ return pretty(this);
2144
+ },
2145
+ [Inspectable_NodeInspectSymbol] () {
2146
+ return this.toJSON();
2147
+ }
2148
+ }, cause_empty = ((o = Object.create(cause_proto))._tag = "Empty", o), cause_fail = (error)=>{
2149
+ let o = Object.create(cause_proto);
2150
+ return o._tag = "Fail", o.error = error, o;
2151
+ }, cause_die = (defect)=>{
2152
+ let o = Object.create(cause_proto);
2153
+ return o._tag = "Die", o.defect = defect, o;
2154
+ }, interrupt = (fiberId)=>{
2155
+ let o = Object.create(cause_proto);
2156
+ return o._tag = OP_INTERRUPT, o.fiberId = fiberId, o;
2157
+ }, cause_parallel = (left, right)=>{
2158
+ let o = Object.create(cause_proto);
2159
+ return o._tag = OP_PARALLEL, o.left = left, o.right = right, o;
2160
+ }, cause_sequential = (left, right)=>{
2161
+ let o = Object.create(cause_proto);
2162
+ return o._tag = OP_SEQUENTIAL, o.left = left, o.right = right, o;
2163
+ }, isCause = (u)=>Predicate_hasProperty(u, CauseTypeId), cause_isEmpty = (self)=>"Empty" === self._tag || cause_reduce(self, !0, (acc, cause)=>{
2164
+ switch(cause._tag){
2165
+ case "Empty":
2166
+ return option_some(acc);
2167
+ case "Die":
2168
+ case "Fail":
2169
+ case OP_INTERRUPT:
2170
+ return option_some(!1);
2171
+ default:
2172
+ return Option_none();
2173
+ }
2174
+ }), isInterruptedOnly = (self)=>reduceWithContext(void 0, IsInterruptedOnlyCauseReducer)(self), cause_defects = (self)=>Chunk_reverse(cause_reduce(self, esm_Chunk_empty(), (list, cause)=>"Die" === cause._tag ? option_some(Function_pipe(list, Chunk_prepend(cause.defect))) : Option_none())), interruptors = (self)=>cause_reduce(self, internal_hashSet_empty(), (set, cause)=>cause._tag === OP_INTERRUPT ? option_some(Function_pipe(set, hashSet_add(cause.fiberId))) : Option_none()), failureOption = (self)=>find(self, (cause)=>"Fail" === cause._tag ? option_some(cause.error) : Option_none()), cause_failureOrCause = (self)=>{
2175
+ let option = failureOption(self);
2176
+ switch(option._tag){
2177
+ case "None":
2178
+ return either_right(self);
2179
+ case "Some":
2180
+ return either_left(option.value);
2181
+ }
2182
+ }, stripFailures = (self)=>cause_match(self, {
2183
+ onEmpty: cause_empty,
2184
+ onFail: ()=>cause_empty,
2185
+ onDie: cause_die,
2186
+ onInterrupt: interrupt,
2187
+ onSequential: cause_sequential,
2188
+ onParallel: cause_parallel
2189
+ }), cause_flatMap = ((self, f)=>cause_flatMap(self, (e)=>cause_fail(f(e))), Function_dual(2, (self, f)=>cause_match(self, {
2190
+ onEmpty: cause_empty,
2191
+ onFail: (error)=>f(error),
2192
+ onDie: (defect)=>cause_die(defect),
2193
+ onInterrupt: (fiberId)=>interrupt(fiberId),
2194
+ onSequential: (left, right)=>cause_sequential(left, right),
2195
+ onParallel: (left, right)=>cause_parallel(left, right)
2196
+ }))), causeEquals = (left, right)=>{
2197
+ let leftStack = Chunk_of(left), rightStack = Chunk_of(right);
2198
+ for(; isNonEmpty(leftStack) && isNonEmpty(rightStack);){
2199
+ let [leftParallel, leftSequential] = Function_pipe(Chunk_unsafeHead(leftStack), cause_reduce([
2200
+ internal_hashSet_empty(),
2201
+ esm_Chunk_empty()
2202
+ ], ([parallel, sequential], cause)=>{
2203
+ let [par, seq] = evaluateCause(cause);
2204
+ return option_some([
2205
+ Function_pipe(parallel, hashSet_union(par)),
2206
+ Function_pipe(sequential, Chunk_appendAll(seq))
2207
+ ]);
2208
+ })), [rightParallel, rightSequential] = Function_pipe(Chunk_unsafeHead(rightStack), cause_reduce([
2209
+ internal_hashSet_empty(),
2210
+ esm_Chunk_empty()
2211
+ ], ([parallel, sequential], cause)=>{
2212
+ let [par, seq] = evaluateCause(cause);
2213
+ return option_some([
2214
+ Function_pipe(parallel, hashSet_union(par)),
2215
+ Function_pipe(sequential, Chunk_appendAll(seq))
2216
+ ]);
2217
+ }));
2218
+ if (!equals(leftParallel, rightParallel)) return !1;
2219
+ leftStack = leftSequential, rightStack = rightSequential;
2220
+ }
2221
+ return !0;
2222
+ }, flattenCause = (cause)=>flattenCauseLoop(Chunk_of(cause), esm_Chunk_empty()), flattenCauseLoop = (causes, flattened)=>{
2223
+ for(;;){
2224
+ let [parallel, sequential] = Function_pipe(causes, Array_reduce([
2225
+ internal_hashSet_empty(),
2226
+ esm_Chunk_empty()
2227
+ ], ([parallel, sequential], cause)=>{
2228
+ let [par, seq] = evaluateCause(cause);
2229
+ return [
2230
+ Function_pipe(parallel, hashSet_union(par)),
2231
+ Function_pipe(sequential, Chunk_appendAll(seq))
2232
+ ];
2233
+ })), updated = HashSet_size(parallel) > 0 ? Function_pipe(flattened, Chunk_prepend(parallel)) : flattened;
2234
+ if (Chunk_isEmpty(sequential)) return Chunk_reverse(updated);
2235
+ causes = sequential, flattened = updated;
2193
2236
  }
2194
- }, hashSetPatch_empty = Object.create(Object.assign(Object.create(hashSetPatch_PatchProto), {
2195
- _tag: "Empty"
2196
- })), hashSetPatch_AndThenProto = Object.assign(Object.create(hashSetPatch_PatchProto), {
2197
- _tag: "AndThen"
2198
- }), hashSetPatch_AddProto = Object.assign(Object.create(hashSetPatch_PatchProto), {
2199
- _tag: "Add"
2200
- }), hashSetPatch_RemoveProto = Object.assign(Object.create(hashSetPatch_PatchProto), {
2201
- _tag: "Remove"
2202
- }), hashSetPatch_combine = Function_dual(2, (self, that)=>{
2203
- let o;
2204
- return (o = Object.create(hashSetPatch_AndThenProto)).first = self, o.second = that, o;
2205
- }), hashSetPatch_patch = Function_dual(2, (self, oldValue)=>{
2206
- if ("Empty" === self._tag) return oldValue;
2207
- let set = oldValue, patches = Chunk_of(self);
2208
- for(; isNonEmpty(patches);){
2209
- let head = Chunk_unsafeHead(patches), tail = Chunk_tailNonEmpty(patches);
2210
- switch(head._tag){
2211
- case "Empty":
2212
- patches = tail;
2213
- break;
2214
- case "AndThen":
2215
- patches = Chunk_prepend(head.first)(Chunk_prepend(head.second)(tail));
2216
- break;
2217
- case "Add":
2218
- set = add(head.value)(set), patches = tail;
2237
+ throw Error(getBugErrorMessage("Cause.flattenCauseLoop"));
2238
+ }, find = Function_dual(2, (self, pf)=>{
2239
+ let stack = [
2240
+ self
2241
+ ];
2242
+ for(; stack.length > 0;){
2243
+ let item = stack.pop(), option = pf(item);
2244
+ switch(option._tag){
2245
+ case "None":
2246
+ switch(item._tag){
2247
+ case OP_SEQUENTIAL:
2248
+ case OP_PARALLEL:
2249
+ stack.push(item.right), stack.push(item.left);
2250
+ }
2219
2251
  break;
2220
- case "Remove":
2221
- set = hashSet_remove(head.value)(set), patches = tail;
2252
+ case "Some":
2253
+ return option;
2222
2254
  }
2223
2255
  }
2224
- return set;
2225
- }), OrPatchTypeId = Symbol.for("effect/DifferOrPatch");
2226
- function orPatch_variance(a) {
2227
- return a;
2228
- }
2229
- let orPatch_PatchProto = {
2230
- ...data_Structural.prototype,
2231
- [OrPatchTypeId]: {
2232
- _Value: orPatch_variance,
2233
- _Key: orPatch_variance,
2234
- _Patch: orPatch_variance
2256
+ return Option_none();
2257
+ }), evaluateCause = (self)=>{
2258
+ let cause = self, stack = [], _parallel = internal_hashSet_empty(), _sequential = esm_Chunk_empty();
2259
+ for(; void 0 !== cause;)switch(cause._tag){
2260
+ case "Empty":
2261
+ if (0 === stack.length) return [
2262
+ _parallel,
2263
+ _sequential
2264
+ ];
2265
+ cause = stack.pop();
2266
+ break;
2267
+ case "Fail":
2268
+ if (_parallel = hashSet_add(_parallel, Chunk_make(cause._tag, cause.error)), 0 === stack.length) return [
2269
+ _parallel,
2270
+ _sequential
2271
+ ];
2272
+ cause = stack.pop();
2273
+ break;
2274
+ case "Die":
2275
+ if (_parallel = hashSet_add(_parallel, Chunk_make(cause._tag, cause.defect)), 0 === stack.length) return [
2276
+ _parallel,
2277
+ _sequential
2278
+ ];
2279
+ cause = stack.pop();
2280
+ break;
2281
+ case OP_INTERRUPT:
2282
+ if (_parallel = hashSet_add(_parallel, Chunk_make(cause._tag, cause.fiberId)), 0 === stack.length) return [
2283
+ _parallel,
2284
+ _sequential
2285
+ ];
2286
+ cause = stack.pop();
2287
+ break;
2288
+ case OP_SEQUENTIAL:
2289
+ switch(cause.left._tag){
2290
+ case "Empty":
2291
+ cause = cause.right;
2292
+ break;
2293
+ case OP_SEQUENTIAL:
2294
+ cause = cause_sequential(cause.left.left, cause_sequential(cause.left.right, cause.right));
2295
+ break;
2296
+ case OP_PARALLEL:
2297
+ cause = cause_parallel(cause_sequential(cause.left.left, cause.right), cause_sequential(cause.left.right, cause.right));
2298
+ break;
2299
+ default:
2300
+ _sequential = Chunk_prepend(_sequential, cause.right), cause = cause.left;
2301
+ }
2302
+ break;
2303
+ case OP_PARALLEL:
2304
+ stack.push(cause.right), cause = cause.left;
2235
2305
  }
2236
- }, orPatch_AndThenProto = Object.assign(Object.create(orPatch_PatchProto), {
2237
- _tag: "AndThen"
2238
- }), ReadonlyArrayPatchTypeId = ((self, that)=>{
2239
- let o;
2240
- return (o = Object.create(orPatch_AndThenProto)).first = self, o.second = that, o;
2241
- }, Symbol.for("effect/DifferReadonlyArrayPatch"));
2242
- function readonlyArrayPatch_variance(a) {
2243
- return a;
2244
- }
2245
- let readonlyArrayPatch_PatchProto = {
2246
- ...data_Structural.prototype,
2247
- [ReadonlyArrayPatchTypeId]: {
2248
- _Value: readonlyArrayPatch_variance,
2249
- _Patch: readonlyArrayPatch_variance
2306
+ throw Error(getBugErrorMessage("Cause.evaluateCauseLoop"));
2307
+ }, IsInterruptedOnlyCauseReducer = {
2308
+ emptyCase: Function_constTrue,
2309
+ failCase: Function_constFalse,
2310
+ dieCase: Function_constFalse,
2311
+ interruptCase: Function_constTrue,
2312
+ sequentialCase: (_, left, right)=>left && right,
2313
+ parallelCase: (_, left, right)=>left && right
2314
+ }, OP_SEQUENTIAL_CASE = "SequentialCase", OP_PARALLEL_CASE = "ParallelCase", cause_match = Function_dual(2, (self, { onDie, onEmpty, onFail, onInterrupt, onParallel, onSequential })=>reduceWithContext(self, void 0, {
2315
+ emptyCase: ()=>onEmpty,
2316
+ failCase: (_, error)=>onFail(error),
2317
+ dieCase: (_, defect)=>onDie(defect),
2318
+ interruptCase: (_, fiberId)=>onInterrupt(fiberId),
2319
+ sequentialCase: (_, left, right)=>onSequential(left, right),
2320
+ parallelCase: (_, left, right)=>onParallel(left, right)
2321
+ })), cause_reduce = Function_dual(3, (self, zero, pf)=>{
2322
+ let accumulator = zero, cause = self, causes = [];
2323
+ for(; void 0 !== cause;){
2324
+ let option = pf(accumulator, cause);
2325
+ switch(accumulator = isSome(option) ? option.value : accumulator, cause._tag){
2326
+ case OP_SEQUENTIAL:
2327
+ case OP_PARALLEL:
2328
+ causes.push(cause.right), cause = cause.left;
2329
+ break;
2330
+ default:
2331
+ cause = void 0;
2332
+ }
2333
+ void 0 === cause && causes.length > 0 && (cause = causes.pop());
2250
2334
  }
2251
- }, readonlyArrayPatch_empty = Object.create(Object.assign(Object.create(readonlyArrayPatch_PatchProto), {
2252
- _tag: "Empty"
2253
- })), readonlyArrayPatch_AndThenProto = Object.assign(Object.create(readonlyArrayPatch_PatchProto), {
2254
- _tag: "AndThen"
2255
- }), readonlyArrayPatch_AppendProto = Object.assign(Object.create(readonlyArrayPatch_PatchProto), {
2256
- _tag: "Append"
2257
- }), readonlyArrayPatch_SliceProto = Object.assign(Object.create(readonlyArrayPatch_PatchProto), {
2258
- _tag: "Slice"
2259
- }), readonlyArrayPatch_UpdateProto = Object.assign(Object.create(readonlyArrayPatch_PatchProto), {
2260
- _tag: "Update"
2261
- }), readonlyArrayPatch_makeUpdate = (index, patch)=>{
2262
- let o = Object.create(readonlyArrayPatch_UpdateProto);
2263
- return o.index = index, o.patch = patch, o;
2264
- }, readonlyArrayPatch_combine = Function_dual(2, (self, that)=>{
2265
- let o;
2266
- return (o = Object.create(readonlyArrayPatch_AndThenProto)).first = self, o.second = that, o;
2267
- }), readonlyArrayPatch_patch = Function_dual(3, (self, oldValue, differ)=>{
2268
- if ("Empty" === self._tag) return oldValue;
2269
- let readonlyArray = oldValue.slice(), patches = Array_of(self);
2270
- for(; isNonEmptyArray(patches);){
2271
- let head = headNonEmpty(patches), tail = tailNonEmpty(patches);
2272
- switch(head._tag){
2335
+ return accumulator;
2336
+ }), reduceWithContext = Function_dual(3, (self, context, reducer)=>{
2337
+ let input = [
2338
+ self
2339
+ ], output = [];
2340
+ for(; input.length > 0;){
2341
+ let cause = input.pop();
2342
+ switch(cause._tag){
2273
2343
  case "Empty":
2274
- patches = tail;
2344
+ output.push(either_right(reducer.emptyCase(context)));
2275
2345
  break;
2276
- case "AndThen":
2277
- tail.unshift(head.first, head.second), patches = tail;
2346
+ case "Fail":
2347
+ output.push(either_right(reducer.failCase(context, cause.error)));
2278
2348
  break;
2279
- case "Append":
2280
- for (let value of head.values)readonlyArray.push(value);
2281
- patches = tail;
2349
+ case "Die":
2350
+ output.push(either_right(reducer.dieCase(context, cause.defect)));
2282
2351
  break;
2283
- case "Slice":
2284
- readonlyArray = readonlyArray.slice(head.from, head.until), patches = tail;
2352
+ case OP_INTERRUPT:
2353
+ output.push(either_right(reducer.interruptCase(context, cause.fiberId)));
2285
2354
  break;
2286
- case "Update":
2287
- readonlyArray[head.index] = differ.patch(head.patch, readonlyArray[head.index]), patches = tail;
2355
+ case OP_SEQUENTIAL:
2356
+ input.push(cause.right), input.push(cause.left), output.push(either_left({
2357
+ _tag: OP_SEQUENTIAL_CASE
2358
+ }));
2359
+ break;
2360
+ case OP_PARALLEL:
2361
+ input.push(cause.right), input.push(cause.left), output.push(either_left({
2362
+ _tag: OP_PARALLEL_CASE
2363
+ }));
2364
+ }
2365
+ }
2366
+ let accumulator = [];
2367
+ for(; output.length > 0;){
2368
+ let either = output.pop();
2369
+ switch(either._tag){
2370
+ case "Left":
2371
+ switch(either.left._tag){
2372
+ case OP_SEQUENTIAL_CASE:
2373
+ {
2374
+ let left = accumulator.pop(), right = accumulator.pop(), value = reducer.sequentialCase(context, left, right);
2375
+ accumulator.push(value);
2376
+ break;
2377
+ }
2378
+ case OP_PARALLEL_CASE:
2379
+ {
2380
+ let left = accumulator.pop(), right = accumulator.pop(), value = reducer.parallelCase(context, left, right);
2381
+ accumulator.push(value);
2382
+ }
2383
+ }
2384
+ break;
2385
+ case "Right":
2386
+ accumulator.push(either.right);
2387
+ }
2388
+ }
2389
+ if (0 === accumulator.length) throw Error("BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");
2390
+ return accumulator.pop();
2391
+ }), pretty = (cause, options)=>isInterruptedOnly(cause) ? "All fibers interrupted without errors." : prettyErrors(cause).map(function(e) {
2392
+ return options?.renderErrorCause !== !0 || void 0 === e.cause ? e.stack : `${e.stack} {\n${renderErrorCause(e.cause, " ")}\n}`;
2393
+ }).join("\n"), renderErrorCause = (cause, prefix)=>{
2394
+ let lines = cause.stack.split("\n"), stack = `${prefix}[cause]: ${lines[0]}`;
2395
+ for(let i = 1, len = lines.length; i < len; i++)stack += `\n${prefix}${lines[i]}`;
2396
+ return cause.cause && (stack += ` {\n${renderErrorCause(cause.cause, `${prefix} `)}\n${prefix}}`), stack;
2397
+ }, makePrettyError = (originalError)=>{
2398
+ let originalErrorIsObject = "object" == typeof originalError && null !== originalError, prevLimit = Error.stackTraceLimit;
2399
+ Error.stackTraceLimit = 1;
2400
+ let error = Error(prettyErrorMessage(originalError), originalErrorIsObject && "cause" in originalError && void 0 !== originalError.cause ? {
2401
+ cause: makePrettyError(originalError.cause)
2402
+ } : void 0);
2403
+ return Error.stackTraceLimit = prevLimit, "" === error.message && (error.message = "An error has occurred"), Error.stackTraceLimit = prevLimit, error.name = originalError instanceof Error ? originalError.name : "Error", originalErrorIsObject && (spanSymbol in originalError && (error.span = originalError[spanSymbol]), Object.keys(originalError).forEach((key)=>{
2404
+ key in error || (error[key] = originalError[key]);
2405
+ })), error.stack = prettyErrorStack(`${error.name}: ${error.message}`, originalError instanceof Error && originalError.stack ? originalError.stack : "", error.span), error;
2406
+ }, prettyErrorMessage = (u)=>{
2407
+ if ("string" == typeof u) return u;
2408
+ if ("object" == typeof u && null !== u && u instanceof Error) return u.message;
2409
+ try {
2410
+ let input;
2411
+ if (Predicate_hasProperty(u, "toString") && (input = u.toString, "function" == typeof input) && u.toString !== Object.prototype.toString && u.toString !== globalThis.Array.prototype.toString) return u.toString();
2412
+ } catch {}
2413
+ return stringifyCircular(u);
2414
+ }, locationRegex = /\((.*)\)/g, spanToTrace = GlobalValue_globalValue("effect/Tracer/spanToTrace", ()=>new WeakMap()), prettyErrorStack = (message, stack, span)=>{
2415
+ let out = [
2416
+ message
2417
+ ], lines = stack.startsWith(message) ? stack.slice(message.length).split("\n") : stack.split("\n");
2418
+ for(let i = 1; i < lines.length; i++){
2419
+ if (lines[i].includes(" at new BaseEffectError") || lines[i].includes(" at new YieldableError")) {
2420
+ i++;
2421
+ continue;
2288
2422
  }
2423
+ if (lines[i].includes("Generator.next") || lines[i].includes("effect_internal_function")) break;
2424
+ out.push(lines[i].replace(/at .*effect_instruction_i.*\((.*)\)/, "at $1").replace(/EffectPrimitive\.\w+/, "<anonymous>"));
2289
2425
  }
2290
- return readonlyArray;
2291
- }), DifferProto = {
2292
- [Symbol.for("effect/Differ")]: {
2293
- _P: Function_identity,
2294
- _V: Function_identity
2295
- },
2296
- pipe () {
2297
- return Pipeable_pipeArguments(this, arguments);
2426
+ if (span) {
2427
+ let current = span, i = 0;
2428
+ for(; current && "Span" === current._tag && i < 10;){
2429
+ let stackFn = spanToTrace.get(current);
2430
+ if ("function" == typeof stackFn) {
2431
+ let stack = stackFn();
2432
+ if ("string" == typeof stack) {
2433
+ let locationMatchAll = stack.matchAll(locationRegex), match = !1;
2434
+ for (let [, location] of locationMatchAll)match = !0, out.push(` at ${current.name} (${location})`);
2435
+ match || out.push(` at ${current.name} (${stack.replace(/^at /, "")})`);
2436
+ } else out.push(` at ${current.name}`);
2437
+ } else out.push(` at ${current.name}`);
2438
+ current = Option_getOrUndefined(current.parent), i++;
2439
+ }
2298
2440
  }
2299
- }, differ_make = (params)=>{
2300
- let differ = Object.create(DifferProto);
2301
- return differ.empty = params.empty, differ.diff = params.diff, differ.combine = params.combine, differ.patch = params.patch, differ;
2302
- }, differ_update = ()=>updateWith((_, a)=>a), updateWith = (f)=>differ_make({
2303
- empty: Function_identity,
2304
- combine: (first, second)=>first === Function_identity ? second : second === Function_identity ? first : (a)=>second(first(a)),
2305
- diff: (oldValue, newValue)=>equals(oldValue, newValue) ? Function_identity : constant(newValue),
2306
- patch: (patch, oldValue)=>f(oldValue, patch(oldValue))
2307
- }), runtimeFlagsPatch_make = (active, enabled)=>(0xff & active) + ((enabled & active & 0xff) << 0x08), runtimeFlagsPatch_empty = runtimeFlagsPatch_make(0, 0), exclude = Function_dual(2, (self, flag)=>runtimeFlagsPatch_make(0xff & self & ~flag, self >> 0x08 & 0xff)), runtimeFlagsPatch_andThen = Function_dual(2, (self, that)=>self | that), cooperativeYielding = (self)=>runtimeFlags_isEnabled(self, 32), runtimeFlags_disable = Function_dual(2, (self, flag)=>self & ~flag), runtimeFlags_enable = Function_dual(2, (self, flag)=>self | flag), runtimeFlags_interruptible = (self)=>runtimeFlags_interruption(self) && !windDown(self), runtimeFlags_interruption = (self)=>runtimeFlags_isEnabled(self, 1), runtimeFlags_isEnabled = Function_dual(2, (self, flag)=>(self & flag) != 0), runtimeFlags_make = (...flags)=>flags.reduce((a, b)=>a | b, 0), runtimeFlags_none = runtimeFlags_make(0), windDown = (self)=>runtimeFlags_isEnabled(self, 16), runtimeFlags_diff = Function_dual(2, (self, that)=>runtimeFlagsPatch_make(self ^ that, that)), runtimeFlags_patch = Function_dual(2, (self, patch)=>self & (~(0xff & patch) >>> 0 & 0xff | patch >> 0x08 & 0xff) | 0xff & patch & (patch >> 0x08 & 0xff)), runtimeFlags_differ = differ_make({
2308
- empty: runtimeFlagsPatch_empty,
2309
- diff: (oldValue, newValue)=>runtimeFlags_diff(oldValue, newValue),
2310
- combine: (first, second)=>runtimeFlagsPatch_andThen(second)(first),
2311
- patch: (_patch, oldValue)=>runtimeFlags_patch(oldValue, _patch)
2312
- }), OP_STATE_PENDING = "Pending", DeferredTypeId = Symbol.for("effect/Deferred"), deferredVariance = {
2441
+ return out.join("\n");
2442
+ }, spanSymbol = Symbol.for("effect/SpanAnnotation"), prettyErrors = (cause)=>reduceWithContext(cause, void 0, {
2443
+ emptyCase: ()=>[],
2444
+ dieCase: (_, unknownError)=>[
2445
+ makePrettyError(unknownError)
2446
+ ],
2447
+ failCase: (_, error)=>[
2448
+ makePrettyError(error)
2449
+ ],
2450
+ interruptCase: ()=>[],
2451
+ parallelCase: (_, l, r)=>[
2452
+ ...l,
2453
+ ...r
2454
+ ],
2455
+ sequentialCase: (_, l, r)=>[
2456
+ ...l,
2457
+ ...r
2458
+ ]
2459
+ }), OP_STATE_PENDING = "Pending", DeferredTypeId = Symbol.for("effect/Deferred"), deferredVariance = {
2313
2460
  _E: (_)=>_,
2314
2461
  _A: (_)=>_
2315
2462
  }, deferred_done = (effect)=>({
@@ -2563,7 +2710,7 @@ let withFiberRuntime = (withRuntime)=>{
2563
2710
  onSequential: cause_sequential,
2564
2711
  onParallel: cause_parallel
2565
2712
  }));
2566
- let failures = Chunk_reverse(cause_reduce(cause, Chunk_empty(), (list, cause)=>"Fail" === cause._tag ? option_some(Function_pipe(list, Chunk_prepend(cause.error))) : Option_none()));
2713
+ let failures = Chunk_reverse(cause_reduce(cause, esm_Chunk_empty(), (list, cause)=>"Fail" === cause._tag ? option_some(Function_pipe(list, Chunk_prepend(cause.error))) : Option_none()));
2567
2714
  return failures.length > 0 ? options.onFailure(Chunk_unsafeHead(failures)) : failCause(cause);
2568
2715
  },
2569
2716
  onSuccess: options.onSuccess
@@ -2763,7 +2910,7 @@ let withFiberRuntime = (withRuntime)=>{
2763
2910
  patch: (patch)=>(oldValue)=>options.differ.patch(patch, oldValue),
2764
2911
  fork: options.fork,
2765
2912
  join: options.join ?? ((_, n)=>n)
2766
- }), currentContext = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentContext"), ()=>fiberRefUnsafeMakeContext(context_empty)), currentSchedulingPriority = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentSchedulingPriority"), ()=>fiberRefUnsafeMake(0)), currentMaxOpsBeforeYield = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentMaxOpsBeforeYield"), ()=>fiberRefUnsafeMake(2048)), currentLogAnnotations = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentLogAnnotation"), ()=>fiberRefUnsafeMake(hashMap_empty)), currentLogLevel = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentLogLevel"), ()=>fiberRefUnsafeMake(logLevelInfo)), currentLogSpan = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentLogSpan"), ()=>fiberRefUnsafeMake(List_empty())), withSchedulingPriority = Function_dual(2, (self, scheduler)=>fiberRefLocally(self, currentSchedulingPriority, scheduler)), currentConcurrency = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentConcurrency"), ()=>fiberRefUnsafeMake("unbounded")), currentRequestBatching = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentRequestBatching"), ()=>fiberRefUnsafeMake(!0)), currentUnhandledErrorLogLevel = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentUnhandledErrorLogLevel"), ()=>fiberRefUnsafeMake(option_some(logLevelDebug))), currentVersionMismatchErrorLogLevel = GlobalValue_globalValue(Symbol.for("effect/FiberRef/versionMismatchErrorLogLevel"), ()=>fiberRefUnsafeMake(option_some(logLevelWarning))), currentMetricLabels = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentMetricLabels"), ()=>{
2913
+ }), currentContext = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentContext"), ()=>fiberRefUnsafeMakeContext(_empty)), currentSchedulingPriority = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentSchedulingPriority"), ()=>fiberRefUnsafeMake(0)), currentMaxOpsBeforeYield = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentMaxOpsBeforeYield"), ()=>fiberRefUnsafeMake(2048)), currentLogAnnotations = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentLogAnnotation"), ()=>fiberRefUnsafeMake(hashMap_empty)), currentLogLevel = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentLogLevel"), ()=>fiberRefUnsafeMake(logLevelInfo)), currentLogSpan = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentLogSpan"), ()=>fiberRefUnsafeMake(List_empty())), withSchedulingPriority = Function_dual(2, (self, scheduler)=>fiberRefLocally(self, currentSchedulingPriority, scheduler)), currentConcurrency = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentConcurrency"), ()=>fiberRefUnsafeMake("unbounded")), currentRequestBatching = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentRequestBatching"), ()=>fiberRefUnsafeMake(!0)), currentUnhandledErrorLogLevel = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentUnhandledErrorLogLevel"), ()=>fiberRefUnsafeMake(option_some(logLevelDebug))), currentVersionMismatchErrorLogLevel = GlobalValue_globalValue(Symbol.for("effect/FiberRef/versionMismatchErrorLogLevel"), ()=>fiberRefUnsafeMake(option_some(logLevelWarning))), currentMetricLabels = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentMetricLabels"), ()=>{
2767
2914
  var initial;
2768
2915
  let differ, differ1;
2769
2916
  return initial = Array_empty(), differ = differ_update(), fiberRefUnsafeMakePatch(initial, {
@@ -2795,7 +2942,7 @@ let withFiberRuntime = (withRuntime)=>{
2795
2942
  join: (parent, _)=>parent
2796
2943
  }));
2797
2944
  ()=>fiberRefUnsafeMake(!0), ()=>fiberRefUnsafeMake(!0);
2798
- ()=>fiberRefUnsafeMake(Chunk_empty());
2945
+ ()=>fiberRefUnsafeMake(esm_Chunk_empty());
2799
2946
  let ScopeTypeId = Symbol.for("effect/Scope"), CloseableScopeTypeId = Symbol.for("effect/CloseableScope"), causeSquashWith = Function_dual(2, (self, f)=>{
2800
2947
  let option = Function_pipe(self, failureOption, Option_map(f));
2801
2948
  switch(option._tag){
@@ -2965,7 +3112,7 @@ let ScopeTypeId = Symbol.for("effect/Scope"), CloseableScopeTypeId = Symbol.for(
2965
3112
  let index = state.joiners.indexOf(joiner);
2966
3113
  index >= 0 && state.joiners.splice(index, 1);
2967
3114
  }
2968
- }), constContext = withFiberRuntime((fiber)=>exitSucceed(fiber.currentContext)), provideContext = Function_dual(2, (self, context)=>fiberRefLocally(currentContext, context)(self)), provideSomeContext = Function_dual(2, (self, context)=>fiberRefLocallyWith(currentContext, (parent)=>context_merge(parent, context))(self)), mapInputContext = Function_dual(2, (self, f)=>core_flatMap(constContext, (context)=>provideContext(self, f(context)))), currentSpanFromFiber = ((self, options)=>core_flatMap(self, (a)=>core_flatMap(options.predicate(a), (pass)=>pass ? succeed(a) : options.orElse(a))), (fiber)=>{
3115
+ }), constContext = withFiberRuntime((fiber)=>exitSucceed(fiber.currentContext)), provideContext = Function_dual(2, (self, context)=>fiberRefLocally(currentContext, context)(self)), provideSomeContext = Function_dual(2, (self, context)=>fiberRefLocallyWith(currentContext, (parent)=>merge(parent, context))(self)), mapInputContext = Function_dual(2, (self, f)=>core_flatMap(constContext, (context)=>provideContext(self, f(context)))), currentSpanFromFiber = ((self, options)=>core_flatMap(self, (a)=>core_flatMap(options.predicate(a), (pass)=>pass ? succeed(a) : options.orElse(a))), (fiber)=>{
2969
3116
  let span = fiber.currentSpan;
2970
3117
  return void 0 !== span && "Span" === span._tag ? option_some(span) : Option_none();
2971
3118
  }), ClockTypeId = Symbol.for("effect/Clock"), clock_clockTag = GenericTag("effect/Clock"), globalClockScheduler = {
@@ -3036,7 +3183,7 @@ let OP_INVALID_DATA = "InvalidData", OP_MISSING_DATA = "MissingData", OP_SOURCE_
3036
3183
  return error._op = OP_INVALID_DATA, error.path = path, error.message = message, Object.defineProperty(error, "toString", {
3037
3184
  enumerable: !1,
3038
3185
  value () {
3039
- let path = Function_pipe(this.path, join(options.pathDelim));
3186
+ let path = Function_pipe(this.path, Array_join(options.pathDelim));
3040
3187
  return `(Invalid data at ${path}: "${this.message}")`;
3041
3188
  }
3042
3189
  }), error;
@@ -3047,7 +3194,7 @@ let OP_INVALID_DATA = "InvalidData", OP_MISSING_DATA = "MissingData", OP_SOURCE_
3047
3194
  return error._op = OP_MISSING_DATA, error.path = path, error.message = message, Object.defineProperty(error, "toString", {
3048
3195
  enumerable: !1,
3049
3196
  value () {
3050
- let path = Function_pipe(this.path, join(options.pathDelim));
3197
+ let path = Function_pipe(this.path, Array_join(options.pathDelim));
3051
3198
  return `(Missing data at ${path}: "${this.message}")`;
3052
3199
  }
3053
3200
  }), error;
@@ -3058,7 +3205,7 @@ let OP_INVALID_DATA = "InvalidData", OP_MISSING_DATA = "MissingData", OP_SOURCE_
3058
3205
  return error._op = OP_SOURCE_UNAVAILABLE, error.path = path, error.message = message, error.cause = cause, Object.defineProperty(error, "toString", {
3059
3206
  enumerable: !1,
3060
3207
  value () {
3061
- let path = Function_pipe(this.path, join(options.pathDelim));
3208
+ let path = Function_pipe(this.path, Array_join(options.pathDelim));
3062
3209
  return `(Source unavailable at ${path}: "${this.message}")`;
3063
3210
  }
3064
3211
  }), error;
@@ -3069,7 +3216,7 @@ let OP_INVALID_DATA = "InvalidData", OP_MISSING_DATA = "MissingData", OP_SOURCE_
3069
3216
  return error._op = OP_UNSUPPORTED, error.path = path, error.message = message, Object.defineProperty(error, "toString", {
3070
3217
  enumerable: !1,
3071
3218
  value () {
3072
- let path = Function_pipe(this.path, join(options.pathDelim));
3219
+ let path = Function_pipe(this.path, Array_join(options.pathDelim));
3073
3220
  return `(Unsupported operation at ${path}: "${this.message}")`;
3074
3221
  }
3075
3222
  }), error;
@@ -3242,7 +3389,7 @@ let OP_INVALID_DATA = "InvalidData", OP_MISSING_DATA = "MissingData", OP_SOURCE_
3242
3389
  if (isRight(left) && isLeft(right)) return core_fail(right.left);
3243
3390
  if (isRight(left) && isRight(right)) {
3244
3391
  var left1, right1;
3245
- let leftPad, rightPad, path = Function_pipe(prefix, join(".")), fail = fromFlatLoopFail(prefix, path), [lefts, rights] = (left1 = Function_pipe(left.right, Array_map(either_right)), right1 = Function_pipe(right.right, Array_map(either_right)), leftPad = Array_unfold(left1.length, (index)=>index >= right1.length ? Option_none() : option_some([
3392
+ let leftPad, rightPad, path = Function_pipe(prefix, Array_join(".")), fail = fromFlatLoopFail(prefix, path), [lefts, rights] = (left1 = Function_pipe(left.right, Array_map(either_right)), right1 = Function_pipe(right.right, Array_map(either_right)), leftPad = Array_unfold(left1.length, (index)=>index >= right1.length ? Option_none() : option_some([
3246
3393
  fail(index),
3247
3394
  index + 1
3248
3395
  ])), rightPad = Array_unfold(right1.length, (index)=>index >= left1.length ? Option_none() : option_some([
@@ -3260,7 +3407,7 @@ let OP_INVALID_DATA = "InvalidData", OP_MISSING_DATA = "MissingData", OP_SOURCE_
3260
3407
  }, fromFlatLoopFail = (prefix, path)=>(index)=>either_left(MissingData(prefix, `The element at index ${index} in a sequence at path "${path}" was missing`)), transpose = (array)=>Object.keys(array[0]).map((column)=>array.map((row)=>row[column])), indicesFrom = (quotedIndices)=>Function_pipe(forEachSequential(quotedIndices, parseQuotedIndex), core_mapBoth({
3261
3408
  onFailure: ()=>Array_empty(),
3262
3409
  onSuccess: sort(Order_number)
3263
- }), core_either, core_map(merge)), QUOTED_INDEX_REGEX = /^(\[(\d+)\])$/, parseQuotedIndex = (str)=>{
3410
+ }), core_either, core_map(Either_merge)), QUOTED_INDEX_REGEX = /^(\[(\d+)\])$/, parseQuotedIndex = (str)=>{
3264
3411
  let match = str.match(QUOTED_INDEX_REGEX);
3265
3412
  if (null !== match) {
3266
3413
  let matchedIndex = match[2];
@@ -3383,7 +3530,7 @@ let nativeTracer = {
3383
3530
  }
3384
3531
  }, DisablePropagation = (Context_Reference())("effect/Tracer/DisablePropagation", {
3385
3532
  defaultValue: Function_constFalse
3386
- }), liveServices = Function_pipe(context_empty, context_add(clock_clockTag, new ClockImpl()), context_add(console_consoleTag, console_defaultConsole), context_add(random_randomTag, new class RandomImpl {
3533
+ }), liveServices = Function_pipe(_empty, add(clock_clockTag, new ClockImpl()), add(console_consoleTag, console_defaultConsole), add(random_randomTag, new class RandomImpl {
3387
3534
  seed;
3388
3535
  [RandomTypeId] = RandomTypeId;
3389
3536
  PRNG;
@@ -3408,7 +3555,7 @@ let nativeTracer = {
3408
3555
  shuffle(elements) {
3409
3556
  return shuffleWith(elements, (n)=>this.nextIntBetween(0, n));
3410
3557
  }
3411
- }(Hash_hash(Math.random()))), context_add(configProviderTag, (()=>{
3558
+ }(Hash_hash(Math.random()))), add(configProviderTag, (()=>{
3412
3559
  let options, { pathDelim, seqDelim } = Object.assign({}, {
3413
3560
  pathDelim: "_",
3414
3561
  seqDelim: ","
@@ -3417,7 +3564,7 @@ let nativeTracer = {
3417
3564
  [FlatConfigProviderTypeId]: FlatConfigProviderTypeId,
3418
3565
  patch: (options = {
3419
3566
  load: (path, primitive, split = !0)=>{
3420
- let pathString = Function_pipe(path, join(pathDelim)), current = getEnv();
3567
+ let pathString = Function_pipe(path, Array_join(pathDelim)), current = getEnv();
3421
3568
  return Function_pipe(pathString in current ? option_some(current[pathString]) : Option_none(), mapError(()=>MissingData(path, `Expected ${pathString} to exist in the process context`)), core_flatMap((value)=>{
3422
3569
  var text, path1, primitive1, delimiter;
3423
3570
  let text1, delim;
@@ -3430,13 +3577,13 @@ let nativeTracer = {
3430
3577
  enumerateChildren: (path)=>sync(()=>{
3431
3578
  var elements = Object.keys(getEnv()).map((value)=>value.toUpperCase().split(pathDelim)).filter((keyPath)=>{
3432
3579
  for(let i = 0; i < path.length; i++){
3433
- let pathComponent = Function_pipe(path, unsafeGet(i)), currentElement = keyPath[i];
3580
+ let pathComponent = Function_pipe(path, Array_unsafeGet(i)), currentElement = keyPath[i];
3434
3581
  if (void 0 === currentElement || pathComponent !== currentElement) return !1;
3435
3582
  }
3436
3583
  return !0;
3437
3584
  }).flatMap((keyPath)=>keyPath.slice(path.length, path.length + 1));
3438
3585
  let set = hashSet_beginMutation(internal_hashSet_empty());
3439
- for (let value of elements)add(set, value);
3586
+ for (let value of elements)hashSet_add(set, value);
3440
3587
  return hashSet_endMutation(set);
3441
3588
  }),
3442
3589
  patch: pathPatch_empty
@@ -3457,7 +3604,7 @@ let nativeTracer = {
3457
3604
  flattened: flat
3458
3605
  }
3459
3606
  };
3460
- })()), context_add(tracerTag, nativeTracer)), currentServices = GlobalValue_globalValue(Symbol.for("effect/DefaultServices/currentServices"), ()=>fiberRefUnsafeMakeContext(liveServices)), clockWith = (f)=>{
3607
+ })()), add(tracerTag, nativeTracer)), currentServices = GlobalValue_globalValue(Symbol.for("effect/DefaultServices/currentServices"), ()=>fiberRefUnsafeMakeContext(liveServices)), clockWith = (f)=>{
3461
3608
  let f1;
3462
3609
  return f1 = (services)=>f(services.unsafeMap.get(clock_clockTag.key)), withFiberRuntime((fiber)=>f1(fiber.currentDefaultServices));
3463
3610
  }, currentTimeMillis = clockWith((clock)=>clock.currentTimeMillis), Effectable_Base = effectable_Base;
@@ -3982,7 +4129,7 @@ class MicroSchedulerDefault {
3982
4129
  let updateContext = Function_dual(2, (self, f)=>withMicroFiber((fiber)=>{
3983
4130
  let prev = fiber.context;
3984
4131
  return fiber.context = f(prev), Micro_onExit(self, ()=>(fiber.context = prev, Micro_void_));
3985
- })), Micro_provideContext = Function_dual(2, (self, provided)=>updateContext(self, context_merge(provided)));
4132
+ })), Micro_provideContext = Function_dual(2, (self, provided)=>updateContext(self, merge(provided)));
3986
4133
  class MaxOpsBeforeYield extends (Context_Reference())("effect/Micro/currentMaxOpsBeforeYield", {
3987
4134
  defaultValue: ()=>2048
3988
4135
  }) {
@@ -4210,7 +4357,7 @@ class SequentialImpl {
4210
4357
  }
4211
4358
  }
4212
4359
  let sequentialCollectionMake = (map)=>new SequentialImpl(map), sequentialCollectionCombine = (self, that)=>new SequentialImpl(hashMap_reduce(that.map, self.map, (map, value, key)=>hashMap_set(map, key, Option_match(hashMap_get(map, key), {
4213
- onNone: ()=>Chunk_empty(),
4360
+ onNone: ()=>esm_Chunk_empty(),
4214
4361
  onSome: (a)=>Chunk_appendAll(a, value)
4215
4362
  })))), sequentialCollectionKeys = (self)=>Array.from(hashMap_keys(self.map)), currentRequestMap = GlobalValue_globalValue(Symbol.for("effect/FiberRef/currentRequestMap"), ()=>fiberRefUnsafeMake(new Map())), concurrency_match = (concurrency, sequential, unbounded, bounded)=>{
4216
4363
  switch(concurrency){
@@ -4254,9 +4401,9 @@ let isMetricLabel = (u)=>Predicate_hasProperty(u, MetricLabelTypeId), core_effec
4254
4401
  }))), core_effect_fiberRefs = withFiberRuntime((state)=>succeed(state.getFiberRefs())), core_effect_mapErrorCause = Function_dual(2, (self, f)=>matchCauseEffect(self, {
4255
4402
  onFailure: (c)=>failCauseSync(()=>f(c)),
4256
4403
  onSuccess: succeed
4257
- })), core_effect_provideService = Function_dual(3, (self, tag, service)=>core_flatMap(constContext, (env)=>provideContext(self, context_add(env, tag, service)))), core_effect_provideServiceEffect = Function_dual(3, (self, tag, effect)=>{
4404
+ })), core_effect_provideService = Function_dual(3, (self, tag, service)=>core_flatMap(constContext, (env)=>provideContext(self, add(env, tag, service)))), core_effect_provideServiceEffect = Function_dual(3, (self, tag, effect)=>{
4258
4405
  let f;
4259
- return f = (env)=>core_flatMap(effect, (service)=>provideContext(self, Function_pipe(env, context_add(tag, service)))), core_flatMap(constContext, f);
4406
+ return f = (env)=>core_flatMap(effect, (service)=>provideContext(self, Function_pipe(env, add(tag, service)))), core_flatMap(constContext, f);
4260
4407
  }), core_effect_succeedNone = succeed(Option_none()), summarized = Function_dual(3, (self, summary, f)=>core_flatMap(summary, (start)=>core_flatMap(self, (value)=>core_map(summary, (end)=>[
4261
4408
  f(start, end),
4262
4409
  value
@@ -4273,7 +4420,7 @@ let isMetricLabel = (u)=>Predicate_hasProperty(u, MetricLabelTypeId), core_effec
4273
4420
  },
4274
4421
  onSuccess: succeed
4275
4422
  });
4276
- let core_effect_when = Function_dual(2, (self, condition)=>core_suspend(()=>condition() ? core_map(self, option_some) : succeed(Option_none()))), filterDisablePropagation = Option_flatMap((span)=>context_unsafeGet(span.context, DisablePropagation) ? "Span" === span._tag ? filterDisablePropagation(span.parent) : Option_none() : option_some(span)), OP_INTERRUPT_SIGNAL = "InterruptSignal", OP_STATEFUL = "Stateful", OP_YIELD_NOW = "YieldNow", interruptSignal = (cause)=>({
4423
+ let core_effect_when = Function_dual(2, (self, condition)=>core_suspend(()=>condition() ? core_map(self, option_some) : succeed(Option_none()))), filterDisablePropagation = Option_flatMap((span)=>unsafeGet(span.context, DisablePropagation) ? "Span" === span._tag ? filterDisablePropagation(span.parent) : Option_none() : option_some(span)), OP_INTERRUPT_SIGNAL = "InterruptSignal", OP_STATEFUL = "Stateful", OP_YIELD_NOW = "YieldNow", interruptSignal = (cause)=>({
4277
4424
  _tag: OP_INTERRUPT_SIGNAL,
4278
4425
  cause
4279
4426
  }), stateful = (onFiber)=>({
@@ -5368,7 +5515,7 @@ class FiberRuntime extends Effectable_Class {
5368
5515
  if (LogLevel_greaterThan(this.getFiberRef(currentMinimumLogLevel), logLevel)) return;
5369
5516
  let spans = this.getFiberRef(currentLogSpan), annotations = this.getFiberRef(currentLogAnnotations), loggers = this.getLoggers(), contextMap = this.getFiberRefs();
5370
5517
  if (HashSet_size(loggers) > 0) {
5371
- let date = new Date(context_unsafeGet(this.getFiberRef(currentServices), clock_clockTag).unsafeCurrentTimeMillis());
5518
+ let date = new Date(unsafeGet(this.getFiberRef(currentServices), clock_clockTag).unsafeCurrentTimeMillis());
5372
5519
  ((context, f)=>{
5373
5520
  let prev = redactableState.fiberRefs;
5374
5521
  redactableState.fiberRefs = context;
@@ -5480,7 +5627,7 @@ class FiberRuntime extends Effectable_Class {
5480
5627
  }
5481
5628
  }
5482
5629
  Tag(op) {
5483
- return sync(()=>context_unsafeGet(this.currentContext, op));
5630
+ return sync(()=>unsafeGet(this.currentContext, op));
5484
5631
  }
5485
5632
  Left(op) {
5486
5633
  return core_fail(op.left);
@@ -5684,11 +5831,11 @@ let currentMinimumLogLevel = GlobalValue_globalValue("effect/FiberRef/currentMin
5684
5831
  return logLevelWarning;
5685
5832
  }
5686
5833
  })("Info"))), defaultLogger = GlobalValue_globalValue(Symbol.for("effect/Logger/defaultLogger"), ()=>makeLogger((opts)=>{
5687
- context_unsafeGet(getOrDefault(opts.context, currentServices), console_consoleTag).unsafe.log(stringLogger.log(opts));
5834
+ unsafeGet(getOrDefault(opts.context, currentServices), console_consoleTag).unsafe.log(stringLogger.log(opts));
5688
5835
  })), tracerLogger = GlobalValue_globalValue(Symbol.for("effect/Logger/tracerLogger"), ()=>makeLogger(({ annotations, cause, context, fiberId, logLevel, message })=>{
5689
5836
  let span = filterDisablePropagation(getOption(getOrDefault(context, currentContext), spanTag));
5690
5837
  if ("None" === span._tag || "ExternalSpan" === span.value._tag) return;
5691
- let clockService = context_unsafeGet(getOrDefault(context, currentServices), clock_clockTag), attributes = {};
5838
+ let clockService = unsafeGet(getOrDefault(context, currentServices), clock_clockTag), attributes = {};
5692
5839
  for (let [key, value] of annotations)attributes[key] = value;
5693
5840
  attributes["effect.fiberId"] = threadName(fiberId), attributes["effect.logLevel"] = logLevel.label, null !== cause && "Empty" !== cause._tag && (attributes["effect.cause"] = pretty(cause, {
5694
5841
  renderErrorCause: !0
@@ -5989,7 +6136,7 @@ let currentMinimumLogLevel = GlobalValue_globalValue("effect/FiberRef/currentMin
5989
6136
  _tag: "Open",
5990
6137
  finalizers: new Map()
5991
6138
  }, scope;
5992
- }, fiberRuntime_scopeMake = (strategy = executionStrategy_sequential)=>sync(()=>fiberRuntime_scopeUnsafeMake(strategy)), scopeExtend = Function_dual(2, (effect, scope)=>mapInputContext(effect, context_merge(context_make(scopeTag, scope)))), currentRuntimeFlags = ((self, value)=>core_asVoid(fiberRuntime_acquireRelease(core_flatMap(fiberRefGet(self), (oldValue)=>core_as(fiberRefSet(self, value), oldValue)), (oldValue)=>fiberRefSet(self, oldValue))), fiberRefUnsafeMakePatch(runtimeFlags_none, {
6139
+ }, fiberRuntime_scopeMake = (strategy = executionStrategy_sequential)=>sync(()=>fiberRuntime_scopeUnsafeMake(strategy)), scopeExtend = Function_dual(2, (effect, scope)=>mapInputContext(effect, merge(make(scopeTag, scope)))), currentRuntimeFlags = ((self, value)=>core_asVoid(fiberRuntime_acquireRelease(core_flatMap(fiberRefGet(self), (oldValue)=>core_as(fiberRefSet(self, value), oldValue)), (oldValue)=>fiberRefSet(self, oldValue))), fiberRefUnsafeMakePatch(runtimeFlags_none, {
5993
6140
  differ: runtimeFlags_differ,
5994
6141
  fork: runtimeFlags_differ.empty
5995
6142
  })), currentSupervisor = fiberRefUnsafeMakePatch(supervisor_none, {
@@ -6194,7 +6341,7 @@ let makeSynchronized = (value)=>sync(()=>unsafeMakeSynchronized(value)), unsafeM
6194
6341
  }, interval_lessThan = Function_dual(2, (self, that)=>interval_min(self, that) === self), interval_min = Function_dual(2, (self, that)=>self.endMillis <= that.startMillis ? self : that.endMillis <= self.startMillis ? that : self.startMillis < that.startMillis ? self : that.startMillis < self.startMillis ? that : self.endMillis <= that.endMillis ? self : that), intersect = Function_dual(2, (self, that)=>interval_make(Math.max(self.startMillis, that.startMillis), Math.min(self.endMillis, that.endMillis))), ScheduleInterval_isEmpty = (self)=>self.startMillis >= self.endMillis, IntervalsTypeId = Symbol.for("effect/ScheduleIntervals"), intervals_make = (intervals)=>({
6195
6342
  [IntervalsTypeId]: IntervalsTypeId,
6196
6343
  intervals
6197
- }), intervals_intersect = Function_dual(2, (self, that)=>intersectLoop(self.intervals, that.intervals, Chunk_empty())), intersectLoop = (_left, _right, _acc)=>{
6344
+ }), intervals_intersect = Function_dual(2, (self, that)=>intersectLoop(self.intervals, that.intervals, esm_Chunk_empty())), intersectLoop = (_left, _right, _acc)=>{
6198
6345
  let left = _left, right = _right, acc = _acc;
6199
6346
  for(; isNonEmpty(left) && isNonEmpty(right);){
6200
6347
  let interval = Function_pipe(Chunk_unsafeHead(left), intersect(Chunk_unsafeHead(right))), intervals = ScheduleInterval_isEmpty(interval) ? acc : Function_pipe(acc, Chunk_prepend(interval));
@@ -6347,7 +6494,7 @@ class RuntimeImpl {
6347
6494
  }
6348
6495
  }
6349
6496
  let runtime_make = (options)=>new RuntimeImpl(options.context, options.runtimeFlags, options.fiberRefs), runtime_runtime = ()=>withFiberRuntime((state, status)=>succeed(new RuntimeImpl(state.getFiberRef(currentContext), status.runtimeFlags, state.getFiberRefs()))), defaultRuntime = runtime_make({
6350
- context: context_empty,
6497
+ context: _empty,
6351
6498
  runtimeFlags: runtimeFlags_make(1, 32, 4),
6352
6499
  fiberRefs: new FiberRefsImpl(new Map())
6353
6500
  }), unsafeForkEffect = ((self, f)=>runtime_make({
@@ -6478,7 +6625,7 @@ let makeMemoMap = core_suspend(()=>core_map(makeSynchronized(new Map()), (ref)=>
6478
6625
  onSuccess: f
6479
6626
  })), layer_fromEffect = Function_dual(2, (a, b)=>{
6480
6627
  let tagFirst = Predicate_hasProperty(a, TagTypeId), tag = tagFirst ? a : b;
6481
- return fromEffectContext(core_map(tagFirst ? b : a, (service)=>context_make(tag, service)));
6628
+ return fromEffectContext(core_map(tagFirst ? b : a, (service)=>make(tag, service)));
6482
6629
  });
6483
6630
  function fromEffectContext(effect) {
6484
6631
  let fromEffect = Object.create(layer_proto);
@@ -6508,7 +6655,7 @@ let layer_matchCause = Function_dual(2, (self, { onFailure, onSuccess })=>{
6508
6655
  return mergeAll._op_layer = "MergeAll", mergeAll.layers = layers, mergeAll;
6509
6656
  }, succeedContext = ((a, b)=>{
6510
6657
  let tagFirst = Predicate_hasProperty(a, TagTypeId);
6511
- return fromEffectContext(succeed(context_make(tagFirst ? a : b, tagFirst ? b : a)));
6658
+ return fromEffectContext(succeed(make(tagFirst ? a : b, tagFirst ? b : a)));
6512
6659
  }, (context)=>fromEffectContext(succeed(context))), layer_suspend = (evaluate)=>{
6513
6660
  let suspend = Object.create(layer_proto);
6514
6661
  return suspend._op_layer = "Suspend", suspend.evaluate = evaluate, suspend;
@@ -6527,7 +6674,7 @@ let layer_matchCause = Function_dual(2, (self, { onFailure, onSuccess })=>{
6527
6674
  value: Array.isArray(that) ? layer_mergeAll(...that) : that
6528
6675
  },
6529
6676
  zipK: {
6530
- value: (a, b)=>Function_pipe(a, context_merge(b))
6677
+ value: (a, b)=>Function_pipe(a, merge(b))
6531
6678
  }
6532
6679
  }), provideTo.second = self, provideTo;
6533
6680
  }), Function_dual(2, (self, layer)=>{
@@ -6537,7 +6684,7 @@ let layer_matchCause = Function_dual(2, (self, { onFailure, onSuccess })=>{
6537
6684
  let patchRefs = patch_diff(defaultRuntime.fiberRefs, rt.fiberRefs), patchFlags = runtimeFlags_diff(defaultRuntime.runtimeFlags, rt.runtimeFlags);
6538
6685
  return uninterruptibleMask((restore)=>withFiberRuntime((fiber)=>{
6539
6686
  let oldContext = fiber.getFiberRef(currentContext), oldRefs = fiber.getFiberRefs(), newRefs = patch_patch(fiber.id(), oldRefs)(patchRefs), oldFlags = fiber.currentRuntimeFlags, newFlags = runtimeFlags_patch(patchFlags)(oldFlags), rollbackRefs = patch_diff(newRefs, oldRefs), rollbackFlags = runtimeFlags_diff(newFlags, oldFlags);
6540
- return fiber.setFiberRefs(newRefs), fiber.currentRuntimeFlags = newFlags, fiberRuntime_ensuring(provideSomeContext(restore(self), context_merge(oldContext, rt.context)), withFiberRuntime((fiber)=>(fiber.setFiberRefs(patch_patch(fiber.id(), fiber.getFiberRefs())(rollbackRefs)), fiber.currentRuntimeFlags = runtimeFlags_patch(rollbackFlags)(fiber.currentRuntimeFlags), core_void_)));
6687
+ return fiber.setFiberRefs(newRefs), fiber.currentRuntimeFlags = newFlags, fiberRuntime_ensuring(provideSomeContext(restore(self), merge(oldContext, rt.context)), withFiberRuntime((fiber)=>(fiber.setFiberRefs(patch_patch(fiber.id(), fiber.getFiberRefs())(rollbackRefs)), fiber.currentRuntimeFlags = runtimeFlags_patch(rollbackFlags)(fiber.currentRuntimeFlags), core_void_)));
6541
6688
  }));
6542
6689
  }), ScheduleTypeId = ((self, source)=>Array.isArray(source) ? provideSomeLayer(self, layer_mergeAll(...source)) : Predicate_hasProperty(source, LayerTypeId) ? provideSomeLayer(self, source) : isContext(source) ? provideSomeContext(self, source) : circular_TypeId in source ? core_flatMap(source.runtimeEffect, (rt)=>provideSomeRuntime(self, rt)) : provideSomeRuntime(self, source), Symbol.for("effect/Schedule")), ScheduleDriverTypeId = Symbol.for("effect/ScheduleDriver"), defaultIterationMetadata = {
6543
6690
  start: 0,
@@ -6887,7 +7034,7 @@ class CacheImpl {
6887
7034
  });
6888
7035
  }
6889
7036
  get(key) {
6890
- return core_map(this.getEither(key), merge);
7037
+ return core_map(this.getEither(key), Either_merge);
6891
7038
  }
6892
7039
  get cacheStats() {
6893
7040
  return sync(()=>({
@@ -7069,9 +7216,56 @@ class CacheImpl {
7069
7216
  return fiberRefUnsafeMake((lookup = ()=>core_map(deferredMake(), (handle)=>({
7070
7217
  listeners: new Listeners(),
7071
7218
  handle
7072
- })), timeToLive = ()=>Duration_seconds(60), new CacheImpl(65536, context_empty, fiberId_none, lookup, (exit)=>decode(timeToLive()))));
7219
+ })), timeToLive = ()=>Duration_seconds(60), new CacheImpl(65536, _empty, fiberId_none, lookup, (exit)=>decode(timeToLive()))));
7073
7220
  }, ()=>fiberRefUnsafeMake(!1);
7074
- let FiberSet_TypeId = Symbol.for("effect/FiberSet"), FiberSet_Proto = {
7221
+ let getManifestAssetType = (name, assetTypesByName)=>{
7222
+ if (/\.hot-update\.[cm]?js(?:[?#]|$)/.test(name)) return;
7223
+ let assetType = assetTypesByName?.[name];
7224
+ if (void 0 !== assetType) return 'extract-css' === assetType ? 'css' : assetType;
7225
+ let path = name.replace(/[?#].*$/, '');
7226
+ return /\.[cm]?js$/.test(path) ? "javascript" : path.endsWith('.css') ? 'css' : void 0;
7227
+ }, orderChunkFiles = (chunkName, files, assetTypesByName)=>{
7228
+ let ownFileIndex = files.findIndex((file)=>"javascript" === getManifestAssetType(file, assetTypesByName) && file.replace(/[?#].*$/, '').replace(/\.[^.]+$/, '').endsWith(chunkName));
7229
+ return ownFileIndex <= 0 ? files : [
7230
+ files[ownFileIndex],
7231
+ ...files.slice(0, ownFileIndex),
7232
+ ...files.slice(ownFileIndex + 1)
7233
+ ];
7234
+ }, collectManifestFilesByName = (items, names, getFiles)=>{
7235
+ let filesByName = {};
7236
+ if (!names) {
7237
+ for (let [name, item] of items)null != item && (filesByName[name] = getFiles(item));
7238
+ return filesByName;
7239
+ }
7240
+ let missingNames = new Set(names);
7241
+ if ('function' == typeof items.get) for (let name of names){
7242
+ let item = items.get(name);
7243
+ item && null != item && (filesByName[name] = getFiles(item), missingNames.delete(name));
7244
+ }
7245
+ if (0 === missingNames.size) return filesByName;
7246
+ for (let [name, item] of items)if (missingNames.has(name) && null != item && (filesByName[name] = getFiles(item), missingNames.delete(name), 0 === missingNames.size)) break;
7247
+ return filesByName;
7248
+ }, createReactRouterManifestStats = (compilation, chunkNames)=>{
7249
+ if (!compilation) return;
7250
+ let assetsByChunkName = collectManifestFilesByName(compilation.namedChunks, chunkNames, (chunk)=>Array.from(chunk.files ?? [])), entrypointFilesByName = compilation.entrypoints ? collectManifestFilesByName(compilation.entrypoints, chunkNames, (entrypoint)=>Array.from(entrypoint.getFiles?.() ?? [])) : {}, assetTypesByName = {};
7251
+ if (compilation.getAsset) for (let file of new Set([
7252
+ ...Object.values(assetsByChunkName).flat(),
7253
+ ...Object.values(entrypointFilesByName).flat()
7254
+ ])){
7255
+ let info = compilation.getAsset(file)?.info, assetType = info?.assetType ?? ('boolean' == typeof info?.javascriptModule ? "javascript" : void 0);
7256
+ void 0 !== assetType && (assetTypesByName[file] = assetType);
7257
+ }
7258
+ for (let [chunkName, files] of Object.entries(assetsByChunkName))assetsByChunkName[chunkName] = orderChunkFiles(chunkName, files, assetTypesByName);
7259
+ return {
7260
+ assetsByChunkName,
7261
+ ...Object.keys(entrypointFilesByName).length > 0 ? {
7262
+ entrypointFilesByName
7263
+ } : {},
7264
+ ...Object.keys(assetTypesByName).length > 0 ? {
7265
+ assetTypesByName
7266
+ } : {}
7267
+ };
7268
+ }, FiberSet_TypeId = Symbol.for("effect/FiberSet"), FiberSet_Proto = {
7075
7269
  [FiberSet_TypeId]: FiberSet_TypeId,
7076
7270
  [Symbol.iterator] () {
7077
7271
  return "Closed" === this.state._tag ? constEmpty : this.state.backing[Symbol.iterator]();
@@ -7103,235 +7297,79 @@ let FiberSet_TypeId = Symbol.for("effect/FiberSet"), FiberSet_Proto = {
7103
7297
  "Closed" !== self.state._tag && (self.state.backing.delete(fiber), "Failure" !== exit._tag || (options?.propagateInterruption === !0 ? isInternalInterruption(exit.cause) : isInterruptedOnly(exit.cause)) || deferredUnsafeDone(self.deferred, exit));
7104
7298
  }));
7105
7299
  });
7106
- function managedRuntime_provide(managed, effect) {
7107
- return core_flatMap(managed.runtimeEffect, (rt)=>withFiberRuntime((fiber)=>(fiber.setFiberRefs(rt.fiberRefs), fiber.currentRuntimeFlags = rt.runtimeFlags, provideContext(effect, rt.context))));
7108
- }
7109
- let ManagedRuntimeProto = {
7110
- ...CommitPrototype,
7111
- [circular_TypeId]: circular_TypeId,
7112
- pipe () {
7113
- return Pipeable_pipeArguments(this, arguments);
7114
- },
7115
- commit () {
7116
- return this.runtimeEffect;
7117
- }
7118
- }, PluginFibers = GenericTag('rsbuild-plugin-react-router/PluginFibers'), PluginResources = GenericTag('rsbuild-plugin-react-router/PluginResources'), PluginRuntimeLive = (effect = core_gen(function*() {
7119
- let self, strategy, self1, strategy1, scope = yield* fiberRuntime_scope, resources = yield* (self = scope, strategy = executionStrategy_sequential, self.fork(strategy)), fiberScope = yield* (self1 = scope, strategy1 = executionStrategy_sequential, self1.fork(strategy1)), fibers = yield* fiberRuntime_acquireRelease(core_map(deferredMake(), (deferred)=>{
7120
- var backing;
7121
- let self;
7122
- return backing = new Set(), (self = Object.create(FiberSet_Proto)).state = {
7123
- _tag: "Open",
7124
- backing
7125
- }, self.deferred = deferred, self;
7126
- }), (set)=>withFiberRuntime((parent)=>{
7127
- let state = set.state;
7128
- return "Closed" === state._tag ? core_void_ : (set.state = {
7129
- _tag: "Closed"
7130
- }, interruptAllAs(state.backing, fiberId_combine(parent.id(), internalFiberId)).pipe(intoDeferred(set.deferred)));
7131
- })).pipe(core_effect_provideService(scopeTag, fiberScope));
7132
- return context_make(scopeTag, resources).pipe(context_add(PluginFibers, fibers), context_add(PluginResources, {
7133
- scope: resources
7134
- }));
7135
- }), (scoped = Object.create(layer_proto))._op_layer = "Scoped", scoped.effect = effect, scoped), normalizeEffectError = (cause)=>cause instanceof Error ? cause : Error(String(cause)), runPluginEffect = async (effect)=>{
7136
- var cause;
7137
- let failure, exit = await unsafeRunPromiseExitEffect(effect);
7138
- if (exitIsSuccess(exit)) return exit.value;
7139
- throw normalizeEffectError(isSome(failure = failureOption(cause = exit.cause)) ? failure.value : causeSquashWith(Function_identity)(cause));
7140
- }, tryPluginPromise = (evaluate)=>{
7141
- var arg;
7142
- let evaluate1, catcher, fail;
7143
- return "function" == typeof (arg = {
7144
- try: ()=>Promise.resolve(evaluate()),
7145
- catch: normalizeEffectError
7146
- }) ? evaluate1 = arg : (evaluate1 = arg.try, catcher = arg.catch), fail = (e)=>catcher ? core_flatMap(sync(()=>catcher(e)), core_fail) : core_fail(new core_UnknownException(e, "An unknown error occurred in Effect.tryPromise")), evaluate1.length >= 1 ? async_((resolve, signal)=>{
7147
- try {
7148
- evaluate1(signal).then((a)=>resolve(succeed(a)), (e)=>resolve(fail(e)));
7149
- } catch (e) {
7150
- resolve(fail(e));
7151
- }
7152
- }) : async_((resolve)=>{
7153
- try {
7154
- evaluate1().then((a)=>resolve(succeed(a)), (e)=>resolve(fail(e)));
7155
- } catch (e) {
7156
- resolve(fail(e));
7157
- }
7158
- });
7159
- }, createDelayedPluginTask = ({ runtime, delayMs, run, onError })=>{
7160
- let fiber, start = ()=>{
7161
- let activeFiber;
7162
- void 0 === fiber && (fiber = activeFiber = runtime.runFork(Clock_sleep(Duration_millis(delayMs)).pipe(zipRightOptions(core_suspend(run)), catchAll((error)=>sync(()=>{
7163
- onError(error);
7164
- })), fiberRuntime_ensuring(sync(()=>{
7165
- fiber === activeFiber && (fiber = void 0);
7166
- })))));
7167
- };
7168
- return {
7169
- schedule: start,
7170
- reschedule: ()=>{
7171
- fiber ? runtime.runFork(interruptFiber(fiber).pipe(fiberRuntime_ensuring(sync(start)))) : start();
7172
- },
7173
- cancelEffect: ()=>core_suspend(()=>{
7174
- let activeFiber = fiber;
7175
- return fiber = null, activeFiber ? interruptFiber(activeFiber).pipe(core_asVoid) : core_void_;
7176
- })
7177
- };
7178
- }, RESOLVABLE_BUILD_EXPORTS = new Set([
7179
- 'allowedActionOrigins',
7180
- 'assets',
7181
- 'assetsBuildDirectory',
7182
- 'basename',
7183
- 'entry',
7184
- 'future',
7185
- 'isSpaMode',
7186
- 'prerender',
7187
- 'publicPath',
7188
- 'routeDiscovery',
7189
- 'routes',
7190
- 'ssr'
7191
- ]);
7192
- function server_build_resolution_isRecord(value) {
7193
- return 'object' == typeof value && null !== value && !Array.isArray(value);
7194
- }
7195
- function server_build_resolution_isPromiseLike(value) {
7196
- return server_build_resolution_isRecord(value) && 'function' == typeof value.then;
7197
- }
7198
- async function resolveBuildExports(build) {
7199
- let resolved = {
7200
- ...build
7201
- };
7202
- for (let key of Object.keys(build)){
7203
- if (!RESOLVABLE_BUILD_EXPORTS.has(key)) continue;
7204
- let value = build[key];
7205
- if ('function' == typeof value && 0 === value.length) {
7206
- let result = value();
7207
- resolved[key] = server_build_resolution_isPromiseLike(result) ? await result : result;
7208
- continue;
7209
- }
7210
- server_build_resolution_isPromiseLike(value) && (resolved[key] = await value);
7211
- }
7212
- return resolved;
7213
- }
7214
- async function resolveServerBuildCandidate(candidate) {
7215
- var value;
7216
- if (!server_build_resolution_isRecord(candidate)) return;
7217
- let resolved = await resolveBuildExports(candidate);
7218
- return server_build_resolution_isRecord(resolved) && server_build_resolution_isRecord(resolved.entry) && server_build_resolution_isRecord(resolved.entry.module) && 'function' == typeof resolved.entry.module.default && server_build_resolution_isRecord(resolved.routes) && server_build_resolution_isRecord(resolved.assets) && 'string' == typeof resolved.assetsBuildDirectory && (void 0 === resolved.basename || 'string' == typeof resolved.basename) && server_build_resolution_isRecord(resolved.future) && 'boolean' == typeof resolved.isSpaMode && Array.isArray(resolved.prerender) && 'string' == typeof resolved.publicPath && (void 0 === (value = resolved.routeDiscovery) || server_build_resolution_isRecord(value) && ('initial' === value.mode || 'lazy' === value.mode && (void 0 === value.manifestPath || 'string' == typeof value.manifestPath))) && 'boolean' == typeof resolved.ssr ? resolved : void 0;
7219
- }
7220
- async function resolveServerBuildModule(buildModule, source) {
7221
- try {
7222
- let moduleValue = server_build_resolution_isPromiseLike(buildModule) ? await buildModule : buildModule, candidates = [
7223
- ()=>moduleValue
7224
- ];
7225
- for (let getCandidate of (server_build_resolution_isRecord(moduleValue) && ('default' in moduleValue && candidates.push(()=>moduleValue.default), 'module.exports' in moduleValue && candidates.push(()=>moduleValue['module.exports'])), candidates)){
7226
- let candidate = await getCandidate(), serverBuild = await resolveServerBuildCandidate(candidate);
7227
- if (serverBuild) return serverBuild;
7228
- }
7229
- throw Error(`[rsbuild-plugin-react-router] ${source} did not contain a valid React Router ServerBuild.`);
7230
- } catch (cause) {
7231
- throw normalizeEffectError(cause);
7232
- }
7233
- }
7234
- function generateServerBuild(routes, options) {
7235
- let manifestId = options.serverManifestId ?? 'virtual/react-router/server-manifest', routeEntries = Object.entries(routes);
7236
- return `
7237
- import * as entryServer from ${JSON.stringify(options.entryServerPath)};
7238
- ${routeEntries.map(([, route], index)=>options.isSpaMode && 'root' !== route.id ? `const route${index} = { default: () => null };` : `import * as route${index} from ${JSON.stringify(external_pathe_resolve(options.appDirectory, route.file))};`).join('\n')}
7239
-
7240
- export { default as assets } from ${JSON.stringify(manifestId)};
7241
- export const assetsBuildDirectory = ${JSON.stringify(options.assetsBuildDirectory)};
7242
- export const basename = ${JSON.stringify(options.basename)};
7243
- export const future = ${JSON.stringify(options.future ?? {})};
7244
- export const isSpaMode = ${options.isSpaMode};
7245
- export const ssr = ${options.ssr};
7246
- export const routeDiscovery = ${JSON.stringify(options.routeDiscovery)};
7247
- export const prerender = ${JSON.stringify(options.prerender ?? [])};
7248
- export const publicPath = ${JSON.stringify(options.publicPath ?? '/')};
7249
- export const entry = { module: entryServer };
7250
- export const allowedActionOrigins = ${JSON.stringify(options.allowedActionOrigins)};
7251
- export var routes = {};
7252
- ${routeEntries.map(([key, route], index)=>`routes[${JSON.stringify(key)}] = {
7253
- id: ${JSON.stringify(route.id)},
7254
- parentId: ${JSON.stringify(route.parentId)},
7255
- path: ${JSON.stringify(route.path)},
7256
- index: ${JSON.stringify(route.index)},
7257
- caseSensitive: ${JSON.stringify(route.caseSensitive)},
7258
- module: route${index}
7259
- };`).join('\n ')}
7260
- `;
7261
- }
7262
- function resolveReactRouterServerBuild(buildModule) {
7263
- return resolveServerBuildModule(buildModule, 'Imported module');
7264
- }
7265
- let normalizePath = (value)=>value.replace(/\/\/+/g, '/').replace(/(.+)\/$/, '$1'), groupRoutesByParentId = (manifest)=>{
7266
- let grouped = {};
7267
- return Object.values(manifest).forEach((route)=>{
7268
- if (!route) return;
7269
- let parentId = route.parentId || '';
7270
- grouped[parentId] ??= [], grouped[parentId].push(route);
7271
- }), grouped;
7272
- }, createPrerenderRoutes = (manifest, parentId = '', grouped = groupRoutesByParentId(manifest))=>(grouped[parentId] || []).map((route)=>{
7273
- let common = {
7274
- id: route.id,
7275
- path: route.path,
7276
- caseSensitive: route.caseSensitive
7277
- };
7278
- return route.index ? {
7279
- index: !0,
7280
- ...common
7281
- } : {
7282
- ...common,
7283
- children: createPrerenderRoutes(manifest, route.id, grouped)
7284
- };
7285
- }), normalizePrerenderMatchPath = (path)=>`/${path}/`.replace(/^\/\/+/, '/'), resolvePrerenderPaths = async (prerender, ssr, routes, options = {})=>{
7286
- let pathsConfig, paths, paramRoutes, recurse;
7287
- if (null == prerender || !1 === prerender || !1 === (pathsConfig = 'object' == typeof prerender && null !== prerender && 'paths' in prerender ? prerender?.paths : prerender)) return [];
7288
- let { paths: paths1, paramRoutes: paramRoutes1 } = (paths = [
7289
- '/'
7290
- ], paramRoutes = [], (recurse = (entries, prefix = '', hasDynamicParent = !1)=>{
7291
- for (let route of entries){
7292
- let routePath = route.path ?? '', hasDynamicSegment = routePath.split('/').filter(Boolean).some((segment)=>segment.startsWith(':') || '*' === segment) || '*' === routePath, nextHasDynamic = hasDynamicParent || hasDynamicSegment;
7293
- if (routePath) {
7294
- let fullPath = normalizePath([
7295
- prefix,
7296
- routePath
7297
- ].join('/'));
7298
- nextHasDynamic ? paramRoutes.push(fullPath) : paths.push(fullPath);
7299
- }
7300
- if (route.children) {
7301
- let newPrefix = routePath ? normalizePath([
7302
- prefix,
7303
- routePath
7304
- ].join('/')) : prefix;
7305
- recurse(route.children, newPrefix, nextHasDynamic);
7306
- }
7300
+ function managedRuntime_provide(managed, effect) {
7301
+ return core_flatMap(managed.runtimeEffect, (rt)=>withFiberRuntime((fiber)=>(fiber.setFiberRefs(rt.fiberRefs), fiber.currentRuntimeFlags = rt.runtimeFlags, provideContext(effect, rt.context))));
7302
+ }
7303
+ let ManagedRuntimeProto = {
7304
+ ...CommitPrototype,
7305
+ [circular_TypeId]: circular_TypeId,
7306
+ pipe () {
7307
+ return Pipeable_pipeArguments(this, arguments);
7308
+ },
7309
+ commit () {
7310
+ return this.runtimeEffect;
7311
+ }
7312
+ }, PluginFibers = GenericTag('rsbuild-plugin-react-router/PluginFibers'), PluginResources = GenericTag('rsbuild-plugin-react-router/PluginResources'), PluginRuntimeLive = (effect = core_gen(function*() {
7313
+ let self, strategy, self1, strategy1, scope = yield* fiberRuntime_scope, resources = yield* (self = scope, strategy = executionStrategy_sequential, self.fork(strategy)), fiberScope = yield* (self1 = scope, strategy1 = executionStrategy_sequential, self1.fork(strategy1)), fibers = yield* fiberRuntime_acquireRelease(core_map(deferredMake(), (deferred)=>{
7314
+ var backing;
7315
+ let self;
7316
+ return backing = new Set(), (self = Object.create(FiberSet_Proto)).state = {
7317
+ _tag: "Open",
7318
+ backing
7319
+ }, self.deferred = deferred, self;
7320
+ }), (set)=>withFiberRuntime((parent)=>{
7321
+ let state = set.state;
7322
+ return "Closed" === state._tag ? core_void_ : (set.state = {
7323
+ _tag: "Closed"
7324
+ }, interruptAllAs(state.backing, fiberId_combine(parent.id(), internalFiberId)).pipe(intoDeferred(set.deferred)));
7325
+ })).pipe(core_effect_provideService(scopeTag, fiberScope));
7326
+ return make(scopeTag, resources).pipe(add(PluginFibers, fibers), add(PluginResources, {
7327
+ scope: resources
7328
+ }));
7329
+ }), (scoped = Object.create(layer_proto))._op_layer = "Scoped", scoped.effect = effect, scoped), normalizeEffectError = (cause)=>cause instanceof Error ? cause : Error(String(cause)), runPluginEffect = async (effect)=>{
7330
+ var cause;
7331
+ let failure, exit = await unsafeRunPromiseExitEffect(effect);
7332
+ if (exitIsSuccess(exit)) return exit.value;
7333
+ throw normalizeEffectError(isSome(failure = failureOption(cause = exit.cause)) ? failure.value : causeSquashWith(Function_identity)(cause));
7334
+ }, tryPluginPromise = (evaluate)=>{
7335
+ var arg;
7336
+ let evaluate1, catcher, fail;
7337
+ return "function" == typeof (arg = {
7338
+ try: ()=>Promise.resolve(evaluate()),
7339
+ catch: normalizeEffectError
7340
+ }) ? evaluate1 = arg : (evaluate1 = arg.try, catcher = arg.catch), fail = (e)=>catcher ? core_flatMap(sync(()=>catcher(e)), core_fail) : core_fail(new core_UnknownException(e, "An unknown error occurred in Effect.tryPromise")), evaluate1.length >= 1 ? async_((resolve, signal)=>{
7341
+ try {
7342
+ evaluate1(signal).then((a)=>resolve(succeed(a)), (e)=>resolve(fail(e)));
7343
+ } catch (e) {
7344
+ resolve(fail(e));
7345
+ }
7346
+ }) : async_((resolve)=>{
7347
+ try {
7348
+ evaluate1().then((a)=>resolve(succeed(a)), (e)=>resolve(fail(e)));
7349
+ } catch (e) {
7350
+ resolve(fail(e));
7307
7351
  }
7308
- })(routes), {
7309
- paths: paths.map(normalizePath),
7310
- paramRoutes: paramRoutes.map(normalizePath)
7311
7352
  });
7312
- if (!0 === pathsConfig) return options.logWarning && !ssr && paramRoutes1.length > 0 && (options.warn ?? ((message)=>{
7313
- console.warn(message);
7314
- }))([
7315
- "⚠️ Paths with dynamic/splat params cannot be prerendered when using `prerender: true`. You may want to use the `prerender()` API to prerender the following paths:",
7316
- ...paramRoutes1.map((path)=>` - ${path.replace(/^\/(?=[:*])/, '')}`)
7317
- ].join('\n')), paths1;
7318
- if ('function' == typeof pathsConfig) {
7319
- let resolved = await pathsConfig({
7320
- getStaticPaths: ()=>paths1
7321
- });
7322
- return !0 === resolved ? paths1 : !1 === resolved || null == resolved ? [] : resolved;
7323
- }
7324
- return pathsConfig ?? [];
7325
- }, getPrerenderConcurrency = (prerender, _cpuCount)=>{
7326
- let config = getPrerenderConfigObject(prerender), value = getPrerenderConcurrencyConfig(config)?.value;
7327
- return 'number' == typeof value && Number.isInteger(value) && value > 0 ? value : 1;
7328
- }, getPrerenderConfigObject = (prerender)=>'object' != typeof prerender || null === prerender || Array.isArray(prerender) ? null : prerender, getPrerenderConcurrencyConfig = (config)=>config?.concurrency !== void 0 ? {
7329
- key: 'prerender.concurrency',
7330
- value: config.concurrency
7331
- } : config?.unstable_concurrency !== void 0 ? {
7332
- key: 'prerender.unstable_concurrency',
7333
- value: config.unstable_concurrency
7334
- } : void 0, ROUTE_ANALYSIS_CONCURRENCY = getCappedPluginConcurrency();
7353
+ }, createDelayedPluginTask = ({ runtime, delayMs, run, onError })=>{
7354
+ let fiber, start = ()=>{
7355
+ let activeFiber;
7356
+ void 0 === fiber && (fiber = activeFiber = runtime.runFork(Clock_sleep(Duration_millis(delayMs)).pipe(zipRightOptions(core_suspend(run)), catchAll((error)=>sync(()=>{
7357
+ onError(error);
7358
+ })), fiberRuntime_ensuring(sync(()=>{
7359
+ fiber === activeFiber && (fiber = void 0);
7360
+ })))));
7361
+ };
7362
+ return {
7363
+ schedule: start,
7364
+ reschedule: ()=>{
7365
+ fiber ? runtime.runFork(interruptFiber(fiber).pipe(fiberRuntime_ensuring(sync(start)))) : start();
7366
+ },
7367
+ cancelEffect: ()=>core_suspend(()=>{
7368
+ let activeFiber = fiber;
7369
+ return fiber = null, activeFiber ? interruptFiber(activeFiber).pipe(core_asVoid) : core_void_;
7370
+ })
7371
+ };
7372
+ }, ROUTE_ANALYSIS_CONCURRENCY = getCappedPluginConcurrency();
7335
7373
  function configRoutesToRouteManifestEntries(appDirectory, routes, rootId = 'root') {
7336
7374
  let routeManifestEntries = [], routeIds = new Set();
7337
7375
  for (let route of routes)!function walk(route, parentId) {
@@ -7358,32 +7396,9 @@ let createReactRouterManifestOptions = ({ routeChunks, routeModuleAnalysis })=>{
7358
7396
  routeModuleAnalysis
7359
7397
  } : {}
7360
7398
  };
7361
- }, isManifestJsAsset = (asset)=>/(?<!\.hot-update)\.[cm]?js(?:\?.*)?$/.test(asset), isManifestCssAsset = (asset)=>/\.css(?:\?.*)?$/.test(asset), hasSome = (iterable)=>{
7399
+ }, isManifestJsAsset = (asset)=>/(?<!\.hot-update)\.[cm]?js(?:\?.*)?$/.test(asset), hasSome = (iterable)=>{
7362
7400
  for (let _ of iterable)return !0;
7363
7401
  return !1;
7364
- }, collectManifestFilesByName = (items, names, getFiles)=>{
7365
- let filesByName = {};
7366
- if (!names) {
7367
- for (let [name, item] of items)null != item && (filesByName[name] = getFiles(name, item));
7368
- return filesByName;
7369
- }
7370
- let missingNames = new Set(names);
7371
- if ('function' == typeof items.get) for (let name of names){
7372
- let item = items.get(name);
7373
- null != item && (filesByName[name] = getFiles(name, item), missingNames.delete(name));
7374
- }
7375
- if (0 === missingNames.size) return filesByName;
7376
- for (let [name, item] of items)if (missingNames.has(name) && null != item && (filesByName[name] = getFiles(name, item), missingNames.delete(name), 0 === missingNames.size)) break;
7377
- return filesByName;
7378
- }, createReactRouterManifestStats = (compilation, chunkNames)=>{
7379
- if (!compilation) return;
7380
- let assetsByChunkName = collectManifestFilesByName(compilation.namedChunks, chunkNames, (_chunkName, chunk)=>Array.from(chunk.files ?? [])), entrypointFilesByName = compilation.entrypoints ? collectManifestFilesByName(compilation.entrypoints, chunkNames, (_name, entrypoint)=>Array.from(entrypoint.getFiles?.() ?? [])) : {};
7381
- return Object.keys(entrypointFilesByName).length > 0 ? {
7382
- assetsByChunkName,
7383
- entrypointFilesByName
7384
- } : {
7385
- assetsByChunkName
7386
- };
7387
7402
  }, CSS_IMPORT_RE = /\.(?:css|less|sass|scss)(?:\?[^'"`]+)?['"`]/, getReactRouterManifestPath = ({ version, isBuild, entryModulePath })=>{
7388
7403
  if (!isBuild) return 'static/js/virtual/react-router/browser-manifest.js';
7389
7404
  let dir = ((entryModulePath)=>{
@@ -7395,11 +7410,11 @@ let createReactRouterManifestOptions = ({ routeChunks, routeModuleAnalysis })=>{
7395
7410
  };
7396
7411
  async function generateReactRouterManifestForDev(routes, _options, clientStats, context, assetPrefix = '/', manifestOptions) {
7397
7412
  return runPluginEffect(core_gen(function*() {
7398
- let chunkAssetsByName, result = {}, splitRouteModules = manifestOptions?.splitRouteModules ?? !1, enforceSplitRouteModules = 'enforce' === splitRouteModules, isBuild = manifestOptions?.isBuild ?? !1, routeChunkConfig = splitRouteModules && manifestOptions?.rootRouteFile ? {
7413
+ let chunkAssetsByName, getAssetType, result = {}, splitRouteModules = manifestOptions?.splitRouteModules ?? !1, enforceSplitRouteModules = 'enforce' === splitRouteModules, isBuild = manifestOptions?.isBuild ?? !1, routeChunkConfig = splitRouteModules && manifestOptions?.rootRouteFile ? {
7399
7414
  splitRouteModules,
7400
7415
  appDirectory: context,
7401
7416
  rootRouteFile: manifestOptions.rootRouteFile
7402
- } : null, getAssetsForChunk = (chunkAssetsByName = new Map(), (chunkName)=>{
7417
+ } : null, getAssetsForChunk = (chunkAssetsByName = new Map(), getAssetType = (name)=>getManifestAssetType(name, clientStats?.assetTypesByName), (chunkName)=>{
7403
7418
  let cached = chunkAssetsByName.get(chunkName);
7404
7419
  if (cached) return cached;
7405
7420
  let assets = clientStats?.assetsByChunkName?.[chunkName];
@@ -7412,13 +7427,19 @@ async function generateReactRouterManifestForDev(routes, _options, clientStats,
7412
7427
  };
7413
7428
  return chunkAssetsByName.set(chunkName, result), result;
7414
7429
  }
7415
- let cssAssets = new Set(), jsAssets = new Set();
7416
- for (let asset of assets)isManifestCssAsset(asset) ? cssAssets.add(asset) : isManifestJsAsset(asset) && jsAssets.add(asset);
7417
- for (let asset of clientStats?.entrypointFilesByName?.[chunkName] ?? [])isManifestCssAsset(asset) ? cssAssets.add(asset) : isBuild && isManifestJsAsset(asset) && jsAssets.add(asset);
7418
- if (0 === jsAssets.size) throw Error(`[react-router] Chunk "${chunkName}" emitted no JavaScript asset the browser manifest can reference (files: ${assets.join(', ') || 'none'}). Check the web \`output.filename.js\` scheme.`);
7430
+ let cssAssets = new Set(), jsAssets = [];
7431
+ for (let asset of assets){
7432
+ let assetType = getAssetType(asset);
7433
+ 'css' === assetType ? cssAssets.add(asset) : "javascript" === assetType && jsAssets.push(asset);
7434
+ }
7435
+ if (0 === jsAssets.length) throw Error(`[react-router] Chunk "${chunkName}" emitted no JavaScript asset the browser manifest can reference (files: ${assets.join(', ') || 'none'}). Check the web \`output.filename.js\` scheme.`);
7436
+ for (let asset of clientStats?.entrypointFilesByName?.[chunkName] ?? []){
7437
+ let assetType = getAssetType(asset);
7438
+ 'css' === assetType ? cssAssets.add(asset) : isBuild && "javascript" === assetType && jsAssets.push(asset);
7439
+ }
7419
7440
  let result = {
7420
7441
  js: [
7421
- ...jsAssets
7442
+ ...new Set(jsAssets)
7422
7443
  ],
7423
7444
  css: [
7424
7445
  ...cssAssets
@@ -7517,12 +7538,12 @@ async function generateReactRouterManifestForDev(routes, _options, clientStats,
7517
7538
  }, version = createHash('sha256').update(JSON.stringify(fingerprintedValues)).digest('hex').slice(0, 8), manifestPath = getReactRouterManifestPath({
7518
7539
  version,
7519
7540
  isBuild,
7520
- entryModulePath: entryJsAssets[0]
7521
- });
7541
+ entryModulePath: (entryJsAssets[0] ?? '').replace(/[?#].*$/, '')
7542
+ }), browserManifestPath = clientStats?.assetsByChunkName?.[BROWSER_MANIFEST_ENTRY_NAME]?.find((name)=>"javascript" === getManifestAssetType(name, clientStats.assetTypesByName)) ?? manifestPath;
7522
7543
  return {
7523
7544
  manifest: {
7524
7545
  version,
7525
- url: combineURLs(assetPrefix, isBuild ? manifestPath : `${manifestPath}?v=${version}`),
7546
+ url: combineURLs(assetPrefix, isBuild ? manifestPath : `${browserManifestPath}${browserManifestPath.includes('?') ? '&' : '?'}v=${version}`),
7526
7547
  hmr: void 0,
7527
7548
  entry: fingerprintedValues.entry,
7528
7549
  sri: void 0,
@@ -7535,7 +7556,111 @@ async function generateReactRouterManifestForDev(routes, _options, clientStats,
7535
7556
  async function getReactRouterManifestForDev(...args) {
7536
7557
  return (await generateReactRouterManifestForDev(...args)).manifest;
7537
7558
  }
7538
- let redirectStatusCodes = new Set([
7559
+ let defaultWorkerPath = fileURLToPath(new URL('./server-build-worker.js', import.meta.url)), replyError = (reply)=>{
7560
+ let error = Error(reply.error.message);
7561
+ return error.name = reply.error.name ?? error.name, reply.error.stack && (error.stack = reply.error.stack), error;
7562
+ }, startServerBuildWorker = async (data, workerPath = defaultWorkerPath)=>{
7563
+ let failure, worker = new Worker(workerPath, {
7564
+ workerData: data
7565
+ }), pending = new Map(), active = new Map(), nextId = 0, acknowledgeClose = ()=>{}, closed = new Promise((resolve)=>{
7566
+ acknowledgeClose = resolve;
7567
+ }), fail = (error)=>{
7568
+ for (let { reject } of (failure ??= error, pending.values()))reject(failure);
7569
+ for (let stop of (pending.clear(), active.values()))stop(failure);
7570
+ active.clear();
7571
+ }, ready = new Promise((resolve, reject)=>{
7572
+ worker.on('message', (message)=>{
7573
+ if ('closed' === message.type) return void acknowledgeClose();
7574
+ if ('ready' === message.type) return void resolve(message.description);
7575
+ let entry = pending.get(message.id);
7576
+ pending.delete(message.id), entry?.resolve(message);
7577
+ }), worker.on('error', (error)=>{
7578
+ acknowledgeClose(), fail(normalizeEffectError(error)), reject(failure);
7579
+ }), worker.on('exit', (code)=>{
7580
+ acknowledgeClose(), fail(Error(`Server build worker exited with code ${code}`)), reject(failure);
7581
+ });
7582
+ }), send = (request, transfer = [])=>{
7583
+ worker.postMessage(request, transfer);
7584
+ };
7585
+ return {
7586
+ description: await ready,
7587
+ async handler (request) {
7588
+ let responseController, id = nextId++, body = request.body ? new Uint8Array(await request.arrayBuffer()) : void 0, cleanup = ()=>{
7589
+ active.delete(id), request.signal.removeEventListener('abort', onAbort);
7590
+ }, stop = (error)=>{
7591
+ responseController?.error(error), pending.get(id)?.reject(error), pending.delete(id), cleanup();
7592
+ }, onAbort = ()=>{
7593
+ send({
7594
+ type: 'abort',
7595
+ id
7596
+ }), responseController && stop(Error('Server build request was aborted'));
7597
+ }, reply = await new Promise((resolve, reject)=>{
7598
+ failure ? reject(failure) : (pending.set(id, {
7599
+ resolve,
7600
+ reject
7601
+ }), active.set(id, stop), request.signal.addEventListener('abort', onAbort, {
7602
+ once: !0
7603
+ }), send({
7604
+ type: 'request',
7605
+ id,
7606
+ url: request.url,
7607
+ method: request.method,
7608
+ headers: headerEntries(request.headers),
7609
+ body
7610
+ }, body ? [
7611
+ body.buffer
7612
+ ] : []), request.signal.aborted && onAbort());
7613
+ }).catch((error)=>{
7614
+ throw cleanup(), error;
7615
+ });
7616
+ if (!reply.ok) throw cleanup(), replyError(reply);
7617
+ if ('reply' !== reply.type) throw Error('Unexpected server build response');
7618
+ let { status, statusText, headers, hasBody } = reply.response, responseBody = hasBody ? new ReadableStream({
7619
+ start (controller) {
7620
+ responseController = controller;
7621
+ },
7622
+ async pull (controller) {
7623
+ try {
7624
+ let result = await new Promise((resolve, reject)=>{
7625
+ failure ? reject(failure) : (pending.set(id, {
7626
+ resolve,
7627
+ reject
7628
+ }), send({
7629
+ type: 'read',
7630
+ id
7631
+ }));
7632
+ });
7633
+ if (!result.ok) throw replyError(result);
7634
+ if ('body' !== result.type) throw Error('Unexpected server build body');
7635
+ controller.enqueue(result.body), controller.close();
7636
+ } catch (error) {
7637
+ controller.error(error);
7638
+ } finally{
7639
+ cleanup();
7640
+ }
7641
+ },
7642
+ cancel () {
7643
+ send({
7644
+ type: 'abort',
7645
+ id
7646
+ }), stop(Error('Server build response was canceled'));
7647
+ }
7648
+ }, {
7649
+ highWaterMark: 0
7650
+ }) : null;
7651
+ return hasBody || cleanup(), new Response(responseBody, {
7652
+ status,
7653
+ statusText,
7654
+ headers
7655
+ });
7656
+ },
7657
+ async close () {
7658
+ fail(Error('Server build worker was closed')), send({
7659
+ type: 'close'
7660
+ }), await closed, await worker.terminate();
7661
+ }
7662
+ };
7663
+ }, redirectStatusCodes = new Set([
7539
7664
  301,
7540
7665
  302,
7541
7666
  303,
@@ -7594,111 +7719,118 @@ let redirectStatusCodes = new Set([
7594
7719
  if (await mkdir(clientBuildDir, {
7595
7720
  recursive: !0
7596
7721
  }), !ssr || isPrerenderEnabled) {
7597
- process.env.IS_RR_BUILD_REQUEST = 'yes';
7598
- let buildModule = await import(pathToFileURL(serverBuildPath).toString()), build = await resolveServerBuildModule(buildModule, `Server build ${JSON.stringify(serverBuildPath)}`), requestHandler = external_react_router_createRequestHandler(build, 'production');
7599
- if (isPrerenderEnabled) {
7600
- if (!ssr) {
7601
- let generated = latestBrowserManifest ? {
7602
- manifest: latestBrowserManifest,
7603
- moduleExportsByRouteId: latestBrowserManifestModuleExports
7604
- } : await generateReactRouterManifestForDev(routes, pluginOptions, clientStats, appDirectory, assetPrefix, createReactRouterManifestOptions({
7605
- routeChunks: routeChunkOptions,
7606
- routeModuleAnalysis
7607
- }));
7608
- (({ routes, manifestRoutes, routeExports, prerenderPaths, api })=>{
7609
- let errors = (({ routes, manifestRoutes, routeExports, prerenderPaths })=>{
7610
- if (0 === prerenderPaths.length) return [];
7611
- let prerenderRoutes = createPrerenderRoutes(routes), prerenderedRoutes = new Set();
7612
- for (let path of prerenderPaths){
7613
- let matches = matchRoutes(prerenderRoutes, normalizePrerenderMatchPath(path));
7614
- if (!matches) throw Error(`Unable to prerender path because it does not match any routes: ${path}`);
7615
- matches.forEach((match)=>prerenderedRoutes.add(match.route.id));
7616
- }
7617
- let errors = [];
7618
- for (let [routeId, route] of Object.entries(manifestRoutes)){
7619
- let exports = routeExports[routeId] ?? [], invalidApis = [
7620
- 'headers',
7621
- 'action',
7622
- 'middleware'
7623
- ].filter((api)=>exports.includes(api));
7624
- if (invalidApis.length > 0 && errors.push(`Prerender: ${invalidApis.length} invalid route export(s) in \`${routeId}\` when pre-rendering with \`ssr:false\`: ${invalidApis.map((api)=>`\`${api}\``).join(', ')}. See https://reactrouter.com/how-to/pre-rendering#invalid-exports for more information.`), !prerenderedRoutes.has(routeId)) {
7625
- exports.includes('loader') && errors.push(`Prerender: 1 invalid route export in \`${routeId}\` when pre-rendering with \`ssr:false\`: \`loader\`. See https://reactrouter.com/how-to/pre-rendering#invalid-exports for more information.`);
7626
- let parentRoute = route.parentId && 'root' !== route.parentId && manifestRoutes[route.parentId] ? manifestRoutes[route.parentId] : null;
7627
- for(; parentRoute && 'root' !== parentRoute.id;)parentRoute.hasLoader && !parentRoute.hasClientLoader && errors.push(`Prerender: 1 invalid route export in \`${parentRoute.id}\` when pre-rendering with \`ssr:false\`: \`loader\`. See https://reactrouter.com/how-to/pre-rendering#invalid-exports for more information.`), parentRoute = parentRoute.parentId && 'root' !== parentRoute.parentId && manifestRoutes[parentRoute.parentId] ? manifestRoutes[parentRoute.parentId] : null;
7722
+ let worker = await startServerBuildWorker({
7723
+ serverBuildPath,
7724
+ mode: 'classic'
7725
+ });
7726
+ try {
7727
+ let build = worker.description;
7728
+ if (!build) throw Error(`[${PLUGIN_NAME}] Server build worker returned no build description`);
7729
+ let requestHandler = worker.handler;
7730
+ if (isPrerenderEnabled) {
7731
+ if (!ssr) {
7732
+ let generated = latestBrowserManifest ? {
7733
+ manifest: latestBrowserManifest,
7734
+ moduleExportsByRouteId: latestBrowserManifestModuleExports
7735
+ } : await generateReactRouterManifestForDev(routes, pluginOptions, clientStats, appDirectory, assetPrefix, createReactRouterManifestOptions({
7736
+ routeChunks: routeChunkOptions,
7737
+ routeModuleAnalysis
7738
+ }));
7739
+ (({ routes, manifestRoutes, routeExports, prerenderPaths, api })=>{
7740
+ let errors = (({ routes, manifestRoutes, routeExports, prerenderPaths })=>{
7741
+ if (0 === prerenderPaths.length) return [];
7742
+ let prerenderRoutes = createPrerenderRoutes(routes), prerenderedRoutes = new Set();
7743
+ for (let path of prerenderPaths){
7744
+ let matches = matchRoutes(prerenderRoutes, normalizePrerenderMatchPath(path));
7745
+ if (!matches) throw Error(`Unable to prerender path because it does not match any routes: ${path}`);
7746
+ matches.forEach((match)=>prerenderedRoutes.add(match.route.id));
7628
7747
  }
7629
- }
7630
- return errors;
7748
+ let errors = [];
7749
+ for (let [routeId, route] of Object.entries(manifestRoutes)){
7750
+ let exports = routeExports[routeId] ?? [], invalidApis = [
7751
+ 'headers',
7752
+ 'action',
7753
+ 'middleware'
7754
+ ].filter((api)=>exports.includes(api));
7755
+ if (invalidApis.length > 0 && errors.push(`Prerender: ${invalidApis.length} invalid route export(s) in \`${routeId}\` when pre-rendering with \`ssr:false\`: ${invalidApis.map((api)=>`\`${api}\``).join(', ')}. See https://reactrouter.com/how-to/pre-rendering#invalid-exports for more information.`), !prerenderedRoutes.has(routeId)) {
7756
+ exports.includes('loader') && errors.push(`Prerender: 1 invalid route export in \`${routeId}\` when pre-rendering with \`ssr:false\`: \`loader\`. See https://reactrouter.com/how-to/pre-rendering#invalid-exports for more information.`);
7757
+ let parentRoute = route.parentId && 'root' !== route.parentId && manifestRoutes[route.parentId] ? manifestRoutes[route.parentId] : null;
7758
+ for(; parentRoute && 'root' !== parentRoute.id;)parentRoute.hasLoader && !parentRoute.hasClientLoader && errors.push(`Prerender: 1 invalid route export in \`${parentRoute.id}\` when pre-rendering with \`ssr:false\`: \`loader\`. See https://reactrouter.com/how-to/pre-rendering#invalid-exports for more information.`), parentRoute = parentRoute.parentId && 'root' !== parentRoute.parentId && manifestRoutes[parentRoute.parentId] ? manifestRoutes[parentRoute.parentId] : null;
7759
+ }
7760
+ }
7761
+ return errors;
7762
+ })({
7763
+ routes,
7764
+ manifestRoutes,
7765
+ routeExports,
7766
+ prerenderPaths
7767
+ });
7768
+ if (errors.length > 0) throw api.logger.error(errors.join('\n')), Error('Invalid route exports found when prerendering with `ssr:false`');
7631
7769
  })({
7632
7770
  routes,
7633
- manifestRoutes,
7634
- routeExports,
7635
- prerenderPaths
7771
+ manifestRoutes: generated.manifest.routes,
7772
+ routeExports: generated.moduleExportsByRouteId,
7773
+ prerenderPaths,
7774
+ api
7636
7775
  });
7637
- if (errors.length > 0) throw api.logger.error(errors.join('\n')), Error('Invalid route exports found when prerendering with `ssr:false`');
7638
- })({
7639
- routes,
7640
- manifestRoutes: generated.manifest.routes,
7641
- routeExports: generated.moduleExportsByRouteId,
7642
- prerenderPaths,
7643
- api
7644
- });
7645
- }
7646
- let routeTree = createPrerenderRoutes(routes);
7647
- for (let path of prerenderPaths)if (!matchRoutes(routeTree, normalizePrerenderMatchPath(path))) throw Error(`Unable to prerender path because it does not match any routes: ${path}`);
7648
- prerenderPaths.length > 0 && api.logger.info(`Prerender (html): ${prerenderPaths.length} path(s)...`);
7649
- let buildRoutes = createPrerenderRoutes(build.routes);
7650
- await runPluginEffect(createBoundedPrerenderTasksEffect(prerenderPaths, getPrerenderConcurrency(prerenderConfig), (path)=>(({ path, build, buildRoutes, requestHandler, clientBuildDir, options })=>core_gen(function*() {
7651
- let encodedData, { api, basename, future } = options, matches = matchRoutes(buildRoutes, normalizePrerenderMatchPath(path));
7652
- if (!matches) return;
7653
- let leafRoute = matches[matches.length - 1]?.route, routeId = leafRoute?.id, manifestRoute = routeId ? build.routes?.[routeId]?.module : null;
7654
- if (manifestRoute && !manifestRoute.default && !manifestRoute.ErrorBoundary) return void (manifestRoute.loader && routeId ? (yield* prerenderDataEffect({
7655
- handler: requestHandler,
7656
- prerenderPath: path,
7657
- onlyRoutes: [
7658
- routeId
7659
- ],
7660
- clientBuildDir,
7661
- basename,
7662
- trailingSlashAwareDataRequests: future.unstable_trailingSlashAwareDataRequests,
7663
- api
7664
- }), yield* (({ handler, prerenderPath, clientBuildDir, basename, api, requestInit })=>{
7665
- let normalizedPath = `${basename}${prerenderPath}/`.replace(/\/\/+/g, '/').replace(/\/$/g, '');
7666
- return createBuildRequestEffect(`http://localhost${normalizedPath}`, requestInit, async (request)=>{
7667
- let response = await handler(request), content = Buffer.from(await response.arrayBuffer());
7668
- if (200 !== response.status) throw Error(`Prerender (resource): Received a ${response.status} status code from \`entry.server.tsx\` while prerendering the \`${normalizedPath}\` path.\n` + content.toString('utf8'));
7669
- let outputPath = external_pathe_resolve(clientBuildDir, ...normalizedPath.split('/'));
7670
- await mkdir(dirname(outputPath), {
7671
- recursive: !0
7672
- }), await writeFile(outputPath, content), api.logger.info(`Prerender (resource): ${prerenderPath} -> ${relative(process.cwd(), outputPath)}`);
7673
- });
7674
- })({
7675
- handler: requestHandler,
7676
- prerenderPath: path,
7677
- clientBuildDir,
7678
- basename,
7679
- api
7680
- })) : yield* sync(()=>{
7681
- api.logger.warn(`⚠️ Skipping prerendering for resource route without a loader: ${routeId}`);
7682
- }));
7683
- let data = matches.some((match)=>{
7684
- let matchedRouteId = match.route.id;
7685
- return !!matchedRouteId && build.assets?.routes?.[matchedRouteId]?.hasLoader;
7686
- }) ? yield* prerenderDataEffect({
7687
- handler: requestHandler,
7688
- prerenderPath: path,
7689
- onlyRoutes: null,
7690
- clientBuildDir,
7691
- basename,
7692
- trailingSlashAwareDataRequests: future.unstable_trailingSlashAwareDataRequests,
7693
- api
7694
- }) : void 0;
7695
- yield* (({ handler, prerenderPath, clientBuildDir, basename, api, requestInit })=>{
7696
- let normalizedPath = `${basename}${prerenderPath}/`.replace(/\/\/+/g, '/');
7697
- return createBuildRequestEffect(`http://localhost${normalizedPath}`, requestInit, async (request)=>{
7698
- let response = await handler(request), html = await response.text();
7699
- if (redirectStatusCodes.has(response.status)) {
7700
- let location = response.headers.get('Location'), delay = 2 * (302 === response.status);
7701
- html = `<!doctype html>
7776
+ }
7777
+ let routeTree = createPrerenderRoutes(routes);
7778
+ for (let path of prerenderPaths)if (!matchRoutes(routeTree, normalizePrerenderMatchPath(path))) throw Error(`Unable to prerender path because it does not match any routes: ${path}`);
7779
+ prerenderPaths.length > 0 && api.logger.info(`Prerender (html): ${prerenderPaths.length} path(s)...`);
7780
+ let buildRoutes = createPrerenderRoutes(build.routes);
7781
+ await runPluginEffect(createBoundedPrerenderTasksEffect(prerenderPaths, getPrerenderConcurrency(prerenderConfig), (path)=>(({ path, build, buildRoutes, requestHandler, clientBuildDir, options })=>core_gen(function*() {
7782
+ var data;
7783
+ let encodedData, { api, basename, future } = options, matches = matchRoutes(buildRoutes, normalizePrerenderMatchPath(path));
7784
+ if (!matches) return;
7785
+ let leafRoute = matches[matches.length - 1]?.route, routeId = leafRoute?.id, manifestRoute = routeId ? build.routes?.[routeId]?.module : null;
7786
+ if (manifestRoute && !manifestRoute.default && !manifestRoute.ErrorBoundary) return void (manifestRoute.loader && routeId ? (yield* prerenderDataEffect({
7787
+ handler: requestHandler,
7788
+ prerenderPath: path,
7789
+ onlyRoutes: [
7790
+ routeId
7791
+ ],
7792
+ clientBuildDir,
7793
+ basename,
7794
+ trailingSlashAwareDataRequests: future.unstable_trailingSlashAwareDataRequests,
7795
+ api
7796
+ }), yield* (({ handler, prerenderPath, clientBuildDir, basename, api, requestInit })=>{
7797
+ let normalizedPath = `${basename}${prerenderPath}/`.replace(/\/\/+/g, '/').replace(/\/$/g, '');
7798
+ return createBuildRequestEffect(`http://localhost${normalizedPath}`, requestInit, async (request)=>{
7799
+ let response = await handler(request), content = Buffer.from(await response.arrayBuffer());
7800
+ if (200 !== response.status) throw Error(`Prerender (resource): Received a ${response.status} status code from \`entry.server.tsx\` while prerendering the \`${normalizedPath}\` path.\n` + content.toString('utf8'));
7801
+ let outputPath = external_pathe_resolve(clientBuildDir, ...normalizedPath.split('/'));
7802
+ await mkdir(dirname(outputPath), {
7803
+ recursive: !0
7804
+ }), await writeFile(outputPath, content), api.logger.info(`Prerender (resource): ${prerenderPath} -> ${relative(process.cwd(), outputPath)}`);
7805
+ });
7806
+ })({
7807
+ handler: requestHandler,
7808
+ prerenderPath: path,
7809
+ clientBuildDir,
7810
+ basename,
7811
+ api
7812
+ })) : yield* sync(()=>{
7813
+ api.logger.warn(`⚠️ Skipping prerendering for resource route without a loader: ${routeId}`);
7814
+ }));
7815
+ let data1 = matches.some((match)=>{
7816
+ let matchedRouteId = match.route.id;
7817
+ return !!matchedRouteId && build.assets?.routes?.[matchedRouteId]?.hasLoader;
7818
+ }) ? yield* prerenderDataEffect({
7819
+ handler: requestHandler,
7820
+ prerenderPath: path,
7821
+ onlyRoutes: null,
7822
+ clientBuildDir,
7823
+ basename,
7824
+ trailingSlashAwareDataRequests: future.unstable_trailingSlashAwareDataRequests,
7825
+ api
7826
+ }) : void 0;
7827
+ yield* (({ handler, prerenderPath, clientBuildDir, basename, api, requestInit })=>{
7828
+ let normalizedPath = `${basename}${prerenderPath}/`.replace(/\/\/+/g, '/');
7829
+ return createBuildRequestEffect(`http://localhost${normalizedPath}`, requestInit, async (request)=>{
7830
+ let response = await handler(request), html = await response.text();
7831
+ if (redirectStatusCodes.has(response.status)) {
7832
+ let location = response.headers.get('Location'), delay = 2 * (302 === response.status);
7833
+ html = `<!doctype html>
7702
7834
  <head>
7703
7835
  <title>Redirecting to: ${location}</title>
7704
7836
  <meta http-equiv="refresh" content="${delay};url=${location}">
@@ -7710,40 +7842,43 @@ let redirectStatusCodes = new Set([
7710
7842
  </a>
7711
7843
  </body>
7712
7844
  </html>`;
7713
- } else if (200 !== response.status) throw Error(`Prerender (html): Received a ${response.status} status code from \`entry.server.tsx\` while prerendering the \`${normalizedPath}\` path.\n` + html);
7714
- let outputPath = external_pathe_resolve(clientBuildDir, ...normalizedPath.split('/'), 'index.html');
7715
- await mkdir(dirname(outputPath), {
7716
- recursive: !0
7717
- }), await writeFile(outputPath, html), api.logger.info(`Prerender (html): ${prerenderPath} -> ${relative(process.cwd(), outputPath)}`);
7845
+ } else if (200 !== response.status) throw Error(`Prerender (html): Received a ${response.status} status code from \`entry.server.tsx\` while prerendering the \`${normalizedPath}\` path.\n` + html);
7846
+ let outputPath = external_pathe_resolve(clientBuildDir, ...normalizedPath.split('/'), 'index.html');
7847
+ await mkdir(dirname(outputPath), {
7848
+ recursive: !0
7849
+ }), await writeFile(outputPath, html), api.logger.info(`Prerender (html): ${prerenderPath} -> ${relative(process.cwd(), outputPath)}`);
7850
+ });
7851
+ })({
7852
+ handler: requestHandler,
7853
+ prerenderPath: path,
7854
+ clientBuildDir,
7855
+ basename,
7856
+ api,
7857
+ requestInit: data1 ? (data = data1, (encodedData = encodeURI(data)).length < 8192 ? {
7858
+ headers: {
7859
+ 'X-React-Router-Prerender-Data': encodedData
7860
+ }
7861
+ } : void 0) : void 0
7718
7862
  });
7719
- })({
7720
- handler: requestHandler,
7721
- prerenderPath: path,
7722
- clientBuildDir,
7723
- basename,
7724
- api,
7725
- requestInit: data && (encodedData = encodeURI(data)).length < 8192 ? {
7726
- headers: {
7727
- 'X-React-Router-Prerender-Data': encodedData
7728
- }
7729
- } : void 0
7730
- });
7731
- }))({
7732
- path,
7733
- build,
7734
- buildRoutes,
7735
- requestHandler,
7736
- clientBuildDir,
7737
- options
7738
- })));
7863
+ }))({
7864
+ path,
7865
+ build,
7866
+ buildRoutes,
7867
+ requestHandler,
7868
+ clientBuildDir,
7869
+ options
7870
+ })));
7871
+ }
7872
+ ssr || await handleSpaMode({
7873
+ handler: requestHandler,
7874
+ build,
7875
+ clientBuildDir,
7876
+ basename,
7877
+ api
7878
+ });
7879
+ } finally{
7880
+ await worker.close();
7739
7881
  }
7740
- ssr || await handleSpaMode({
7741
- handler: requestHandler,
7742
- build,
7743
- clientBuildDir,
7744
- basename,
7745
- api
7746
- });
7747
7882
  }
7748
7883
  ssr || (await fs_extra.remove(serverBuildDir), api.logger.info(`[${PLUGIN_NAME}] Removed server build (static deployment)`)), buildEnd && await buildEnd({
7749
7884
  buildManifest,
@@ -7849,14 +7984,12 @@ let redirectStatusCodes = new Set([
7849
7984
  await mkdir(clientBuildDir, {
7850
7985
  recursive: !0
7851
7986
  });
7852
- let previousBuildRequestFlag = process.env.IS_RR_BUILD_REQUEST;
7853
- process.env.IS_RR_BUILD_REQUEST = 'yes';
7987
+ let worker = await startServerBuildWorker({
7988
+ serverBuildPath,
7989
+ mode: 'rsc'
7990
+ });
7854
7991
  try {
7855
- let buildModule = await import(pathToFileURL(serverBuildPath).toString()), handler = ((buildModule, serverBuildPath)=>{
7856
- let handler = 'function' == typeof buildModule?.default?.fetch ? buildModule.default.fetch : 'function' == typeof buildModule?.default?.default?.fetch ? buildModule.default.default.fetch : null;
7857
- if (!handler) throw Error(`[${PLUGIN_NAME}] RSC server build ${JSON.stringify(serverBuildPath)} must default-export an object with a fetch function.`);
7858
- return handler;
7859
- })(buildModule, serverBuildPath);
7992
+ let handler = worker.handler;
7860
7993
  api.logger.info(`Prerender: ${prerenderRequests.length} path(s)...`), await runPluginEffect(createBoundedPrerenderTasksEffect(prerenderRequests, getPrerenderConcurrency(prerenderConfig), (prerenderRequest)=>prerenderRscUrlEffect({
7861
7994
  api,
7862
7995
  artifactPath: prerenderRequest.artifactPath,
@@ -7865,7 +7998,7 @@ let redirectStatusCodes = new Set([
7865
7998
  url: new URL(`http://localhost${prerenderRequest.requestPath}`)
7866
7999
  })));
7867
8000
  } finally{
7868
- void 0 === previousBuildRequestFlag ? delete process.env.IS_RR_BUILD_REQUEST : process.env.IS_RR_BUILD_REQUEST = previousBuildRequestFlag;
8001
+ await worker.close();
7869
8002
  }
7870
8003
  }, DEFAULT_CONFIG = {
7871
8004
  appDirectory: 'app',
@@ -7902,8 +8035,8 @@ let redirectStatusCodes = new Set([
7902
8035
  unstable_subResourceIntegrity: subResourceIntegrity
7903
8036
  }
7904
8037
  };
7905
- }, BROWSER_MANIFEST_ASSET = 'static/js/virtual/react-router/browser-manifest.js', ABSOLUTE_URL_RE = /^[a-zA-Z][a-zA-Z\d+\-.]*:/, addIntegrity = (sri, assetPrefix, assetName, integrity)=>{
7906
- 'string' == typeof assetName && isManifestJsAsset(assetName) && 'string' == typeof integrity && (sri[ABSOLUTE_URL_RE.test(assetName) || assetName.startsWith('//') || assetName.startsWith('/') ? assetName : combineURLs(assetPrefix, assetName)] = integrity);
8038
+ }, ABSOLUTE_URL_RE = /^[a-zA-Z][a-zA-Z\d+\-.]*:/, addIntegrity = (sri, assetPrefix, assetName, integrity)=>{
8039
+ 'string' == typeof integrity && (sri[ABSOLUTE_URL_RE.test(assetName) || assetName.startsWith('//') || assetName.startsWith('/') ? assetName : combineURLs(assetPrefix, assetName)] = integrity);
7907
8040
  }, computeSubresourceIntegrity = (source)=>{
7908
8041
  if (source) return `sha384-${createHash('sha384').update(source.source()).digest('base64')}`;
7909
8042
  };
@@ -7928,7 +8061,7 @@ let isRelocatableServerAsset = (info)=>!!info?.sourceFilename && !info?.javascri
7928
8061
  return collected.sort((a, b)=>a.name < b.name ? -1 : +(a.name > b.name)), collected;
7929
8062
  })(compilation), written = [], skipped = [];
7930
8063
  for (let asset of assets){
7931
- let destination = external_pathe_join(outputClientPath, asset.name), sourceBuffer = asset.source.buffer(), sourceDigest = digestBuffer(sourceBuffer);
8064
+ let destination = join(outputClientPath, asset.name), sourceBuffer = asset.source.buffer(), sourceDigest = digestBuffer(sourceBuffer);
7932
8065
  if (relocatedDestinations?.get(destination) === sourceDigest || existsSyncFn(destination) && digestBuffer(await readFileFn(destination)) === sourceDigest) skipped.push(asset.name);
7933
8066
  else {
7934
8067
  await mkdirFn(dirname(destination));
@@ -8006,7 +8139,7 @@ let VIRTUAL_MODULE_PREFIX = 'virtual/react-router/', getVirtualModuleFilePath =
8006
8139
  let relativeId = moduleId.slice(VIRTUAL_MODULE_PREFIX.length), segments = relativeId.split('/');
8007
8140
  if (!relativeId || segments.some((segment)=>!segment || '.' === segment || '..' === segment)) throw Error(`Invalid virtual module id: ${moduleId}`);
8008
8141
  return `node_modules/${moduleId}.js`;
8009
- }, DEV_MANIFEST_UPDATE_EVENT = 'react-router:manifest-update', dev_hmr_isObject = (value)=>null !== value && 'object' == typeof value, isSwcLoader = (loader)=>'string' == typeof loader && loader.includes('builtin:swc-loader'), readSwcLoaderRefresh = (value)=>Array.isArray(value) ? value.some(readSwcLoaderRefresh) : !!dev_hmr_isObject(value) && (isSwcLoader(value.loader) ? value.options?.jsc?.transform?.react?.refresh === !0 : Object.values(value).some(readSwcLoaderRefresh)), readRuleSwcRefresh = (rule)=>!!dev_hmr_isObject(rule) && (isSwcLoader(rule.loader) ? readSwcLoaderRefresh(rule) : readSwcLoaderRefresh(rule.use) || readRuleSetSwcRefresh(rule.oneOf) || readRuleSetSwcRefresh(rule.rules)), readRuleSetSwcRefresh = (rules)=>Array.isArray(rules) && rules.some(readRuleSwcRefresh), isRspackSwcReactRefreshEnabled = (rspackConfig)=>readRuleSetSwcRefresh(rspackConfig.module?.rules), REACT_ROUTER_EXTERNALS = [
8142
+ }, REACT_ROUTER_EXTERNALS = [
8010
8143
  'react-router',
8011
8144
  'react-router-dom',
8012
8145
  '@react-router/architect',
@@ -9020,7 +9153,7 @@ export function EnsureClientRouteModuleForHMR___() { return ___EnsureClientRoute
9020
9153
  });
9021
9154
  return {
9022
9155
  buildManifest,
9023
- devRuntime: (({ api, isBuild, buildPlan, clientPatchesRouteMetadata, onNodeRebuildCommitted })=>{
9156
+ devRuntime: (({ api, isBuild, buildPlan, clientPatchesRouteMetadata })=>{
9024
9157
  let scheduledCssAssetOwnershipReload, state, nextSessionId, closeObservationByServer, isCurrentBinding, applyCloseOutcome, observeClose, identityByCompilation, webIdentityByNodeCompilation, attemptIdentityByCompilation;
9025
9158
  if (isBuild) return {
9026
9159
  captureWeb () {},
@@ -9037,8 +9170,8 @@ export function EnsureClientRouteModuleForHMR___() { return ___EnsureClientRoute
9037
9170
  scheduledCssAssetOwnershipReload = setTimeout(()=>{
9038
9171
  scheduledCssAssetOwnershipReload = void 0, lastCssAssetOwnershipReloadAt > scheduledAt || sendCssAssetOwnershipReload();
9039
9172
  }, 1000);
9040
- }, closeBinding = (binding, error)=>{
9041
- scheduledCssAssetOwnershipReload && (clearTimeout(scheduledCssAssetOwnershipReload), scheduledCssAssetOwnershipReload = void 0), reloadAfterCssAssetOwnershipRemoval = !1;
9173
+ }, hdrChannels = new WeakMap(), isHmrEnabled = ()=>'function' == typeof clientPatchesRouteMetadata ? clientPatchesRouteMetadata() : !0 === clientPatchesRouteMetadata, closeBinding = (binding, error)=>{
9174
+ hdrChannels.get(binding)?.close(), hdrChannels.delete(binding), scheduledCssAssetOwnershipReload && (clearTimeout(scheduledCssAssetOwnershipReload), scheduledCssAssetOwnershipReload = void 0), reloadAfterCssAssetOwnershipRemoval = !1;
9042
9175
  let pair = binding.compilers;
9043
9176
  pair && (pair.pendingAttempt = void 0, pair.currentAttemptIdentity = void 0, pair.latestCompletedWebIdentity = void 0, pair.latestCompletedWebStats = void 0, pair.latestCompletedNodeStats = void 0, pair.latestWebStart = void 0, pair.latestNodeStart = void 0), binding.compilers = void 0, binding.runtime.close(error);
9044
9177
  var server = binding.server, runtime = binding.runtime;
@@ -9146,7 +9279,7 @@ export function EnsureClientRouteModuleForHMR___() { return ___EnsureClientRoute
9146
9279
  if ('retry-node' === result) return void pair.node.watching?.invalidate();
9147
9280
  let nodeCompilation = getEnvironmentStats(stats, 'node')?.compilation;
9148
9281
  'committed' === result && nodeCompilation && identity.node === binding.runtime.getCommittedNodeIdentity() && hdrIntentsByPair.get(pair)?.signalCommitted(nodeCompilation, ()=>{
9149
- onNodeRebuildCommitted?.();
9282
+ hdrChannels.get(binding)?.publish();
9150
9283
  });
9151
9284
  } catch (cause) {
9152
9285
  sessions.getActiveBinding()?.id === binding.id && binding.runtime.failAttempt(normalizeEffectError(cause));
@@ -9375,7 +9508,7 @@ export function EnsureClientRouteModuleForHMR___() { return ___EnsureClientRoute
9375
9508
  sessions.getActiveBinding()?.runtime === runtime && (reloadAfterCssAssetOwnershipRemoval = 'removed' === change, sendCssAssetOwnershipReload());
9376
9509
  },
9377
9510
  onRouteManifestChanged (manifest) {
9378
- sessions.getActiveBinding()?.runtime !== runtime || (('function' == typeof clientPatchesRouteMetadata ? clientPatchesRouteMetadata() : clientPatchesRouteMetadata) ? server.sockWrite('custom', {
9511
+ sessions.getActiveBinding()?.runtime === runtime && (isHmrEnabled() ? server.sockWrite('custom', {
9379
9512
  event: DEV_MANIFEST_UPDATE_EVENT,
9380
9513
  data: manifest.routes
9381
9514
  }) : server.sockWrite('full-reload', {
@@ -9384,7 +9517,28 @@ export function EnsureClientRouteModuleForHMR___() { return ___EnsureClientRoute
9384
9517
  },
9385
9518
  onWarning: (message)=>api.logger.warn(message)
9386
9519
  }), binding = sessions.createBinding(server, runtime);
9387
- Object.defineProperty(server, DEV_RUNTIME_KEY, {
9520
+ hdrChannels.set(binding, (({ hot, isEnabled })=>{
9521
+ let sessionId = randomUUID(), revision = 0, closed = !1, payload = ()=>({
9522
+ event: DEV_HDR_UPDATE_EVENT,
9523
+ data: {
9524
+ sessionId,
9525
+ revision
9526
+ }
9527
+ }), unsubscribe = hot.onConnect((client)=>{
9528
+ !closed && isEnabled() && revision > 0 && client.send('custom', payload());
9529
+ });
9530
+ return {
9531
+ publish () {
9532
+ !closed && isEnabled() && (revision += 1, hot.send('custom', payload()));
9533
+ },
9534
+ close () {
9535
+ closed || (closed = !0, unsubscribe());
9536
+ }
9537
+ };
9538
+ })({
9539
+ hot: server.environments.web.hot,
9540
+ isEnabled: ()=>sessions.getActiveBinding() === binding && isHmrEnabled()
9541
+ })), Object.defineProperty(server, DEV_RUNTIME_KEY, {
9388
9542
  configurable: !0,
9389
9543
  enumerable: !1,
9390
9544
  value: runtime
@@ -9456,7 +9610,7 @@ export function EnsureClientRouteModuleForHMR___() { return ___EnsureClientRoute
9456
9610
  }), node.hooks.thisCompilation.tap(`${PLUGIN_NAME}:dev-node-web-compilation`, (compilation)=>{
9457
9611
  if (sessions.getActiveBinding()?.id !== sessionId) return;
9458
9612
  let changes = snapshotDevChangedFiles(pair.node);
9459
- hdrIntents.capture(compilation, changes.known && Array.from(changes.files).some((file)=>!file.includes('.react-router/hdr-revision.mjs') && !/\.css(?:\.[cm]?[jt]s)?$/.test(file))), pair.latestNodeStart = {
9613
+ hdrIntents.capture(compilation, changes.known && Array.from(changes.files).some((file)=>!/\.css(?:\.[cm]?[jt]s)?$/.test(file))), pair.latestNodeStart = {
9460
9614
  status: 'started',
9461
9615
  identity: getCompilationIdentity(compilation)
9462
9616
  }, pair.currentAttemptIdentity && compilationIdentities.setAttemptIdentityForCompilation(compilation, pair.currentAttemptIdentity), pair.latestCompletedWebIdentity && compilationIdentities.setWebIdentityForNodeCompilation(compilation, pair.latestCompletedWebIdentity);
@@ -9510,8 +9664,7 @@ export function EnsureClientRouteModuleForHMR___() { return ___EnsureClientRoute
9510
9664
  api,
9511
9665
  isBuild,
9512
9666
  buildPlan: serverBuildPlan,
9513
- clientPatchesRouteMetadata: devHmr?.isEnabled,
9514
- onNodeRebuildCommitted: devHmr?.onNodeRebuildCommitted
9667
+ clientPatchesRouteMetadata: devHmr?.isEnabled
9515
9668
  }),
9516
9669
  prerenderPaths,
9517
9670
  routesByServerBundleId,
@@ -9798,7 +9951,7 @@ export {
9798
9951
  nodeDependencies: {}
9799
9952
  };
9800
9953
  }, createClassicModePlan = async ({ api, allowedActionOriginsForBuild, appDirectory, assetsBuildDirectory, basename, customServer, defaultEntryName, devHmr, entryServerPath, finalEntryClientPath, future, hasServerApp, isBuild, isSpaMode, prerenderConfig, reactRouterConfig, routeChunkCache, routeConfig, routeDiscovery, routes, rootRouteFile, serverAppPath, shouldDependOnWebCompiler, splitRouteModules, ssr })=>{
9801
- var rootDirectory;
9954
+ var rootPath, rootDirectory;
9802
9955
  let reactRouterPath, reactRouterDomPath, { manifestChunkNames, webRouteEntries } = (({ appDirectory, isBuild, routes, splitRouteModules })=>{
9803
9956
  let manifestChunkNames = new Set([
9804
9957
  'entry.client'
@@ -9847,7 +10000,7 @@ export {
9847
10000
  rootDirectory: process.cwd(),
9848
10001
  ssr,
9849
10002
  devHmr
9850
- }), reactRouterAliases = (reactRouterPath = resolveAppPackagePath('react-router'), reactRouterDomPath = resolveAppPackagePath('react-router/dom'), {
10003
+ }), reactRouterAliases = (reactRouterPath = resolveAppPackagePath('react-router', rootPath = api.context.rootPath), reactRouterDomPath = resolveAppPackagePath('react-router/dom', rootPath), {
9851
10004
  ...reactRouterPath ? {
9852
10005
  'react-router$': reactRouterPath
9853
10006
  } : {},
@@ -9928,7 +10081,7 @@ export {
9928
10081
  ...bundleManifestModules,
9929
10082
  'virtual/react-router/with-props': generateWithProps(),
9930
10083
  ...void 0 !== devHmrRuntimeModule ? {
9931
- 'virtual/react-router/hmr-runtime': devHmrRuntimeModule
10084
+ [DEV_HMR_RUNTIME_MODULE_ID]: devHmrRuntimeModule
9932
10085
  } : {}
9933
10086
  };
9934
10087
  })({
@@ -9952,14 +10105,21 @@ export {
9952
10105
  }),
9953
10106
  server: customServer ? void 0 : {
9954
10107
  setup: [
9955
- (({ loadBuild })=>function(context) {
10108
+ (({ loadBuild, rootPath })=>function(context) {
9956
10109
  if ('dev' === context.action) return ()=>{
9957
10110
  var dependencies;
9958
10111
  let listenerPromise, getListener;
9959
10112
  installDevServerSourceMapSupport(), context.server.middlewares.use((dependencies = {
9960
- loadBuild
10113
+ loadBuild,
10114
+ rootPath
9961
10115
  }, (getListener = ()=>listenerPromise ??= (async ()=>{
9962
- let createRequestHandler = dependencies.createRequestHandler ?? (await import("react-router")).createRequestHandler, createRequestListener = dependencies.createRequestListener ?? (await import("@remix-run/node-fetch-server")).createRequestListener, requestHandler = createRequestHandler(dependencies.loadBuild, 'development');
10116
+ let createRequestHandler = dependencies.createRequestHandler;
10117
+ if (!createRequestHandler) {
10118
+ let reactRouterPath = resolveAppPackagePath('react-router', dependencies.rootPath);
10119
+ if (!reactRouterPath) throw Error('Cannot resolve react-router from the application.');
10120
+ createRequestHandler = (await import(pathToFileURL(reactRouterPath).href)).createRequestHandler;
10121
+ }
10122
+ let createRequestListener = dependencies.createRequestListener ?? (await import("@remix-run/node-fetch-server")).createRequestListener, requestHandler = createRequestHandler(dependencies.loadBuild, 'development');
9963
10123
  return createRequestListener((request)=>requestHandler(request));
9964
10124
  })())().catch(()=>{
9965
10125
  listenerPromise = void 0;
@@ -9973,7 +10133,8 @@ export {
9973
10133
  }));
9974
10134
  };
9975
10135
  })({
9976
- loadBuild: artifacts.devRuntime.createBuildLoader()
10136
+ loadBuild: artifacts.devRuntime.createBuildLoader(),
10137
+ rootPath: api.context.rootPath
9977
10138
  })
9978
10139
  ]
9979
10140
  },
@@ -10053,7 +10214,7 @@ export {
10053
10214
  name: PLUGIN_NAME,
10054
10215
  async setup (api) {
10055
10216
  var memoMap;
10056
- let sendRscDevUpdate, scheduledRscDevUpdate, clientStats, fiberRunFork, disposePromise, buildFiber, scope, runtimeEffect, self, runtime, reactRouterUserConfig, effectRuntime = (memoMap = memoMap ?? unsafeMakeMemoMap(), scope = unsafeRunSyncEffect(fiberRuntime_scopeMake()), runtimeEffect = core_suspend(()=>{
10217
+ let sendRscDevUpdate, scheduledRscDevUpdate, persistedSnapshotError, clientStats, fiberRunFork, disposePromise, buildFiber, scope, runtimeEffect, self, runtime, reactRouterUserConfig, effectRuntime = (memoMap = memoMap ?? unsafeMakeMemoMap(), scope = unsafeRunSyncEffect(fiberRuntime_scopeMake()), runtimeEffect = core_suspend(()=>{
10057
10218
  if (!buildFiber) {
10058
10219
  let scheduler = new SyncScheduler();
10059
10220
  buildFiber = unsafeForkEffect(core_tap(scopeExtend(toRuntimeWithMemoMap(PluginRuntimeLive, memoMap), scope), (rt)=>{
@@ -10150,7 +10311,7 @@ export {
10150
10311
  (isSourceMapEnabled(sourceMapSetting) || !0 === devtoolSetting || ('string' == typeof devtoolSetting ? devtoolSetting.includes('source-map') : null !== devtoolSetting && 'object' == typeof devtoolSetting)) && warn("\n WARNING: Source maps are enabled in production\n This makes your server code publicly visible in the browser.\n This is highly discouraged! If you insist, ensure that you are using\n environment variables for secrets and not hard-coding them in your source code.\n");
10151
10312
  }(api.getNormalizedConfig(), (msg)=>api.logger.warn(msg), 'web');
10152
10313
  }), api.onBeforeCreateCompiler(()=>{
10153
- let root = api.getNormalizedConfig(), web = root.environments.web;
10314
+ let root = api.getNormalizedConfig(), web = root.environments.web ?? api.getRsbuildConfig().environments?.web;
10154
10315
  assetPrefix = resolveEffectiveAssetPrefix({
10155
10316
  dev: web?.dev,
10156
10317
  output: web?.output,
@@ -10240,7 +10401,7 @@ export {
10240
10401
  hasConfiguredServerModuleFormat: void 0 !== userAndPresetConfigs.serverModuleFormat
10241
10402
  };
10242
10403
  }))), { appDirectory, basename, buildDirectory, future, allowedActionOrigins, routeDiscovery: userRouteDiscovery, ssr, prerender: prerenderConfig, serverBuildFile, serverBundles, serverModuleFormat, splitRouteModules, subResourceIntegrity, buildEnd } = resolvedConfig;
10243
- await registerReactRouterTypegen(api, {
10404
+ !1 !== pluginOptions.typegen && await registerReactRouterTypegen(api, {
10244
10405
  runtime: effectRuntime,
10245
10406
  appDirectory
10246
10407
  });
@@ -10496,42 +10657,59 @@ export {
10496
10657
  routeConfigWatchPaths,
10497
10658
  routeRestartMarkerPath,
10498
10659
  onRouteTopologyChange: pluginOptions.onRouteTopologyChange
10499
- }), latestBrowserManifest = null, latestBrowserManifestModuleExports = {}, latestServerManifest = null, latestServerManifestsByBundleId = {}, routeByFilePath = new Map(Object.values(routes).map((route)=>[
10660
+ }), serverManifestStampPath = external_pathe_resolve(api.context.cachePath, 'react-router', createHash('sha256').update(JSON.stringify([
10661
+ appDirectory,
10662
+ outputClientPath
10663
+ ])).digest('hex'), 'server-manifest.json'), writeServerManifestStamp = (snapshot)=>{
10664
+ let previous, stamp = JSON.stringify({
10665
+ schema: 1,
10666
+ isBuild,
10667
+ appDirectory,
10668
+ outputClientPath,
10669
+ routes,
10670
+ assetPrefix,
10671
+ snapshot
10672
+ });
10673
+ try {
10674
+ previous = readFileSync(serverManifestStampPath, 'utf8');
10675
+ } catch (error) {
10676
+ if ('ENOENT' !== error.code) throw error;
10677
+ }
10678
+ stamp !== previous && fs_extra.outputFileSync(serverManifestStampPath, stamp);
10679
+ }, routeByFilePath = new Map(Object.values(routes).map((route)=>[
10500
10680
  external_pathe_resolve(appDirectory, route.file),
10501
10681
  route
10502
10682
  ])), devHmrRefreshRuntimePath = isBuild || isRscMode ? void 0 : ((rootPath)=>{
10503
- let resolveFrom = (base, request)=>createRequire(base).resolve(request), rootPackageJson = external_pathe_join(rootPath, 'package.json');
10683
+ let resolveFrom = (base, request)=>createRequire(base).resolve(request), rootPackageJson = join(rootPath, 'package.json');
10504
10684
  try {
10505
10685
  let pluginReactEntry = resolveFrom(rootPackageJson, '@rsbuild/plugin-react'), refreshPluginEntry = resolveFrom(pluginReactEntry, '@rspack/plugin-react-refresh');
10506
10686
  return resolveFrom(refreshPluginEntry, 'react-refresh/runtime');
10507
10687
  } catch {
10508
10688
  return;
10509
10689
  }
10510
- })(api.context.rootPath), devHdrSignal = devHmrRefreshRuntimePath ? (({ filePath, onError })=>{
10511
- let revision = 0, dirEnsured = !1, write = ()=>{
10512
- try {
10513
- let revision1;
10514
- dirEnsured || (mkdirSync(dirname(filePath), {
10515
- recursive: !0
10516
- }), dirEnsured = !0), writeFileSync(filePath, (revision1 = revision, `export default ${revision1};\n`));
10517
- } catch (error) {
10518
- onError?.(error instanceof Error ? error : Error(String(error)));
10519
- }
10520
- };
10521
- return {
10522
- filePath,
10523
- ensure: write,
10524
- bump () {
10525
- revision += 1, write();
10526
- }
10527
- };
10528
- })({
10529
- filePath: external_pathe_join(api.context.rootPath, '.react-router', 'hdr-revision.mjs'),
10530
- onError: (error)=>api.logger.debug(`[${PLUGIN_NAME}] Failed to signal hot data revalidation: ${error.message}`)
10531
- }) : void 0, devHmrEnabled = !1;
10532
- devHmrRefreshRuntimePath && devHdrSignal && api.modifyEnvironmentConfig(async (environmentConfig, { name, mergeEnvironmentConfig })=>'web' !== name ? environmentConfig : mergeEnvironmentConfig(environmentConfig, {
10690
+ })(api.context.rootPath), devHmrEnabled = !1;
10691
+ devHmrRefreshRuntimePath && api.modifyEnvironmentConfig(async (environmentConfig, { name, mergeEnvironmentConfig })=>'web' !== name ? environmentConfig : mergeEnvironmentConfig(environmentConfig, {
10533
10692
  tools: {
10534
- rspack: (rspackConfig)=>((devHmrEnabled = isRspackSwcReactRefreshEnabled(rspackConfig)) && devHdrSignal.ensure(), rspackConfig)
10693
+ rspack: (rspackConfig)=>{
10694
+ if (devHmrEnabled = isRspackSwcReactRefreshEnabled(rspackConfig)) {
10695
+ let entries = rspackConfig.entry;
10696
+ if (entries && 'object' == typeof entries && !Array.isArray(entries)) for (let [name, entry] of Object.entries(entries)){
10697
+ let description = 'string' == typeof entry || Array.isArray(entry) ? {
10698
+ import: entry
10699
+ } : entry;
10700
+ entries[name] = {
10701
+ ...description,
10702
+ import: [
10703
+ DEV_HMR_RUNTIME_MODULE_ID,
10704
+ ...[
10705
+ description.import ?? []
10706
+ ].flat()
10707
+ ]
10708
+ };
10709
+ }
10710
+ }
10711
+ return rspackConfig;
10712
+ }
10535
10713
  }
10536
10714
  }));
10537
10715
  let commonModeOptions = {
@@ -10572,18 +10750,10 @@ export {
10572
10750
  routeChunkCache,
10573
10751
  serverAppPath,
10574
10752
  shouldDependOnWebCompiler,
10575
- devHmr: devHmrRefreshRuntimePath && devHdrSignal ? {
10753
+ devHmr: devHmrRefreshRuntimePath ? {
10576
10754
  isEnabled: ()=>devHmrEnabled,
10577
- runtimeModule: (({ reactRefreshRuntimePath, hdrRevisionFilePath })=>`
10755
+ runtimeModule: (({ reactRefreshRuntimePath })=>`
10578
10756
  import * as __refreshRuntimeModule from ${JSON.stringify(reactRefreshRuntimePath)};
10579
- // Read revision so the import survives sideEffects: false tree-shaking.
10580
- import __hdrRevision from ${JSON.stringify(hdrRevisionFilePath)};
10581
-
10582
- let latestHdrRevision = __hdrRevision;
10583
-
10584
- export function getReactRouterHdrRevision() {
10585
- return latestHdrRevision;
10586
- }
10587
10757
 
10588
10758
  const RefreshRuntime =
10589
10759
  __refreshRuntimeModule && __refreshRuntimeModule.performReactRefresh
@@ -10593,7 +10763,24 @@ const RefreshRuntime =
10593
10763
  const pendingRouteUpdates = new Map();
10594
10764
  let flushTimeout;
10595
10765
  let pendingRevalidation = false;
10596
- let pendingComponentRouteRevalidation = false;
10766
+ let flushing = false;
10767
+ let hdrSession;
10768
+ let latestHdrRevision = 0;
10769
+ const retiredHdrSessions = new Set();
10770
+
10771
+ function receiveHdrRevision(message) {
10772
+ if (!message || typeof message.sessionId !== 'string' ||
10773
+ !Number.isSafeInteger(message.revision) || message.revision < 1 ||
10774
+ retiredHdrSessions.has(message.sessionId)) return;
10775
+ if (hdrSession !== message.sessionId) {
10776
+ if (hdrSession) retiredHdrSessions.add(hdrSession);
10777
+ hdrSession = message.sessionId;
10778
+ latestHdrRevision = 0;
10779
+ }
10780
+ if (message.revision <= latestHdrRevision) return;
10781
+ latestHdrRevision = message.revision;
10782
+ scheduleReactRouterRevalidation();
10783
+ }
10597
10784
 
10598
10785
  function getCurrentRouterPath(router) {
10599
10786
  const basename = router.basename || '/';
@@ -10634,7 +10821,7 @@ export function scheduleReactRouterRouteUpdate(
10634
10821
  scheduleFlush();
10635
10822
  }
10636
10823
 
10637
- export function scheduleReactRouterRevalidation() {
10824
+ function scheduleReactRouterRevalidation() {
10638
10825
  pendingRevalidation = true;
10639
10826
  scheduleFlush();
10640
10827
  }
@@ -10833,45 +11020,50 @@ function applyManifestUpdate(nextRoutes) {
10833
11020
  }
10834
11021
 
10835
11022
  async function flush() {
11023
+ if (flushing) return;
11024
+ if (import.meta.webpackHot && import.meta.webpackHot.status() !== 'idle') {
11025
+ scheduleFlush();
11026
+ return;
11027
+ }
10836
11028
  const router = window.__reactRouterDataRouter;
10837
11029
  const routeModules = window.__reactRouterRouteModules;
10838
11030
  const manifest = window.__reactRouterManifest;
10839
11031
  const context = window.__reactRouterContext;
10840
11032
  if (!router || !routeModules || !manifest || !context) {
11033
+ scheduleFlush();
10841
11034
  return;
10842
11035
  }
10843
-
10844
- let shouldRevalidate = pendingRevalidation;
10845
- pendingRevalidation = false;
10846
- const { nextManifest, hmrRoutes, shouldRefreshRouteState } =
10847
- applyPendingRouteUpdates(router, routeModules, manifest, context);
10848
- // Loader updates must be visible during revalidation. Component-only routes
10849
- // stay staged until revalidation completes, matching React Router's HMR flow.
10850
- if (nextManifest && shouldRefreshRouteState) {
10851
- pendingComponentRouteRevalidation = false;
10852
- if (hmrRoutes) {
10853
- patchCurrentRouteMatches(router, hmrRoutes);
10854
- }
10855
- Object.assign(manifest, nextManifest);
10856
- await refreshRouteState(router);
10857
- shouldRevalidate = false;
10858
- } else if (nextManifest) {
10859
- if (hmrRoutes) {
10860
- patchCurrentRouteMatches(router, hmrRoutes);
10861
- }
10862
- Object.assign(manifest, nextManifest);
10863
- // The node compiler also emits an HDR revision for this route edit. If it
10864
- // did not arrive in this flush, consume that redundant revalidation later.
10865
- pendingComponentRouteRevalidation = !shouldRevalidate;
10866
- shouldRevalidate = false;
10867
- } else if (shouldRevalidate) {
10868
- if (pendingComponentRouteRevalidation) {
10869
- pendingComponentRouteRevalidation = false;
10870
- } else {
11036
+ flushing = true;
11037
+ try {
11038
+ let shouldRevalidate = pendingRevalidation;
11039
+ pendingRevalidation = false;
11040
+ const { nextManifest, hmrRoutes, shouldRefreshRouteState } =
11041
+ applyPendingRouteUpdates(router, routeModules, manifest, context);
11042
+ // Loader updates must be visible during revalidation. Component-only routes
11043
+ // stay staged until revalidation completes, matching React Router's HMR flow.
11044
+ if (nextManifest && shouldRefreshRouteState) {
11045
+ if (hmrRoutes) {
11046
+ patchCurrentRouteMatches(router, hmrRoutes);
11047
+ }
11048
+ Object.assign(manifest, nextManifest);
11049
+ await refreshRouteState(router);
11050
+ shouldRevalidate = false;
11051
+ } else if (nextManifest) {
11052
+ if (hmrRoutes) {
11053
+ patchCurrentRouteMatches(router, hmrRoutes);
11054
+ }
11055
+ Object.assign(manifest, nextManifest);
11056
+ }
11057
+ // A replay may represent several server edits, not just the component
11058
+ // update in this batch. Only an actual data revalidation can consume it.
11059
+ if (shouldRevalidate) {
10871
11060
  await revalidateRouter(router);
10872
11061
  }
11062
+ performReactRefresh();
11063
+ } finally {
11064
+ flushing = false;
11065
+ if (pendingRevalidation || pendingRouteUpdates.size > 0) scheduleFlush();
10873
11066
  }
10874
- performReactRefresh();
10875
11067
  }
10876
11068
 
10877
11069
  if (typeof window !== 'undefined' && import.meta.webpackHot) {
@@ -10879,21 +11071,14 @@ if (typeof window !== 'undefined' && import.meta.webpackHot) {
10879
11071
  ${JSON.stringify(DEV_MANIFEST_UPDATE_EVENT)},
10880
11072
  applyManifestUpdate
10881
11073
  );
10882
- import.meta.webpackHot.accept(
10883
- ${JSON.stringify(hdrRevisionFilePath)},
10884
- () => {
10885
- latestHdrRevision = __hdrRevision;
10886
- scheduleReactRouterRevalidation();
10887
- }
11074
+ import.meta.webpackHot.on(
11075
+ ${JSON.stringify(DEV_HDR_UPDATE_EVENT)},
11076
+ receiveHdrRevision
10888
11077
  );
10889
11078
  }
10890
11079
  `)({
10891
- reactRefreshRuntimePath: devHmrRefreshRuntimePath,
10892
- hdrRevisionFilePath: devHdrSignal.filePath
10893
- }),
10894
- onNodeRebuildCommitted: ()=>{
10895
- devHmrEnabled && devHdrSignal.bump();
10896
- }
11080
+ reactRefreshRuntimePath: devHmrRefreshRuntimePath
11081
+ })
10897
11082
  } : void 0
10898
11083
  })), { manifestChunkNames } = modePlan, hasPendingRscNodeUpdate = !1, pendingRscNodeFiles = new Set();
10899
11084
  isRscMode && !isBuild && (api.onBeforeStartDevServer(({ server })=>{
@@ -10936,8 +11121,81 @@ if (typeof window !== 'undefined' && import.meta.webpackHot) {
10936
11121
  getRouteTopology: routeTopology.getRouteTopology,
10937
11122
  initialRouteTopology: routeTopology.initialRouteTopology,
10938
11123
  onRouteTopologyChange: pluginOptions.onRouteTopologyChange
11124
+ }), manifestState = (({ api, isBuild, onPublish })=>{
11125
+ let latest = null, pending = new WeakMap();
11126
+ return isBuild && api.onBeforeEnvironmentCompile(({ environment })=>{
11127
+ 'web' === environment.name && (latest = null);
11128
+ }), api.onAfterEnvironmentCompile(({ environment, stats })=>{
11129
+ if ('web' !== environment.name) return;
11130
+ let snapshot = stats && !stats.hasErrors() ? pending.get(stats.compilation) : void 0;
11131
+ if (stats && pending.delete(stats.compilation), snapshot && stats) {
11132
+ var compilation;
11133
+ compilation = stats.compilation, latest = snapshot, onPublish(compilation, snapshot);
11134
+ } else isBuild && (latest = null);
11135
+ }), {
11136
+ stage (compilation, snapshot) {
11137
+ pending.set(compilation, snapshot);
11138
+ },
11139
+ read: ()=>latest
11140
+ };
11141
+ })({
11142
+ api,
11143
+ isBuild,
11144
+ onPublish: (compilation, snapshot)=>{
11145
+ writeServerManifestStamp(snapshot), devBackgroundResources.setManifest(snapshot.browser), isBuild || 'classic' !== modePlan.kind || modePlan.artifacts.devRuntime.captureWeb(compilation, snapshot.serverByEntryName);
11146
+ }
11147
+ }), persistedSnapshot = null;
11148
+ api.onBeforeCreateCompiler(()=>{
11149
+ if (!isBuild || 'classic' !== modePlan.kind || api.getNormalizedConfig().environments.web) return;
11150
+ let rebuildMessage = `[${PLUGIN_NAME}] Run a full build before building only the node environment; no compatible finalized browser manifest is available.`;
11151
+ try {
11152
+ let stamp = JSON.parse(readFileSync(serverManifestStampPath, 'utf8'));
11153
+ if (1 !== stamp.schema || !0 !== stamp.isBuild || stamp.appDirectory !== appDirectory || stamp.outputClientPath !== outputClientPath || stamp.assetPrefix !== assetPrefix || JSON.stringify(stamp.routes) !== JSON.stringify(routes) || 'string' != typeof stamp.snapshot?.server?.version || !stamp.snapshot?.serverByBundleId || !stamp.snapshot?.browser) throw Error(rebuildMessage);
11154
+ persistedSnapshot = createReactRouterManifestSnapshot({
11155
+ manifest: stamp.snapshot.browser,
11156
+ sri: stamp.snapshot.server.sri,
11157
+ moduleExportsByRouteId: stamp.snapshot.moduleExportsByRouteId,
11158
+ serverBuildPlan: {
11159
+ defaultEntryName: devServerBuildEntryName,
11160
+ serverBundleEntries: modePlan.artifacts.serverBundleEntries
11161
+ },
11162
+ routesByServerBundleId: modePlan.artifacts.routesByServerBundleId
11163
+ }), writeServerManifestStamp(persistedSnapshot);
11164
+ } catch (cause) {
11165
+ persistedSnapshotError = Error(rebuildMessage, {
11166
+ cause
11167
+ });
11168
+ }
10939
11169
  });
10940
- if (api.onAfterEnvironmentCompile(({ stats, environment })=>{
11170
+ let readManifestSnapshot = ()=>{
11171
+ if (persistedSnapshotError) throw persistedSnapshotError;
11172
+ return manifestState.read() ?? persistedSnapshot;
11173
+ };
11174
+ if (isBuild && 'classic' === modePlan.kind && (({ api, routeByFilePath, getSnapshot })=>{
11175
+ api.modifyRspackConfig((config, { environment })=>{
11176
+ 'node' === environment.name && (config.plugins ??= [], config.plugins.push({
11177
+ apply (compiler) {
11178
+ let name = 'ReactRouterNodeOnlyManifestValidation';
11179
+ compiler.hooks.thisCompilation.tap(name, (compilation)=>{
11180
+ compilation.hooks.afterOptimizeModules.tap(name, (modules)=>{
11181
+ let snapshot = getSnapshot();
11182
+ if (snapshot) for (let module of modules){
11183
+ if (!(module instanceof rspack.NormalModule)) continue;
11184
+ let route = routeByFilePath.get(external_pathe_resolve(module.resource.split('?')[0]));
11185
+ if (!route) continue;
11186
+ let exports = compilation.moduleGraph.getProvidedExports(module), saved = snapshot.browser.routes[route.id];
11187
+ if (!Array.isArray(exports) || !saved || exports.includes('loader') !== saved.hasLoader || exports.includes('action') !== saved.hasAction) throw Error(`Run a full build before building only the node environment: loader/action exports changed for route "${route.id}".`);
11188
+ }
11189
+ });
11190
+ });
11191
+ }
11192
+ }));
11193
+ });
11194
+ })({
11195
+ api,
11196
+ routeByFilePath,
11197
+ getSnapshot: ()=>persistedSnapshot
11198
+ }), api.onAfterEnvironmentCompile(({ stats, environment })=>{
10941
11199
  if ('web' === environment.name && (clientStats = createReactRouterManifestStats(stats?.compilation, manifestChunkNames), isRscMode && stats)) {
10942
11200
  let unsupported = ((compilation)=>{
10943
11201
  let unsupported = new Set();
@@ -10967,7 +11225,7 @@ if (typeof window !== 'undefined' && import.meta.webpackHot) {
10967
11225
  logPerformance && performanceProfiler.flush(environment.name, {
10968
11226
  compilerLifecycleMs: roundMs(performance.now() - setupStartMs)
10969
11227
  });
10970
- }), 'classic' === modePlan.kind ? api.onAfterBuild(({ environments })=>effectRuntime.runPromise(tryPluginPromise(()=>runReactRouterPrerenderBuild({
11228
+ }), 'classic' === modePlan.kind ? api.onAfterBuild(({ environments, stats })=>stats?.hasErrors() ? void 0 : effectRuntime.runPromise(tryPluginPromise(()=>runReactRouterPrerenderBuild({
10971
11229
  api,
10972
11230
  hasWebEnvironment: !!environments.web,
10973
11231
  buildDirectory,
@@ -10979,8 +11237,8 @@ if (typeof window !== 'undefined' && import.meta.webpackHot) {
10979
11237
  basename,
10980
11238
  future,
10981
11239
  routes,
10982
- latestBrowserManifest,
10983
- latestBrowserManifestModuleExports,
11240
+ latestBrowserManifest: readManifestSnapshot()?.browser ?? null,
11241
+ latestBrowserManifestModuleExports: readManifestSnapshot()?.moduleExportsByRouteId ?? {},
10984
11242
  clientStats,
10985
11243
  pluginOptions,
10986
11244
  appDirectory,
@@ -10990,7 +11248,7 @@ if (typeof window !== 'undefined' && import.meta.webpackHot) {
10990
11248
  buildManifest: modePlan.artifacts.buildManifest,
10991
11249
  buildEndReactRouterConfig: resolvedConfigWithRoutes,
10992
11250
  buildEnd
10993
- })))) : api.onAfterBuild(({ environments })=>effectRuntime.runPromise(tryPluginPromise(()=>runReactRouterRscPrerenderBuild({
11251
+ })))) : api.onAfterBuild(({ environments, stats })=>stats?.hasErrors() ? void 0 : effectRuntime.runPromise(tryPluginPromise(()=>runReactRouterRscPrerenderBuild({
10994
11252
  api,
10995
11253
  hasWebEnvironment: !!environments.web,
10996
11254
  buildDirectory,
@@ -11357,7 +11615,7 @@ if (typeof window !== 'undefined' && import.meta.webpackHot) {
11357
11615
  outputClientPath,
11358
11616
  performanceProfiler
11359
11617
  })) : (!function(api, routes, pluginOptions, appDirectory, assetPrefix = '/', routeChunkOptions, options) {
11360
- let getAssetPrefix = 'function' == typeof assetPrefix ? assetPrefix : ()=>assetPrefix, manifestChunkNames = options?.manifestChunkNames ?? ((routes, appDirectory, splitRouteModules = !1)=>{
11618
+ let getAssetPrefix = 'function' == typeof assetPrefix ? assetPrefix : ()=>assetPrefix, manifestChunkNames = new Set(options?.manifestChunkNames ?? ((routes, appDirectory, splitRouteModules = !1)=>{
11361
11619
  let chunkNames = new Set([
11362
11620
  'entry.client'
11363
11621
  ]);
@@ -11366,7 +11624,10 @@ if (typeof window !== 'undefined' && import.meta.webpackHot) {
11366
11624
  if (chunkNames.add(routeEntryName), splitRouteModules && 'root' !== route.id) for (let exportName of routeChunkExportNames)chunkNames.add(getRouteChunkEntryName(routeEntryName, exportName));
11367
11625
  }
11368
11626
  return chunkNames;
11369
- })(routes, appDirectory, routeChunkOptions?.splitRouteModules), isBuild = !!routeChunkOptions?.isBuild, finalizeSri = !!(isBuild && (options?.subResourceIntegrity ?? options?.future?.unstable_subResourceIntegrity)), buildAndEmitManifest = async ({ assets, sources, compilation }, { withSri })=>{
11627
+ })(routes, appDirectory, routeChunkOptions?.splitRouteModules));
11628
+ manifestChunkNames.add(BROWSER_MANIFEST_ENTRY_NAME);
11629
+ let isBuild = !!routeChunkOptions?.isBuild, finalizeSri = !!(isBuild && (options?.subResourceIntegrity ?? options?.future?.unstable_subResourceIntegrity)), buildAndEmitManifest = async ({ assets, sources, compilation }, { withSri })=>{
11630
+ if (compilation.errors?.length) return;
11370
11631
  let currentAssetPrefix = getAssetPrefix(), stats = createReactRouterManifestStats(compilation, manifestChunkNames), { manifest, moduleExportsByRouteId } = await generateReactRouterManifestForDev(routes, pluginOptions, stats, appDirectory, currentAssetPrefix, createReactRouterManifestOptions({
11371
11632
  routeChunks: routeChunkOptions,
11372
11633
  routeModuleAnalysis: options?.routeModuleAnalysis
@@ -11374,18 +11635,22 @@ if (typeof window !== 'undefined' && import.meta.webpackHot) {
11374
11635
  ...manifest
11375
11636
  };
11376
11637
  delete browserManifest.sri;
11377
- let browserManifestAsset = assets[BROWSER_MANIFEST_ASSET];
11378
- if (browserManifestAsset) {
11638
+ let browserManifestPaths = stats?.assetsByChunkName?.[BROWSER_MANIFEST_ENTRY_NAME]?.filter((name)=>"javascript" === getManifestAssetType(name, stats.assetTypesByName)) ?? [
11639
+ 'static/js/virtual/react-router/browser-manifest.js'
11640
+ ];
11641
+ for (let browserManifestPath of isBuild ? [] : browserManifestPaths){
11642
+ let browserManifestAsset = assets[browserManifestPath];
11643
+ if (!browserManifestAsset) continue;
11379
11644
  let originalSource = browserManifestAsset.source().toString(), serializedManifest = jsesc(browserManifest, {
11380
11645
  es6: !0
11381
11646
  }), newSource = originalSource.replace(/["'`]PLACEHOLDER["'`]/, ()=>serializedManifest);
11382
- compilation.updateAsset(BROWSER_MANIFEST_ASSET, new sources.RawSource(newSource));
11647
+ compilation.updateAsset(browserManifestPath, new sources.RawSource(newSource));
11383
11648
  }
11384
11649
  if (isBuild) {
11385
- let entryAssets = stats?.assetsByChunkName?.['entry.client'], entryJsAssets = entryAssets?.filter(isManifestJsAsset) || [], manifestPath = getReactRouterManifestPath({
11650
+ let entryAssets = stats?.assetsByChunkName?.['entry.client'], entryJsAssets = entryAssets?.filter((name)=>"javascript" === getManifestAssetType(name, stats?.assetTypesByName)) || [], manifestPath = getReactRouterManifestPath({
11386
11651
  version: manifest.version,
11387
11652
  isBuild: !0,
11388
- entryModulePath: entryJsAssets[0]
11653
+ entryModulePath: (entryJsAssets[0] ?? '').replace(/[?#].*$/, '')
11389
11654
  }), manifestSource = `window.__reactRouterManifest=${jsesc(browserManifest, {
11390
11655
  es6: !0
11391
11656
  })};`, source = new sources.RawSource(manifestSource);
@@ -11393,8 +11658,13 @@ if (typeof window !== 'undefined' && import.meta.webpackHot) {
11393
11658
  }
11394
11659
  let sri = withSri ? ((stats, compilation, assetPrefix = '/')=>{
11395
11660
  let sri = {};
11396
- for (let asset of stats?.assets ?? [])addIntegrity(sri, assetPrefix, asset.name, asset.integrity);
11397
- if ('function' == typeof compilation?.getAssets) for (let asset of compilation.getAssets())isManifestJsAsset(asset.name) && addIntegrity(sri, assetPrefix, asset.name, computeSubresourceIntegrity(asset.source) ?? asset.info?.integrity);
11661
+ for (let asset of stats?.assets ?? [])'string' == typeof asset.name && isManifestJsAsset(asset.name) && addIntegrity(sri, assetPrefix, asset.name, asset.integrity);
11662
+ if ('function' == typeof compilation?.getAssets) for (let asset of compilation.getAssets()){
11663
+ let assetType = asset.info?.assetType ?? ('boolean' == typeof asset.info?.javascriptModule ? "javascript" : void 0);
11664
+ "javascript" === getManifestAssetType(asset.name, void 0 === assetType ? void 0 : {
11665
+ [asset.name]: assetType
11666
+ }) && addIntegrity(sri, assetPrefix, asset.name, computeSubresourceIntegrity(asset.source) ?? asset.info?.integrity);
11667
+ }
11398
11668
  return Object.keys(sri).length > 0 ? sri : void 0;
11399
11669
  })(compilation.getStats().toJson({
11400
11670
  all: !1,
@@ -11418,33 +11688,17 @@ if (typeof window !== 'undefined' && import.meta.webpackHot) {
11418
11688
  future,
11419
11689
  manifestChunkNames,
11420
11690
  routeModuleAnalysis,
11421
- onManifest: (manifest, sri, moduleExportsByRouteId, context)=>{
11422
- var compilation;
11423
- return compilation = context.compilation, void performanceProfiler.recordSync('web', 'manifest:stage', 'virtual/react-router/browser-manifest', ()=>{
11424
- latestBrowserManifest = manifest, devBackgroundResources.setManifest(manifest), latestBrowserManifestModuleExports = moduleExportsByRouteId;
11425
- let baseServerManifest = {
11426
- ...manifest,
11427
- sri: sri
11428
- };
11429
- latestServerManifest = baseServerManifest;
11430
- let manifestsByEntryName = {
11431
- [devServerBuildEntryName]: baseServerManifest
11432
- };
11433
- if ('classic' === modePlan.kind) {
11434
- for (let { bundleId, entryName } of modePlan.artifacts.serverBundleEntries){
11435
- let bundleRoutes = modePlan.artifacts.routesByServerBundleId[bundleId];
11436
- if (!bundleRoutes) continue;
11437
- let routeIds = new Set(Object.keys(bundleRoutes)), filteredRoutes = Object.fromEntries(Object.entries(manifest.routes).filter(([routeId])=>routeIds.has(routeId))), bundleManifest = {
11438
- ...baseServerManifest,
11439
- routes: filteredRoutes
11440
- };
11441
- latestServerManifestsByBundleId[bundleId] = bundleManifest, manifestsByEntryName[entryName] = bundleManifest;
11442
- }
11443
- isBuild || modePlan.artifacts.devRuntime.captureWeb(compilation, manifestsByEntryName);
11444
- }
11445
- });
11446
- }
11447
- }), (({ api, resolvedServerOutput, performanceProfiler, getLatestServerManifest, getLatestServerManifestByBundleId, routes, pluginOptions, getClientStats, appDirectory, getAssetPrefix, routeChunkOptions, routeModuleAnalysis, routeTransformRunner, routeByFilePath, routeChunkConfig, isBuild, splitRouteModules, useRouteModuleTransformApi, ssr, isSpaMode, rootRoutePath, outputClientPath, isDevHmrEnabled = ()=>!1, onRouteModuleAnalysis })=>{
11691
+ onManifest: (manifest, sri, moduleExportsByRouteId, context)=>performanceProfiler.recordSync('web', 'manifest:stage', 'virtual/react-router/browser-manifest', ()=>manifestState.stage(context.compilation, createReactRouterManifestSnapshot({
11692
+ manifest,
11693
+ sri,
11694
+ moduleExportsByRouteId,
11695
+ serverBuildPlan: {
11696
+ defaultEntryName: devServerBuildEntryName,
11697
+ serverBundleEntries: modePlan.artifacts.serverBundleEntries
11698
+ },
11699
+ routesByServerBundleId: modePlan.artifacts.routesByServerBundleId
11700
+ })))
11701
+ }), (({ api, resolvedServerOutput, performanceProfiler, getLatestServerManifest, serverManifestStampPath, getLatestServerManifestByBundleId, routes, pluginOptions, getClientStats, appDirectory, getAssetPrefix, routeChunkOptions, routeModuleAnalysis, routeTransformRunner, routeByFilePath, routeChunkConfig, isBuild, splitRouteModules, useRouteModuleTransformApi, ssr, isSpaMode, rootRoutePath, outputClientPath, isDevHmrEnabled = ()=>!1, onRouteModuleAnalysis })=>{
11448
11702
  let transformRouteModule = async (args)=>performanceProfiler.record(args.environment?.name, 'route:module', args.resource, async ()=>routeTransformRunner({
11449
11703
  kind: 'routeModule',
11450
11704
  code: args.code,
@@ -11471,12 +11725,17 @@ if (typeof window !== 'undefined' && import.meta.webpackHot) {
11471
11725
  outputClientPath,
11472
11726
  performanceProfiler
11473
11727
  }), api.transform({
11474
- test: /virtual\/react-router\/(browser|server)-manifest/
11728
+ test: /virtual\/react-router\/((browser|server)-manifest|server-build)/
11475
11729
  }, async (args)=>performanceProfiler.record(args.environment?.name, 'manifest:transform', args.resource, async ()=>{
11476
11730
  if ('web' === args.environment.name) return {
11477
11731
  code: 'window.__reactRouterManifest = "PLACEHOLDER";'
11478
11732
  };
11479
- let bundleMatch = args.resource.match(/virtual\/react-router\/server-manifest(?:-([^?]+))?/), bundleId = bundleMatch?.[1]?.replace(/\.js$/, ''), latestServerManifest = getLatestServerManifest(), manifest = (latestServerManifest ? (bundleId && getLatestServerManifestByBundleId(bundleId)) ?? latestServerManifest : null) ?? await getReactRouterManifestForDev(routes, pluginOptions, getClientStats(), appDirectory, getAssetPrefix(), createReactRouterManifestOptions({
11733
+ if (existsSync(serverManifestStampPath) ? args.addDependency(serverManifestStampPath) : args.addMissingDependency(serverManifestStampPath), args.resource.includes('virtual/react-router/server-build')) return {
11734
+ code: args.code
11735
+ };
11736
+ let bundleMatch = args.resource.match(/virtual\/react-router\/server-manifest(?:-([^?]+))?/), bundleId = bundleMatch?.[1]?.replace(/\.js$/, ''), latestServerManifest = getLatestServerManifest();
11737
+ if (isBuild && !latestServerManifest) throw Error(`[${PLUGIN_NAME}] Production server manifest requested before the browser manifest was finalized.`);
11738
+ let manifest = (latestServerManifest ? (bundleId && getLatestServerManifestByBundleId(bundleId)) ?? latestServerManifest : null) ?? await getReactRouterManifestForDev(routes, pluginOptions, getClientStats(), appDirectory, getAssetPrefix(), createReactRouterManifestOptions({
11480
11739
  routeChunks: routeChunkOptions,
11481
11740
  routeModuleAnalysis
11482
11741
  }));
@@ -11579,8 +11838,9 @@ if (typeof window !== 'undefined' && import.meta.webpackHot) {
11579
11838
  api,
11580
11839
  resolvedServerOutput,
11581
11840
  performanceProfiler,
11582
- getLatestServerManifest: ()=>latestServerManifest,
11583
- getLatestServerManifestByBundleId: (bundleId)=>latestServerManifestsByBundleId[bundleId],
11841
+ getLatestServerManifest: ()=>readManifestSnapshot()?.server ?? null,
11842
+ serverManifestStampPath,
11843
+ getLatestServerManifestByBundleId: (bundleId)=>readManifestSnapshot()?.serverByBundleId[bundleId],
11584
11844
  routes,
11585
11845
  pluginOptions,
11586
11846
  getClientStats: ()=>clientStats,