tnega 0.1.0 → 0.3.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 (110) hide show
  1. package/README.md +115 -189
  2. package/dist/agent.js +2907 -0
  3. package/dist/agent.js.map +7 -0
  4. package/dist/bin.js +32512 -4419
  5. package/dist/bin.js.map +4 -4
  6. package/dist/cli-runtime.js +33404 -0
  7. package/dist/cli-runtime.js.map +7 -0
  8. package/dist/coding-agent.js +19088 -0
  9. package/dist/coding-agent.js.map +7 -0
  10. package/dist/core.js +1398 -0
  11. package/dist/core.js.map +7 -0
  12. package/dist/eval.js +23905 -0
  13. package/dist/eval.js.map +7 -0
  14. package/dist/events.js +1215 -0
  15. package/dist/events.js.map +7 -0
  16. package/dist/evolve.js +18303 -0
  17. package/dist/evolve.js.map +7 -0
  18. package/dist/index.js +33087 -4450
  19. package/dist/index.js.map +4 -4
  20. package/dist/llm.js +1016 -0
  21. package/dist/llm.js.map +7 -0
  22. package/dist/services.js +1142 -0
  23. package/dist/services.js.map +7 -0
  24. package/dist/session.js +1045 -0
  25. package/dist/session.js.map +7 -0
  26. package/dist/tools.js +2577 -0
  27. package/dist/tools.js.map +7 -0
  28. package/dist/types/packages/agent/src/definition.d.ts +17 -0
  29. package/dist/types/packages/agent/src/inbox-durable.d.ts +54 -0
  30. package/dist/types/packages/agent/src/index.d.ts +7 -0
  31. package/dist/types/packages/agent/src/live.d.ts +115 -0
  32. package/dist/types/packages/agent/src/llm-service.d.ts +32 -0
  33. package/dist/types/packages/agent/src/prompt.d.ts +55 -0
  34. package/dist/types/packages/agent/src/service.d.ts +68 -0
  35. package/dist/types/packages/agent/src/types.d.ts +215 -0
  36. package/dist/types/packages/benchmark/src/bigcodebench.d.ts +6 -0
  37. package/dist/types/packages/benchmark/src/humaneval.d.ts +11 -0
  38. package/dist/types/packages/benchmark/src/index.d.ts +9 -0
  39. package/dist/types/packages/benchmark/src/manifest.d.ts +10 -0
  40. package/dist/types/packages/benchmark/src/mbpp.d.ts +10 -0
  41. package/dist/types/packages/benchmark/src/parquet.d.ts +2 -0
  42. package/dist/types/packages/benchmark/src/stdlib.d.ts +3 -0
  43. package/dist/types/packages/benchmark/src/swebench.d.ts +2 -0
  44. package/dist/types/packages/benchmark/src/types.d.ts +58 -0
  45. package/dist/types/packages/cli/src/bin.d.ts +2 -0
  46. package/dist/types/packages/cli/src/commands.d.ts +146 -0
  47. package/dist/types/packages/cli/src/config.d.ts +28 -0
  48. package/dist/types/packages/cli/src/index.d.ts +9 -0
  49. package/dist/types/packages/cli/src/profile-file.d.ts +26 -0
  50. package/dist/types/packages/cli/src/profile.d.ts +9 -0
  51. package/dist/types/packages/cli/src/server.d.ts +14 -0
  52. package/dist/types/packages/cli/src/store.d.ts +60 -0
  53. package/dist/types/packages/cli/src/yaml.d.ts +1 -0
  54. package/dist/types/packages/coding-agent/src/codingAgent.d.ts +25 -0
  55. package/dist/types/packages/coding-agent/src/index.d.ts +6 -0
  56. package/dist/types/packages/coding-agent/src/mcp.d.ts +24 -0
  57. package/dist/types/packages/coding-agent/src/plan.d.ts +13 -0
  58. package/dist/types/packages/coding-agent/src/skills.d.ts +12 -0
  59. package/dist/types/packages/coding-agent/src/slash.d.ts +28 -0
  60. package/dist/types/packages/coding-agent/src/types.d.ts +41 -0
  61. package/dist/types/packages/core/src/context.d.ts +28 -0
  62. package/dist/types/packages/core/src/events.d.ts +57 -0
  63. package/dist/types/packages/core/src/fiber.d.ts +79 -0
  64. package/dist/types/packages/core/src/index.d.ts +10 -0
  65. package/dist/types/packages/core/src/invariant.d.ts +45 -0
  66. package/dist/types/packages/core/src/logger.d.ts +48 -0
  67. package/dist/types/packages/core/src/reflect.d.ts +42 -0
  68. package/dist/types/packages/core/src/registry.d.ts +54 -0
  69. package/dist/types/packages/core/src/service.d.ts +19 -0
  70. package/dist/types/packages/core/src/utils.d.ts +54 -0
  71. package/dist/types/packages/eval/src/codingRuntime.d.ts +18 -0
  72. package/dist/types/packages/eval/src/index.d.ts +5 -0
  73. package/dist/types/packages/eval/src/policy.d.ts +8 -0
  74. package/dist/types/packages/eval/src/runner.d.ts +31 -0
  75. package/dist/types/packages/eval/src/service.d.ts +23 -0
  76. package/dist/types/packages/eval/src/strategies.d.ts +58 -0
  77. package/dist/types/packages/eval/src/trace.d.ts +7 -0
  78. package/dist/types/packages/eval/src/types.d.ts +281 -0
  79. package/dist/types/packages/eval/src/utils.d.ts +5 -0
  80. package/dist/types/packages/eval/src/workspace.d.ts +17 -0
  81. package/dist/types/packages/evolve/src/diagnose.d.ts +9 -0
  82. package/dist/types/packages/evolve/src/index.d.ts +7 -0
  83. package/dist/types/packages/evolve/src/llm.d.ts +39 -0
  84. package/dist/types/packages/evolve/src/log.d.ts +26 -0
  85. package/dist/types/packages/evolve/src/select.d.ts +3 -0
  86. package/dist/types/packages/evolve/src/service.d.ts +29 -0
  87. package/dist/types/packages/evolve/src/types.d.ts +176 -0
  88. package/dist/types/packages/llm/src/anthropic-messages.d.ts +4 -0
  89. package/dist/types/packages/llm/src/errors.d.ts +6 -0
  90. package/dist/types/packages/llm/src/index.d.ts +7 -0
  91. package/dist/types/packages/llm/src/models.d.ts +29 -0
  92. package/dist/types/packages/llm/src/openai.d.ts +4 -0
  93. package/dist/types/packages/llm/src/provider.d.ts +3 -0
  94. package/dist/types/packages/llm/src/shared.d.ts +15 -0
  95. package/dist/types/packages/llm/src/types.d.ts +13 -0
  96. package/dist/types/packages/session/src/index.d.ts +500 -0
  97. package/dist/types/packages/session/src/invariant.d.ts +33 -0
  98. package/dist/types/packages/tools/src/builtins.d.ts +25 -0
  99. package/dist/types/packages/tools/src/calc.d.ts +4 -0
  100. package/dist/types/packages/tools/src/execution.d.ts +31 -0
  101. package/dist/types/packages/tools/src/index.d.ts +107 -0
  102. package/dist/types/packages/tools/src/path.d.ts +4 -0
  103. package/dist/types/packages/tools/src/policy.d.ts +14 -0
  104. package/dist/types/src/events.d.ts +1 -0
  105. package/dist/types/src/index.d.ts +15 -0
  106. package/dist/types/src/services.d.ts +4 -0
  107. package/dist/web/assets/index-45pokiBH.js +270 -0
  108. package/dist/web/assets/index-DCLL69Kz.css +1 -0
  109. package/dist/web/index.html +13 -0
  110. package/package.json +92 -35
package/dist/core.js ADDED
@@ -0,0 +1,1398 @@
1
+ import { createRequire as __tnegaCreateRequire } from 'node:module'; const require = __tnegaCreateRequire(import.meta.url);
2
+
3
+ // packages/core/src/utils.ts
4
+ var DisposableList = class {
5
+ sn = 0;
6
+ map = /* @__PURE__ */ new Map();
7
+ weak = /* @__PURE__ */ new WeakMap();
8
+ get length() {
9
+ return this.map.size;
10
+ }
11
+ push(value) {
12
+ const sn = ++this.sn;
13
+ this.map.set(sn, value);
14
+ this.weak.set(value, sn);
15
+ return () => this.map.delete(sn);
16
+ }
17
+ unshift(value) {
18
+ const sn = ++this.sn;
19
+ const entries = [...this.map.entries()];
20
+ this.map.clear();
21
+ this.map.set(sn, value);
22
+ this.weak.set(value, sn);
23
+ for (const [oldSn, oldValue] of entries) {
24
+ this.map.set(oldSn, oldValue);
25
+ }
26
+ return () => this.map.delete(sn);
27
+ }
28
+ delete(value) {
29
+ const sn = this.weak.get(value);
30
+ if (!sn) return false;
31
+ return this.map.delete(sn);
32
+ }
33
+ clear() {
34
+ const values = [...this.map.values()];
35
+ this.map.clear();
36
+ return values.reverse();
37
+ }
38
+ [Symbol.iterator]() {
39
+ return this.map.values();
40
+ }
41
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
42
+ return [...this];
43
+ }
44
+ };
45
+ var symbols = {
46
+ shadow: /* @__PURE__ */ Symbol.for("tnega.shadow"),
47
+ caller: /* @__PURE__ */ Symbol.for("tnega.caller"),
48
+ receiver: /* @__PURE__ */ Symbol.for("tnega.receiver"),
49
+ original: /* @__PURE__ */ Symbol.for("tnega.original"),
50
+ metadata: /* @__PURE__ */ Symbol.for("tnega.metadata"),
51
+ initHooks: /* @__PURE__ */ Symbol.for("tnega.initHooks"),
52
+ checkProto: /* @__PURE__ */ Symbol.for("tnega.checkProto"),
53
+ effect: /* @__PURE__ */ Symbol.for("tnega.effect"),
54
+ filter: /* @__PURE__ */ Symbol.for("tnega.filter"),
55
+ isolate: /* @__PURE__ */ Symbol.for("tnega.isolate"),
56
+ intercept: /* @__PURE__ */ Symbol.for("tnega.intercept"),
57
+ init: /* @__PURE__ */ Symbol.for("tnega.init"),
58
+ check: /* @__PURE__ */ Symbol.for("tnega.check"),
59
+ config: /* @__PURE__ */ Symbol.for("tnega.config"),
60
+ invoke: /* @__PURE__ */ Symbol.for("tnega.invoke"),
61
+ extend: /* @__PURE__ */ Symbol.for("tnega.extend"),
62
+ tracker: /* @__PURE__ */ Symbol.for("tnega.tracker"),
63
+ resolveConfig: /* @__PURE__ */ Symbol.for("tnega.resolveConfig")
64
+ };
65
+ var GeneratorFunction = function* () {
66
+ }.constructor;
67
+ var AsyncGeneratorFunction = async function* () {
68
+ }.constructor;
69
+ function isConstructor(func) {
70
+ if (typeof func !== "function") return false;
71
+ if (func instanceof GeneratorFunction) return false;
72
+ if (AsyncGeneratorFunction !== Function && func instanceof AsyncGeneratorFunction) return false;
73
+ return /^class\s/.test(Function.prototype.toString.call(func));
74
+ }
75
+ function isObject(value) {
76
+ return !!value && (typeof value === "object" || typeof value === "function");
77
+ }
78
+ function isNullable(value) {
79
+ return value == null;
80
+ }
81
+ function joinPrototype(proto1, proto2) {
82
+ if (proto1 === Object.prototype) return proto2;
83
+ const result = Object.create(joinPrototype(Object.getPrototypeOf(proto1), proto2));
84
+ for (const key of Reflect.ownKeys(proto1)) {
85
+ Object.defineProperty(result, key, Reflect.getOwnPropertyDescriptor(proto1, key));
86
+ }
87
+ return result;
88
+ }
89
+ function getPropertyDescriptor(target, prop) {
90
+ let proto = target;
91
+ while (proto) {
92
+ const desc = Reflect.getOwnPropertyDescriptor(proto, prop);
93
+ if (desc) return desc;
94
+ proto = Object.getPrototypeOf(proto);
95
+ }
96
+ }
97
+ function getTraceable(ctx, value) {
98
+ if (!isObject(value)) return value;
99
+ if (Object.hasOwn(value, symbols.shadow)) {
100
+ return Object.getPrototypeOf(value);
101
+ }
102
+ const tracker = value[symbols.tracker];
103
+ if (!tracker) return value;
104
+ return createTraceable(ctx, value, tracker);
105
+ }
106
+ function withProps(target, props) {
107
+ if (!props) return target;
108
+ return new Proxy(target, {
109
+ get: (target2, prop, receiver) => {
110
+ if (prop in props && prop !== "constructor") return Reflect.get(props, prop, receiver);
111
+ return Reflect.get(target2, prop, receiver);
112
+ },
113
+ set: (target2, prop, value, receiver) => {
114
+ if (prop in props && prop !== "constructor") return Reflect.set(props, prop, value, receiver);
115
+ return Reflect.set(target2, prop, value, receiver);
116
+ }
117
+ });
118
+ }
119
+ function withProp(target, prop, value) {
120
+ return withProps(target, Object.defineProperty(/* @__PURE__ */ Object.create(null), prop, {
121
+ value,
122
+ writable: false
123
+ }));
124
+ }
125
+ function createShadow(ctx, target, property, receiver) {
126
+ if (!property) return receiver;
127
+ const origin = getPropertyDescriptor(target, property)?.value;
128
+ if (!origin) return receiver;
129
+ return withProp(receiver, property, ctx.extend({ [symbols.shadow]: origin }));
130
+ }
131
+ function createShadowMethod(ctx, value, outer, shadow) {
132
+ const proxy = new Proxy(value, {
133
+ apply: (target, thisArg, args) => {
134
+ if (thisArg === outer) thisArg = shadow;
135
+ return getTraceable(ctx, Reflect.apply(target, thisArg, args));
136
+ }
137
+ });
138
+ return proxy;
139
+ }
140
+ function createTraceable(ctx, value, tracker) {
141
+ const caller = ctx[symbols.shadow] ?? ctx;
142
+ if (ctx[symbols.shadow]) {
143
+ ctx = Object.getPrototypeOf(ctx);
144
+ }
145
+ const proxy = new Proxy(value, {
146
+ get: (target, prop, receiver) => {
147
+ if (prop === symbols.original) return target;
148
+ if (prop === symbols.caller) return caller;
149
+ if (prop === tracker.property) return ctx;
150
+ if (typeof prop === "symbol") {
151
+ return Reflect.get(target, prop, receiver);
152
+ }
153
+ if (tracker.associate && ctx.reflect.props[`${tracker.associate}.${prop}`]) {
154
+ return Reflect.get(ctx, `${tracker.associate}.${prop}`, withProp(ctx, symbols.receiver, receiver));
155
+ }
156
+ let shadow;
157
+ let innerValue;
158
+ const desc = getPropertyDescriptor(target, prop);
159
+ if (desc?.value !== void 0) {
160
+ innerValue = desc.value;
161
+ } else {
162
+ shadow = createShadow(ctx, target, tracker.property, receiver);
163
+ innerValue = Reflect.get(target, prop, shadow);
164
+ }
165
+ const innerTracker = innerValue?.[symbols.tracker];
166
+ if (innerTracker) {
167
+ return createTraceable(ctx, innerValue, innerTracker);
168
+ } else if (!tracker.noShadow && typeof innerValue === "function") {
169
+ shadow ??= createShadow(ctx, target, tracker.property, receiver);
170
+ return createShadowMethod(ctx, innerValue, receiver, shadow);
171
+ } else {
172
+ return innerValue;
173
+ }
174
+ },
175
+ set: (target, prop, value2, receiver) => {
176
+ if (prop === symbols.original || prop === symbols.caller || prop === tracker.property) return false;
177
+ if (typeof prop === "symbol") {
178
+ return Reflect.set(target, prop, value2, receiver);
179
+ }
180
+ if (tracker.associate && ctx.reflect.props[`${tracker.associate}.${prop}`]) {
181
+ return Reflect.set(ctx, `${tracker.associate}.${prop}`, value2, withProp(ctx, symbols.receiver, receiver));
182
+ }
183
+ const shadow = createShadow(ctx, target, tracker.property, receiver);
184
+ return Reflect.set(target, prop, value2, shadow);
185
+ },
186
+ apply: (target, thisArg, args) => {
187
+ const receiver = tracker.noShadow ? proxy : createShadow(ctx, target, tracker.property, proxy);
188
+ return applyTraceable(receiver, target, thisArg, args);
189
+ }
190
+ });
191
+ return proxy;
192
+ }
193
+ function applyTraceable(proxy, value, thisArg, args) {
194
+ if (!value[symbols.invoke]) return Reflect.apply(value, thisArg, args);
195
+ return value[symbols.invoke].apply(proxy, args);
196
+ }
197
+ function createCallable(name2, proto, tracker) {
198
+ const self = function(...args) {
199
+ const proxy = createTraceable(self.ctx, self, tracker);
200
+ return Reflect.apply(proxy, this, args);
201
+ };
202
+ Object.defineProperty(self, "name", { value: name2, configurable: true, writable: true });
203
+ return Object.setPrototypeOf(self, proto);
204
+ }
205
+ function handleError(info, reason, getOuterStack) {
206
+ const innerLines = info.error.stack.split("\n");
207
+ if (typeof reason?.stack !== "string") {
208
+ const outerError = new Error(reason);
209
+ const lines2 = outerError.stack.split("\n");
210
+ lines2.splice(1, Infinity, ...getOuterStack());
211
+ outerError.stack = lines2.join("\n");
212
+ throw outerError;
213
+ }
214
+ const lines = reason.stack.split("\n");
215
+ const index = lines.indexOf(innerLines[2]);
216
+ if (index === -1) throw reason;
217
+ lines.splice(index - info.offset, Infinity, ...getOuterStack());
218
+ reason.stack = lines.join("\n");
219
+ throw reason;
220
+ }
221
+ function composeError(callback, getOuterStack = buildOuterStack()) {
222
+ const info = { offset: 1, error: new Error() };
223
+ try {
224
+ const result = callback(info);
225
+ if (isObject(result) && "then" in result) {
226
+ return result.then(void 0, (reason) => handleError(info, reason, getOuterStack));
227
+ }
228
+ return result;
229
+ } catch (reason) {
230
+ handleError(info, reason, getOuterStack);
231
+ }
232
+ }
233
+ function buildOuterStack(offset = 0) {
234
+ const outerError = new Error();
235
+ return () => outerError.stack.split("\n").slice(3 + offset);
236
+ }
237
+
238
+ // packages/core/src/events.ts
239
+ function isBailed(value) {
240
+ return value !== null && value !== false && value !== void 0;
241
+ }
242
+ var EventsService = class {
243
+ constructor(ctx) {
244
+ this.ctx = ctx;
245
+ Object.defineProperty(this, symbols.tracker, {
246
+ value: { property: "ctx", noShadow: true }
247
+ });
248
+ this.on("internal/listener", function(name2, listener, options) {
249
+ if (name2 === "internal/update" && !options.global) {
250
+ const hooks = this.fiber._hooks["internal/update"] ??= new DisposableList();
251
+ const method = options.prepend ? "unshift" : "push";
252
+ return hooks[method](listener);
253
+ }
254
+ });
255
+ this.on("internal/update", function(config, noSave, next) {
256
+ const cbs = [...this.fiber._hooks["internal/update"] ?? []];
257
+ const _next = () => {
258
+ const cb = cbs.shift() ?? next;
259
+ return cb.call(this, config, noSave, _next);
260
+ };
261
+ return _next();
262
+ }, { global: true, prepend: true });
263
+ }
264
+ ctx;
265
+ _hooks = /* @__PURE__ */ Object.create(null);
266
+ _resolve(type, args) {
267
+ const thisArg = typeof args[0] === "object" || typeof args[0] === "function" ? args.shift() : null;
268
+ const name2 = args.shift();
269
+ if (!name2.startsWith("internal/") && this._hooks["internal/dispatch"]?.length) {
270
+ this.emit("internal/dispatch", type, name2, args, thisArg);
271
+ }
272
+ const filter = thisArg?.[Context.filter];
273
+ return [thisArg, (this._hooks[name2] || []).filter((hook) => hook.global || !filter || filter.call(thisArg, hook.ctx)).map((hook) => hook.callback)];
274
+ }
275
+ dispatch(type, args) {
276
+ const [thisArg, callbacks] = this._resolve(type, args);
277
+ return callbacks.map((callback) => callback.bind(thisArg));
278
+ }
279
+ async parallel(...args) {
280
+ const [thisArg, callbacks] = this._resolve("parallel", args);
281
+ const results = await Promise.allSettled(callbacks.map(async (callback) => Reflect.apply(callback, thisArg, args)));
282
+ const errors = results.filter((result) => result.status === "rejected").map((result) => result.reason);
283
+ if (errors.length) throw new AggregateError(errors);
284
+ }
285
+ emit(...args) {
286
+ const [thisArg, callbacks] = this._resolve("emit", args);
287
+ for (const callback of callbacks) Reflect.apply(callback, thisArg, args);
288
+ }
289
+ async serial(...args) {
290
+ const [thisArg, callbacks] = this._resolve("serial", args);
291
+ for (const callback of callbacks) {
292
+ const result = await Reflect.apply(callback, thisArg, args);
293
+ if (isBailed(result)) return result;
294
+ }
295
+ }
296
+ bail(...args) {
297
+ const [thisArg, callbacks] = this._resolve("bail", args);
298
+ for (const callback of callbacks) {
299
+ const result = Reflect.apply(callback, thisArg, args);
300
+ if (isBailed(result)) return result;
301
+ }
302
+ }
303
+ waterfall(...args) {
304
+ const [thisArg, callbacks] = this._resolve("waterfall", args);
305
+ const inner = args.pop();
306
+ const next = () => {
307
+ const callback = callbacks.shift();
308
+ return callback ? Reflect.apply(callback, thisArg, args) : inner(...args);
309
+ };
310
+ args.push(next);
311
+ return next();
312
+ }
313
+ async waterfallAsync(...args) {
314
+ const [thisArg, callbacks] = this._resolve("waterfallAsync", args);
315
+ const inner = args.pop();
316
+ const next = async () => {
317
+ const callback = callbacks.shift();
318
+ return callback ? await Reflect.apply(callback, thisArg, args) : inner(...args);
319
+ };
320
+ args.push(next);
321
+ return next();
322
+ }
323
+ register(label, hooks, callback, options) {
324
+ const method = options.prepend ? "unshift" : "push";
325
+ return this.ctx.fiber.effect(() => {
326
+ hooks[method]({ ctx: this.ctx, callback, ...options });
327
+ return () => this.unregister(hooks, callback);
328
+ }, label);
329
+ }
330
+ unregister(hooks, callback) {
331
+ const index = hooks.findIndex((hook) => hook.callback === callback);
332
+ if (index >= 0) {
333
+ hooks.splice(index, 1);
334
+ return true;
335
+ }
336
+ }
337
+ on(name2, listener, options = {}) {
338
+ if (typeof options !== "object") {
339
+ options = { prepend: options };
340
+ }
341
+ this.ctx.fiber.assertActive();
342
+ listener = this.ctx.reflect.bind(listener);
343
+ const result = this.bail(this.ctx, "internal/listener", name2, listener, options);
344
+ if (result) return result;
345
+ const hooks = this._hooks[name2] ??= [];
346
+ return this.register(`ctx.on(${JSON.stringify(name2)})`, hooks, listener, options);
347
+ }
348
+ once(name2, listener, options = {}) {
349
+ const dispose = this.on(name2, function(...args) {
350
+ dispose();
351
+ return listener.apply(this, args);
352
+ }, options);
353
+ return dispose;
354
+ }
355
+ };
356
+
357
+ // packages/core/src/fiber.ts
358
+ var INACTIVE = "__INACTIVE__";
359
+ var ValidationError = class extends TypeError {
360
+ name = "ValidationError";
361
+ constructor(issues) {
362
+ super("invalid config:\n" + issues.map((issue) => {
363
+ if (issue.path) {
364
+ return ` - ${issue.message} (at ${issue.path.join(".")})`;
365
+ }
366
+ return ` - ${issue.message}`;
367
+ }).join("\n"));
368
+ }
369
+ };
370
+ function resolveConfig(runtime, config) {
371
+ if (!runtime.Config) return config;
372
+ const schema = runtime.Config;
373
+ if (typeof schema === "function") return schema(config);
374
+ const validate = schema?.["~standard"]?.validate;
375
+ if (typeof validate === "function") {
376
+ const result = validate(config);
377
+ if ("then" in result) {
378
+ throw new TypeError("Async config validation is not supported");
379
+ }
380
+ if (result.issues) {
381
+ throw new ValidationError(result.issues);
382
+ }
383
+ return result.value;
384
+ }
385
+ return config;
386
+ }
387
+ var FiberState = /* @__PURE__ */ ((FiberState2) => {
388
+ FiberState2[FiberState2["PENDING"] = 0] = "PENDING";
389
+ FiberState2[FiberState2["LOADING"] = 1] = "LOADING";
390
+ FiberState2[FiberState2["ACTIVE"] = 2] = "ACTIVE";
391
+ FiberState2[FiberState2["FAILED"] = 3] = "FAILED";
392
+ FiberState2[FiberState2["DISPOSED"] = 4] = "DISPOSED";
393
+ FiberState2[FiberState2["UNLOADING"] = 5] = "UNLOADING";
394
+ return FiberState2;
395
+ })(FiberState || {});
396
+ var CordisErrorCode = {
397
+ INACTIVE_EFFECT: "cannot create effect on inactive context"
398
+ };
399
+ var CordisError = class extends Error {
400
+ constructor(code, message) {
401
+ super(message ?? CordisErrorCode[code]);
402
+ this.code = code;
403
+ }
404
+ code;
405
+ };
406
+ var Fiber = class {
407
+ constructor(parent, config, inject, runtime, getOuterStack) {
408
+ this.parent = parent;
409
+ this.inject = inject;
410
+ this.runtime = runtime;
411
+ const collect = (dispose) => {
412
+ this._disposables.push(dispose);
413
+ };
414
+ if (runtime) {
415
+ this.uid = parent.registry.counter;
416
+ this.ctx = this.context = parent.extend({ fiber: this });
417
+ const injectEntries = Object.entries(this.inject);
418
+ if (injectEntries.length) {
419
+ this.ctx[symbols.intercept] = Object.create(parent[symbols.intercept]);
420
+ for (const [name2, config2] of injectEntries) {
421
+ if (isNullable(config2)) continue;
422
+ this.ctx[symbols.intercept][name2] = config2;
423
+ }
424
+ }
425
+ this._runner = {
426
+ epoch: INACTIVE,
427
+ getOuterStack,
428
+ execute: () => {
429
+ if (isConstructor(runtime.callback)) {
430
+ const instance = new runtime.callback(this.ctx, this.config);
431
+ for (const hook of instance?.[symbols.initHooks] ?? []) {
432
+ hook();
433
+ }
434
+ return instance?.[symbols.init]?.();
435
+ } else {
436
+ return runtime.callback(this.ctx, this.config);
437
+ }
438
+ },
439
+ collect
440
+ };
441
+ this.context.emit(this, "internal/plugin");
442
+ for (const name2 of Object.keys(this.inject)) {
443
+ this._checkImpl(name2);
444
+ }
445
+ this.dispose = parent.fiber.effect(() => {
446
+ const remove = runtime.fibers.push(this);
447
+ try {
448
+ this.config = resolveConfig(runtime, config);
449
+ this._refresh();
450
+ } catch (error) {
451
+ this.ctx.logger.error(error);
452
+ this._error = error;
453
+ }
454
+ return async () => {
455
+ this.uid = null;
456
+ this.context.emit(this, "internal/plugin");
457
+ if (this.ctx.registry.has(runtime.callback)) {
458
+ remove();
459
+ if (!runtime.fibers.length) {
460
+ this.ctx.registry.delete(runtime.callback);
461
+ }
462
+ }
463
+ this._setEpoch(INACTIVE);
464
+ while (this.inertia) {
465
+ await this.inertia;
466
+ }
467
+ };
468
+ }, "ctx.plugin()");
469
+ } else {
470
+ this.uid = 0;
471
+ this.ctx = this.context = parent;
472
+ this.state = 2 /* ACTIVE */;
473
+ this.store = /* @__PURE__ */ Object.create(null);
474
+ this._runner = {
475
+ epoch: "",
476
+ getOuterStack,
477
+ execute: () => {
478
+ },
479
+ collect
480
+ };
481
+ this.dispose = () => this.restart();
482
+ }
483
+ }
484
+ parent;
485
+ inject;
486
+ runtime;
487
+ uid;
488
+ ctx;
489
+ config;
490
+ state = 0 /* PENDING */;
491
+ dispose;
492
+ store;
493
+ inertia;
494
+ _hooks = /* @__PURE__ */ Object.create(null);
495
+ _disposables = new DisposableList();
496
+ context;
497
+ _error = void 0;
498
+ _runner;
499
+ _store = /* @__PURE__ */ Object.create(null);
500
+ _restarting;
501
+ get name() {
502
+ if (this.runtime?.name) return this.runtime.name;
503
+ let fiber = this.parent.fiber;
504
+ while (fiber !== fiber.parent.fiber) {
505
+ if (fiber.runtime?.name) return fiber.runtime.name;
506
+ fiber = fiber.parent.fiber;
507
+ }
508
+ return "root";
509
+ }
510
+ assertActive() {
511
+ if (this.uid !== null) return;
512
+ throw new CordisError("INACTIVE_EFFECT");
513
+ }
514
+ _execute(runner) {
515
+ const oldEpoch = runner.epoch;
516
+ return composeError((info) => {
517
+ const safeCollect = (dispose) => {
518
+ if (typeof dispose === "function") {
519
+ runner.collect(dispose);
520
+ } else if (!isNullable(dispose)) {
521
+ throw new TypeError("Invalid effect");
522
+ }
523
+ };
524
+ const effect = runner.execute.call(this);
525
+ if (typeof effect === "function") {
526
+ return runner.collect(effect);
527
+ } else if (isNullable(effect)) {
528
+ return;
529
+ } else if (!isObject(effect)) {
530
+ throw new TypeError("Invalid effect");
531
+ } else if ("then" in effect) {
532
+ return effect.then(safeCollect);
533
+ } else if (Symbol.iterator in effect) {
534
+ info.error = new Error();
535
+ const iter = effect[Symbol.iterator]();
536
+ while (true) {
537
+ const result = iter.next();
538
+ safeCollect(result.value);
539
+ if (result.done) return;
540
+ }
541
+ } else if (Symbol.asyncIterator in effect) {
542
+ const iter = effect[Symbol.asyncIterator]();
543
+ return (async () => {
544
+ await Promise.resolve();
545
+ info.error = new Error();
546
+ while (true) {
547
+ if (runner.epoch !== oldEpoch) return;
548
+ const result = await iter.next();
549
+ safeCollect(result.value);
550
+ if (result.done) return;
551
+ }
552
+ })();
553
+ } else {
554
+ throw new TypeError("Invalid effect");
555
+ }
556
+ }, runner.getOuterStack);
557
+ }
558
+ effect(execute, label = "anonymous") {
559
+ this.assertActive();
560
+ const disposables = [];
561
+ const dispose = () => {
562
+ let task2;
563
+ for (const dispose2 of disposables.splice(0).reverse()) {
564
+ if (task2) {
565
+ task2 = task2.then(dispose2);
566
+ } else {
567
+ const result = dispose2();
568
+ if (isObject(result) && "then" in result) {
569
+ task2 = result;
570
+ }
571
+ }
572
+ }
573
+ return task2;
574
+ };
575
+ const meta = { label, children: [] };
576
+ const runner = {
577
+ execute,
578
+ epoch: true,
579
+ collect: (dispose2) => {
580
+ disposables.push(dispose2);
581
+ this._disposables.delete(dispose2);
582
+ if (dispose2[symbols.effect]) {
583
+ meta.children.push(dispose2[symbols.effect]);
584
+ }
585
+ },
586
+ getOuterStack: buildOuterStack()
587
+ };
588
+ let task;
589
+ try {
590
+ task = this._execute(runner);
591
+ } catch (reason) {
592
+ dispose();
593
+ throw reason;
594
+ }
595
+ task?.catch(dispose).catch((error) => this.ctx.logger.error(error));
596
+ const wrapper = Object.defineProperty(() => {
597
+ if (!runner.epoch) return;
598
+ runner.epoch = false;
599
+ return task ? task.then(dispose) : dispose();
600
+ }, symbols.effect, { value: meta });
601
+ const disposeAsync = () => {
602
+ if (!runner.epoch) return;
603
+ runner.epoch = false;
604
+ return dispose();
605
+ };
606
+ wrapper.then = async (onFulfilled, onRejected) => {
607
+ return Promise.resolve(task).then(() => disposeAsync).then(onFulfilled, onRejected);
608
+ };
609
+ disposables.push(this._disposables.push(wrapper));
610
+ return wrapper;
611
+ }
612
+ getEffects() {
613
+ return [...this._disposables].map((dispose) => dispose[symbols.effect]).filter(Boolean);
614
+ }
615
+ _getState() {
616
+ if (this.uid === null) return 4 /* DISPOSED */;
617
+ if (this._error) return 3 /* FAILED */;
618
+ if (this._runner.epoch !== INACTIVE) return 2 /* ACTIVE */;
619
+ return 0 /* PENDING */;
620
+ }
621
+ _updateState(callback) {
622
+ const oldState = this.state;
623
+ this.state = callback?.() ?? this._getState();
624
+ if (oldState === this.state) return;
625
+ this.context.emit(this, "internal/status", oldState);
626
+ if (oldState !== 2 /* ACTIVE */ && this.state !== 2 /* ACTIVE */) return;
627
+ for (const key of Reflect.ownKeys(this.ctx.reflect.store)) {
628
+ const impl = this.ctx.reflect.store[key];
629
+ if (!impl) continue;
630
+ if (impl.fiber !== this) continue;
631
+ this.ctx.reflect.notify([impl.name]);
632
+ }
633
+ }
634
+ _checkImpl(name2) {
635
+ const impl = this.ctx.reflect._getImpl(name2, true);
636
+ if (!impl) return delete this._store[name2];
637
+ try {
638
+ if (impl.check && !impl.check.call(getTraceable(this.ctx, impl.value))) {
639
+ return delete this._store[name2];
640
+ }
641
+ } catch (error) {
642
+ impl.fiber.ctx.logger.error(error);
643
+ return delete this._store[name2];
644
+ }
645
+ this._store[name2] = impl;
646
+ }
647
+ _refresh() {
648
+ let epoch = "";
649
+ for (const name2 of Object.keys(this.inject)) {
650
+ const impl = this._store[name2];
651
+ if (!impl) {
652
+ epoch = INACTIVE;
653
+ break;
654
+ }
655
+ epoch += ":" + impl.fiber.uid;
656
+ }
657
+ this._setEpoch(epoch);
658
+ }
659
+ _setEpoch(epoch) {
660
+ const oldEpoch = this._runner.epoch;
661
+ if (epoch === oldEpoch) return;
662
+ this._runner.epoch = epoch;
663
+ if (this.inertia) return;
664
+ this._updateState(() => {
665
+ if (epoch !== INACTIVE && oldEpoch === INACTIVE) {
666
+ this.inertia = this._reload();
667
+ return 1 /* LOADING */;
668
+ } else {
669
+ this.inertia = this._unload();
670
+ return 5 /* UNLOADING */;
671
+ }
672
+ });
673
+ }
674
+ async _reload() {
675
+ this.store = { ...this._store };
676
+ const oldEpoch = this._runner.epoch;
677
+ try {
678
+ await Promise.resolve();
679
+ await this._execute(this._runner);
680
+ } catch (reason) {
681
+ this.ctx.logger.error(reason);
682
+ this._error = reason;
683
+ this._runner.epoch = INACTIVE;
684
+ }
685
+ this._updateState(() => {
686
+ if (this._runner.epoch === oldEpoch) {
687
+ this.inertia = void 0;
688
+ } else {
689
+ this.inertia = this._unload();
690
+ return 5 /* UNLOADING */;
691
+ }
692
+ });
693
+ }
694
+ async _unload() {
695
+ await Promise.all(this._disposables.clear().map(async (dispose) => {
696
+ try {
697
+ await composeError(async (info) => {
698
+ await Promise.resolve();
699
+ info.error = new Error();
700
+ await dispose();
701
+ }, this._runner.getOuterStack);
702
+ } catch (reason) {
703
+ this.ctx.logger.error(reason);
704
+ }
705
+ }));
706
+ this.store = void 0;
707
+ this._updateState(() => {
708
+ if (this._runner.epoch === INACTIVE) {
709
+ this.inertia = void 0;
710
+ } else {
711
+ this.inertia = this._reload();
712
+ return 1 /* LOADING */;
713
+ }
714
+ });
715
+ }
716
+ async await() {
717
+ while (this.inertia || this._restarting) {
718
+ await Promise.all([this.inertia, this._restarting].filter((task) => !!task));
719
+ }
720
+ if (this._error) throw this._error;
721
+ return this;
722
+ }
723
+ async restart() {
724
+ const fiber = this.ctx.fiber;
725
+ fiber.assertActive();
726
+ if (fiber._restarting) return fiber._restarting.then(() => void 0);
727
+ let resolve;
728
+ const restarting = new Promise((resolvePromise) => {
729
+ resolve = resolvePromise;
730
+ });
731
+ fiber._restarting = restarting;
732
+ try {
733
+ await this._runRestart(fiber);
734
+ } finally {
735
+ fiber._restarting = void 0;
736
+ resolve();
737
+ }
738
+ }
739
+ async _runRestart(fiber) {
740
+ if (fiber.inertia) {
741
+ fiber._setEpoch(INACTIVE);
742
+ while (fiber.inertia) await fiber.inertia;
743
+ }
744
+ fiber._setEpoch(INACTIVE);
745
+ fiber._refresh();
746
+ while (fiber.inertia) await fiber.inertia;
747
+ }
748
+ update(config, noSave = false) {
749
+ const fiber = this.ctx.fiber;
750
+ fiber.assertActive();
751
+ config = resolveConfig(fiber.runtime, config);
752
+ fiber.context.waterfall(fiber.context, "internal/update", config, noSave, () => {
753
+ fiber.config = config;
754
+ fiber._error = void 0;
755
+ return fiber.restart();
756
+ });
757
+ }
758
+ };
759
+
760
+ // packages/core/src/logger.ts
761
+ var Logger = class {
762
+ constructor(options, service) {
763
+ this.service = service;
764
+ this.name = options.name;
765
+ this.level = options.level;
766
+ this.error = this._method("error");
767
+ this.info = this._method("info");
768
+ this.warn = this._method("warn");
769
+ this.debug = this._method("debug");
770
+ }
771
+ service;
772
+ name;
773
+ level;
774
+ error;
775
+ info;
776
+ warn;
777
+ debug;
778
+ _method(type) {
779
+ return (...args) => this.service._log({ name: this.name, type, args });
780
+ }
781
+ };
782
+ var LoggerService = class {
783
+ buffer = [];
784
+ ctx;
785
+ _snMessage = 0;
786
+ _snExporter = 0;
787
+ exporters = /* @__PURE__ */ new Map();
788
+ constructor(ctx) {
789
+ const tracker = {
790
+ property: "ctx",
791
+ noShadow: true
792
+ };
793
+ const self = createCallable("logger", joinPrototype(Object.getPrototypeOf(this), Function.prototype), tracker);
794
+ Object.assign(self, this);
795
+ self.ctx = ctx;
796
+ Object.defineProperty(self, symbols.tracker, { value: tracker });
797
+ self.exporter({
798
+ export: (message) => {
799
+ self.buffer.push(message);
800
+ }
801
+ });
802
+ ctx.reflect.provide("logger", self);
803
+ return self;
804
+ }
805
+ exporter(exporter) {
806
+ return this.ctx.fiber.effect(() => {
807
+ const id = ++this._snExporter;
808
+ this.exporters.set(id, exporter);
809
+ return () => this.exporters.delete(id);
810
+ }, "ctx.logger.exporter()");
811
+ }
812
+ [symbols.invoke](name2) {
813
+ const caller = this[symbols.caller];
814
+ const fiber = (caller ?? this.ctx).fiber;
815
+ return new Logger({
816
+ name: name2 ?? fiber.name
817
+ }, this);
818
+ }
819
+ _log(message) {
820
+ const sn = ++this._snMessage;
821
+ const ts = Date.now();
822
+ for (const exporter of this.exporters.values()) {
823
+ if (exporter.level != null && exporter.level < 0) continue;
824
+ exporter.export({ sn, ts, ...message });
825
+ }
826
+ }
827
+ error(...args) {
828
+ return this().error(...args);
829
+ }
830
+ info(...args) {
831
+ return this().info(...args);
832
+ }
833
+ warn(...args) {
834
+ return this().warn(...args);
835
+ }
836
+ debug(...args) {
837
+ return this().debug(...args);
838
+ }
839
+ };
840
+
841
+ // packages/core/src/reflect.ts
842
+ function enhanceError(error) {
843
+ const lines = error.stack.split("\n");
844
+ lines.splice(0, 2, `Error: ${error.message}`);
845
+ error.stack = lines.join("\n");
846
+ return error;
847
+ }
848
+ var RESERVED_WORDS = ["prototype", "then"];
849
+ function isSpecialProperty(prop) {
850
+ return typeof prop === "symbol" || RESERVED_WORDS.includes(prop) || parseInt(prop).toString() === prop || prop.startsWith("_");
851
+ }
852
+ var ReflectService = class {
853
+ constructor(ctx) {
854
+ this.ctx = ctx;
855
+ Object.defineProperty(this, symbols.tracker, {
856
+ value: { property: "ctx", noShadow: true }
857
+ });
858
+ this.mixin("reflect", ["get", "set", "provide", "accessor", "mixin"]);
859
+ this.mixin("fiber", ["runtime", "effect"]);
860
+ this.mixin("registry", ["inject", "plugin"]);
861
+ this.mixin("events", [
862
+ "on",
863
+ "once",
864
+ "parallel",
865
+ "emit",
866
+ "serial",
867
+ "bail",
868
+ "waterfall",
869
+ "waterfallAsync"
870
+ ]);
871
+ }
872
+ ctx;
873
+ static handler = {
874
+ get: (target, prop, ctx) => {
875
+ if (isSpecialProperty(prop)) {
876
+ return Reflect.get(target, prop, ctx);
877
+ }
878
+ if (Reflect.has(target, prop)) {
879
+ return getTraceable(ctx, Reflect.get(target, prop, ctx));
880
+ }
881
+ const error = new Error(`cannot get property "${String(prop)}" without inject`);
882
+ try {
883
+ const def = target.reflect.props[prop];
884
+ if (def?.type === "accessor") {
885
+ return def.get.call(ctx, ctx[symbols.receiver], error);
886
+ }
887
+ if (!ctx.fiber.runtime) return ctx.reflect.get(prop, false);
888
+ return ctx.events.waterfall(ctx, "internal/get", prop, error, () => {
889
+ const key = target[symbols.isolate][prop];
890
+ let fiber = (ctx[symbols.shadow] ?? ctx).fiber;
891
+ while (true) {
892
+ const impl = fiber.store?.[prop];
893
+ if (impl) return getTraceable(ctx, impl.value);
894
+ if (prop in fiber.inject) {
895
+ error.message = `cannot get required service "${String(prop)}" in inactive context`;
896
+ throw error;
897
+ }
898
+ if (!fiber.runtime) throw error;
899
+ if (fiber.parent[symbols.isolate][prop] !== key) throw error;
900
+ fiber = fiber.parent.fiber;
901
+ }
902
+ });
903
+ } catch (e) {
904
+ throw e === error ? enhanceError(e) : e;
905
+ }
906
+ },
907
+ set: (target, prop, value, ctx) => {
908
+ if (isSpecialProperty(prop)) {
909
+ return Reflect.set(target, prop, value, ctx);
910
+ }
911
+ const error = new Error(`cannot set property "${String(prop)}" without provide`);
912
+ const def = target.reflect.props[prop];
913
+ try {
914
+ if (def?.type === "accessor") {
915
+ if (!def.set) return false;
916
+ return def.set.call(ctx, value, ctx[symbols.receiver], error);
917
+ }
918
+ if (!def && !ctx.fiber.runtime) {
919
+ return Reflect.set(target, prop, value, ctx);
920
+ }
921
+ return ctx.events.waterfall(ctx, "internal/set", prop, value, error, () => {
922
+ if (!def) throw error;
923
+ return ctx.reflect.set(prop, value);
924
+ });
925
+ } catch (e) {
926
+ throw e === error ? enhanceError(e) : e;
927
+ }
928
+ },
929
+ has: (target, prop) => {
930
+ if (isSpecialProperty(prop)) {
931
+ return Reflect.has(target, prop);
932
+ }
933
+ if (Reflect.has(target, prop)) return true;
934
+ return !!target.reflect.props[prop];
935
+ }
936
+ };
937
+ store = /* @__PURE__ */ Object.create(null);
938
+ props = /* @__PURE__ */ Object.create(null);
939
+ get(name2, strict = true) {
940
+ return getTraceable(this.ctx, this._getImpl(name2, strict)?.value);
941
+ }
942
+ _getImpl(name2, strict = true) {
943
+ const key = this.ctx[symbols.isolate][name2];
944
+ const impl = key && this.store[key];
945
+ if (!impl) return;
946
+ if (strict && impl.fiber.state !== 2 /* ACTIVE */) return;
947
+ return impl;
948
+ }
949
+ set(name2, value) {
950
+ const key = this.ctx[symbols.isolate][name2];
951
+ const impl = key && this.store[key];
952
+ if (!impl) {
953
+ throw new Error(`cannot set property "${name2}" without provide`);
954
+ }
955
+ if (impl.fiber !== this.ctx.fiber) {
956
+ throw new Error(`cannot set property "${name2}" in multiple fibers`);
957
+ }
958
+ impl.value = value;
959
+ return true;
960
+ }
961
+ provide(name2, value, check) {
962
+ return this.ctx.fiber.effect(() => {
963
+ if (!this.props[name2]) {
964
+ this.props[name2] = { type: "service" };
965
+ } else if (this.props[name2].type !== "service") {
966
+ throw new Error(`property "${name2}" is already declared as ${this.props[name2].type}`);
967
+ }
968
+ this.props[name2] = { type: "service" };
969
+ this.ctx.root[symbols.isolate][name2] ??= Symbol(name2);
970
+ const key = this.ctx[symbols.isolate][name2];
971
+ const impl = {
972
+ name: name2,
973
+ value,
974
+ fiber: this.ctx.fiber,
975
+ ...check ? { check } : {}
976
+ };
977
+ if (key && this.store[key]) {
978
+ throw new Error(`service "${name2}" has been registered at <${this.store[key].fiber.name}>`);
979
+ }
980
+ this.store[key] = impl;
981
+ this.ctx.fiber.store[name2] = impl;
982
+ if (this.ctx.fiber.state === 2 /* ACTIVE */) {
983
+ this.notify([name2]);
984
+ }
985
+ return async () => {
986
+ delete this.store[key];
987
+ const fibers = this.notify([name2]);
988
+ await Promise.allSettled(fibers.map((fiber) => fiber.await()));
989
+ delete this.ctx.fiber.store[name2];
990
+ };
991
+ }, `ctx.provide(${JSON.stringify(name2)})`);
992
+ }
993
+ notify(names, filter = (ctx, name2) => ctx[symbols.isolate][name2] === this.ctx[symbols.isolate][name2]) {
994
+ const fibers = [];
995
+ for (const runtime of this.ctx.registry.values()) {
996
+ for (const fiber of runtime.fibers) {
997
+ let hasUpdate = false;
998
+ for (const name2 of names) {
999
+ if (!(name2 in fiber.inject)) continue;
1000
+ if (!filter(fiber.ctx, name2)) continue;
1001
+ hasUpdate = true;
1002
+ fiber._checkImpl(name2);
1003
+ }
1004
+ if (!hasUpdate) continue;
1005
+ fiber._refresh();
1006
+ fibers.push(fiber);
1007
+ }
1008
+ }
1009
+ for (const name2 of names) {
1010
+ const self = Object.create(this.ctx);
1011
+ self[symbols.filter] = (target) => filter(target, name2);
1012
+ this.ctx.events.emit(self, "internal/service", name2, this._getImpl(name2, false)?.value);
1013
+ }
1014
+ return fibers;
1015
+ }
1016
+ accessor(name2, options) {
1017
+ return this.ctx.fiber.effect(() => {
1018
+ if (name2 in this.props) {
1019
+ throw new Error(`property "${name2}" is already declared as ${this.props[name2].type}`);
1020
+ }
1021
+ this.props[name2] = { type: "accessor", ...options };
1022
+ return () => delete this.props[name2];
1023
+ }, `ctx.accessor(${JSON.stringify(name2)})`);
1024
+ }
1025
+ mixin(source, mixins) {
1026
+ return this.ctx.fiber.effect(() => {
1027
+ const entries = Array.isArray(mixins) ? mixins.map((key) => [key, key]) : Object.entries(mixins);
1028
+ const getTarget = (target) => target[source];
1029
+ return entries.map(([key, value]) => {
1030
+ return this.accessor(value, {
1031
+ get(receiver) {
1032
+ const service = getTarget(this);
1033
+ if (service == null) return service;
1034
+ const mixin = receiver ? withProps(receiver, service) : service;
1035
+ const result = Reflect.get(service, key, mixin);
1036
+ if (typeof result !== "function") return result;
1037
+ return result.bind(mixin ?? service);
1038
+ },
1039
+ set(value2, receiver) {
1040
+ const service = getTarget(this);
1041
+ const mixin = receiver ? withProps(receiver, service) : service;
1042
+ return Reflect.set(service, key, value2, mixin);
1043
+ }
1044
+ });
1045
+ });
1046
+ }, `ctx.mixin(${JSON.stringify(source)})`);
1047
+ }
1048
+ trace(value) {
1049
+ return getTraceable(this.ctx, value);
1050
+ }
1051
+ bind(callback) {
1052
+ return new Proxy(callback, {
1053
+ apply: (target, thisArg, args) => {
1054
+ return Reflect.apply(target, this.trace(thisArg), args.map((arg) => this.trace(arg)));
1055
+ },
1056
+ construct: (target, args, newTarget) => {
1057
+ return Reflect.construct(target, args.map((arg) => this.trace(arg)), newTarget);
1058
+ }
1059
+ });
1060
+ }
1061
+ };
1062
+
1063
+ // packages/core/src/registry.ts
1064
+ function isApplicable(object) {
1065
+ return object && typeof object === "object" && typeof object.apply === "function";
1066
+ }
1067
+ function Inject(name2, config) {
1068
+ return function(value, decorator) {
1069
+ if (decorator.kind === "class") {
1070
+ if (!Object.hasOwn(value, "inject")) {
1071
+ Object.defineProperty(value, "inject", {
1072
+ value: Object.create(Object.getPrototypeOf(value).inject ?? null)
1073
+ });
1074
+ Object.defineProperty(value.inject, symbols.checkProto, { value: true });
1075
+ }
1076
+ value.inject[name2] = config;
1077
+ } else if (decorator.kind === "method") {
1078
+ const inject = (value[symbols.metadata] ??= {}).inject ??= /* @__PURE__ */ Object.create(null);
1079
+ inject[name2] = config;
1080
+ decorator.addInitializer(function() {
1081
+ const property = this[symbols.tracker]?.property;
1082
+ (this[symbols.initHooks] ??= []).push(() => {
1083
+ this.ctx.inject(inject, (ctx) => {
1084
+ return value.call(property ? withProps(this, { [property]: ctx }) : this);
1085
+ });
1086
+ });
1087
+ });
1088
+ } else {
1089
+ throw new Error("@Inject() can only be used on class or class methods");
1090
+ }
1091
+ };
1092
+ }
1093
+ function resolveInject(inject, result = /* @__PURE__ */ Object.create(null)) {
1094
+ if (!inject) return result;
1095
+ if (Array.isArray(inject)) {
1096
+ for (const name2 of inject) {
1097
+ result[name2] = null;
1098
+ }
1099
+ } else if (Reflect.has(inject, symbols.checkProto)) {
1100
+ Object.assign(result, resolveInject(Object.getPrototypeOf(inject)));
1101
+ for (const name2 of Object.keys(inject)) {
1102
+ result[name2] = inject[name2] ?? null;
1103
+ }
1104
+ } else {
1105
+ for (const name2 of Object.keys(inject)) {
1106
+ result[name2] = inject[name2] ?? null;
1107
+ }
1108
+ }
1109
+ return result;
1110
+ }
1111
+ var RegistryService = class {
1112
+ constructor(ctx) {
1113
+ this.ctx = ctx;
1114
+ Object.defineProperty(this, symbols.tracker, {
1115
+ value: { property: "ctx", noShadow: true }
1116
+ });
1117
+ }
1118
+ ctx;
1119
+ _counter = 0;
1120
+ _internal = /* @__PURE__ */ new Map();
1121
+ get counter() {
1122
+ return ++this._counter;
1123
+ }
1124
+ get size() {
1125
+ return this._internal.size;
1126
+ }
1127
+ resolve(plugin) {
1128
+ try {
1129
+ if (typeof plugin === "function") return plugin;
1130
+ if (isApplicable(plugin)) return plugin.apply;
1131
+ } catch {
1132
+ }
1133
+ }
1134
+ get(plugin) {
1135
+ const key = this.resolve(plugin);
1136
+ return key && this._internal.get(key);
1137
+ }
1138
+ has(plugin) {
1139
+ const key = this.resolve(plugin);
1140
+ return !!key && this._internal.has(key);
1141
+ }
1142
+ delete(plugin) {
1143
+ const key = this.resolve(plugin);
1144
+ const runtime = key && this._internal.get(key);
1145
+ if (!runtime) return;
1146
+ this._internal.delete(key);
1147
+ for (const fiber of [...runtime.fibers]) {
1148
+ fiber.dispose();
1149
+ }
1150
+ return runtime;
1151
+ }
1152
+ keys() {
1153
+ return this._internal.keys();
1154
+ }
1155
+ values() {
1156
+ return this._internal.values();
1157
+ }
1158
+ entries() {
1159
+ return this._internal.entries();
1160
+ }
1161
+ forEach(callback) {
1162
+ return this._internal.forEach(callback);
1163
+ }
1164
+ inject(inject, callback) {
1165
+ const name2 = callback.name || void 0;
1166
+ return this.plugin(Object.assign(
1167
+ { inject, apply: callback },
1168
+ name2 ? { name: name2 } : {}
1169
+ ));
1170
+ }
1171
+ plugin(plugin, config, getOuterStack = buildOuterStack()) {
1172
+ const callback = this.resolve(plugin);
1173
+ if (!callback) throw new Error('invalid plugin, expect function or object with an "apply" method, received ' + typeof plugin);
1174
+ this.ctx.fiber.assertActive();
1175
+ let runtime = this._internal.get(callback);
1176
+ if (!runtime) {
1177
+ let name2 = plugin.name;
1178
+ if (name2 === "apply") name2 = void 0;
1179
+ runtime = {
1180
+ callback,
1181
+ fibers: new DisposableList(),
1182
+ ...name2 ? { name: name2 } : {},
1183
+ ...plugin.Config ? { Config: plugin.Config } : {}
1184
+ };
1185
+ this._internal.set(callback, runtime);
1186
+ }
1187
+ const fiber = new Fiber(this.ctx, config, resolveInject(plugin.inject), runtime, getOuterStack);
1188
+ const wrapped = Object.create(fiber);
1189
+ wrapped.then = (onFulfilled, onRejected) => {
1190
+ return fiber.await().then(onFulfilled, onRejected);
1191
+ };
1192
+ return wrapped;
1193
+ }
1194
+ };
1195
+
1196
+ // packages/core/src/context.ts
1197
+ var Context = class _Context {
1198
+ static effect = symbols.effect;
1199
+ static filter = symbols.filter;
1200
+ static isolate = symbols.isolate;
1201
+ static intercept = symbols.intercept;
1202
+ static marker = /* @__PURE__ */ Symbol.for("tnega.is");
1203
+ static is(value) {
1204
+ return !!value?.[_Context.marker];
1205
+ }
1206
+ static {
1207
+ _Context.prototype[_Context.marker] = true;
1208
+ }
1209
+ constructor() {
1210
+ this[symbols.isolate] = /* @__PURE__ */ Object.create(null);
1211
+ this[symbols.intercept] = /* @__PURE__ */ Object.create(null);
1212
+ const self = new Proxy(this, ReflectService.handler);
1213
+ this.root = self;
1214
+ this.baseUrl = void 0;
1215
+ this.fiber = new Fiber(self, {}, /* @__PURE__ */ Object.create(null), null, () => []);
1216
+ this.reflect = new ReflectService(self);
1217
+ this.registry = new RegistryService(self);
1218
+ this.events = new EventsService(self);
1219
+ this.logger = new LoggerService(self);
1220
+ this.fiber._disposables.clear();
1221
+ return self;
1222
+ }
1223
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
1224
+ return `Context <${this.fiber.name}>`;
1225
+ }
1226
+ extend(meta = {}) {
1227
+ const shadow = Reflect.getOwnPropertyDescriptor(this, symbols.shadow)?.value;
1228
+ const self = Object.create(getTraceable(this, this));
1229
+ for (const prop of Reflect.ownKeys(meta)) {
1230
+ Object.defineProperty(self, prop, Reflect.getOwnPropertyDescriptor(meta, prop));
1231
+ }
1232
+ if (!shadow) return self;
1233
+ return Object.assign(Object.create(self), { [symbols.shadow]: shadow });
1234
+ }
1235
+ isolate(name2, label) {
1236
+ const shadow = Object.create(this[symbols.isolate]);
1237
+ shadow[name2] = label ?? Symbol(name2);
1238
+ return this.extend({ [symbols.isolate]: shadow });
1239
+ }
1240
+ intercept(name2, config) {
1241
+ const intercept = Object.create(this[symbols.intercept]);
1242
+ intercept[name2] = config;
1243
+ return this.extend({ [symbols.intercept]: intercept });
1244
+ }
1245
+ };
1246
+
1247
+ // packages/core/src/invariant.ts
1248
+ var InvariantRegistry = class {
1249
+ _checks = /* @__PURE__ */ new Map();
1250
+ register(definition) {
1251
+ if (this._checks.has(definition.name)) {
1252
+ throw new Error(`invariant already registered: ${definition.name}`);
1253
+ }
1254
+ this._checks.set(definition.name, definition);
1255
+ return () => {
1256
+ this._checks.delete(definition.name);
1257
+ };
1258
+ }
1259
+ has(name2) {
1260
+ return this._checks.has(name2);
1261
+ }
1262
+ list() {
1263
+ return [...this._checks.values()];
1264
+ }
1265
+ async runAll(context) {
1266
+ const violations = [];
1267
+ for (const definition of this._checks.values()) {
1268
+ const found = await definition.check(context);
1269
+ violations.push(...found);
1270
+ }
1271
+ return violations;
1272
+ }
1273
+ };
1274
+ var InvariantViolationError = class extends Error {
1275
+ constructor(violations) {
1276
+ super(violations.join("; "));
1277
+ this.violations = violations;
1278
+ }
1279
+ violations;
1280
+ name = "InvariantViolationError";
1281
+ };
1282
+ function assertInvariants(violations) {
1283
+ if (violations.length) throw new InvariantViolationError(violations);
1284
+ }
1285
+ var invariant = {
1286
+ name: "invariants",
1287
+ apply: (ctx) => {
1288
+ const registry = new InvariantRegistry();
1289
+ ctx.provide("invariants", registry);
1290
+ return () => {
1291
+ };
1292
+ }
1293
+ };
1294
+
1295
+ // packages/core/src/service.ts
1296
+ var Service = class _Service {
1297
+ constructor(ctx, name2) {
1298
+ this.ctx = ctx;
1299
+ name2 ??= this.constructor.provide;
1300
+ const tracker = {
1301
+ associate: name2,
1302
+ property: "ctx"
1303
+ };
1304
+ const self = this[symbols.invoke] ? createCallable(name2, joinPrototype(Object.getPrototypeOf(this), Function.prototype), tracker) : this;
1305
+ self.ctx = ctx;
1306
+ self.name = name2;
1307
+ Object.defineProperty(self, symbols.tracker, { value: tracker });
1308
+ self.ctx.reflect.provide(name2, self, this[symbols.check]);
1309
+ return self;
1310
+ }
1311
+ ctx;
1312
+ static init = symbols.init;
1313
+ static check = symbols.check;
1314
+ static config = symbols.config;
1315
+ static invoke = symbols.invoke;
1316
+ static extend = symbols.extend;
1317
+ static tracker = symbols.tracker;
1318
+ static resolveConfig = symbols.resolveConfig;
1319
+ name;
1320
+ [symbols.filter](ctx) {
1321
+ return ctx[symbols.isolate][this.name] === this.ctx[symbols.isolate][this.name];
1322
+ }
1323
+ [symbols.extend](props) {
1324
+ let self;
1325
+ if (this[_Service.invoke]) {
1326
+ self = createCallable(this.name, this, this[symbols.tracker]);
1327
+ } else {
1328
+ self = Object.create(this);
1329
+ }
1330
+ return Object.assign(self, props);
1331
+ }
1332
+ [symbols.resolveConfig](base, head) {
1333
+ let intercept = this.ctx[symbols.intercept];
1334
+ const configs = [];
1335
+ while (this.name in intercept) {
1336
+ if (Object.hasOwn(intercept, this.name)) {
1337
+ configs.unshift(intercept[this.name]);
1338
+ }
1339
+ intercept = Object.getPrototypeOf(intercept);
1340
+ }
1341
+ if (base) configs.unshift(base);
1342
+ if (head) configs.push(head);
1343
+ if (this["Config"]?.merge) {
1344
+ return this["Config"].merge(...configs);
1345
+ } else {
1346
+ return Object.assign({}, ...configs);
1347
+ }
1348
+ }
1349
+ static [Symbol.hasInstance](instance) {
1350
+ if (!instance) return false;
1351
+ let constructor = instance.constructor;
1352
+ while (constructor) {
1353
+ constructor = constructor.prototype?.constructor;
1354
+ if (constructor === this) return true;
1355
+ constructor &&= Object.getPrototypeOf(constructor);
1356
+ }
1357
+ return false;
1358
+ }
1359
+ };
1360
+
1361
+ // packages/core/src/index.ts
1362
+ var name = "@tnega/core";
1363
+ export {
1364
+ Context,
1365
+ CordisError,
1366
+ CordisErrorCode,
1367
+ DisposableList,
1368
+ EventsService,
1369
+ Fiber,
1370
+ FiberState,
1371
+ Inject,
1372
+ InvariantRegistry,
1373
+ InvariantViolationError,
1374
+ Logger,
1375
+ LoggerService,
1376
+ ReflectService,
1377
+ RegistryService,
1378
+ Service,
1379
+ ValidationError,
1380
+ assertInvariants,
1381
+ buildOuterStack,
1382
+ composeError,
1383
+ createCallable,
1384
+ getPropertyDescriptor,
1385
+ getTraceable,
1386
+ invariant,
1387
+ isBailed,
1388
+ isConstructor,
1389
+ isNullable,
1390
+ isObject,
1391
+ joinPrototype,
1392
+ name,
1393
+ resolveConfig,
1394
+ resolveInject,
1395
+ symbols,
1396
+ withProps
1397
+ };
1398
+ //# sourceMappingURL=core.js.map