@graftland/hmr 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +16 -2
- package/dist/index.d.ts +47 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +115 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/modules.js +81 -0
- package/dist/internal/modules.js.map +1 -0
- package/package.json +37 -3
- package/src/index.ts +214 -0
- package/src/internal/modules.ts +123 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
package/README.md
CHANGED
|
@@ -1,3 +1,17 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @graftland/hmr
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Reloads plugin modules on Node.js without restarting the process.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @graftland/hmr effect
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
`Hmr.make` gives an importer for the loader, and `reload` and `watch` to replace
|
|
10
|
+
plugins with new code. Needs Node.js 22.15 or later.
|
|
11
|
+
|
|
12
|
+
## Documentation
|
|
13
|
+
|
|
14
|
+
- [Hot reload](https://graftland.github.io/graft/hot-reload/)
|
|
15
|
+
|
|
16
|
+
Part of [Graft](https://github.com/graftland/graft). Licensed under
|
|
17
|
+
[Apache 2.0](https://github.com/graftland/graft/blob/main/LICENSE).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { Graft } from "@graftland/graft";
|
|
2
|
+
import { Cause, Duration, Effect, FileSystem, PlatformError, Schema, Scope, Stream } from "effect";
|
|
3
|
+
declare const HmrError_base: Schema.Class<HmrError, Schema.TaggedStruct<"HmrError", {
|
|
4
|
+
readonly stage: Schema.Literals<readonly ["import", "exports", "closed"]>;
|
|
5
|
+
readonly specifier: Schema.String;
|
|
6
|
+
readonly cause: Schema.Unknown;
|
|
7
|
+
}>, Cause.YieldableError & {
|
|
8
|
+
readonly brand: unique symbol;
|
|
9
|
+
}>;
|
|
10
|
+
export declare class HmrError extends HmrError_base {
|
|
11
|
+
get message(): string;
|
|
12
|
+
}
|
|
13
|
+
export type ReloadResult = {
|
|
14
|
+
readonly _tag: "Reloaded";
|
|
15
|
+
readonly entries: ReadonlyArray<string>;
|
|
16
|
+
} | {
|
|
17
|
+
readonly _tag: "Skipped";
|
|
18
|
+
readonly modules: ReadonlyArray<string>;
|
|
19
|
+
readonly reason: "restart-required";
|
|
20
|
+
};
|
|
21
|
+
export type WatchResult = ReloadResult | {
|
|
22
|
+
readonly _tag: "Failed";
|
|
23
|
+
readonly cause: Cause.Cause<HmrError>;
|
|
24
|
+
};
|
|
25
|
+
export interface Options {
|
|
26
|
+
/** Application module URL, usually import.meta.url; used for bare and relative resolution. */
|
|
27
|
+
readonly base: string;
|
|
28
|
+
/** Files to version. Defaults to file URLs outside node_modules. Entries are always included. */
|
|
29
|
+
readonly include?: (url: string) => boolean;
|
|
30
|
+
}
|
|
31
|
+
export interface Hmr {
|
|
32
|
+
/** Pass directly to ModuleResolver.layer({ base, importer }). */
|
|
33
|
+
readonly importer: (specifier: string) => Promise<unknown>;
|
|
34
|
+
/** Imports every entry before replacing anything. Activation failures belong to Graft. */
|
|
35
|
+
readonly reload: Effect.Effect<ReloadResult, HmrError>;
|
|
36
|
+
/** Consuming this stream installs the watchers; the consumer owns their lifetime. */
|
|
37
|
+
readonly watch: (paths: ReadonlyArray<string>, options?: FileSystem.WatchOptions & {
|
|
38
|
+
readonly debounce?: Duration.Input;
|
|
39
|
+
}) => Stream.Stream<WatchResult, PlatformError.PlatformError, FileSystem.FileSystem>;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Installs Node module hooks until the enclosing scope closes. Module evaluation
|
|
43
|
+
* must be side-effect free. Versioned ESM cache entries are not reclaimed.
|
|
44
|
+
*/
|
|
45
|
+
export declare const make: (options: Options) => Effect.Effect<Hmr, never, Graft.Graft | Scope.Scope>;
|
|
46
|
+
export {};
|
|
47
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;WAwBmB;;qBAFN,iBAAiB;MAQhB;;YAKF;WACE;WAA2B,SAAS;;WAEtC;WACA,SAAS;WACT;;YAGA,cACT;WAES;WACA,OAAO,MAAM,MAAM;;iBAGd;;WAEP;;WAEA,WAAW;;iBAGJ;;WAEP,WAAW,sBAAsB;;WAEjC,QAAQ,OAAO,OAAO,cAAc;;WAEpC,QACR,OAAO,uBACP,UAAU,WAAW;aAA0B,WAAW,SAAS;QAC/D,OAAO,OACX,aACA,cAAc,eACd,WAAW;;;;;;qBAQA,OAAI,SACP,YACP,OAAO,OAAO,YAAY,MAAM,QAAQ,MAAM"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { RestartRequired, isMissingEntry, modules } from "./internal/modules.js";
|
|
2
|
+
import { Graft, Plugin } from "@graftland/graft";
|
|
3
|
+
import { Array, Effect, Exit, FiberSet, FileSystem, HashMap, HashSet, Option, Schema, Semaphore, Stream, String } from "effect";
|
|
4
|
+
// src/index.ts
|
|
5
|
+
/**
|
|
6
|
+
* Hot module replacement for Graft plugins on Node.js.
|
|
7
|
+
*/
|
|
8
|
+
var HmrError = class extends Schema.TaggedError()("HmrError", {
|
|
9
|
+
stage: Schema.Literals([
|
|
10
|
+
"import",
|
|
11
|
+
"exports",
|
|
12
|
+
"closed"
|
|
13
|
+
]),
|
|
14
|
+
specifier: Schema.String,
|
|
15
|
+
cause: Schema.Unknown
|
|
16
|
+
}) {
|
|
17
|
+
get message() {
|
|
18
|
+
return `HMR ${this.stage} failed for ${this.specifier || "the closed session"}`;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Installs Node module hooks until the enclosing scope closes. Module evaluation
|
|
23
|
+
* must be side-effect free. Versioned ESM cache entries are not reclaimed.
|
|
24
|
+
*/
|
|
25
|
+
const make = (options) => Effect.gen(function* () {
|
|
26
|
+
const graft = yield* Graft.Graft;
|
|
27
|
+
const semaphore = yield* Semaphore.make(1);
|
|
28
|
+
let closed = false;
|
|
29
|
+
const serial = (effect) => semaphore.withPermits(1)(Effect.uninterruptible(effect));
|
|
30
|
+
const hooks = yield* Effect.acquireRelease(Effect.sync(() => modules(options.base, options.include ?? ((url) => !String.includes("/node_modules/")(new URL(url).pathname)))), (hooks) => serial(Effect.sync(() => {
|
|
31
|
+
closed = true;
|
|
32
|
+
hooks.close();
|
|
33
|
+
})));
|
|
34
|
+
let generation = hooks.prepare();
|
|
35
|
+
let entries = HashMap.empty();
|
|
36
|
+
const run = yield* FiberSet.makeRuntimePromise();
|
|
37
|
+
const checkOpen = Effect.suspend(() => closed ? Effect.fail(HmrError.make({
|
|
38
|
+
stage: "closed",
|
|
39
|
+
specifier: "",
|
|
40
|
+
cause: "HMR scope is closed"
|
|
41
|
+
})) : Effect.void);
|
|
42
|
+
const load = Effect.fnUntraced(function* (specifier) {
|
|
43
|
+
const namespace = yield* Effect.tryPromise({
|
|
44
|
+
try: () => import(
|
|
45
|
+
/* @vite-ignore */
|
|
46
|
+
hooks.request(specifier)
|
|
47
|
+
),
|
|
48
|
+
catch: (cause) => HmrError.make({
|
|
49
|
+
stage: "import",
|
|
50
|
+
specifier,
|
|
51
|
+
cause
|
|
52
|
+
})
|
|
53
|
+
});
|
|
54
|
+
const plugin = Plugin.fromModule(namespace);
|
|
55
|
+
if (Option.isNone(plugin)) return yield* HmrError.make({
|
|
56
|
+
stage: "exports",
|
|
57
|
+
specifier,
|
|
58
|
+
cause: "Expected a default or named plugin export"
|
|
59
|
+
});
|
|
60
|
+
return {
|
|
61
|
+
namespace,
|
|
62
|
+
plugin: plugin.value,
|
|
63
|
+
url: hooks.resolved()
|
|
64
|
+
};
|
|
65
|
+
});
|
|
66
|
+
const importer = (specifier) => run(Effect.gen(function* () {
|
|
67
|
+
yield* checkOpen;
|
|
68
|
+
hooks.start(generation);
|
|
69
|
+
const entry = yield* load(specifier);
|
|
70
|
+
entries = HashMap.set(entries, entry.url, entry.plugin);
|
|
71
|
+
return entry.namespace;
|
|
72
|
+
}).pipe(Effect.ensuring(Effect.sync(hooks.discard)), serial));
|
|
73
|
+
const reload = serial(Effect.gen(function* () {
|
|
74
|
+
yield* checkOpen;
|
|
75
|
+
if (HashSet.size(generation.unsupported) > 0) return {
|
|
76
|
+
_tag: "Skipped",
|
|
77
|
+
modules: Array.fromIterable(generation.unsupported),
|
|
78
|
+
reason: "restart-required"
|
|
79
|
+
};
|
|
80
|
+
const candidate = hooks.prepare();
|
|
81
|
+
hooks.start(candidate, true);
|
|
82
|
+
return yield* Effect.gen(function* () {
|
|
83
|
+
let next = HashMap.empty();
|
|
84
|
+
let pairs = [];
|
|
85
|
+
for (const [url, previous] of entries) {
|
|
86
|
+
const entry = yield* load(url).pipe(Effect.catchIf((error) => error.stage === "import" && isMissingEntry(url, error.cause), () => Effect.undefined));
|
|
87
|
+
if (entry === void 0) continue;
|
|
88
|
+
next = HashMap.set(next, url, entry.plugin);
|
|
89
|
+
pairs = Array.append(pairs, [previous, entry.plugin]);
|
|
90
|
+
}
|
|
91
|
+
yield* Graft.replace(pairs).pipe(Effect.provideService(Graft.Graft, graft));
|
|
92
|
+
entries = next;
|
|
93
|
+
generation = candidate;
|
|
94
|
+
return {
|
|
95
|
+
_tag: "Reloaded",
|
|
96
|
+
entries: Array.fromIterable(HashMap.keys(entries))
|
|
97
|
+
};
|
|
98
|
+
}).pipe(Effect.catchIf((error) => Schema.is(RestartRequired)(error.cause), () => Effect.succeed({
|
|
99
|
+
_tag: "Skipped",
|
|
100
|
+
modules: Array.fromIterable(candidate.unsupported),
|
|
101
|
+
reason: "restart-required"
|
|
102
|
+
})), Effect.ensuring(Effect.sync(hooks.discard)));
|
|
103
|
+
}));
|
|
104
|
+
return {
|
|
105
|
+
importer,
|
|
106
|
+
reload,
|
|
107
|
+
watch: (paths, watchOptions) => Stream.unwrap(Effect.map(FileSystem.FileSystem, (fs) => Stream.mergeAll(Array.map(paths, (path) => fs.watch(path, watchOptions)), { concurrency: "unbounded" }).pipe(Stream.debounce(watchOptions?.debounce ?? "50 millis"), Stream.mapEffect(() => Effect.map(Effect.exit(reload), (exit) => Exit.isSuccess(exit) ? exit.value : {
|
|
108
|
+
_tag: "Failed",
|
|
109
|
+
cause: exit.cause
|
|
110
|
+
})))))
|
|
111
|
+
};
|
|
112
|
+
});
|
|
113
|
+
export { HmrError, make };
|
|
114
|
+
|
|
115
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["Str","Arr"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Hot module replacement for Graft plugins on Node.js.\n */\nimport { Graft, Plugin } from \"@graftland/graft\"\nimport {\n\tArray as Arr,\n\tCause,\n\tEffect,\n\tExit,\n\tFiberSet,\n\tFileSystem,\n\tHashMap,\n\tHashSet,\n\tOption,\n\tString as Str,\n\tSchema,\n\tSemaphore,\n\tStream,\n} from \"effect\"\nimport type { Duration, PlatformError, Scope } from \"effect\"\nimport { isMissingEntry, modules, RestartRequired } from \"./internal/modules\"\n\nexport class HmrError extends Schema.TaggedError<\n\tHmrError,\n\t{ readonly brand: unique symbol }\n>()(\"HmrError\", {\n\tstage: Schema.Literals([\"import\", \"exports\", \"closed\"]),\n\tspecifier: Schema.String,\n\tcause: Schema.Unknown,\n}) {\n\toverride get message(): string {\n\t\treturn `HMR ${this.stage} failed for ${this.specifier || \"the closed session\"}`\n\t}\n}\n\nexport type ReloadResult =\n\t| { readonly _tag: \"Reloaded\"; readonly entries: ReadonlyArray<string> }\n\t| {\n\t\t\treadonly _tag: \"Skipped\"\n\t\t\treadonly modules: ReadonlyArray<string>\n\t\t\treadonly reason: \"restart-required\"\n\t }\n\nexport type WatchResult =\n\t| ReloadResult\n\t| {\n\t\t\treadonly _tag: \"Failed\"\n\t\t\treadonly cause: Cause.Cause<HmrError>\n\t }\n\nexport interface Options {\n\t/** Application module URL, usually import.meta.url; used for bare and relative resolution. */\n\treadonly base: string\n\t/** Files to version. Defaults to file URLs outside node_modules. Entries are always included. */\n\treadonly include?: (url: string) => boolean\n}\n\nexport interface Hmr {\n\t/** Pass directly to ModuleResolver.layer({ base, importer }). */\n\treadonly importer: (specifier: string) => Promise<unknown>\n\t/** Imports every entry before replacing anything. Activation failures belong to Graft. */\n\treadonly reload: Effect.Effect<ReloadResult, HmrError>\n\t/** Consuming this stream installs the watchers; the consumer owns their lifetime. */\n\treadonly watch: (\n\t\tpaths: ReadonlyArray<string>,\n\t\toptions?: FileSystem.WatchOptions & { readonly debounce?: Duration.Input },\n\t) => Stream.Stream<\n\t\tWatchResult,\n\t\tPlatformError.PlatformError,\n\t\tFileSystem.FileSystem\n\t>\n}\n\n/**\n * Installs Node module hooks until the enclosing scope closes. Module evaluation\n * must be side-effect free. Versioned ESM cache entries are not reclaimed.\n */\nexport const make = (\n\toptions: Options,\n): Effect.Effect<Hmr, never, Graft.Graft | Scope.Scope> =>\n\tEffect.gen(function* () {\n\t\tconst graft = yield* Graft.Graft\n\t\tconst semaphore = yield* Semaphore.make(1)\n\t\tlet closed = false\n\t\t// Native imports cannot be cancelled: keep the lock until their promises settle.\n\t\tconst serial = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n\t\t\tsemaphore.withPermits(1)(Effect.uninterruptible(effect))\n\t\tconst hooks = yield* Effect.acquireRelease(\n\t\t\tEffect.sync(() =>\n\t\t\t\tmodules(\n\t\t\t\t\toptions.base,\n\t\t\t\t\toptions.include ??\n\t\t\t\t\t\t((url) => !Str.includes(\"/node_modules/\")(new URL(url).pathname)),\n\t\t\t\t),\n\t\t\t),\n\t\t\t(hooks) =>\n\t\t\t\tserial(\n\t\t\t\t\tEffect.sync(() => {\n\t\t\t\t\t\tclosed = true\n\t\t\t\t\t\thooks.close()\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t)\n\t\tlet generation = hooks.prepare()\n\t\tlet entries = HashMap.empty<string, Plugin.Plugin>()\n\t\tconst run = yield* FiberSet.makeRuntimePromise<never, unknown, HmrError>()\n\t\tconst checkOpen = Effect.suspend(() =>\n\t\t\tclosed\n\t\t\t\t? Effect.fail(\n\t\t\t\t\t\tHmrError.make({\n\t\t\t\t\t\t\tstage: \"closed\",\n\t\t\t\t\t\t\tspecifier: \"\",\n\t\t\t\t\t\t\tcause: \"HMR scope is closed\",\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t: Effect.void,\n\t\t)\n\t\tconst load = Effect.fnUntraced(function* (specifier: string) {\n\t\t\tconst namespace = yield* Effect.tryPromise({\n\t\t\t\ttry: () => import(/* @vite-ignore */ hooks.request(specifier)),\n\t\t\t\tcatch: (cause) => HmrError.make({ stage: \"import\", specifier, cause }),\n\t\t\t})\n\t\t\tconst plugin = Plugin.fromModule(namespace)\n\t\t\tif (Option.isNone(plugin))\n\t\t\t\treturn yield* HmrError.make({\n\t\t\t\t\tstage: \"exports\",\n\t\t\t\t\tspecifier,\n\t\t\t\t\tcause: \"Expected a default or named plugin export\",\n\t\t\t\t})\n\t\t\treturn { namespace, plugin: plugin.value, url: hooks.resolved()! }\n\t\t})\n\t\tconst importer = (specifier: string): Promise<unknown> =>\n\t\t\trun(\n\t\t\t\tEffect.gen(function* () {\n\t\t\t\t\tyield* checkOpen\n\t\t\t\t\thooks.start(generation)\n\t\t\t\t\tconst entry = yield* load(specifier)\n\t\t\t\t\tentries = HashMap.set(entries, entry.url, entry.plugin)\n\t\t\t\t\treturn entry.namespace\n\t\t\t\t}).pipe(Effect.ensuring(Effect.sync(hooks.discard)), serial),\n\t\t\t)\n\t\tconst reload = serial(\n\t\t\tEffect.gen(function* () {\n\t\t\t\tyield* checkOpen\n\t\t\t\tif (HashSet.size(generation.unsupported) > 0)\n\t\t\t\t\treturn {\n\t\t\t\t\t\t_tag: \"Skipped\" as const,\n\t\t\t\t\t\tmodules: Arr.fromIterable(generation.unsupported),\n\t\t\t\t\t\treason: \"restart-required\" as const,\n\t\t\t\t\t}\n\t\t\t\t// Advance even without entries so retries bypass cached failed imports.\n\t\t\t\tconst candidate = hooks.prepare()\n\t\t\t\thooks.start(candidate, true)\n\t\t\t\treturn yield* Effect.gen(function* () {\n\t\t\t\t\tlet next = HashMap.empty<string, Plugin.Plugin>()\n\t\t\t\t\tlet pairs: ReadonlyArray<readonly [Plugin.Plugin, Plugin.Plugin]> = []\n\t\t\t\t\tfor (const [url, previous] of entries) {\n\t\t\t\t\t\tconst entry = yield* load(url).pipe(\n\t\t\t\t\t\t\tEffect.catchIf(\n\t\t\t\t\t\t\t\t(error) =>\n\t\t\t\t\t\t\t\t\terror.stage === \"import\" && isMissingEntry(url, error.cause),\n\t\t\t\t\t\t\t\t() => Effect.undefined,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t\tif (entry === undefined) continue\n\t\t\t\t\t\tnext = HashMap.set(next, url, entry.plugin)\n\t\t\t\t\t\tpairs = Arr.append(pairs, [previous, entry.plugin])\n\t\t\t\t\t}\n\t\t\t\t\tyield* Graft.replace(pairs).pipe(\n\t\t\t\t\t\tEffect.provideService(Graft.Graft, graft),\n\t\t\t\t\t)\n\t\t\t\t\tentries = next\n\t\t\t\t\tgeneration = candidate\n\t\t\t\t\treturn {\n\t\t\t\t\t\t_tag: \"Reloaded\" as const,\n\t\t\t\t\t\tentries: Arr.fromIterable(HashMap.keys(entries)),\n\t\t\t\t\t}\n\t\t\t\t}).pipe(\n\t\t\t\t\tEffect.catchIf(\n\t\t\t\t\t\t(error) => Schema.is(RestartRequired)(error.cause),\n\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\tEffect.succeed({\n\t\t\t\t\t\t\t\t_tag: \"Skipped\" as const,\n\t\t\t\t\t\t\t\tmodules: Arr.fromIterable(candidate.unsupported),\n\t\t\t\t\t\t\t\treason: \"restart-required\" as const,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\tEffect.ensuring(Effect.sync(hooks.discard)),\n\t\t\t\t)\n\t\t\t}),\n\t\t)\n\t\treturn {\n\t\t\timporter,\n\t\t\treload,\n\t\t\twatch: (paths, watchOptions) =>\n\t\t\t\tStream.unwrap(\n\t\t\t\t\tEffect.map(FileSystem.FileSystem, (fs) =>\n\t\t\t\t\t\tStream.mergeAll(\n\t\t\t\t\t\t\tArr.map(paths, (path) => fs.watch(path, watchOptions)),\n\t\t\t\t\t\t\t{ concurrency: \"unbounded\" },\n\t\t\t\t\t\t).pipe(\n\t\t\t\t\t\t\tStream.debounce(watchOptions?.debounce ?? \"50 millis\"),\n\t\t\t\t\t\t\tStream.mapEffect(() =>\n\t\t\t\t\t\t\t\tEffect.map(Effect.exit(reload), (exit): WatchResult =>\n\t\t\t\t\t\t\t\t\tExit.isSuccess(exit)\n\t\t\t\t\t\t\t\t\t\t? exit.value\n\t\t\t\t\t\t\t\t\t\t: { _tag: \"Failed\", cause: exit.cause },\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t}\n\t})\n"],"mappings":"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"}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { registerHooks } from "node:module";
|
|
2
|
+
import { HashSet, Option, Predicate, Schema, String as String$1 } from "effect";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
// src/internal/modules.ts
|
|
5
|
+
var RestartRequired = class extends Schema.TaggedError()("RestartRequired", { url: Schema.String }) {};
|
|
6
|
+
const isMissingEntry = (url, cause) => String$1.startsWith("file:")(url) && Predicate.hasProperty(cause, "code") && (cause.code === "ERR_MODULE_NOT_FOUND" && Predicate.hasProperty(cause, "url") && cause.url === url || cause.code === "ENOENT" && Predicate.hasProperty(cause, "path") && cause.path === fileURLToPath(url));
|
|
7
|
+
let sessions = 0;
|
|
8
|
+
/** A scoped Node hook. Mutable bindings bridge synchronous hooks to Effect. */
|
|
9
|
+
const modules = (base, include) => {
|
|
10
|
+
const key = `graft-hmr-${++sessions}`;
|
|
11
|
+
const prefix = `${key}:`;
|
|
12
|
+
let revision = 0;
|
|
13
|
+
let recording;
|
|
14
|
+
let reloading = false;
|
|
15
|
+
let resolved;
|
|
16
|
+
const prepare = () => ({
|
|
17
|
+
id: String(++revision),
|
|
18
|
+
unsupported: HashSet.empty()
|
|
19
|
+
});
|
|
20
|
+
const clean = (url) => {
|
|
21
|
+
const value = new URL(url);
|
|
22
|
+
value.searchParams.delete(key);
|
|
23
|
+
return value.href;
|
|
24
|
+
};
|
|
25
|
+
const version = (url) => url === void 0 ? null : new URL(url).searchParams.get(key);
|
|
26
|
+
const unsupported = (url, format) => format === "commonjs" || format === "commonjs-typescript" || format === "addon" || String$1.endsWith(".node")(new URL(url).pathname);
|
|
27
|
+
const record = (url, id, format) => {
|
|
28
|
+
if (recording?.id !== id) return;
|
|
29
|
+
if (unsupported(url, format)) {
|
|
30
|
+
recording.unsupported = HashSet.add(recording.unsupported, url);
|
|
31
|
+
if (reloading) throw RestartRequired.make({ url });
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
const hooks = registerHooks({
|
|
35
|
+
resolve(specifier, context, nextResolve) {
|
|
36
|
+
const entry = String$1.startsWith(prefix)(specifier);
|
|
37
|
+
const separator = !entry ? 0 : prefix.length + Option.getOrThrow(String$1.indexOf(":")(String$1.slice(prefix.length)(specifier)));
|
|
38
|
+
const id = entry ? String$1.slice(prefix.length, separator)(specifier) : version(context.parentURL);
|
|
39
|
+
if (id === void 0 || id === null) return nextResolve(specifier, context);
|
|
40
|
+
const result = nextResolve(entry ? String$1.slice(separator + 1)(specifier) : specifier, {
|
|
41
|
+
...context,
|
|
42
|
+
parentURL: entry ? base : clean(context.parentURL)
|
|
43
|
+
});
|
|
44
|
+
if (entry) resolved = result.url;
|
|
45
|
+
if (!String$1.startsWith("file:")(result.url) || !entry && !include(result.url)) return result;
|
|
46
|
+
record(result.url, id, result.format);
|
|
47
|
+
if (unsupported(result.url, result.format)) return result;
|
|
48
|
+
const url = new URL(result.url);
|
|
49
|
+
url.searchParams.set(key, id);
|
|
50
|
+
return {
|
|
51
|
+
...result,
|
|
52
|
+
url: url.href
|
|
53
|
+
};
|
|
54
|
+
},
|
|
55
|
+
load(url, context, nextLoad) {
|
|
56
|
+
const id = version(url);
|
|
57
|
+
if (id === null) return nextLoad(url, context);
|
|
58
|
+
const original = clean(url);
|
|
59
|
+
record(original, id, context.format);
|
|
60
|
+
const result = nextLoad(original, context);
|
|
61
|
+
record(original, id, result.format);
|
|
62
|
+
return result;
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
return {
|
|
66
|
+
prepare,
|
|
67
|
+
start: (generation, reload = false) => {
|
|
68
|
+
recording = generation;
|
|
69
|
+
reloading = reload;
|
|
70
|
+
},
|
|
71
|
+
discard: () => {
|
|
72
|
+
recording = void 0;
|
|
73
|
+
},
|
|
74
|
+
request: (specifier) => `${prefix}${recording.id}:${specifier}`,
|
|
75
|
+
resolved: () => resolved,
|
|
76
|
+
close: () => hooks.deregister()
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
export { RestartRequired, isMissingEntry, modules };
|
|
80
|
+
|
|
81
|
+
//# sourceMappingURL=modules.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"modules.js","names":["Str"],"sources":["../../src/internal/modules.ts"],"sourcesContent":["// Node's synchronous module hooks have no Effect equivalent.\nimport { registerHooks } from \"node:module\"\nimport { fileURLToPath } from \"node:url\"\nimport { HashSet, Option, Predicate, Schema, String as Str } from \"effect\"\n\nexport class RestartRequired extends Schema.TaggedError<\n\tRestartRequired,\n\t{ readonly brand: unique symbol }\n>()(\"RestartRequired\", { url: Schema.String }) {}\n\n// Only a missing entry is disposable; missing dependencies still fail the reload.\nexport const isMissingEntry = (url: string, cause: unknown): boolean =>\n\tStr.startsWith(\"file:\")(url) &&\n\tPredicate.hasProperty(cause, \"code\") &&\n\t((cause.code === \"ERR_MODULE_NOT_FOUND\" &&\n\t\tPredicate.hasProperty(cause, \"url\") &&\n\t\tcause.url === url) ||\n\t\t(cause.code === \"ENOENT\" &&\n\t\t\tPredicate.hasProperty(cause, \"path\") &&\n\t\t\tcause.path === fileURLToPath(url)))\n\n// Allocated only when a session starts; importing this module performs no I/O.\nlet sessions = 0\n\nexport interface Generation {\n\treadonly id: string\n\tunsupported: HashSet.HashSet<string>\n}\n\n/** A scoped Node hook. Mutable bindings bridge synchronous hooks to Effect. */\nexport const modules = (base: string, include: (url: string) => boolean) => {\n\tconst key = `graft-hmr-${++sessions}`\n\tconst prefix = `${key}:`\n\tlet revision = 0\n\tlet recording: Generation | undefined\n\tlet reloading = false\n\tlet resolved: string | undefined\n\n\tconst prepare = (): Generation => ({\n\t\tid: String(++revision),\n\t\tunsupported: HashSet.empty(),\n\t})\n\tconst clean = (url: string): string => {\n\t\tconst value = new URL(url)\n\t\tvalue.searchParams.delete(key)\n\t\treturn value.href\n\t}\n\tconst version = (url: string | undefined): string | null =>\n\t\turl === undefined ? null : new URL(url).searchParams.get(key)\n\tconst unsupported = (url: string, format: string | null | undefined) =>\n\t\tformat === \"commonjs\" ||\n\t\tformat === \"commonjs-typescript\" ||\n\t\tformat === \"addon\" ||\n\t\tStr.endsWith(\".node\")(new URL(url).pathname)\n\tconst record = (\n\t\turl: string,\n\t\tid: string,\n\t\tformat: string | null | undefined,\n\t) => {\n\t\tif (recording?.id !== id) return\n\t\tif (unsupported(url, format)) {\n\t\t\trecording.unsupported = HashSet.add(recording.unsupported, url)\n\t\t\tif (reloading) throw RestartRequired.make({ url })\n\t\t}\n\t}\n\n\tconst hooks = registerHooks({\n\t\tresolve(specifier, context, nextResolve) {\n\t\t\tconst entry = Str.startsWith(prefix)(specifier)\n\t\t\tconst separator = !entry\n\t\t\t\t? 0\n\t\t\t\t: prefix.length +\n\t\t\t\t\tOption.getOrThrow(\n\t\t\t\t\t\tStr.indexOf(\":\")(Str.slice(prefix.length)(specifier)),\n\t\t\t\t\t)\n\t\t\tconst id = entry\n\t\t\t\t? Str.slice(prefix.length, separator)(specifier)\n\t\t\t\t: version(context.parentURL)\n\t\t\tif (id === undefined || id === null)\n\t\t\t\treturn nextResolve(specifier, context)\n\t\t\tconst result = nextResolve(\n\t\t\t\tentry ? Str.slice(separator + 1)(specifier) : specifier,\n\t\t\t\t{\n\t\t\t\t\t...context,\n\t\t\t\t\tparentURL: entry ? base : clean(context.parentURL!),\n\t\t\t\t},\n\t\t\t)\n\t\t\tif (entry) resolved = result.url\n\t\t\tif (\n\t\t\t\t!Str.startsWith(\"file:\")(result.url) ||\n\t\t\t\t(!entry && !include(result.url))\n\t\t\t)\n\t\t\t\treturn result\n\t\t\trecord(result.url, id, result.format)\n\t\t\tif (unsupported(result.url, result.format)) return result\n\t\t\tconst url = new URL(result.url)\n\t\t\turl.searchParams.set(key, id)\n\t\t\treturn { ...result, url: url.href }\n\t\t},\n\t\tload(url, context, nextLoad) {\n\t\t\tconst id = version(url)\n\t\t\tif (id === null) return nextLoad(url, context)\n\t\t\tconst original = clean(url)\n\t\t\trecord(original, id, context.format)\n\t\t\tconst result = nextLoad(original, context)\n\t\t\trecord(original, id, result.format)\n\t\t\treturn result\n\t\t},\n\t})\n\treturn {\n\t\tprepare,\n\t\tstart: (generation: Generation, reload = false) => {\n\t\t\trecording = generation\n\t\t\treloading = reload\n\t\t},\n\t\tdiscard: () => {\n\t\t\trecording = undefined\n\t\t},\n\t\trequest: (specifier: string) => `${prefix}${recording!.id}:${specifier}`,\n\t\tresolved: () => resolved,\n\t\tclose: () => hooks.deregister(),\n\t}\n}\n"],"mappings":"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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@graftland/hmr",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"engines": {
|
|
6
|
+
"node": ">=22.15.0"
|
|
7
|
+
},
|
|
8
|
+
"description": "Reloads plugin modules on Node.js without restarting the process",
|
|
9
|
+
"license": "Apache-2.0",
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/graftland/graft.git",
|
|
13
|
+
"directory": "packages/hmr"
|
|
14
|
+
},
|
|
15
|
+
"sideEffects": false,
|
|
16
|
+
"files": [
|
|
17
|
+
"dist",
|
|
18
|
+
"src"
|
|
19
|
+
],
|
|
20
|
+
"exports": {
|
|
21
|
+
".": "./dist/index.js",
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"effect": "4.1.2"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@effect/platform-node": "4.1.2",
|
|
29
|
+
"@effect/vitest": "4.1.2",
|
|
30
|
+
"effect": "4.1.2",
|
|
31
|
+
"vitest": "5.1.0"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@graftland/graft": "0.1.0"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "tsdown",
|
|
38
|
+
"test": "vitest run"
|
|
39
|
+
}
|
|
6
40
|
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hot module replacement for Graft plugins on Node.js.
|
|
3
|
+
*/
|
|
4
|
+
import { Graft, Plugin } from "@graftland/graft"
|
|
5
|
+
import {
|
|
6
|
+
Array as Arr,
|
|
7
|
+
Cause,
|
|
8
|
+
Effect,
|
|
9
|
+
Exit,
|
|
10
|
+
FiberSet,
|
|
11
|
+
FileSystem,
|
|
12
|
+
HashMap,
|
|
13
|
+
HashSet,
|
|
14
|
+
Option,
|
|
15
|
+
String as Str,
|
|
16
|
+
Schema,
|
|
17
|
+
Semaphore,
|
|
18
|
+
Stream,
|
|
19
|
+
} from "effect"
|
|
20
|
+
import type { Duration, PlatformError, Scope } from "effect"
|
|
21
|
+
import { isMissingEntry, modules, RestartRequired } from "./internal/modules"
|
|
22
|
+
|
|
23
|
+
export class HmrError extends Schema.TaggedError<
|
|
24
|
+
HmrError,
|
|
25
|
+
{ readonly brand: unique symbol }
|
|
26
|
+
>()("HmrError", {
|
|
27
|
+
stage: Schema.Literals(["import", "exports", "closed"]),
|
|
28
|
+
specifier: Schema.String,
|
|
29
|
+
cause: Schema.Unknown,
|
|
30
|
+
}) {
|
|
31
|
+
override get message(): string {
|
|
32
|
+
return `HMR ${this.stage} failed for ${this.specifier || "the closed session"}`
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type ReloadResult =
|
|
37
|
+
| { readonly _tag: "Reloaded"; readonly entries: ReadonlyArray<string> }
|
|
38
|
+
| {
|
|
39
|
+
readonly _tag: "Skipped"
|
|
40
|
+
readonly modules: ReadonlyArray<string>
|
|
41
|
+
readonly reason: "restart-required"
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export type WatchResult =
|
|
45
|
+
| ReloadResult
|
|
46
|
+
| {
|
|
47
|
+
readonly _tag: "Failed"
|
|
48
|
+
readonly cause: Cause.Cause<HmrError>
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface Options {
|
|
52
|
+
/** Application module URL, usually import.meta.url; used for bare and relative resolution. */
|
|
53
|
+
readonly base: string
|
|
54
|
+
/** Files to version. Defaults to file URLs outside node_modules. Entries are always included. */
|
|
55
|
+
readonly include?: (url: string) => boolean
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface Hmr {
|
|
59
|
+
/** Pass directly to ModuleResolver.layer({ base, importer }). */
|
|
60
|
+
readonly importer: (specifier: string) => Promise<unknown>
|
|
61
|
+
/** Imports every entry before replacing anything. Activation failures belong to Graft. */
|
|
62
|
+
readonly reload: Effect.Effect<ReloadResult, HmrError>
|
|
63
|
+
/** Consuming this stream installs the watchers; the consumer owns their lifetime. */
|
|
64
|
+
readonly watch: (
|
|
65
|
+
paths: ReadonlyArray<string>,
|
|
66
|
+
options?: FileSystem.WatchOptions & { readonly debounce?: Duration.Input },
|
|
67
|
+
) => Stream.Stream<
|
|
68
|
+
WatchResult,
|
|
69
|
+
PlatformError.PlatformError,
|
|
70
|
+
FileSystem.FileSystem
|
|
71
|
+
>
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Installs Node module hooks until the enclosing scope closes. Module evaluation
|
|
76
|
+
* must be side-effect free. Versioned ESM cache entries are not reclaimed.
|
|
77
|
+
*/
|
|
78
|
+
export const make = (
|
|
79
|
+
options: Options,
|
|
80
|
+
): Effect.Effect<Hmr, never, Graft.Graft | Scope.Scope> =>
|
|
81
|
+
Effect.gen(function* () {
|
|
82
|
+
const graft = yield* Graft.Graft
|
|
83
|
+
const semaphore = yield* Semaphore.make(1)
|
|
84
|
+
let closed = false
|
|
85
|
+
// Native imports cannot be cancelled: keep the lock until their promises settle.
|
|
86
|
+
const serial = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
|
87
|
+
semaphore.withPermits(1)(Effect.uninterruptible(effect))
|
|
88
|
+
const hooks = yield* Effect.acquireRelease(
|
|
89
|
+
Effect.sync(() =>
|
|
90
|
+
modules(
|
|
91
|
+
options.base,
|
|
92
|
+
options.include ??
|
|
93
|
+
((url) => !Str.includes("/node_modules/")(new URL(url).pathname)),
|
|
94
|
+
),
|
|
95
|
+
),
|
|
96
|
+
(hooks) =>
|
|
97
|
+
serial(
|
|
98
|
+
Effect.sync(() => {
|
|
99
|
+
closed = true
|
|
100
|
+
hooks.close()
|
|
101
|
+
}),
|
|
102
|
+
),
|
|
103
|
+
)
|
|
104
|
+
let generation = hooks.prepare()
|
|
105
|
+
let entries = HashMap.empty<string, Plugin.Plugin>()
|
|
106
|
+
const run = yield* FiberSet.makeRuntimePromise<never, unknown, HmrError>()
|
|
107
|
+
const checkOpen = Effect.suspend(() =>
|
|
108
|
+
closed
|
|
109
|
+
? Effect.fail(
|
|
110
|
+
HmrError.make({
|
|
111
|
+
stage: "closed",
|
|
112
|
+
specifier: "",
|
|
113
|
+
cause: "HMR scope is closed",
|
|
114
|
+
}),
|
|
115
|
+
)
|
|
116
|
+
: Effect.void,
|
|
117
|
+
)
|
|
118
|
+
const load = Effect.fnUntraced(function* (specifier: string) {
|
|
119
|
+
const namespace = yield* Effect.tryPromise({
|
|
120
|
+
try: () => import(/* @vite-ignore */ hooks.request(specifier)),
|
|
121
|
+
catch: (cause) => HmrError.make({ stage: "import", specifier, cause }),
|
|
122
|
+
})
|
|
123
|
+
const plugin = Plugin.fromModule(namespace)
|
|
124
|
+
if (Option.isNone(plugin))
|
|
125
|
+
return yield* HmrError.make({
|
|
126
|
+
stage: "exports",
|
|
127
|
+
specifier,
|
|
128
|
+
cause: "Expected a default or named plugin export",
|
|
129
|
+
})
|
|
130
|
+
return { namespace, plugin: plugin.value, url: hooks.resolved()! }
|
|
131
|
+
})
|
|
132
|
+
const importer = (specifier: string): Promise<unknown> =>
|
|
133
|
+
run(
|
|
134
|
+
Effect.gen(function* () {
|
|
135
|
+
yield* checkOpen
|
|
136
|
+
hooks.start(generation)
|
|
137
|
+
const entry = yield* load(specifier)
|
|
138
|
+
entries = HashMap.set(entries, entry.url, entry.plugin)
|
|
139
|
+
return entry.namespace
|
|
140
|
+
}).pipe(Effect.ensuring(Effect.sync(hooks.discard)), serial),
|
|
141
|
+
)
|
|
142
|
+
const reload = serial(
|
|
143
|
+
Effect.gen(function* () {
|
|
144
|
+
yield* checkOpen
|
|
145
|
+
if (HashSet.size(generation.unsupported) > 0)
|
|
146
|
+
return {
|
|
147
|
+
_tag: "Skipped" as const,
|
|
148
|
+
modules: Arr.fromIterable(generation.unsupported),
|
|
149
|
+
reason: "restart-required" as const,
|
|
150
|
+
}
|
|
151
|
+
// Advance even without entries so retries bypass cached failed imports.
|
|
152
|
+
const candidate = hooks.prepare()
|
|
153
|
+
hooks.start(candidate, true)
|
|
154
|
+
return yield* Effect.gen(function* () {
|
|
155
|
+
let next = HashMap.empty<string, Plugin.Plugin>()
|
|
156
|
+
let pairs: ReadonlyArray<readonly [Plugin.Plugin, Plugin.Plugin]> = []
|
|
157
|
+
for (const [url, previous] of entries) {
|
|
158
|
+
const entry = yield* load(url).pipe(
|
|
159
|
+
Effect.catchIf(
|
|
160
|
+
(error) =>
|
|
161
|
+
error.stage === "import" && isMissingEntry(url, error.cause),
|
|
162
|
+
() => Effect.undefined,
|
|
163
|
+
),
|
|
164
|
+
)
|
|
165
|
+
if (entry === undefined) continue
|
|
166
|
+
next = HashMap.set(next, url, entry.plugin)
|
|
167
|
+
pairs = Arr.append(pairs, [previous, entry.plugin])
|
|
168
|
+
}
|
|
169
|
+
yield* Graft.replace(pairs).pipe(
|
|
170
|
+
Effect.provideService(Graft.Graft, graft),
|
|
171
|
+
)
|
|
172
|
+
entries = next
|
|
173
|
+
generation = candidate
|
|
174
|
+
return {
|
|
175
|
+
_tag: "Reloaded" as const,
|
|
176
|
+
entries: Arr.fromIterable(HashMap.keys(entries)),
|
|
177
|
+
}
|
|
178
|
+
}).pipe(
|
|
179
|
+
Effect.catchIf(
|
|
180
|
+
(error) => Schema.is(RestartRequired)(error.cause),
|
|
181
|
+
() =>
|
|
182
|
+
Effect.succeed({
|
|
183
|
+
_tag: "Skipped" as const,
|
|
184
|
+
modules: Arr.fromIterable(candidate.unsupported),
|
|
185
|
+
reason: "restart-required" as const,
|
|
186
|
+
}),
|
|
187
|
+
),
|
|
188
|
+
Effect.ensuring(Effect.sync(hooks.discard)),
|
|
189
|
+
)
|
|
190
|
+
}),
|
|
191
|
+
)
|
|
192
|
+
return {
|
|
193
|
+
importer,
|
|
194
|
+
reload,
|
|
195
|
+
watch: (paths, watchOptions) =>
|
|
196
|
+
Stream.unwrap(
|
|
197
|
+
Effect.map(FileSystem.FileSystem, (fs) =>
|
|
198
|
+
Stream.mergeAll(
|
|
199
|
+
Arr.map(paths, (path) => fs.watch(path, watchOptions)),
|
|
200
|
+
{ concurrency: "unbounded" },
|
|
201
|
+
).pipe(
|
|
202
|
+
Stream.debounce(watchOptions?.debounce ?? "50 millis"),
|
|
203
|
+
Stream.mapEffect(() =>
|
|
204
|
+
Effect.map(Effect.exit(reload), (exit): WatchResult =>
|
|
205
|
+
Exit.isSuccess(exit)
|
|
206
|
+
? exit.value
|
|
207
|
+
: { _tag: "Failed", cause: exit.cause },
|
|
208
|
+
),
|
|
209
|
+
),
|
|
210
|
+
),
|
|
211
|
+
),
|
|
212
|
+
),
|
|
213
|
+
}
|
|
214
|
+
})
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// Node's synchronous module hooks have no Effect equivalent.
|
|
2
|
+
import { registerHooks } from "node:module"
|
|
3
|
+
import { fileURLToPath } from "node:url"
|
|
4
|
+
import { HashSet, Option, Predicate, Schema, String as Str } from "effect"
|
|
5
|
+
|
|
6
|
+
export class RestartRequired extends Schema.TaggedError<
|
|
7
|
+
RestartRequired,
|
|
8
|
+
{ readonly brand: unique symbol }
|
|
9
|
+
>()("RestartRequired", { url: Schema.String }) {}
|
|
10
|
+
|
|
11
|
+
// Only a missing entry is disposable; missing dependencies still fail the reload.
|
|
12
|
+
export const isMissingEntry = (url: string, cause: unknown): boolean =>
|
|
13
|
+
Str.startsWith("file:")(url) &&
|
|
14
|
+
Predicate.hasProperty(cause, "code") &&
|
|
15
|
+
((cause.code === "ERR_MODULE_NOT_FOUND" &&
|
|
16
|
+
Predicate.hasProperty(cause, "url") &&
|
|
17
|
+
cause.url === url) ||
|
|
18
|
+
(cause.code === "ENOENT" &&
|
|
19
|
+
Predicate.hasProperty(cause, "path") &&
|
|
20
|
+
cause.path === fileURLToPath(url)))
|
|
21
|
+
|
|
22
|
+
// Allocated only when a session starts; importing this module performs no I/O.
|
|
23
|
+
let sessions = 0
|
|
24
|
+
|
|
25
|
+
export interface Generation {
|
|
26
|
+
readonly id: string
|
|
27
|
+
unsupported: HashSet.HashSet<string>
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** A scoped Node hook. Mutable bindings bridge synchronous hooks to Effect. */
|
|
31
|
+
export const modules = (base: string, include: (url: string) => boolean) => {
|
|
32
|
+
const key = `graft-hmr-${++sessions}`
|
|
33
|
+
const prefix = `${key}:`
|
|
34
|
+
let revision = 0
|
|
35
|
+
let recording: Generation | undefined
|
|
36
|
+
let reloading = false
|
|
37
|
+
let resolved: string | undefined
|
|
38
|
+
|
|
39
|
+
const prepare = (): Generation => ({
|
|
40
|
+
id: String(++revision),
|
|
41
|
+
unsupported: HashSet.empty(),
|
|
42
|
+
})
|
|
43
|
+
const clean = (url: string): string => {
|
|
44
|
+
const value = new URL(url)
|
|
45
|
+
value.searchParams.delete(key)
|
|
46
|
+
return value.href
|
|
47
|
+
}
|
|
48
|
+
const version = (url: string | undefined): string | null =>
|
|
49
|
+
url === undefined ? null : new URL(url).searchParams.get(key)
|
|
50
|
+
const unsupported = (url: string, format: string | null | undefined) =>
|
|
51
|
+
format === "commonjs" ||
|
|
52
|
+
format === "commonjs-typescript" ||
|
|
53
|
+
format === "addon" ||
|
|
54
|
+
Str.endsWith(".node")(new URL(url).pathname)
|
|
55
|
+
const record = (
|
|
56
|
+
url: string,
|
|
57
|
+
id: string,
|
|
58
|
+
format: string | null | undefined,
|
|
59
|
+
) => {
|
|
60
|
+
if (recording?.id !== id) return
|
|
61
|
+
if (unsupported(url, format)) {
|
|
62
|
+
recording.unsupported = HashSet.add(recording.unsupported, url)
|
|
63
|
+
if (reloading) throw RestartRequired.make({ url })
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const hooks = registerHooks({
|
|
68
|
+
resolve(specifier, context, nextResolve) {
|
|
69
|
+
const entry = Str.startsWith(prefix)(specifier)
|
|
70
|
+
const separator = !entry
|
|
71
|
+
? 0
|
|
72
|
+
: prefix.length +
|
|
73
|
+
Option.getOrThrow(
|
|
74
|
+
Str.indexOf(":")(Str.slice(prefix.length)(specifier)),
|
|
75
|
+
)
|
|
76
|
+
const id = entry
|
|
77
|
+
? Str.slice(prefix.length, separator)(specifier)
|
|
78
|
+
: version(context.parentURL)
|
|
79
|
+
if (id === undefined || id === null)
|
|
80
|
+
return nextResolve(specifier, context)
|
|
81
|
+
const result = nextResolve(
|
|
82
|
+
entry ? Str.slice(separator + 1)(specifier) : specifier,
|
|
83
|
+
{
|
|
84
|
+
...context,
|
|
85
|
+
parentURL: entry ? base : clean(context.parentURL!),
|
|
86
|
+
},
|
|
87
|
+
)
|
|
88
|
+
if (entry) resolved = result.url
|
|
89
|
+
if (
|
|
90
|
+
!Str.startsWith("file:")(result.url) ||
|
|
91
|
+
(!entry && !include(result.url))
|
|
92
|
+
)
|
|
93
|
+
return result
|
|
94
|
+
record(result.url, id, result.format)
|
|
95
|
+
if (unsupported(result.url, result.format)) return result
|
|
96
|
+
const url = new URL(result.url)
|
|
97
|
+
url.searchParams.set(key, id)
|
|
98
|
+
return { ...result, url: url.href }
|
|
99
|
+
},
|
|
100
|
+
load(url, context, nextLoad) {
|
|
101
|
+
const id = version(url)
|
|
102
|
+
if (id === null) return nextLoad(url, context)
|
|
103
|
+
const original = clean(url)
|
|
104
|
+
record(original, id, context.format)
|
|
105
|
+
const result = nextLoad(original, context)
|
|
106
|
+
record(original, id, result.format)
|
|
107
|
+
return result
|
|
108
|
+
},
|
|
109
|
+
})
|
|
110
|
+
return {
|
|
111
|
+
prepare,
|
|
112
|
+
start: (generation: Generation, reload = false) => {
|
|
113
|
+
recording = generation
|
|
114
|
+
reloading = reload
|
|
115
|
+
},
|
|
116
|
+
discard: () => {
|
|
117
|
+
recording = undefined
|
|
118
|
+
},
|
|
119
|
+
request: (specifier: string) => `${prefix}${recording!.id}:${specifier}`,
|
|
120
|
+
resolved: () => resolved,
|
|
121
|
+
close: () => hooks.deregister(),
|
|
122
|
+
}
|
|
123
|
+
}
|