@affectively/aeon-pages-runtime 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3913 +1,76 @@
1
- // @bun
2
- var __create = Object.create;
3
- var __getProtoOf = Object.getPrototypeOf;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __toESM = (mod, isNodeMode, target) => {
8
- target = mod != null ? __create(__getProtoOf(mod)) : {};
9
- const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
10
- for (let key of __getOwnPropNames(mod))
11
- if (!__hasOwnProp.call(to, key))
12
- __defProp(to, key, {
13
- get: () => mod[key],
14
- enumerable: true
15
- });
16
- return to;
17
- };
18
- var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
19
- var __export = (target, all) => {
20
- for (var name in all)
21
- __defProp(target, name, {
22
- get: all[name],
23
- enumerable: true,
24
- configurable: true,
25
- set: (newValue) => all[name] = () => newValue
26
- });
27
- };
28
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
29
- var __require = import.meta.require;
30
-
31
- // ../../../../node_modules/.bun/react@19.2.3/node_modules/react/cjs/react.development.js
32
- var require_react_development = __commonJS((exports, module) => {
33
- (function() {
34
- function defineDeprecationWarning(methodName, info) {
35
- Object.defineProperty(Component.prototype, methodName, {
36
- get: function() {
37
- console.warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]);
38
- }
39
- });
40
- }
41
- function getIteratorFn(maybeIterable) {
42
- if (maybeIterable === null || typeof maybeIterable !== "object")
43
- return null;
44
- maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
45
- return typeof maybeIterable === "function" ? maybeIterable : null;
46
- }
47
- function warnNoop(publicInstance, callerName) {
48
- publicInstance = (publicInstance = publicInstance.constructor) && (publicInstance.displayName || publicInstance.name) || "ReactClass";
49
- var warningKey = publicInstance + "." + callerName;
50
- didWarnStateUpdateForUnmountedComponent[warningKey] || (console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, publicInstance), didWarnStateUpdateForUnmountedComponent[warningKey] = true);
51
- }
52
- function Component(props, context, updater) {
53
- this.props = props;
54
- this.context = context;
55
- this.refs = emptyObject;
56
- this.updater = updater || ReactNoopUpdateQueue;
57
- }
58
- function ComponentDummy() {}
59
- function PureComponent(props, context, updater) {
60
- this.props = props;
61
- this.context = context;
62
- this.refs = emptyObject;
63
- this.updater = updater || ReactNoopUpdateQueue;
64
- }
65
- function noop() {}
66
- function testStringCoercion(value) {
67
- return "" + value;
68
- }
69
- function checkKeyStringCoercion(value) {
70
- try {
71
- testStringCoercion(value);
72
- var JSCompiler_inline_result = false;
73
- } catch (e) {
74
- JSCompiler_inline_result = true;
75
- }
76
- if (JSCompiler_inline_result) {
77
- JSCompiler_inline_result = console;
78
- var JSCompiler_temp_const = JSCompiler_inline_result.error;
79
- var JSCompiler_inline_result$jscomp$0 = typeof Symbol === "function" && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
80
- JSCompiler_temp_const.call(JSCompiler_inline_result, "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", JSCompiler_inline_result$jscomp$0);
81
- return testStringCoercion(value);
82
- }
83
- }
84
- function getComponentNameFromType(type) {
85
- if (type == null)
86
- return null;
87
- if (typeof type === "function")
88
- return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
89
- if (typeof type === "string")
90
- return type;
91
- switch (type) {
92
- case REACT_FRAGMENT_TYPE:
93
- return "Fragment";
94
- case REACT_PROFILER_TYPE:
95
- return "Profiler";
96
- case REACT_STRICT_MODE_TYPE:
97
- return "StrictMode";
98
- case REACT_SUSPENSE_TYPE:
99
- return "Suspense";
100
- case REACT_SUSPENSE_LIST_TYPE:
101
- return "SuspenseList";
102
- case REACT_ACTIVITY_TYPE:
103
- return "Activity";
104
- }
105
- if (typeof type === "object")
106
- switch (typeof type.tag === "number" && console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."), type.$$typeof) {
107
- case REACT_PORTAL_TYPE:
108
- return "Portal";
109
- case REACT_CONTEXT_TYPE:
110
- return type.displayName || "Context";
111
- case REACT_CONSUMER_TYPE:
112
- return (type._context.displayName || "Context") + ".Consumer";
113
- case REACT_FORWARD_REF_TYPE:
114
- var innerType = type.render;
115
- type = type.displayName;
116
- type || (type = innerType.displayName || innerType.name || "", type = type !== "" ? "ForwardRef(" + type + ")" : "ForwardRef");
117
- return type;
118
- case REACT_MEMO_TYPE:
119
- return innerType = type.displayName || null, innerType !== null ? innerType : getComponentNameFromType(type.type) || "Memo";
120
- case REACT_LAZY_TYPE:
121
- innerType = type._payload;
122
- type = type._init;
123
- try {
124
- return getComponentNameFromType(type(innerType));
125
- } catch (x) {}
126
- }
127
- return null;
128
- }
129
- function getTaskName(type) {
130
- if (type === REACT_FRAGMENT_TYPE)
131
- return "<>";
132
- if (typeof type === "object" && type !== null && type.$$typeof === REACT_LAZY_TYPE)
133
- return "<...>";
134
- try {
135
- var name = getComponentNameFromType(type);
136
- return name ? "<" + name + ">" : "<...>";
137
- } catch (x) {
138
- return "<...>";
139
- }
140
- }
141
- function getOwner() {
142
- var dispatcher = ReactSharedInternals.A;
143
- return dispatcher === null ? null : dispatcher.getOwner();
144
- }
145
- function UnknownOwner() {
146
- return Error("react-stack-top-frame");
147
- }
148
- function hasValidKey(config) {
149
- if (hasOwnProperty.call(config, "key")) {
150
- var getter = Object.getOwnPropertyDescriptor(config, "key").get;
151
- if (getter && getter.isReactWarning)
152
- return false;
153
- }
154
- return config.key !== undefined;
155
- }
156
- function defineKeyPropWarningGetter(props, displayName) {
157
- function warnAboutAccessingKey() {
158
- specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", displayName));
159
- }
160
- warnAboutAccessingKey.isReactWarning = true;
161
- Object.defineProperty(props, "key", {
162
- get: warnAboutAccessingKey,
163
- configurable: true
164
- });
165
- }
166
- function elementRefGetterWithDeprecationWarning() {
167
- var componentName = getComponentNameFromType(this.type);
168
- didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."));
169
- componentName = this.props.ref;
170
- return componentName !== undefined ? componentName : null;
171
- }
172
- function ReactElement(type, key, props, owner, debugStack, debugTask) {
173
- var refProp = props.ref;
174
- type = {
175
- $$typeof: REACT_ELEMENT_TYPE,
176
- type,
177
- key,
178
- props,
179
- _owner: owner
180
- };
181
- (refProp !== undefined ? refProp : null) !== null ? Object.defineProperty(type, "ref", {
182
- enumerable: false,
183
- get: elementRefGetterWithDeprecationWarning
184
- }) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
185
- type._store = {};
186
- Object.defineProperty(type._store, "validated", {
187
- configurable: false,
188
- enumerable: false,
189
- writable: true,
190
- value: 0
191
- });
192
- Object.defineProperty(type, "_debugInfo", {
193
- configurable: false,
194
- enumerable: false,
195
- writable: true,
196
- value: null
197
- });
198
- Object.defineProperty(type, "_debugStack", {
199
- configurable: false,
200
- enumerable: false,
201
- writable: true,
202
- value: debugStack
203
- });
204
- Object.defineProperty(type, "_debugTask", {
205
- configurable: false,
206
- enumerable: false,
207
- writable: true,
208
- value: debugTask
209
- });
210
- Object.freeze && (Object.freeze(type.props), Object.freeze(type));
211
- return type;
212
- }
213
- function cloneAndReplaceKey(oldElement, newKey) {
214
- newKey = ReactElement(oldElement.type, newKey, oldElement.props, oldElement._owner, oldElement._debugStack, oldElement._debugTask);
215
- oldElement._store && (newKey._store.validated = oldElement._store.validated);
216
- return newKey;
217
- }
218
- function validateChildKeys(node) {
219
- isValidElement(node) ? node._store && (node._store.validated = 1) : typeof node === "object" && node !== null && node.$$typeof === REACT_LAZY_TYPE && (node._payload.status === "fulfilled" ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1));
220
- }
221
- function isValidElement(object) {
222
- return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
223
- }
224
- function escape(key) {
225
- var escaperLookup = { "=": "=0", ":": "=2" };
226
- return "$" + key.replace(/[=:]/g, function(match) {
227
- return escaperLookup[match];
228
- });
229
- }
230
- function getElementKey(element, index) {
231
- return typeof element === "object" && element !== null && element.key != null ? (checkKeyStringCoercion(element.key), escape("" + element.key)) : index.toString(36);
232
- }
233
- function resolveThenable(thenable) {
234
- switch (thenable.status) {
235
- case "fulfilled":
236
- return thenable.value;
237
- case "rejected":
238
- throw thenable.reason;
239
- default:
240
- switch (typeof thenable.status === "string" ? thenable.then(noop, noop) : (thenable.status = "pending", thenable.then(function(fulfilledValue) {
241
- thenable.status === "pending" && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
242
- }, function(error) {
243
- thenable.status === "pending" && (thenable.status = "rejected", thenable.reason = error);
244
- })), thenable.status) {
245
- case "fulfilled":
246
- return thenable.value;
247
- case "rejected":
248
- throw thenable.reason;
249
- }
250
- }
251
- throw thenable;
252
- }
253
- function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
254
- var type = typeof children;
255
- if (type === "undefined" || type === "boolean")
256
- children = null;
257
- var invokeCallback = false;
258
- if (children === null)
259
- invokeCallback = true;
260
- else
261
- switch (type) {
262
- case "bigint":
263
- case "string":
264
- case "number":
265
- invokeCallback = true;
266
- break;
267
- case "object":
268
- switch (children.$$typeof) {
269
- case REACT_ELEMENT_TYPE:
270
- case REACT_PORTAL_TYPE:
271
- invokeCallback = true;
272
- break;
273
- case REACT_LAZY_TYPE:
274
- return invokeCallback = children._init, mapIntoArray(invokeCallback(children._payload), array, escapedPrefix, nameSoFar, callback);
275
- }
276
- }
277
- if (invokeCallback) {
278
- invokeCallback = children;
279
- callback = callback(invokeCallback);
280
- var childKey = nameSoFar === "" ? "." + getElementKey(invokeCallback, 0) : nameSoFar;
281
- isArrayImpl(callback) ? (escapedPrefix = "", childKey != null && (escapedPrefix = childKey.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array, escapedPrefix, "", function(c) {
282
- return c;
283
- })) : callback != null && (isValidElement(callback) && (callback.key != null && (invokeCallback && invokeCallback.key === callback.key || checkKeyStringCoercion(callback.key)), escapedPrefix = cloneAndReplaceKey(callback, escapedPrefix + (callback.key == null || invokeCallback && invokeCallback.key === callback.key ? "" : ("" + callback.key).replace(userProvidedKeyEscapeRegex, "$&/") + "/") + childKey), nameSoFar !== "" && invokeCallback != null && isValidElement(invokeCallback) && invokeCallback.key == null && invokeCallback._store && !invokeCallback._store.validated && (escapedPrefix._store.validated = 2), callback = escapedPrefix), array.push(callback));
284
- return 1;
285
- }
286
- invokeCallback = 0;
287
- childKey = nameSoFar === "" ? "." : nameSoFar + ":";
288
- if (isArrayImpl(children))
289
- for (var i = 0;i < children.length; i++)
290
- nameSoFar = children[i], type = childKey + getElementKey(nameSoFar, i), invokeCallback += mapIntoArray(nameSoFar, array, escapedPrefix, type, callback);
291
- else if (i = getIteratorFn(children), typeof i === "function")
292
- for (i === children.entries && (didWarnAboutMaps || console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."), didWarnAboutMaps = true), children = i.call(children), i = 0;!(nameSoFar = children.next()).done; )
293
- nameSoFar = nameSoFar.value, type = childKey + getElementKey(nameSoFar, i++), invokeCallback += mapIntoArray(nameSoFar, array, escapedPrefix, type, callback);
294
- else if (type === "object") {
295
- if (typeof children.then === "function")
296
- return mapIntoArray(resolveThenable(children), array, escapedPrefix, nameSoFar, callback);
297
- array = String(children);
298
- throw Error("Objects are not valid as a React child (found: " + (array === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : array) + "). If you meant to render a collection of children, use an array instead.");
299
- }
300
- return invokeCallback;
301
- }
302
- function mapChildren(children, func, context) {
303
- if (children == null)
304
- return children;
305
- var result = [], count = 0;
306
- mapIntoArray(children, result, "", "", function(child) {
307
- return func.call(context, child, count++);
308
- });
309
- return result;
310
- }
311
- function lazyInitializer(payload) {
312
- if (payload._status === -1) {
313
- var ioInfo = payload._ioInfo;
314
- ioInfo != null && (ioInfo.start = ioInfo.end = performance.now());
315
- ioInfo = payload._result;
316
- var thenable = ioInfo();
317
- thenable.then(function(moduleObject) {
318
- if (payload._status === 0 || payload._status === -1) {
319
- payload._status = 1;
320
- payload._result = moduleObject;
321
- var _ioInfo = payload._ioInfo;
322
- _ioInfo != null && (_ioInfo.end = performance.now());
323
- thenable.status === undefined && (thenable.status = "fulfilled", thenable.value = moduleObject);
324
- }
325
- }, function(error) {
326
- if (payload._status === 0 || payload._status === -1) {
327
- payload._status = 2;
328
- payload._result = error;
329
- var _ioInfo2 = payload._ioInfo;
330
- _ioInfo2 != null && (_ioInfo2.end = performance.now());
331
- thenable.status === undefined && (thenable.status = "rejected", thenable.reason = error);
332
- }
333
- });
334
- ioInfo = payload._ioInfo;
335
- if (ioInfo != null) {
336
- ioInfo.value = thenable;
337
- var displayName = thenable.displayName;
338
- typeof displayName === "string" && (ioInfo.name = displayName);
339
- }
340
- payload._status === -1 && (payload._status = 0, payload._result = thenable);
341
- }
342
- if (payload._status === 1)
343
- return ioInfo = payload._result, ioInfo === undefined && console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
344
-
345
- Your code should look like:
346
- const MyComponent = lazy(() => import('./MyComponent'))
347
-
348
- Did you accidentally put curly braces around the import?`, ioInfo), "default" in ioInfo || console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
349
-
350
- Your code should look like:
351
- const MyComponent = lazy(() => import('./MyComponent'))`, ioInfo), ioInfo.default;
352
- throw payload._result;
353
- }
354
- function resolveDispatcher() {
355
- var dispatcher = ReactSharedInternals.H;
356
- dispatcher === null && console.error(`Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
357
- 1. You might have mismatching versions of React and the renderer (such as React DOM)
358
- 2. You might be breaking the Rules of Hooks
359
- 3. You might have more than one copy of React in the same app
360
- See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.`);
361
- return dispatcher;
362
- }
363
- function releaseAsyncTransition() {
364
- ReactSharedInternals.asyncTransitions--;
365
- }
366
- function enqueueTask(task) {
367
- if (enqueueTaskImpl === null)
368
- try {
369
- var requireString = ("require" + Math.random()).slice(0, 7);
370
- enqueueTaskImpl = (module && module[requireString]).call(module, "timers").setImmediate;
371
- } catch (_err) {
372
- enqueueTaskImpl = function(callback) {
373
- didWarnAboutMessageChannel === false && (didWarnAboutMessageChannel = true, typeof MessageChannel === "undefined" && console.error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));
374
- var channel = new MessageChannel;
375
- channel.port1.onmessage = callback;
376
- channel.port2.postMessage(undefined);
377
- };
378
- }
379
- return enqueueTaskImpl(task);
380
- }
381
- function aggregateErrors(errors) {
382
- return 1 < errors.length && typeof AggregateError === "function" ? new AggregateError(errors) : errors[0];
383
- }
384
- function popActScope(prevActQueue, prevActScopeDepth) {
385
- prevActScopeDepth !== actScopeDepth - 1 && console.error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. ");
386
- actScopeDepth = prevActScopeDepth;
387
- }
388
- function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
389
- var queue = ReactSharedInternals.actQueue;
390
- if (queue !== null)
391
- if (queue.length !== 0)
392
- try {
393
- flushActQueue(queue);
394
- enqueueTask(function() {
395
- return recursivelyFlushAsyncActWork(returnValue, resolve, reject);
396
- });
397
- return;
398
- } catch (error) {
399
- ReactSharedInternals.thrownErrors.push(error);
400
- }
401
- else
402
- ReactSharedInternals.actQueue = null;
403
- 0 < ReactSharedInternals.thrownErrors.length ? (queue = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(queue)) : resolve(returnValue);
404
- }
405
- function flushActQueue(queue) {
406
- if (!isFlushing) {
407
- isFlushing = true;
408
- var i = 0;
409
- try {
410
- for (;i < queue.length; i++) {
411
- var callback = queue[i];
412
- do {
413
- ReactSharedInternals.didUsePromise = false;
414
- var continuation = callback(false);
415
- if (continuation !== null) {
416
- if (ReactSharedInternals.didUsePromise) {
417
- queue[i] = callback;
418
- queue.splice(0, i);
419
- return;
420
- }
421
- callback = continuation;
422
- } else
423
- break;
424
- } while (1);
425
- }
426
- queue.length = 0;
427
- } catch (error) {
428
- queue.splice(0, i + 1), ReactSharedInternals.thrownErrors.push(error);
429
- } finally {
430
- isFlushing = false;
431
- }
432
- }
433
- }
434
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
435
- var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, didWarnStateUpdateForUnmountedComponent = {}, ReactNoopUpdateQueue = {
436
- isMounted: function() {
437
- return false;
438
- },
439
- enqueueForceUpdate: function(publicInstance) {
440
- warnNoop(publicInstance, "forceUpdate");
441
- },
442
- enqueueReplaceState: function(publicInstance) {
443
- warnNoop(publicInstance, "replaceState");
444
- },
445
- enqueueSetState: function(publicInstance) {
446
- warnNoop(publicInstance, "setState");
447
- }
448
- }, assign = Object.assign, emptyObject = {};
449
- Object.freeze(emptyObject);
450
- Component.prototype.isReactComponent = {};
451
- Component.prototype.setState = function(partialState, callback) {
452
- if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null)
453
- throw Error("takes an object of state variables to update or a function which returns an object of state variables.");
454
- this.updater.enqueueSetState(this, partialState, callback, "setState");
455
- };
456
- Component.prototype.forceUpdate = function(callback) {
457
- this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
458
- };
459
- var deprecatedAPIs = {
460
- isMounted: [
461
- "isMounted",
462
- "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."
463
- ],
464
- replaceState: [
465
- "replaceState",
466
- "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."
467
- ]
468
- };
469
- for (fnName in deprecatedAPIs)
470
- deprecatedAPIs.hasOwnProperty(fnName) && defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
471
- ComponentDummy.prototype = Component.prototype;
472
- deprecatedAPIs = PureComponent.prototype = new ComponentDummy;
473
- deprecatedAPIs.constructor = PureComponent;
474
- assign(deprecatedAPIs, Component.prototype);
475
- deprecatedAPIs.isPureReactComponent = true;
476
- var isArrayImpl = Array.isArray, REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), ReactSharedInternals = {
477
- H: null,
478
- A: null,
479
- T: null,
480
- S: null,
481
- actQueue: null,
482
- asyncTransitions: 0,
483
- isBatchingLegacy: false,
484
- didScheduleLegacyUpdate: false,
485
- didUsePromise: false,
486
- thrownErrors: [],
487
- getCurrentStack: null,
488
- recentlyCreatedOwnerStacks: 0
489
- }, hasOwnProperty = Object.prototype.hasOwnProperty, createTask = console.createTask ? console.createTask : function() {
490
- return null;
491
- };
492
- deprecatedAPIs = {
493
- react_stack_bottom_frame: function(callStackForError) {
494
- return callStackForError();
495
- }
496
- };
497
- var specialPropKeyWarningShown, didWarnAboutOldJSXRuntime;
498
- var didWarnAboutElementRef = {};
499
- var unknownOwnerDebugStack = deprecatedAPIs.react_stack_bottom_frame.bind(deprecatedAPIs, UnknownOwner)();
500
- var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
501
- var didWarnAboutMaps = false, userProvidedKeyEscapeRegex = /\/+/g, reportGlobalError = typeof reportError === "function" ? reportError : function(error) {
502
- if (typeof window === "object" && typeof window.ErrorEvent === "function") {
503
- var event = new window.ErrorEvent("error", {
504
- bubbles: true,
505
- cancelable: true,
506
- message: typeof error === "object" && error !== null && typeof error.message === "string" ? String(error.message) : String(error),
507
- error
508
- });
509
- if (!window.dispatchEvent(event))
510
- return;
511
- } else if (typeof process === "object" && typeof process.emit === "function") {
512
- process.emit("uncaughtException", error);
513
- return;
514
- }
515
- console.error(error);
516
- }, didWarnAboutMessageChannel = false, enqueueTaskImpl = null, actScopeDepth = 0, didWarnNoAwaitAct = false, isFlushing = false, queueSeveralMicrotasks = typeof queueMicrotask === "function" ? function(callback) {
517
- queueMicrotask(function() {
518
- return queueMicrotask(callback);
519
- });
520
- } : enqueueTask;
521
- deprecatedAPIs = Object.freeze({
522
- __proto__: null,
523
- c: function(size) {
524
- return resolveDispatcher().useMemoCache(size);
525
- }
526
- });
527
- var fnName = {
528
- map: mapChildren,
529
- forEach: function(children, forEachFunc, forEachContext) {
530
- mapChildren(children, function() {
531
- forEachFunc.apply(this, arguments);
532
- }, forEachContext);
533
- },
534
- count: function(children) {
535
- var n = 0;
536
- mapChildren(children, function() {
537
- n++;
538
- });
539
- return n;
540
- },
541
- toArray: function(children) {
542
- return mapChildren(children, function(child) {
543
- return child;
544
- }) || [];
545
- },
546
- only: function(children) {
547
- if (!isValidElement(children))
548
- throw Error("React.Children.only expected to receive a single React element child.");
549
- return children;
550
- }
551
- };
552
- exports.Activity = REACT_ACTIVITY_TYPE;
553
- exports.Children = fnName;
554
- exports.Component = Component;
555
- exports.Fragment = REACT_FRAGMENT_TYPE;
556
- exports.Profiler = REACT_PROFILER_TYPE;
557
- exports.PureComponent = PureComponent;
558
- exports.StrictMode = REACT_STRICT_MODE_TYPE;
559
- exports.Suspense = REACT_SUSPENSE_TYPE;
560
- exports.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals;
561
- exports.__COMPILER_RUNTIME = deprecatedAPIs;
562
- exports.act = function(callback) {
563
- var prevActQueue = ReactSharedInternals.actQueue, prevActScopeDepth = actScopeDepth;
564
- actScopeDepth++;
565
- var queue = ReactSharedInternals.actQueue = prevActQueue !== null ? prevActQueue : [], didAwaitActCall = false;
566
- try {
567
- var result = callback();
568
- } catch (error) {
569
- ReactSharedInternals.thrownErrors.push(error);
570
- }
571
- if (0 < ReactSharedInternals.thrownErrors.length)
572
- throw popActScope(prevActQueue, prevActScopeDepth), callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
573
- if (result !== null && typeof result === "object" && typeof result.then === "function") {
574
- var thenable = result;
575
- queueSeveralMicrotasks(function() {
576
- didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"));
577
- });
578
- return {
579
- then: function(resolve, reject) {
580
- didAwaitActCall = true;
581
- thenable.then(function(returnValue) {
582
- popActScope(prevActQueue, prevActScopeDepth);
583
- if (prevActScopeDepth === 0) {
584
- try {
585
- flushActQueue(queue), enqueueTask(function() {
586
- return recursivelyFlushAsyncActWork(returnValue, resolve, reject);
587
- });
588
- } catch (error$0) {
589
- ReactSharedInternals.thrownErrors.push(error$0);
590
- }
591
- if (0 < ReactSharedInternals.thrownErrors.length) {
592
- var _thrownError = aggregateErrors(ReactSharedInternals.thrownErrors);
593
- ReactSharedInternals.thrownErrors.length = 0;
594
- reject(_thrownError);
595
- }
596
- } else
597
- resolve(returnValue);
598
- }, function(error) {
599
- popActScope(prevActQueue, prevActScopeDepth);
600
- 0 < ReactSharedInternals.thrownErrors.length ? (error = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(error)) : reject(error);
601
- });
602
- }
603
- };
604
- }
605
- var returnValue$jscomp$0 = result;
606
- popActScope(prevActQueue, prevActScopeDepth);
607
- prevActScopeDepth === 0 && (flushActQueue(queue), queue.length !== 0 && queueSeveralMicrotasks(function() {
608
- didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error("A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"));
609
- }), ReactSharedInternals.actQueue = null);
610
- if (0 < ReactSharedInternals.thrownErrors.length)
611
- throw callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
612
- return {
613
- then: function(resolve, reject) {
614
- didAwaitActCall = true;
615
- prevActScopeDepth === 0 ? (ReactSharedInternals.actQueue = queue, enqueueTask(function() {
616
- return recursivelyFlushAsyncActWork(returnValue$jscomp$0, resolve, reject);
617
- })) : resolve(returnValue$jscomp$0);
618
- }
619
- };
620
- };
621
- exports.cache = function(fn) {
622
- return function() {
623
- return fn.apply(null, arguments);
624
- };
625
- };
626
- exports.cacheSignal = function() {
627
- return null;
628
- };
629
- exports.captureOwnerStack = function() {
630
- var getCurrentStack = ReactSharedInternals.getCurrentStack;
631
- return getCurrentStack === null ? null : getCurrentStack();
632
- };
633
- exports.cloneElement = function(element, config, children) {
634
- if (element === null || element === undefined)
635
- throw Error("The argument must be a React element, but you passed " + element + ".");
636
- var props = assign({}, element.props), key = element.key, owner = element._owner;
637
- if (config != null) {
638
- var JSCompiler_inline_result;
639
- a: {
640
- if (hasOwnProperty.call(config, "ref") && (JSCompiler_inline_result = Object.getOwnPropertyDescriptor(config, "ref").get) && JSCompiler_inline_result.isReactWarning) {
641
- JSCompiler_inline_result = false;
642
- break a;
643
- }
644
- JSCompiler_inline_result = config.ref !== undefined;
645
- }
646
- JSCompiler_inline_result && (owner = getOwner());
647
- hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key);
648
- for (propName in config)
649
- !hasOwnProperty.call(config, propName) || propName === "key" || propName === "__self" || propName === "__source" || propName === "ref" && config.ref === undefined || (props[propName] = config[propName]);
650
- }
651
- var propName = arguments.length - 2;
652
- if (propName === 1)
653
- props.children = children;
654
- else if (1 < propName) {
655
- JSCompiler_inline_result = Array(propName);
656
- for (var i = 0;i < propName; i++)
657
- JSCompiler_inline_result[i] = arguments[i + 2];
658
- props.children = JSCompiler_inline_result;
659
- }
660
- props = ReactElement(element.type, key, props, owner, element._debugStack, element._debugTask);
661
- for (key = 2;key < arguments.length; key++)
662
- validateChildKeys(arguments[key]);
663
- return props;
664
- };
665
- exports.createContext = function(defaultValue) {
666
- defaultValue = {
667
- $$typeof: REACT_CONTEXT_TYPE,
668
- _currentValue: defaultValue,
669
- _currentValue2: defaultValue,
670
- _threadCount: 0,
671
- Provider: null,
672
- Consumer: null
673
- };
674
- defaultValue.Provider = defaultValue;
675
- defaultValue.Consumer = {
676
- $$typeof: REACT_CONSUMER_TYPE,
677
- _context: defaultValue
678
- };
679
- defaultValue._currentRenderer = null;
680
- defaultValue._currentRenderer2 = null;
681
- return defaultValue;
682
- };
683
- exports.createElement = function(type, config, children) {
684
- for (var i = 2;i < arguments.length; i++)
685
- validateChildKeys(arguments[i]);
686
- i = {};
687
- var key = null;
688
- if (config != null)
689
- for (propName in didWarnAboutOldJSXRuntime || !("__self" in config) || "key" in config || (didWarnAboutOldJSXRuntime = true, console.warn("Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform")), hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key), config)
690
- hasOwnProperty.call(config, propName) && propName !== "key" && propName !== "__self" && propName !== "__source" && (i[propName] = config[propName]);
691
- var childrenLength = arguments.length - 2;
692
- if (childrenLength === 1)
693
- i.children = children;
694
- else if (1 < childrenLength) {
695
- for (var childArray = Array(childrenLength), _i = 0;_i < childrenLength; _i++)
696
- childArray[_i] = arguments[_i + 2];
697
- Object.freeze && Object.freeze(childArray);
698
- i.children = childArray;
699
- }
700
- if (type && type.defaultProps)
701
- for (propName in childrenLength = type.defaultProps, childrenLength)
702
- i[propName] === undefined && (i[propName] = childrenLength[propName]);
703
- key && defineKeyPropWarningGetter(i, typeof type === "function" ? type.displayName || type.name || "Unknown" : type);
704
- var propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
705
- return ReactElement(type, key, i, getOwner(), propName ? Error("react-stack-top-frame") : unknownOwnerDebugStack, propName ? createTask(getTaskName(type)) : unknownOwnerDebugTask);
706
- };
707
- exports.createRef = function() {
708
- var refObject = { current: null };
709
- Object.seal(refObject);
710
- return refObject;
711
- };
712
- exports.forwardRef = function(render) {
713
- render != null && render.$$typeof === REACT_MEMO_TYPE ? console.error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...)).") : typeof render !== "function" ? console.error("forwardRef requires a render function but was given %s.", render === null ? "null" : typeof render) : render.length !== 0 && render.length !== 2 && console.error("forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined.");
714
- render != null && render.defaultProps != null && console.error("forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?");
715
- var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render }, ownName;
716
- Object.defineProperty(elementType, "displayName", {
717
- enumerable: false,
718
- configurable: true,
719
- get: function() {
720
- return ownName;
721
- },
722
- set: function(name) {
723
- ownName = name;
724
- render.name || render.displayName || (Object.defineProperty(render, "name", { value: name }), render.displayName = name);
725
- }
726
- });
727
- return elementType;
728
- };
729
- exports.isValidElement = isValidElement;
730
- exports.lazy = function(ctor) {
731
- ctor = { _status: -1, _result: ctor };
732
- var lazyType = {
733
- $$typeof: REACT_LAZY_TYPE,
734
- _payload: ctor,
735
- _init: lazyInitializer
736
- }, ioInfo = {
737
- name: "lazy",
738
- start: -1,
739
- end: -1,
740
- value: null,
741
- owner: null,
742
- debugStack: Error("react-stack-top-frame"),
743
- debugTask: console.createTask ? console.createTask("lazy()") : null
744
- };
745
- ctor._ioInfo = ioInfo;
746
- lazyType._debugInfo = [{ awaited: ioInfo }];
747
- return lazyType;
748
- };
749
- exports.memo = function(type, compare) {
750
- type == null && console.error("memo: The first argument must be a component. Instead received: %s", type === null ? "null" : typeof type);
751
- compare = {
752
- $$typeof: REACT_MEMO_TYPE,
753
- type,
754
- compare: compare === undefined ? null : compare
755
- };
756
- var ownName;
757
- Object.defineProperty(compare, "displayName", {
758
- enumerable: false,
759
- configurable: true,
760
- get: function() {
761
- return ownName;
762
- },
763
- set: function(name) {
764
- ownName = name;
765
- type.name || type.displayName || (Object.defineProperty(type, "name", { value: name }), type.displayName = name);
766
- }
767
- });
768
- return compare;
769
- };
770
- exports.startTransition = function(scope) {
771
- var prevTransition = ReactSharedInternals.T, currentTransition = {};
772
- currentTransition._updatedFibers = new Set;
773
- ReactSharedInternals.T = currentTransition;
774
- try {
775
- var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S;
776
- onStartTransitionFinish !== null && onStartTransitionFinish(currentTransition, returnValue);
777
- typeof returnValue === "object" && returnValue !== null && typeof returnValue.then === "function" && (ReactSharedInternals.asyncTransitions++, returnValue.then(releaseAsyncTransition, releaseAsyncTransition), returnValue.then(noop, reportGlobalError));
778
- } catch (error) {
779
- reportGlobalError(error);
780
- } finally {
781
- prevTransition === null && currentTransition._updatedFibers && (scope = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < scope && console.warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table.")), prevTransition !== null && currentTransition.types !== null && (prevTransition.types !== null && prevTransition.types !== currentTransition.types && console.error("We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."), prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition;
782
- }
783
- };
784
- exports.unstable_useCacheRefresh = function() {
785
- return resolveDispatcher().useCacheRefresh();
786
- };
787
- exports.use = function(usable) {
788
- return resolveDispatcher().use(usable);
789
- };
790
- exports.useActionState = function(action, initialState, permalink) {
791
- return resolveDispatcher().useActionState(action, initialState, permalink);
792
- };
793
- exports.useCallback = function(callback, deps) {
794
- return resolveDispatcher().useCallback(callback, deps);
795
- };
796
- exports.useContext = function(Context) {
797
- var dispatcher = resolveDispatcher();
798
- Context.$$typeof === REACT_CONSUMER_TYPE && console.error("Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?");
799
- return dispatcher.useContext(Context);
800
- };
801
- exports.useDebugValue = function(value, formatterFn) {
802
- return resolveDispatcher().useDebugValue(value, formatterFn);
803
- };
804
- exports.useDeferredValue = function(value, initialValue) {
805
- return resolveDispatcher().useDeferredValue(value, initialValue);
806
- };
807
- exports.useEffect = function(create, deps) {
808
- create == null && console.warn("React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?");
809
- return resolveDispatcher().useEffect(create, deps);
810
- };
811
- exports.useEffectEvent = function(callback) {
812
- return resolveDispatcher().useEffectEvent(callback);
813
- };
814
- exports.useId = function() {
815
- return resolveDispatcher().useId();
816
- };
817
- exports.useImperativeHandle = function(ref, create, deps) {
818
- return resolveDispatcher().useImperativeHandle(ref, create, deps);
819
- };
820
- exports.useInsertionEffect = function(create, deps) {
821
- create == null && console.warn("React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?");
822
- return resolveDispatcher().useInsertionEffect(create, deps);
823
- };
824
- exports.useLayoutEffect = function(create, deps) {
825
- create == null && console.warn("React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?");
826
- return resolveDispatcher().useLayoutEffect(create, deps);
827
- };
828
- exports.useMemo = function(create, deps) {
829
- return resolveDispatcher().useMemo(create, deps);
830
- };
831
- exports.useOptimistic = function(passthrough, reducer) {
832
- return resolveDispatcher().useOptimistic(passthrough, reducer);
833
- };
834
- exports.useReducer = function(reducer, initialArg, init) {
835
- return resolveDispatcher().useReducer(reducer, initialArg, init);
836
- };
837
- exports.useRef = function(initialValue) {
838
- return resolveDispatcher().useRef(initialValue);
839
- };
840
- exports.useState = function(initialState) {
841
- return resolveDispatcher().useState(initialState);
842
- };
843
- exports.useSyncExternalStore = function(subscribe, getSnapshot, getServerSnapshot) {
844
- return resolveDispatcher().useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
845
- };
846
- exports.useTransition = function() {
847
- return resolveDispatcher().useTransition();
848
- };
849
- exports.version = "19.2.3";
850
- typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function" && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
851
- })();
852
- });
853
-
854
- // ../../../../node_modules/.bun/react@19.2.3/node_modules/react/index.js
855
- var require_react = __commonJS((exports, module) => {
856
- var react_development = __toESM(require_react_development());
857
- if (false) {} else {
858
- module.exports = react_development;
859
- }
860
- });
861
-
862
- // ../../../../node_modules/.bun/react@19.2.3/node_modules/react/cjs/react-jsx-dev-runtime.development.js
863
- var require_react_jsx_dev_runtime_development = __commonJS((exports) => {
864
- var React = __toESM(require_react());
865
- (function() {
866
- function getComponentNameFromType(type) {
867
- if (type == null)
868
- return null;
869
- if (typeof type === "function")
870
- return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
871
- if (typeof type === "string")
872
- return type;
873
- switch (type) {
874
- case REACT_FRAGMENT_TYPE:
875
- return "Fragment";
876
- case REACT_PROFILER_TYPE:
877
- return "Profiler";
878
- case REACT_STRICT_MODE_TYPE:
879
- return "StrictMode";
880
- case REACT_SUSPENSE_TYPE:
881
- return "Suspense";
882
- case REACT_SUSPENSE_LIST_TYPE:
883
- return "SuspenseList";
884
- case REACT_ACTIVITY_TYPE:
885
- return "Activity";
886
- }
887
- if (typeof type === "object")
888
- switch (typeof type.tag === "number" && console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."), type.$$typeof) {
889
- case REACT_PORTAL_TYPE:
890
- return "Portal";
891
- case REACT_CONTEXT_TYPE:
892
- return type.displayName || "Context";
893
- case REACT_CONSUMER_TYPE:
894
- return (type._context.displayName || "Context") + ".Consumer";
895
- case REACT_FORWARD_REF_TYPE:
896
- var innerType = type.render;
897
- type = type.displayName;
898
- type || (type = innerType.displayName || innerType.name || "", type = type !== "" ? "ForwardRef(" + type + ")" : "ForwardRef");
899
- return type;
900
- case REACT_MEMO_TYPE:
901
- return innerType = type.displayName || null, innerType !== null ? innerType : getComponentNameFromType(type.type) || "Memo";
902
- case REACT_LAZY_TYPE:
903
- innerType = type._payload;
904
- type = type._init;
905
- try {
906
- return getComponentNameFromType(type(innerType));
907
- } catch (x) {}
908
- }
909
- return null;
910
- }
911
- function testStringCoercion(value) {
912
- return "" + value;
913
- }
914
- function checkKeyStringCoercion(value) {
915
- try {
916
- testStringCoercion(value);
917
- var JSCompiler_inline_result = false;
918
- } catch (e) {
919
- JSCompiler_inline_result = true;
920
- }
921
- if (JSCompiler_inline_result) {
922
- JSCompiler_inline_result = console;
923
- var JSCompiler_temp_const = JSCompiler_inline_result.error;
924
- var JSCompiler_inline_result$jscomp$0 = typeof Symbol === "function" && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
925
- JSCompiler_temp_const.call(JSCompiler_inline_result, "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", JSCompiler_inline_result$jscomp$0);
926
- return testStringCoercion(value);
927
- }
928
- }
929
- function getTaskName(type) {
930
- if (type === REACT_FRAGMENT_TYPE)
931
- return "<>";
932
- if (typeof type === "object" && type !== null && type.$$typeof === REACT_LAZY_TYPE)
933
- return "<...>";
934
- try {
935
- var name = getComponentNameFromType(type);
936
- return name ? "<" + name + ">" : "<...>";
937
- } catch (x) {
938
- return "<...>";
939
- }
940
- }
941
- function getOwner() {
942
- var dispatcher = ReactSharedInternals.A;
943
- return dispatcher === null ? null : dispatcher.getOwner();
944
- }
945
- function UnknownOwner() {
946
- return Error("react-stack-top-frame");
947
- }
948
- function hasValidKey(config) {
949
- if (hasOwnProperty.call(config, "key")) {
950
- var getter = Object.getOwnPropertyDescriptor(config, "key").get;
951
- if (getter && getter.isReactWarning)
952
- return false;
953
- }
954
- return config.key !== undefined;
955
- }
956
- function defineKeyPropWarningGetter(props, displayName) {
957
- function warnAboutAccessingKey() {
958
- specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", displayName));
959
- }
960
- warnAboutAccessingKey.isReactWarning = true;
961
- Object.defineProperty(props, "key", {
962
- get: warnAboutAccessingKey,
963
- configurable: true
964
- });
965
- }
966
- function elementRefGetterWithDeprecationWarning() {
967
- var componentName = getComponentNameFromType(this.type);
968
- didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."));
969
- componentName = this.props.ref;
970
- return componentName !== undefined ? componentName : null;
971
- }
972
- function ReactElement(type, key, props, owner, debugStack, debugTask) {
973
- var refProp = props.ref;
974
- type = {
975
- $$typeof: REACT_ELEMENT_TYPE,
976
- type,
977
- key,
978
- props,
979
- _owner: owner
980
- };
981
- (refProp !== undefined ? refProp : null) !== null ? Object.defineProperty(type, "ref", {
982
- enumerable: false,
983
- get: elementRefGetterWithDeprecationWarning
984
- }) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
985
- type._store = {};
986
- Object.defineProperty(type._store, "validated", {
987
- configurable: false,
988
- enumerable: false,
989
- writable: true,
990
- value: 0
991
- });
992
- Object.defineProperty(type, "_debugInfo", {
993
- configurable: false,
994
- enumerable: false,
995
- writable: true,
996
- value: null
997
- });
998
- Object.defineProperty(type, "_debugStack", {
999
- configurable: false,
1000
- enumerable: false,
1001
- writable: true,
1002
- value: debugStack
1003
- });
1004
- Object.defineProperty(type, "_debugTask", {
1005
- configurable: false,
1006
- enumerable: false,
1007
- writable: true,
1008
- value: debugTask
1009
- });
1010
- Object.freeze && (Object.freeze(type.props), Object.freeze(type));
1011
- return type;
1012
- }
1013
- function jsxDEVImpl(type, config, maybeKey, isStaticChildren, debugStack, debugTask) {
1014
- var children = config.children;
1015
- if (children !== undefined)
1016
- if (isStaticChildren)
1017
- if (isArrayImpl(children)) {
1018
- for (isStaticChildren = 0;isStaticChildren < children.length; isStaticChildren++)
1019
- validateChildKeys(children[isStaticChildren]);
1020
- Object.freeze && Object.freeze(children);
1021
- } else
1022
- console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");
1023
- else
1024
- validateChildKeys(children);
1025
- if (hasOwnProperty.call(config, "key")) {
1026
- children = getComponentNameFromType(type);
1027
- var keys = Object.keys(config).filter(function(k) {
1028
- return k !== "key";
1029
- });
1030
- isStaticChildren = 0 < keys.length ? "{key: someKey, " + keys.join(": ..., ") + ": ...}" : "{key: someKey}";
1031
- didWarnAboutKeySpread[children + isStaticChildren] || (keys = 0 < keys.length ? "{" + keys.join(": ..., ") + ": ...}" : "{}", console.error(`A props object containing a "key" prop is being spread into JSX:
1032
- let props = %s;
1033
- <%s {...props} />
1034
- React keys must be passed directly to JSX without using spread:
1035
- let props = %s;
1036
- <%s key={someKey} {...props} />`, isStaticChildren, children, keys, children), didWarnAboutKeySpread[children + isStaticChildren] = true);
1037
- }
1038
- children = null;
1039
- maybeKey !== undefined && (checkKeyStringCoercion(maybeKey), children = "" + maybeKey);
1040
- hasValidKey(config) && (checkKeyStringCoercion(config.key), children = "" + config.key);
1041
- if ("key" in config) {
1042
- maybeKey = {};
1043
- for (var propName in config)
1044
- propName !== "key" && (maybeKey[propName] = config[propName]);
1045
- } else
1046
- maybeKey = config;
1047
- children && defineKeyPropWarningGetter(maybeKey, typeof type === "function" ? type.displayName || type.name || "Unknown" : type);
1048
- return ReactElement(type, children, maybeKey, getOwner(), debugStack, debugTask);
1049
- }
1050
- function validateChildKeys(node) {
1051
- isValidElement(node) ? node._store && (node._store.validated = 1) : typeof node === "object" && node !== null && node.$$typeof === REACT_LAZY_TYPE && (node._payload.status === "fulfilled" ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1));
1052
- }
1053
- function isValidElement(object) {
1054
- return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
1055
- }
1056
- var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), ReactSharedInternals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, hasOwnProperty = Object.prototype.hasOwnProperty, isArrayImpl = Array.isArray, createTask = console.createTask ? console.createTask : function() {
1057
- return null;
1058
- };
1059
- React = {
1060
- react_stack_bottom_frame: function(callStackForError) {
1061
- return callStackForError();
1062
- }
1063
- };
1064
- var specialPropKeyWarningShown;
1065
- var didWarnAboutElementRef = {};
1066
- var unknownOwnerDebugStack = React.react_stack_bottom_frame.bind(React, UnknownOwner)();
1067
- var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
1068
- var didWarnAboutKeySpread = {};
1069
- exports.Fragment = REACT_FRAGMENT_TYPE;
1070
- exports.jsxDEV = function(type, config, maybeKey, isStaticChildren) {
1071
- var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
1072
- return jsxDEVImpl(type, config, maybeKey, isStaticChildren, trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack, trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask);
1073
- };
1074
- })();
1075
- });
1076
-
1077
- // ../../../../node_modules/.bun/react@19.2.3/node_modules/react/jsx-dev-runtime.js
1078
- var require_jsx_dev_runtime = __commonJS((exports, module) => {
1079
- var react_jsx_dev_runtime_development = __toESM(require_react_jsx_dev_runtime_development());
1080
- if (false) {} else {
1081
- module.exports = react_jsx_dev_runtime_development;
1082
- }
1083
- });
1084
-
1085
- // src/router/types.ts
1086
- var DEFAULT_ROUTER_CONFIG = {
1087
- adapter: "heuristic",
1088
- speculation: {
1089
- enabled: true,
1090
- depth: 2,
1091
- prerenderTop: 1,
1092
- maxPrefetch: 5
1093
- },
1094
- personalization: {
1095
- featureGating: true,
1096
- emotionTheming: true,
1097
- componentOrdering: true,
1098
- densityAdaptation: true
1099
- }
1100
- };
1101
- var DEFAULT_ESI_CONFIG = {
1102
- enabled: false,
1103
- endpoint: process.env.ESI_ENDPOINT || "",
1104
- timeout: 5000,
1105
- defaultCacheTtl: 300,
1106
- maxConcurrent: 5,
1107
- warmupModels: ["llm"],
1108
- tierLimits: {
1109
- free: {
1110
- maxInferencesPerRequest: 2,
1111
- allowedModels: ["llm", "embed"],
1112
- maxTokens: 500
1113
- },
1114
- starter: {
1115
- maxInferencesPerRequest: 5,
1116
- allowedModels: ["llm", "embed", "classify"],
1117
- maxTokens: 1000
1118
- },
1119
- pro: {
1120
- maxInferencesPerRequest: 20,
1121
- allowedModels: ["llm", "embed", "classify", "vision", "tts"],
1122
- maxTokens: 4000
1123
- },
1124
- enterprise: {
1125
- maxInferencesPerRequest: 100,
1126
- allowedModels: ["llm", "embed", "classify", "vision", "tts", "stt", "custom"],
1127
- maxTokens: 32000
1128
- }
1129
- }
1130
- };
1131
- // src/router/esi-cyrano.ts
1132
- function esiContext(context, options = {}) {
1133
- const { emitExhaust = true, id } = options;
1134
- return {
1135
- id: id || `esi-context-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
1136
- params: {
1137
- model: "custom",
1138
- custom: {
1139
- type: "context-drop",
1140
- emitExhaust
1141
- }
1142
- },
1143
- content: {
1144
- type: "json",
1145
- value: JSON.stringify(context)
1146
- },
1147
- contextAware: true,
1148
- signals: ["emotion", "preferences", "history", "time", "device"]
1149
- };
1150
- }
1151
- function esiCyrano(config, options = {}) {
1152
- const {
1153
- intent,
1154
- tone = "warm",
1155
- trigger = "always",
1156
- fallback,
1157
- suggestTool,
1158
- suggestRoute,
1159
- autoAcceptNavigation = false,
1160
- priority = 1,
1161
- maxTriggersPerSession,
1162
- cooldownSeconds,
1163
- speak = false,
1164
- showCaption = true,
1165
- requiredTier
1166
- } = config;
1167
- const systemPrompt = buildCyranoSystemPrompt(intent, tone);
1168
- return {
1169
- id: `esi-cyrano-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
1170
- params: {
1171
- model: "llm",
1172
- system: systemPrompt,
1173
- temperature: 0.7,
1174
- maxTokens: 150,
1175
- fallback,
1176
- custom: {
1177
- type: "cyrano-whisper",
1178
- intent,
1179
- tone,
1180
- trigger,
1181
- suggestTool,
1182
- suggestRoute,
1183
- autoAcceptNavigation,
1184
- priority,
1185
- maxTriggersPerSession,
1186
- cooldownSeconds,
1187
- speak,
1188
- showCaption
1189
- },
1190
- ...options
1191
- },
1192
- content: {
1193
- type: "template",
1194
- value: buildCyranoPrompt(intent, trigger),
1195
- variables: {
1196
- intent,
1197
- tone,
1198
- trigger
1199
- }
1200
- },
1201
- contextAware: true,
1202
- signals: ["emotion", "preferences", "history", "time"],
1203
- requiredTier
1204
- };
1205
- }
1206
- function buildCyranoSystemPrompt(intent, tone) {
1207
- const toneGuide = {
1208
- warm: "Be warm, caring, and approachable. Use gentle language.",
1209
- calm: "Be calm, measured, and reassuring. Use a steady pace.",
1210
- encouraging: "Be supportive and uplifting. Celebrate small wins.",
1211
- playful: "Be light-hearted and fun. Use appropriate humor.",
1212
- professional: "Be clear and direct. Maintain professionalism.",
1213
- empathetic: "Show deep understanding. Validate feelings.",
1214
- neutral: "Be balanced and objective. Provide information."
1215
- };
1216
- const intentGuide = {
1217
- greeting: "Welcome the user. Make them feel at home.",
1218
- "proactive-check-in": "Check in gently. Ask how they are doing.",
1219
- "supportive-presence": "Simply acknowledge. Let them know you are here.",
1220
- "gentle-nudge": "Suggest an action softly. No pressure.",
1221
- "tool-suggestion": "Recommend a tool that might help.",
1222
- "navigation-hint": "Suggest exploring another area.",
1223
- intervention: "Step in supportively. Offer help.",
1224
- celebration: "Celebrate their progress. Be genuinely happy for them.",
1225
- reflection: "Invite them to reflect. Ask thoughtful questions.",
1226
- guidance: "Offer helpful guidance. Be a trusted advisor.",
1227
- farewell: "Wish them well. Leave the door open.",
1228
- custom: "Respond appropriately to the context."
1229
- };
1230
- return `You are Cyrano, an ambient AI companion. ${toneGuide[tone]} ${intentGuide[intent]}
1231
-
1232
- Keep responses brief (1-2 sentences). Be natural and conversational.
1233
- Never start with "I" - use "You" or the situation as the subject.
1234
- Never say "As an AI" or similar phrases.
1235
- Respond to the emotional context provided.`;
1236
- }
1237
- function buildCyranoPrompt(intent, trigger) {
1238
- const prompts = {
1239
- greeting: "Generate a warm greeting based on the time of day and user context.",
1240
- "proactive-check-in": "Check in with the user based on their emotional state and behavior.",
1241
- "supportive-presence": "Acknowledge the user's presence and current activity.",
1242
- "gentle-nudge": "Gently suggest the user might benefit from a particular action.",
1243
- "tool-suggestion": "Suggest a specific tool that could help with the user's current state.",
1244
- "navigation-hint": "Suggest the user might want to explore a different area.",
1245
- intervention: "Offer supportive intervention based on detected stress or difficulty.",
1246
- celebration: "Celebrate the user's progress or achievement.",
1247
- reflection: "Invite the user to reflect on their current experience.",
1248
- guidance: "Offer helpful guidance for the user's current situation.",
1249
- farewell: "Say goodbye warmly, acknowledging the session.",
1250
- custom: "Respond appropriately to the context provided."
1251
- };
1252
- let prompt = prompts[intent] || prompts.custom;
1253
- if (trigger !== "always" && trigger !== "never") {
1254
- prompt += ` The trigger condition is: ${trigger}.`;
1255
- }
1256
- return prompt;
1257
- }
1258
- function esiHalo(config, options = {}) {
1259
- const {
1260
- observe,
1261
- window: window2 = "session",
1262
- action = "whisper-to-cyrano",
1263
- sensitivity = 0.5,
1264
- crisisLevel = false,
1265
- parameters = {}
1266
- } = config;
1267
- return {
1268
- id: `esi-halo-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
1269
- params: {
1270
- model: "custom",
1271
- custom: {
1272
- type: "halo-insight",
1273
- observe,
1274
- window: window2,
1275
- action,
1276
- sensitivity,
1277
- crisisLevel,
1278
- parameters
1279
- },
1280
- ...options
1281
- },
1282
- content: {
1283
- type: "json",
1284
- value: JSON.stringify({
1285
- observation: observe,
1286
- window: window2,
1287
- action,
1288
- sensitivity,
1289
- crisisLevel
1290
- })
1291
- },
1292
- contextAware: true,
1293
- signals: ["emotion", "history", "time"]
1294
- };
1295
- }
1296
- function evaluateTrigger(trigger, context, sessionContext) {
1297
- if (trigger === "always")
1298
- return true;
1299
- if (trigger === "never")
1300
- return false;
1301
- const [type, condition] = trigger.split(":");
1302
- switch (type) {
1303
- case "dwell": {
1304
- const match = condition?.match(/>(\d+)s/);
1305
- if (!match)
1306
- return false;
1307
- const threshold = parseInt(match[1], 10) * 1000;
1308
- const dwellTime = sessionContext?.behavior?.dwellTime || 0;
1309
- return dwellTime > threshold;
1310
- }
1311
- case "scroll": {
1312
- const match = condition?.match(/>(\d+\.?\d*)/);
1313
- if (!match)
1314
- return false;
1315
- const threshold = parseFloat(match[1]);
1316
- const scrollDepth = sessionContext?.behavior?.scrollDepth || 0;
1317
- return scrollDepth > threshold;
1318
- }
1319
- case "emotion": {
1320
- const targetEmotion = condition;
1321
- return sessionContext?.emotion?.primary === targetEmotion || context.emotionState?.primary === targetEmotion;
1322
- }
1323
- case "behavior": {
1324
- if (condition === "aimless") {
1325
- return sessionContext?.behavior?.isAimlessClicking === true;
1326
- }
1327
- if (condition === "hesitation") {
1328
- return sessionContext?.behavior?.hesitationDetected === true;
1329
- }
1330
- return false;
1331
- }
1332
- case "hrv": {
1333
- const match = condition?.match(/<(\d+)/);
1334
- if (!match)
1335
- return false;
1336
- const threshold = parseInt(match[1], 10);
1337
- const hrv = sessionContext?.biometric?.hrv || 100;
1338
- return hrv < threshold;
1339
- }
1340
- case "stress": {
1341
- const match = condition?.match(/>(\d+)/);
1342
- if (!match)
1343
- return false;
1344
- const threshold = parseInt(match[1], 10);
1345
- const stress = sessionContext?.biometric?.stressScore || 0;
1346
- return stress > threshold;
1347
- }
1348
- case "session": {
1349
- if (condition === "start") {
1350
- return context.isNewSession;
1351
- }
1352
- const idleMatch = condition?.match(/idle:(\d+)m/);
1353
- if (idleMatch) {
1354
- return false;
1355
- }
1356
- return false;
1357
- }
1358
- case "navigation": {
1359
- const targetRoute = condition?.replace("to:", "");
1360
- return sessionContext?.currentRoute === targetRoute;
1361
- }
1362
- case "time": {
1363
- const hour = context.localHour;
1364
- if (condition === "morning")
1365
- return hour >= 6 && hour < 12;
1366
- if (condition === "afternoon")
1367
- return hour >= 12 && hour < 18;
1368
- if (condition === "evening")
1369
- return hour >= 18 && hour < 22;
1370
- if (condition === "night")
1371
- return hour >= 22 || hour < 6;
1372
- return false;
1373
- }
1374
- default:
1375
- return false;
1376
- }
1377
- }
1378
- function createExhaustEntry(directive, result, type) {
1379
- return {
1380
- type,
1381
- timestamp: Date.now(),
1382
- content: {
1383
- directiveId: directive.id,
1384
- output: result.output,
1385
- model: result.model,
1386
- success: result.success,
1387
- latencyMs: result.latencyMs
1388
- },
1389
- visible: type === "cyrano" || type === "user",
1390
- source: directive.params.model
1391
- };
1392
- }
1393
- var CYRANO_TOOL_SUGGESTIONS = {
1394
- breathing: {
1395
- triggers: ["stress:>70", "hrv:<40", "emotion:anxious"],
1396
- tool: "breathing/4-7-8",
1397
- reason: "You seem stressed - a breathing exercise might help"
1398
- },
1399
- grounding: {
1400
- triggers: ["emotion:overwhelmed", "behavior:aimless"],
1401
- tool: "grounding/5-4-3-2-1",
1402
- reason: "A grounding exercise can help center you"
1403
- },
1404
- journaling: {
1405
- triggers: ["dwell:>120s", "emotion:reflective"],
1406
- tool: "journaling/freeform",
1407
- reason: "Would you like to write about what's on your mind?"
1408
- },
1409
- insights: {
1410
- triggers: ["navigation:to:/insights", "dwell:>60s"],
1411
- tool: "insights/dashboard",
1412
- reason: "Your recent patterns are ready to explore"
1413
- }
1414
- };
1415
- function getToolSuggestions(context, sessionContext) {
1416
- const suggestions = [];
1417
- for (const [, config] of Object.entries(CYRANO_TOOL_SUGGESTIONS)) {
1418
- for (const trigger of config.triggers) {
1419
- if (evaluateTrigger(trigger, context, sessionContext)) {
1420
- suggestions.push({
1421
- tool: config.tool,
1422
- reason: config.reason,
1423
- priority: trigger.startsWith("stress") || trigger.startsWith("hrv") ? 2 : 1
1424
- });
1425
- break;
1426
- }
1427
- }
1428
- }
1429
- return suggestions.sort((a, b) => b.priority - a.priority);
1430
- }
1431
-
1432
- // src/router/esi.ts
1433
- var esiCache = new Map;
1434
- function getCacheKey(directive, context) {
1435
- const contextParts = directive.contextAware ? [
1436
- context.tier,
1437
- context.emotionState?.primary,
1438
- context.localHour
1439
- ].join(":") : "";
1440
- return directive.cacheKey || `esi:${directive.params.model}:${directive.content.value}:${contextParts}`;
1441
- }
1442
- function getCached(key) {
1443
- const entry = esiCache.get(key);
1444
- if (!entry)
1445
- return null;
1446
- if (Date.now() > entry.expiresAt) {
1447
- esiCache.delete(key);
1448
- return null;
1449
- }
1450
- return { ...entry.result, cached: true };
1451
- }
1452
- function setCache(key, result, ttl) {
1453
- if (ttl <= 0)
1454
- return;
1455
- esiCache.set(key, {
1456
- result,
1457
- expiresAt: Date.now() + ttl * 1000
1458
- });
1459
- }
1460
- function interpolatePrompt(content, context, signals = []) {
1461
- let prompt = content.value;
1462
- if (content.type === "template" && content.variables) {
1463
- for (const [key, value] of Object.entries(content.variables)) {
1464
- prompt = prompt.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), String(value));
1465
- }
1466
- }
1467
- if (signals.length > 0) {
1468
- const contextParts = [];
1469
- if (signals.includes("emotion") && context.emotionState) {
1470
- contextParts.push(`User emotion: ${context.emotionState.primary} ` + `(valence: ${context.emotionState.valence.toFixed(2)}, ` + `arousal: ${context.emotionState.arousal.toFixed(2)})`);
1471
- }
1472
- if (signals.includes("preferences") && Object.keys(context.preferences).length > 0) {
1473
- contextParts.push(`User preferences: ${JSON.stringify(context.preferences)}`);
1474
- }
1475
- if (signals.includes("history") && context.recentPages.length > 0) {
1476
- contextParts.push(`Recent pages: ${context.recentPages.slice(-5).join(", ")}`);
1477
- }
1478
- if (signals.includes("time")) {
1479
- contextParts.push(`Local time: ${context.localHour}:00, Timezone: ${context.timezone}`);
1480
- }
1481
- if (signals.includes("device")) {
1482
- contextParts.push(`Device: ${context.viewport.width}x${context.viewport.height}, ` + `Connection: ${context.connection}`);
1483
- }
1484
- if (contextParts.length > 0) {
1485
- prompt = `[Context]
1486
- ${contextParts.join(`
1487
- `)}
1488
-
1489
- [Task]
1490
- ${prompt}`;
1491
- }
1492
- }
1493
- return prompt;
1494
- }
1495
- function checkTierAccess(directive, context, config) {
1496
- const tierLimits = config.tierLimits?.[context.tier];
1497
- if (!tierLimits) {
1498
- return { allowed: true };
1499
- }
1500
- if (!tierLimits.allowedModels.includes(directive.params.model)) {
1501
- return {
1502
- allowed: false,
1503
- reason: `Model '${directive.params.model}' not available for ${context.tier} tier`
1504
- };
1505
- }
1506
- if (directive.params.maxTokens && directive.params.maxTokens > tierLimits.maxTokens) {
1507
- return {
1508
- allowed: false,
1509
- reason: `Token limit ${directive.params.maxTokens} exceeds ${context.tier} tier max of ${tierLimits.maxTokens}`
1510
- };
1511
- }
1512
- return { allowed: true };
1513
- }
1514
-
1515
- class EdgeWorkersESIProcessor {
1516
- name = "edge-workers";
1517
- config;
1518
- warmupPromise;
1519
- constructor(config = {}) {
1520
- this.config = {
1521
- enabled: config.enabled ?? false,
1522
- endpoint: config.endpoint || process.env.ESI_ENDPOINT || "",
1523
- timeout: config.timeout ?? 5000,
1524
- defaultCacheTtl: config.defaultCacheTtl ?? 300,
1525
- maxConcurrent: config.maxConcurrent ?? 5,
1526
- warmupModels: config.warmupModels,
1527
- tierLimits: config.tierLimits
1528
- };
1529
- }
1530
- async warmup() {
1531
- if (this.warmupPromise)
1532
- return this.warmupPromise;
1533
- this.warmupPromise = (async () => {
1534
- if (!this.config.warmupModels?.length)
1535
- return;
1536
- await Promise.all(this.config.warmupModels.map((model) => fetch(`${this.config.endpoint}/api/warmup`, {
1537
- method: "POST",
1538
- headers: { "Content-Type": "application/json" },
1539
- body: JSON.stringify({ model })
1540
- }).catch(() => {})));
1541
- })();
1542
- return this.warmupPromise;
1543
- }
1544
- isModelAvailable(model) {
1545
- return ["llm", "embed", "vision", "tts", "stt", "emotion", "classify", "custom"].includes(model);
1546
- }
1547
- async process(directive, context) {
1548
- const startTime = Date.now();
1549
- const cacheKey = getCacheKey(directive, context);
1550
- const cached = getCached(cacheKey);
1551
- if (cached) {
1552
- return cached;
1553
- }
1554
- const access = checkTierAccess(directive, context, this.config);
1555
- if (!access.allowed) {
1556
- return {
1557
- id: directive.id,
1558
- success: false,
1559
- error: access.reason,
1560
- latencyMs: Date.now() - startTime,
1561
- cached: false,
1562
- model: directive.params.model
1563
- };
1564
- }
1565
- const prompt = directive.contextAware ? interpolatePrompt(directive.content, context, directive.signals) : directive.content.value;
1566
- try {
1567
- const result = await this.callEdgeWorkers(directive, prompt);
1568
- const cacheTtl = directive.params.cacheTtl ?? this.config.defaultCacheTtl;
1569
- setCache(cacheKey, result, cacheTtl);
1570
- return {
1571
- ...result,
1572
- latencyMs: Date.now() - startTime
1573
- };
1574
- } catch (error) {
1575
- if (directive.params.fallback) {
1576
- return {
1577
- id: directive.id,
1578
- success: true,
1579
- output: directive.params.fallback,
1580
- latencyMs: Date.now() - startTime,
1581
- cached: false,
1582
- model: directive.params.model
1583
- };
1584
- }
1585
- return {
1586
- id: directive.id,
1587
- success: false,
1588
- error: error instanceof Error ? error.message : "Unknown error",
1589
- latencyMs: Date.now() - startTime,
1590
- cached: false,
1591
- model: directive.params.model
1592
- };
1593
- }
1594
- }
1595
- async processBatch(directives, context) {
1596
- const semaphore = new Semaphore(this.config.maxConcurrent);
1597
- return Promise.all(directives.map(async (directive) => {
1598
- await semaphore.acquire();
1599
- try {
1600
- return await this.process(directive, context);
1601
- } finally {
1602
- semaphore.release();
1603
- }
1604
- }));
1605
- }
1606
- async stream(directive, context, onChunk) {
1607
- const startTime = Date.now();
1608
- const access = checkTierAccess(directive, context, this.config);
1609
- if (!access.allowed) {
1610
- return {
1611
- id: directive.id,
1612
- success: false,
1613
- error: access.reason,
1614
- latencyMs: Date.now() - startTime,
1615
- cached: false,
1616
- model: directive.params.model
1617
- };
1618
- }
1619
- const prompt = directive.contextAware ? interpolatePrompt(directive.content, context, directive.signals) : directive.content.value;
1620
- try {
1621
- const response = await fetch(`${this.config.endpoint}/api/llm/stream`, {
1622
- method: "POST",
1623
- headers: { "Content-Type": "application/json" },
1624
- body: JSON.stringify({
1625
- input: prompt,
1626
- model: directive.params.variant,
1627
- options: {
1628
- temperature: directive.params.temperature,
1629
- max_tokens: directive.params.maxTokens,
1630
- stop: directive.params.stop,
1631
- top_p: directive.params.topP,
1632
- system: directive.params.system
1633
- }
1634
- }),
1635
- signal: AbortSignal.timeout(directive.params.timeout ?? this.config.timeout)
1636
- });
1637
- if (!response.ok) {
1638
- throw new Error(`Stream failed: ${response.status}`);
1639
- }
1640
- const reader = response.body?.getReader();
1641
- if (!reader) {
1642
- throw new Error("No response body");
1643
- }
1644
- const decoder = new TextDecoder;
1645
- let fullOutput = "";
1646
- while (true) {
1647
- const { done, value } = await reader.read();
1648
- if (done)
1649
- break;
1650
- const chunk = decoder.decode(value);
1651
- fullOutput += chunk;
1652
- onChunk(chunk);
1653
- }
1654
- return {
1655
- id: directive.id,
1656
- success: true,
1657
- output: fullOutput,
1658
- latencyMs: Date.now() - startTime,
1659
- cached: false,
1660
- model: directive.params.variant || directive.params.model
1661
- };
1662
- } catch (error) {
1663
- if (directive.params.fallback) {
1664
- onChunk(directive.params.fallback);
1665
- return {
1666
- id: directive.id,
1667
- success: true,
1668
- output: directive.params.fallback,
1669
- latencyMs: Date.now() - startTime,
1670
- cached: false,
1671
- model: directive.params.model
1672
- };
1673
- }
1674
- return {
1675
- id: directive.id,
1676
- success: false,
1677
- error: error instanceof Error ? error.message : "Stream failed",
1678
- latencyMs: Date.now() - startTime,
1679
- cached: false,
1680
- model: directive.params.model
1681
- };
1682
- }
1683
- }
1684
- async callEdgeWorkers(directive, prompt) {
1685
- const endpoint = this.getEndpointForModel(directive.params.model);
1686
- const response = await fetch(`${this.config.endpoint}${endpoint}`, {
1687
- method: "POST",
1688
- headers: { "Content-Type": "application/json" },
1689
- body: JSON.stringify(this.buildRequestBody(directive, prompt)),
1690
- signal: AbortSignal.timeout(directive.params.timeout ?? this.config.timeout)
1691
- });
1692
- if (!response.ok) {
1693
- const error = await response.text();
1694
- throw new Error(`ESI inference failed: ${response.status} - ${error}`);
1695
- }
1696
- const data = await response.json();
1697
- return this.parseResponse(directive, data);
1698
- }
1699
- getEndpointForModel(model) {
1700
- switch (model) {
1701
- case "llm":
1702
- return "/api/llm/infer";
1703
- case "embed":
1704
- return "/api/embed";
1705
- case "vision":
1706
- return "/api/vision";
1707
- case "tts":
1708
- return "/api/tts";
1709
- case "stt":
1710
- return "/api/stt";
1711
- case "emotion":
1712
- return "/api/emotion";
1713
- case "classify":
1714
- return "/api/classify";
1715
- case "custom":
1716
- return "/api/custom";
1717
- default:
1718
- return "/api/llm/infer";
1719
- }
1720
- }
1721
- buildRequestBody(directive, prompt) {
1722
- const { params, content } = directive;
1723
- const body = {
1724
- input: content.type === "base64" ? content.value : prompt,
1725
- model: params.variant
1726
- };
1727
- if (params.model === "llm") {
1728
- body.options = {
1729
- temperature: params.temperature,
1730
- max_tokens: params.maxTokens,
1731
- stop: params.stop,
1732
- top_p: params.topP,
1733
- frequency_penalty: params.frequencyPenalty,
1734
- presence_penalty: params.presencePenalty,
1735
- system: params.system
1736
- };
1737
- }
1738
- if (params.custom) {
1739
- body.custom = params.custom;
1740
- }
1741
- return body;
1742
- }
1743
- parseResponse(directive, data) {
1744
- const base = {
1745
- id: directive.id,
1746
- success: true,
1747
- latencyMs: 0,
1748
- cached: false,
1749
- model: String(data.model || directive.params.model)
1750
- };
1751
- switch (directive.params.model) {
1752
- case "embed":
1753
- return { ...base, embedding: data.embedding };
1754
- case "tts":
1755
- return { ...base, audio: data.audio };
1756
- default:
1757
- return {
1758
- ...base,
1759
- output: String(data.output || data.text || data.result || ""),
1760
- tokens: data.tokens
1761
- };
1762
- }
1763
- }
1764
- }
1765
-
1766
- class Semaphore {
1767
- permits;
1768
- queue = [];
1769
- constructor(permits) {
1770
- this.permits = permits;
1771
- }
1772
- async acquire() {
1773
- if (this.permits > 0) {
1774
- this.permits--;
1775
- return;
1776
- }
1777
- return new Promise((resolve) => {
1778
- this.queue.push(resolve);
1779
- });
1780
- }
1781
- release() {
1782
- const next = this.queue.shift();
1783
- if (next) {
1784
- next();
1785
- } else {
1786
- this.permits++;
1787
- }
1788
- }
1789
- }
1790
- function esiInfer(prompt, options = {}) {
1791
- return {
1792
- id: `esi-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
1793
- params: {
1794
- model: "llm",
1795
- ...options
1796
- },
1797
- content: {
1798
- type: "text",
1799
- value: prompt
1800
- },
1801
- contextAware: options.system?.includes("{context}")
1802
- };
1803
- }
1804
- function esiEmbed(text) {
1805
- return {
1806
- id: `esi-embed-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
1807
- params: { model: "embed" },
1808
- content: { type: "text", value: text }
1809
- };
1810
- }
1811
- function esiEmotion(text, contextAware = true) {
1812
- return {
1813
- id: `esi-emotion-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
1814
- params: { model: "emotion" },
1815
- content: { type: "text", value: text },
1816
- contextAware,
1817
- signals: contextAware ? ["emotion", "history"] : undefined
1818
- };
1819
- }
1820
- function esiVision(base64Image, prompt, options = {}) {
1821
- return {
1822
- id: `esi-vision-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
1823
- params: {
1824
- model: "vision",
1825
- system: prompt,
1826
- ...options
1827
- },
1828
- content: { type: "base64", value: base64Image }
1829
- };
1830
- }
1831
- function esiWithContext(prompt, signals = ["emotion", "preferences", "time"], options = {}) {
1832
- return {
1833
- id: `esi-ctx-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
1834
- params: {
1835
- model: "llm",
1836
- ...options
1837
- },
1838
- content: { type: "text", value: prompt },
1839
- contextAware: true,
1840
- signals
1841
- };
1842
- }
1843
- // src/router/esi-react.tsx
1844
- var import_react = __toESM(require_react(), 1);
1845
- var jsx_dev_runtime = __toESM(require_jsx_dev_runtime(), 1);
1846
- var ESIContext = import_react.createContext(null);
1847
- var ESIProvider = ({
1848
- children,
1849
- config,
1850
- userContext,
1851
- processor: customProcessor
1852
- }) => {
1853
- const [processor] = import_react.useState(() => customProcessor || new EdgeWorkersESIProcessor(config));
1854
- import_react.useEffect(() => {
1855
- processor.warmup?.();
1856
- }, [processor]);
1857
- const process2 = import_react.useCallback(async (directive) => {
1858
- if (!userContext) {
1859
- return {
1860
- id: directive.id,
1861
- success: false,
1862
- error: "No user context available",
1863
- latencyMs: 0,
1864
- cached: false,
1865
- model: directive.params.model
1866
- };
1867
- }
1868
- return processor.process(directive, userContext);
1869
- }, [processor, userContext]);
1870
- const processWithStream = import_react.useCallback(async (directive, onChunk) => {
1871
- if (!userContext) {
1872
- return {
1873
- id: directive.id,
1874
- success: false,
1875
- error: "No user context available",
1876
- latencyMs: 0,
1877
- cached: false,
1878
- model: directive.params.model
1879
- };
1880
- }
1881
- if (!processor.stream) {
1882
- return processor.process(directive, userContext);
1883
- }
1884
- return processor.stream(directive, userContext, onChunk);
1885
- }, [processor, userContext]);
1886
- return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ESIContext.Provider, {
1887
- value: {
1888
- processor,
1889
- userContext: userContext || null,
1890
- enabled: config?.enabled ?? true,
1891
- process: process2,
1892
- processWithStream
1893
- },
1894
- children
1895
- }, undefined, false, undefined, this);
1896
- };
1897
- function useESI() {
1898
- const ctx = import_react.useContext(ESIContext);
1899
- if (!ctx) {
1900
- throw new Error("useESI must be used within an ESIProvider");
1901
- }
1902
- return ctx;
1903
- }
1904
- var ESIInfer = ({
1905
- children,
1906
- prompt,
1907
- model = "llm",
1908
- variant,
1909
- temperature,
1910
- maxTokens,
1911
- system,
1912
- stream = false,
1913
- fallback,
1914
- loading = "...",
1915
- contextAware = false,
1916
- signals,
1917
- cacheTtl,
1918
- render,
1919
- className,
1920
- onComplete,
1921
- onError
1922
- }) => {
1923
- const { process: process2, processWithStream, enabled } = useESI();
1924
- const [output, setOutput] = import_react.useState("");
1925
- const [isLoading, setIsLoading] = import_react.useState(true);
1926
- const [error, setError] = import_react.useState(null);
1927
- const promptText = prompt || (typeof children === "string" ? children : String(children || ""));
1928
- import_react.useEffect(() => {
1929
- if (!enabled) {
1930
- setOutput(typeof fallback === "string" ? fallback : "");
1931
- setIsLoading(false);
1932
- return;
1933
- }
1934
- const directive = contextAware ? esiWithContext(promptText, signals, {
1935
- model,
1936
- variant,
1937
- temperature,
1938
- maxTokens,
1939
- system,
1940
- cacheTtl,
1941
- fallback: typeof fallback === "string" ? fallback : undefined
1942
- }) : esiInfer(promptText, {
1943
- model,
1944
- variant,
1945
- temperature,
1946
- maxTokens,
1947
- system,
1948
- cacheTtl,
1949
- fallback: typeof fallback === "string" ? fallback : undefined
1950
- });
1951
- if (stream) {
1952
- setOutput("");
1953
- processWithStream(directive, (chunk) => {
1954
- setOutput((prev) => prev + chunk);
1955
- }).then((result) => {
1956
- setIsLoading(false);
1957
- if (!result.success) {
1958
- setError(result.error || "Inference failed");
1959
- onError?.(result.error || "Inference failed");
1960
- }
1961
- onComplete?.(result);
1962
- });
1963
- } else {
1964
- process2(directive).then((result) => {
1965
- setIsLoading(false);
1966
- if (result.success && result.output) {
1967
- setOutput(result.output);
1968
- } else {
1969
- setError(result.error || "Inference failed");
1970
- onError?.(result.error || "Inference failed");
1971
- }
1972
- onComplete?.(result);
1973
- });
1974
- }
1975
- }, [promptText, model, variant, temperature, maxTokens, system, contextAware, stream, enabled]);
1976
- if (isLoading && !stream) {
1977
- return /* @__PURE__ */ jsx_dev_runtime.jsxDEV("span", {
1978
- className,
1979
- children: loading
1980
- }, undefined, false, undefined, this);
1981
- }
1982
- if (error && fallback) {
1983
- return /* @__PURE__ */ jsx_dev_runtime.jsxDEV("span", {
1984
- className,
1985
- children: fallback
1986
- }, undefined, false, undefined, this);
1987
- }
1988
- if (render) {
1989
- return /* @__PURE__ */ jsx_dev_runtime.jsxDEV("span", {
1990
- className,
1991
- children: render({
1992
- id: "",
1993
- success: !error,
1994
- output,
1995
- error: error || undefined,
1996
- latencyMs: 0,
1997
- cached: false,
1998
- model
1999
- })
2000
- }, undefined, false, undefined, this);
2001
- }
2002
- return /* @__PURE__ */ jsx_dev_runtime.jsxDEV("span", {
2003
- className,
2004
- children: output || (isLoading ? loading : "")
2005
- }, undefined, false, undefined, this);
2006
- };
2007
- var ESIEmbed = ({ children, onComplete, onError }) => {
2008
- const { process: process2, enabled } = useESI();
2009
- const text = typeof children === "string" ? children : String(children || "");
2010
- import_react.useEffect(() => {
2011
- if (!enabled)
2012
- return;
2013
- const directive = esiEmbed(text);
2014
- process2(directive).then((result) => {
2015
- if (result.success && result.embedding) {
2016
- onComplete?.(result.embedding);
2017
- } else {
2018
- onError?.(result.error || "Embedding failed");
2019
- }
2020
- });
2021
- }, [text, enabled]);
2022
- return null;
2023
- };
2024
- var ESIEmotion = ({
2025
- children,
2026
- contextAware = true,
2027
- onComplete,
2028
- onError
2029
- }) => {
2030
- const { process: process2, enabled } = useESI();
2031
- const text = typeof children === "string" ? children : String(children || "");
2032
- import_react.useEffect(() => {
2033
- if (!enabled)
2034
- return;
2035
- const directive = esiEmotion(text, contextAware);
2036
- process2(directive).then((result) => {
2037
- if (result.success && result.output) {
2038
- try {
2039
- const parsed = JSON.parse(result.output);
2040
- onComplete?.(parsed);
2041
- } catch {
2042
- onComplete?.({ emotion: result.output, confidence: 1 });
2043
- }
2044
- } else {
2045
- onError?.(result.error || "Emotion detection failed");
2046
- }
2047
- });
2048
- }, [text, contextAware, enabled]);
2049
- return null;
2050
- };
2051
- var ESIVision = ({
2052
- src,
2053
- prompt,
2054
- fallback,
2055
- loading = "...",
2056
- className,
2057
- onComplete,
2058
- onError
2059
- }) => {
2060
- const { process: process2, enabled } = useESI();
2061
- const [output, setOutput] = import_react.useState("");
2062
- const [isLoading, setIsLoading] = import_react.useState(true);
2063
- const [error, setError] = import_react.useState(null);
2064
- import_react.useEffect(() => {
2065
- if (!enabled) {
2066
- setOutput(typeof fallback === "string" ? fallback : "");
2067
- setIsLoading(false);
2068
- return;
2069
- }
2070
- const directive = esiVision(src, prompt);
2071
- process2(directive).then((result) => {
2072
- setIsLoading(false);
2073
- if (result.success && result.output) {
2074
- setOutput(result.output);
2075
- } else {
2076
- setError(result.error || "Vision analysis failed");
2077
- onError?.(result.error || "Vision analysis failed");
2078
- }
2079
- onComplete?.(result);
2080
- });
2081
- }, [src, prompt, enabled]);
2082
- if (isLoading) {
2083
- return /* @__PURE__ */ jsx_dev_runtime.jsxDEV("span", {
2084
- className,
2085
- children: loading
2086
- }, undefined, false, undefined, this);
2087
- }
2088
- if (error && fallback) {
2089
- return /* @__PURE__ */ jsx_dev_runtime.jsxDEV("span", {
2090
- className,
2091
- children: fallback
2092
- }, undefined, false, undefined, this);
2093
- }
2094
- return /* @__PURE__ */ jsx_dev_runtime.jsxDEV("span", {
2095
- className,
2096
- children: output
2097
- }, undefined, false, undefined, this);
2098
- };
2099
- function useESIInfer(options = {}) {
2100
- const { process: process2, processWithStream, enabled } = useESI();
2101
- const [result, setResult] = import_react.useState(null);
2102
- const [isLoading, setIsLoading] = import_react.useState(false);
2103
- const [error, setError] = import_react.useState(null);
2104
- const run = import_react.useCallback(async (prompt) => {
2105
- if (!enabled) {
2106
- setError("ESI is disabled");
2107
- return null;
2108
- }
2109
- setIsLoading(true);
2110
- setError(null);
2111
- const directive = options.contextAware ? esiWithContext(prompt, options.signals, {
2112
- model: options.model,
2113
- variant: options.variant,
2114
- temperature: options.temperature,
2115
- maxTokens: options.maxTokens,
2116
- system: options.system,
2117
- cacheTtl: options.cacheTtl
2118
- }) : esiInfer(prompt, {
2119
- model: options.model,
2120
- variant: options.variant,
2121
- temperature: options.temperature,
2122
- maxTokens: options.maxTokens,
2123
- system: options.system,
2124
- cacheTtl: options.cacheTtl
2125
- });
2126
- try {
2127
- let inferenceResult;
2128
- if (options.stream) {
2129
- let output = "";
2130
- inferenceResult = await processWithStream(directive, (chunk) => {
2131
- output += chunk;
2132
- setResult((prev) => ({
2133
- ...prev,
2134
- output
2135
- }));
2136
- });
2137
- } else {
2138
- inferenceResult = await process2(directive);
2139
- }
2140
- setResult(inferenceResult);
2141
- setIsLoading(false);
2142
- if (!inferenceResult.success) {
2143
- setError(inferenceResult.error || "Inference failed");
2144
- }
2145
- options.onComplete?.(inferenceResult);
2146
- return inferenceResult;
2147
- } catch (err) {
2148
- const errorMsg = err instanceof Error ? err.message : "Unknown error";
2149
- setError(errorMsg);
2150
- setIsLoading(false);
2151
- options.onError?.(errorMsg);
2152
- return null;
2153
- }
2154
- }, [process2, processWithStream, enabled, options]);
2155
- const reset = import_react.useCallback(() => {
2156
- setResult(null);
2157
- setError(null);
2158
- setIsLoading(false);
2159
- }, []);
2160
- return { run, result, isLoading, error, reset };
2161
- }
2162
- var DEFAULT_ESI_STATE = {
2163
- userTier: "free",
2164
- emotionState: null,
2165
- preferences: {
2166
- theme: "auto",
2167
- reducedMotion: false
2168
- },
2169
- localHour: new Date().getHours(),
2170
- timezone: "UTC",
2171
- features: {
2172
- aiInference: true,
2173
- emotionTracking: true,
2174
- collaboration: false,
2175
- advancedInsights: false,
2176
- customThemes: false,
2177
- voiceSynthesis: false,
2178
- imageAnalysis: false
2179
- },
2180
- isNewSession: true,
2181
- recentPages: [],
2182
- viewport: { width: 1920, height: 1080 },
2183
- connection: "4g"
2184
- };
2185
- function useGlobalESIState() {
2186
- const [state, setState] = import_react.useState(() => {
2187
- if (typeof window !== "undefined" && window.__AEON_ESI_STATE__) {
2188
- return window.__AEON_ESI_STATE__;
2189
- }
2190
- return DEFAULT_ESI_STATE;
2191
- });
2192
- import_react.useEffect(() => {
2193
- if (typeof window !== "undefined" && window.__AEON_ESI_STATE__?.subscribe) {
2194
- const unsubscribe = window.__AEON_ESI_STATE__.subscribe((newState) => {
2195
- setState(newState);
2196
- });
2197
- return unsubscribe;
2198
- }
2199
- }, []);
2200
- return state;
2201
- }
2202
- function useESIFeature(feature) {
2203
- const { features } = useGlobalESIState();
2204
- return features[feature] ?? false;
2205
- }
2206
- function useESITier() {
2207
- const { userTier } = useGlobalESIState();
2208
- return userTier;
2209
- }
2210
- function useESIEmotionState() {
2211
- const { emotionState } = useGlobalESIState();
2212
- return emotionState;
2213
- }
2214
- function useESIPreferences() {
2215
- const { preferences } = useGlobalESIState();
2216
- return preferences;
2217
- }
2218
- function updateGlobalESIState(partial) {
2219
- if (typeof window !== "undefined" && window.__AEON_ESI_STATE__?.update) {
2220
- window.__AEON_ESI_STATE__.update(partial);
2221
- } else if (typeof window !== "undefined" && window.__AEON_ESI_STATE__) {
2222
- Object.assign(window.__AEON_ESI_STATE__, partial);
2223
- }
2224
- }
2225
- var ESI = {
2226
- Provider: ESIProvider,
2227
- Infer: ESIInfer,
2228
- Embed: ESIEmbed,
2229
- Emotion: ESIEmotion,
2230
- Vision: ESIVision
2231
- };
2232
- // src/router/heuristic-adapter.ts
2233
- var DEFAULT_CONFIG = {
2234
- tierFeatures: {
2235
- free: {},
2236
- starter: {},
2237
- pro: {},
2238
- enterprise: {}
2239
- },
2240
- defaultAccent: "#6366f1",
2241
- signals: {},
2242
- defaultPaths: ["/"],
2243
- maxSpeculationPaths: 5
2244
- };
2245
- function defaultDeriveTheme(context) {
2246
- if (context.preferences.theme) {
2247
- return context.preferences.theme;
2248
- }
2249
- const hour = context.localHour;
2250
- const isNight = hour >= 20 || hour < 6;
2251
- const isEvening = hour >= 18 && hour < 20;
2252
- if (isNight) {
2253
- return "dark";
2254
- }
2255
- if (isEvening) {
2256
- return "auto";
2257
- }
2258
- return "light";
2259
- }
2260
- function determineDensity(context) {
2261
- if (context.preferences.density) {
2262
- return context.preferences.density;
2263
- }
2264
- const { width, height } = context.viewport;
2265
- if (width < 768) {
2266
- return "compact";
2267
- }
2268
- if (width >= 1440 && height >= 900) {
2269
- return "comfortable";
2270
- }
2271
- return "normal";
2272
- }
2273
- function buildTransitionMatrix(history) {
2274
- const matrix = {};
2275
- for (let i = 0;i < history.length - 1; i++) {
2276
- const from = history[i];
2277
- const to = history[i + 1];
2278
- if (!matrix[from]) {
2279
- matrix[from] = {};
2280
- }
2281
- matrix[from][to] = (matrix[from][to] || 0) + 1;
2282
- }
2283
- for (const from of Object.keys(matrix)) {
2284
- const total = Object.values(matrix[from]).reduce((a, b) => a + b, 0);
2285
- for (const to of Object.keys(matrix[from])) {
2286
- matrix[from][to] /= total;
2287
- }
2288
- }
2289
- return matrix;
2290
- }
2291
- function defaultPredictNavigation(currentPath, context, defaultPaths, topN) {
2292
- const history = context.recentPages;
2293
- if (history.length >= 3) {
2294
- const matrix = buildTransitionMatrix(history);
2295
- const transitions = matrix[currentPath];
2296
- if (transitions) {
2297
- const sorted = Object.entries(transitions).sort(([, a], [, b]) => b - a).slice(0, topN).map(([path]) => path);
2298
- if (sorted.length > 0) {
2299
- return sorted;
2300
- }
2301
- }
2302
- }
2303
- return defaultPaths.filter((p) => p !== currentPath).slice(0, topN);
2304
- }
2305
- function defaultScoreRelevance(node, context) {
2306
- let score = 50;
2307
- if (node.requiredTier) {
2308
- const tierOrder = ["free", "starter", "pro", "enterprise"];
2309
- const requiredIndex = tierOrder.indexOf(node.requiredTier);
2310
- const userIndex = tierOrder.indexOf(context.tier);
2311
- if (userIndex < requiredIndex) {
2312
- return 0;
2313
- }
2314
- score += 10;
2315
- }
2316
- if (node.relevanceSignals) {
2317
- for (const signal of node.relevanceSignals) {
2318
- if (signal.startsWith("recentPage:")) {
2319
- const page = signal.slice("recentPage:".length);
2320
- if (context.recentPages.includes(page)) {
2321
- score += 20;
2322
- }
2323
- }
2324
- if (signal.startsWith("timeOfDay:")) {
2325
- const timeRange = signal.slice("timeOfDay:".length);
2326
- const hour = context.localHour;
2327
- if (timeRange === "morning" && hour >= 5 && hour < 12)
2328
- score += 15;
2329
- if (timeRange === "afternoon" && hour >= 12 && hour < 17)
2330
- score += 15;
2331
- if (timeRange === "evening" && hour >= 17 && hour < 21)
2332
- score += 15;
2333
- if (timeRange === "night" && (hour >= 21 || hour < 5))
2334
- score += 15;
2335
- }
2336
- if (signal.startsWith("preference:")) {
2337
- const pref = signal.slice("preference:".length);
2338
- if (context.preferences[pref]) {
2339
- score += 20;
2340
- }
2341
- }
2342
- if (signal.startsWith("tier:")) {
2343
- const requiredTier = signal.slice("tier:".length);
2344
- const tierOrder = ["free", "starter", "pro", "enterprise"];
2345
- if (tierOrder.indexOf(context.tier) >= tierOrder.indexOf(requiredTier)) {
2346
- score += 15;
2347
- }
2348
- }
2349
- }
2350
- }
2351
- if (node.defaultHidden) {
2352
- score -= 30;
2353
- }
2354
- return Math.max(0, Math.min(100, score));
2355
- }
2356
- function orderComponentsByRelevance(tree, context, scoreRelevance) {
2357
- const scored = [];
2358
- tree.nodes.forEach((node, id) => {
2359
- scored.push({
2360
- id,
2361
- score: scoreRelevance(node, context)
2362
- });
2363
- });
2364
- return scored.sort((a, b) => b.score - a.score).map((s) => s.id);
2365
- }
2366
- function findHiddenComponents(tree, context, scoreRelevance) {
2367
- const hidden = [];
2368
- tree.nodes.forEach((node, id) => {
2369
- const score = scoreRelevance(node, context);
2370
- if (score === 0) {
2371
- hidden.push(id);
2372
- }
2373
- });
2374
- return hidden;
2375
- }
2376
- function computeSkeletonHints(route, context, tree) {
2377
- let layout = "custom";
2378
- if (route === "/" || route.includes("dashboard")) {
2379
- layout = "dashboard";
2380
- } else if (route.includes("chat") || route.includes("message")) {
2381
- layout = "chat";
2382
- } else if (route.includes("setting") || route.includes("config")) {
2383
- layout = "settings";
2384
- } else if (route.includes("tool")) {
2385
- layout = "tools";
2386
- }
2387
- const baseHeight = context.viewport.height;
2388
- const contentMultiplier = tree.nodes.size > 10 ? 1.5 : 1;
2389
- const estimatedHeight = Math.round(baseHeight * contentMultiplier);
2390
- const sections = tree.getChildren(tree.rootId).map((child, i) => ({
2391
- id: child.id,
2392
- height: Math.round(estimatedHeight / (tree.nodes.size || 1)),
2393
- priority: i + 1
2394
- }));
2395
- return {
2396
- layout,
2397
- estimatedHeight,
2398
- sections
2399
- };
2400
- }
2401
- function getPrefetchDepth(context) {
2402
- switch (context.connection) {
2403
- case "fast":
2404
- case "4g":
2405
- return { prefetch: 5, prerender: 1 };
2406
- case "3g":
2407
- return { prefetch: 3, prerender: 0 };
2408
- case "2g":
2409
- return { prefetch: 1, prerender: 0 };
2410
- case "slow-2g":
2411
- return { prefetch: 0, prerender: 0 };
2412
- default:
2413
- return { prefetch: 3, prerender: 0 };
2414
- }
2415
- }
2416
-
2417
- class HeuristicAdapter {
2418
- name = "heuristic";
2419
- config;
2420
- constructor(config = {}) {
2421
- this.config = {
2422
- ...DEFAULT_CONFIG,
2423
- ...config,
2424
- tierFeatures: config.tierFeatures ?? DEFAULT_CONFIG.tierFeatures,
2425
- signals: config.signals ?? DEFAULT_CONFIG.signals
2426
- };
2427
- }
2428
- async route(path, context, tree) {
2429
- const startTime = Date.now();
2430
- const sessionId = this.generateSessionId(path, context);
2431
- const featureFlags = { ...this.config.tierFeatures[context.tier] };
2432
- const theme = this.config.signals.deriveTheme ? this.config.signals.deriveTheme(context) : defaultDeriveTheme(context);
2433
- const accent = this.config.signals.deriveAccent ? this.config.signals.deriveAccent(context) : this.config.defaultAccent;
2434
- const density = determineDensity(context);
2435
- const scoreRelevance = this.config.signals.scoreRelevance ?? defaultScoreRelevance;
2436
- const componentOrder = orderComponentsByRelevance(tree, context, scoreRelevance);
2437
- const hiddenComponents = findHiddenComponents(tree, context, scoreRelevance);
2438
- const predictions = this.config.signals.predictNavigation ? this.config.signals.predictNavigation(path, context) : defaultPredictNavigation(path, context, this.config.defaultPaths, this.config.maxSpeculationPaths);
2439
- const { prefetch: prefetchDepth, prerender: prerenderCount } = getPrefetchDepth(context);
2440
- const prefetch = predictions.slice(0, prefetchDepth);
2441
- const prerender = predictions.slice(0, prerenderCount);
2442
- const skeleton = computeSkeletonHints(path, context, tree);
2443
- return {
2444
- route: path,
2445
- sessionId,
2446
- componentOrder,
2447
- hiddenComponents,
2448
- featureFlags,
2449
- theme,
2450
- accent,
2451
- density,
2452
- prefetch,
2453
- prerender,
2454
- skeleton,
2455
- routedAt: startTime,
2456
- routerName: this.name,
2457
- confidence: 0.85
2458
- };
2459
- }
2460
- async speculate(currentPath, context) {
2461
- return this.config.signals.predictNavigation ? this.config.signals.predictNavigation(currentPath, context) : defaultPredictNavigation(currentPath, context, this.config.defaultPaths, this.config.maxSpeculationPaths);
2462
- }
2463
- personalizeTree(tree, decision) {
2464
- const cloned = tree.clone();
2465
- if (decision.hiddenComponents) {
2466
- for (const id of decision.hiddenComponents) {
2467
- const node = cloned.getNode(id);
2468
- if (node) {
2469
- node.defaultHidden = true;
2470
- }
2471
- }
2472
- }
2473
- return cloned;
2474
- }
2475
- emotionToAccent(emotionState) {
2476
- if (this.config.signals.deriveAccent) {
2477
- return this.config.signals.deriveAccent({
2478
- emotionState,
2479
- tier: "free",
2480
- recentPages: [],
2481
- dwellTimes: new Map,
2482
- clickPatterns: [],
2483
- preferences: {},
2484
- viewport: { width: 0, height: 0 },
2485
- connection: "fast",
2486
- reducedMotion: false,
2487
- localHour: 12,
2488
- timezone: "UTC",
2489
- isNewSession: true
2490
- });
2491
- }
2492
- return this.config.defaultAccent;
2493
- }
2494
- generateSessionId(path, context) {
2495
- const base = path.replace(/^\/|\/$/g, "").replace(/\//g, "-") || "index";
2496
- const userId = context.userId || "anon";
2497
- const sessionPrefix = context.sessionId || Date.now().toString(36);
2498
- return `${base}-${userId.slice(0, 8)}-${sessionPrefix.slice(0, 8)}`;
2499
- }
2500
- }
2501
- // src/router/context-extractor.ts
2502
- function parseCookies(cookieHeader) {
2503
- if (!cookieHeader)
2504
- return {};
2505
- return cookieHeader.split(";").reduce((acc, cookie) => {
2506
- const [key, value] = cookie.trim().split("=");
2507
- if (key && value) {
2508
- acc[key] = decodeURIComponent(value);
2509
- }
2510
- return acc;
2511
- }, {});
2512
- }
2513
- function parseJSON(value, fallback) {
2514
- if (!value)
2515
- return fallback;
2516
- try {
2517
- return JSON.parse(value);
2518
- } catch {
2519
- return fallback;
2520
- }
2521
- }
2522
- function extractViewport(request) {
2523
- const headers = request.headers;
2524
- const viewportWidth = headers.get("sec-ch-viewport-width");
2525
- const viewportHeight = headers.get("sec-ch-viewport-height");
2526
- const dpr = headers.get("sec-ch-dpr");
2527
- if (viewportWidth && viewportHeight) {
2528
- return {
2529
- width: parseInt(viewportWidth, 10),
2530
- height: parseInt(viewportHeight, 10),
2531
- devicePixelRatio: dpr ? parseFloat(dpr) : undefined
2532
- };
2533
- }
2534
- const xViewport = headers.get("x-viewport");
2535
- if (xViewport) {
2536
- const [width, height, devicePixelRatio] = xViewport.split(",").map(Number);
2537
- return { width: width || 1920, height: height || 1080, devicePixelRatio };
2538
- }
2539
- return { width: 1920, height: 1080 };
2540
- }
2541
- function extractConnection(request) {
2542
- const headers = request.headers;
2543
- const downlink = headers.get("downlink");
2544
- const rtt = headers.get("rtt");
2545
- const ect = headers.get("ect");
2546
- if (ect) {
2547
- switch (ect) {
2548
- case "4g":
2549
- return "fast";
2550
- case "3g":
2551
- return "3g";
2552
- case "2g":
2553
- return "2g";
2554
- case "slow-2g":
2555
- return "slow-2g";
2556
- }
2557
- }
2558
- if (downlink) {
2559
- const mbps = parseFloat(downlink);
2560
- if (mbps >= 10)
2561
- return "fast";
2562
- if (mbps >= 2)
2563
- return "4g";
2564
- if (mbps >= 0.5)
2565
- return "3g";
2566
- if (mbps >= 0.1)
2567
- return "2g";
2568
- return "slow-2g";
2569
- }
2570
- if (rtt) {
2571
- const ms = parseInt(rtt, 10);
2572
- if (ms < 50)
2573
- return "fast";
2574
- if (ms < 100)
2575
- return "4g";
2576
- if (ms < 300)
2577
- return "3g";
2578
- if (ms < 700)
2579
- return "2g";
2580
- return "slow-2g";
2581
- }
2582
- return "4g";
2583
- }
2584
- function extractReducedMotion(request) {
2585
- const prefersReducedMotion = request.headers.get("sec-ch-prefers-reduced-motion");
2586
- return prefersReducedMotion === "reduce";
2587
- }
2588
- function extractTimeContext(request) {
2589
- const headers = request.headers;
2590
- const xTimezone = headers.get("x-timezone");
2591
- const xLocalHour = headers.get("x-local-hour");
2592
- const cfTimezone = request.cf?.timezone;
2593
- const timezone = xTimezone || cfTimezone || "UTC";
2594
- const localHour = xLocalHour ? parseInt(xLocalHour, 10) : new Date().getUTCHours();
2595
- return { timezone, localHour };
2596
- }
2597
- function extractIdentity(cookies, request) {
2598
- const userId = cookies["user_id"] || request.headers.get("x-user-id") || undefined;
2599
- const tierCookie = cookies["user_tier"];
2600
- const tierHeader = request.headers.get("x-user-tier");
2601
- const tier = tierCookie || tierHeader || "free";
2602
- return { userId, tier };
2603
- }
2604
- function extractNavigationHistory(cookies) {
2605
- const recentPages = parseJSON(cookies["recent_pages"], []);
2606
- const dwellTimesObj = parseJSON(cookies["dwell_times"], {});
2607
- const clickPatterns = parseJSON(cookies["click_patterns"], []);
2608
- return {
2609
- recentPages,
2610
- dwellTimes: new Map(Object.entries(dwellTimesObj)),
2611
- clickPatterns
2612
- };
2613
- }
2614
- function extractEmotionState(cookies, request) {
2615
- const xEmotion = request.headers.get("x-emotion-state");
2616
- if (xEmotion) {
2617
- return parseJSON(xEmotion, undefined);
2618
- }
2619
- const emotionCookie = cookies["emotion_state"];
2620
- if (emotionCookie) {
2621
- return parseJSON(emotionCookie, undefined);
2622
- }
2623
- return;
2624
- }
2625
- function extractPreferences(cookies) {
2626
- return parseJSON(cookies["user_preferences"], {});
2627
- }
2628
- function extractSessionInfo(cookies) {
2629
- const sessionId = cookies["session_id"];
2630
- const sessionStarted = cookies["session_started"];
2631
- return {
2632
- sessionId,
2633
- isNewSession: !sessionId,
2634
- sessionStartedAt: sessionStarted ? new Date(sessionStarted) : undefined
2635
- };
2636
- }
2637
- async function extractUserContext(request, options = {}) {
2638
- const cookies = parseCookies(request.headers.get("cookie"));
2639
- const viewport = extractViewport(request);
2640
- const connection = extractConnection(request);
2641
- const reducedMotion = extractReducedMotion(request);
2642
- const { timezone, localHour } = extractTimeContext(request);
2643
- const { userId, tier: initialTier } = extractIdentity(cookies, request);
2644
- const { recentPages, dwellTimes, clickPatterns } = extractNavigationHistory(cookies);
2645
- const preferences = extractPreferences(cookies);
2646
- const { sessionId, isNewSession, sessionStartedAt } = extractSessionInfo(cookies);
2647
- let tier = initialTier;
2648
- if (options.resolveUserTier && userId) {
2649
- try {
2650
- tier = await options.resolveUserTier(userId);
2651
- } catch {}
2652
- }
2653
- let emotionState = extractEmotionState(cookies, request);
2654
- if (!emotionState && options.detectEmotion) {
2655
- try {
2656
- emotionState = await options.detectEmotion(request);
2657
- } catch {}
2658
- }
2659
- let context = {
2660
- userId,
2661
- tier,
2662
- recentPages,
2663
- dwellTimes,
2664
- clickPatterns,
2665
- emotionState,
2666
- preferences,
2667
- viewport,
2668
- connection,
2669
- reducedMotion,
2670
- localHour,
2671
- timezone,
2672
- sessionId,
2673
- isNewSession,
2674
- sessionStartedAt
2675
- };
2676
- if (options.enrich) {
2677
- context = await options.enrich(context, request);
2678
- }
2679
- return context;
2680
- }
2681
- function createContextMiddleware(options = {}) {
2682
- return async (request) => {
2683
- return extractUserContext(request, options);
2684
- };
2685
- }
2686
- function setContextCookies(response, context, currentPath) {
2687
- const headers = new Headers(response.headers);
2688
- const recentPages = [...context.recentPages.slice(-9), currentPath];
2689
- headers.append("Set-Cookie", `recent_pages=${encodeURIComponent(JSON.stringify(recentPages))}; Path=/; Max-Age=604800; SameSite=Lax`);
2690
- if (context.isNewSession) {
2691
- const sessionId = `sess_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
2692
- headers.append("Set-Cookie", `session_id=${sessionId}; Path=/; Max-Age=86400; SameSite=Lax`);
2693
- headers.append("Set-Cookie", `session_started=${new Date().toISOString()}; Path=/; Max-Age=86400; SameSite=Lax`);
2694
- }
2695
- return new Response(response.body, {
2696
- status: response.status,
2697
- statusText: response.statusText,
2698
- headers
2699
- });
2700
- }
2701
- function addSpeculationHeaders(response, prefetch, prerender) {
2702
- const headers = new Headers(response.headers);
2703
- if (prefetch.length > 0) {
2704
- const linkHeader = prefetch.map((path) => `<${path}>; rel=prefetch`).join(", ");
2705
- headers.append("Link", linkHeader);
2706
- }
2707
- if (prerender.length > 0) {
2708
- headers.set("X-Prerender-Hints", prerender.join(","));
2709
- }
2710
- return new Response(response.body, {
2711
- status: response.status,
2712
- statusText: response.statusText,
2713
- headers
2714
- });
2715
- }
2716
- function serializeToESIState(context) {
2717
- const tierFeatures = {
2718
- free: {
2719
- aiInference: true,
2720
- emotionTracking: true,
2721
- collaboration: false,
2722
- advancedInsights: false,
2723
- customThemes: false,
2724
- voiceSynthesis: false,
2725
- imageAnalysis: false
2726
- },
2727
- starter: {
2728
- aiInference: true,
2729
- emotionTracking: true,
2730
- collaboration: false,
2731
- advancedInsights: true,
2732
- customThemes: true,
2733
- voiceSynthesis: false,
2734
- imageAnalysis: false
2735
- },
2736
- pro: {
2737
- aiInference: true,
2738
- emotionTracking: true,
2739
- collaboration: true,
2740
- advancedInsights: true,
2741
- customThemes: true,
2742
- voiceSynthesis: true,
2743
- imageAnalysis: true
2744
- },
2745
- enterprise: {
2746
- aiInference: true,
2747
- emotionTracking: true,
2748
- collaboration: true,
2749
- advancedInsights: true,
2750
- customThemes: true,
2751
- voiceSynthesis: true,
2752
- imageAnalysis: true
2753
- }
2754
- };
2755
- return {
2756
- userTier: context.tier,
2757
- emotionState: context.emotionState ? {
2758
- primary: context.emotionState.primary,
2759
- valence: context.emotionState.valence,
2760
- arousal: context.emotionState.arousal,
2761
- confidence: context.emotionState.confidence
2762
- } : undefined,
2763
- preferences: {
2764
- theme: context.preferences.theme,
2765
- reducedMotion: context.reducedMotion,
2766
- language: context.preferences.language
2767
- },
2768
- sessionId: context.sessionId,
2769
- localHour: context.localHour,
2770
- timezone: context.timezone,
2771
- features: tierFeatures[context.tier],
2772
- userId: context.userId,
2773
- isNewSession: context.isNewSession,
2774
- recentPages: context.recentPages.slice(-10),
2775
- viewport: {
2776
- width: context.viewport.width,
2777
- height: context.viewport.height
2778
- },
2779
- connection: context.connection
2780
- };
2781
- }
2782
- function generateESIStateScript(esiState) {
2783
- const stateJson = JSON.stringify(esiState);
2784
- return `<script>window.__AEON_ESI_STATE__=${stateJson};</script>`;
2785
- }
2786
- function generateESIStateScriptFromContext(context) {
2787
- const esiState = serializeToESIState(context);
2788
- return generateESIStateScript(esiState);
2789
- }
2790
- // src/router/speculation.ts
2791
- function supportsSpeculationRules() {
2792
- if (typeof document === "undefined")
2793
- return false;
2794
- return "supports" in HTMLScriptElement && HTMLScriptElement.supports?.("speculationrules");
2795
- }
2796
- function supportsLinkPrefetch() {
2797
- if (typeof document === "undefined")
2798
- return false;
2799
- const link = document.createElement("link");
2800
- return link.relList?.supports?.("prefetch") ?? false;
2801
- }
2802
- function addSpeculationRules(prefetch, prerender) {
2803
- if (!supportsSpeculationRules())
2804
- return null;
2805
- const rules = {};
2806
- if (prefetch.length > 0) {
2807
- rules.prefetch = [{ urls: prefetch }];
2808
- }
2809
- if (prerender.length > 0) {
2810
- rules.prerender = [{ urls: prerender }];
2811
- }
2812
- if (Object.keys(rules).length === 0)
2813
- return null;
2814
- const script = document.createElement("script");
2815
- script.type = "speculationrules";
2816
- script.textContent = JSON.stringify(rules);
2817
- document.head.appendChild(script);
2818
- return script;
2819
- }
2820
- function removeSpeculationRules(script) {
2821
- script.remove();
2822
- }
2823
- function linkPrefetch(path) {
2824
- if (!supportsLinkPrefetch())
2825
- return null;
2826
- const existing = document.querySelector(`link[rel="prefetch"][href="${path}"]`);
2827
- if (existing)
2828
- return existing;
2829
- const link = document.createElement("link");
2830
- link.rel = "prefetch";
2831
- link.href = path;
2832
- document.head.appendChild(link);
2833
- return link;
2834
- }
2835
- function removePrefetch(link) {
2836
- link.remove();
2837
- }
2838
-
2839
- class SpeculationManager {
2840
- options;
2841
- state;
2842
- observers = new Map;
2843
- hoverTimers = new Map;
2844
- speculationScript = null;
2845
- prefetchLinks = new Map;
2846
- constructor(options = {}) {
2847
- this.options = {
2848
- maxPrefetch: options.maxPrefetch ?? 5,
2849
- maxPrerender: options.maxPrerender ?? 1,
2850
- hoverDelay: options.hoverDelay ?? 100,
2851
- prefetchOnVisible: options.prefetchOnVisible ?? true,
2852
- visibilityThreshold: options.visibilityThreshold ?? 0.1,
2853
- cacheDuration: options.cacheDuration ?? 5 * 60 * 1000,
2854
- onSpeculate: options.onSpeculate ?? (() => {})
2855
- };
2856
- this.state = {
2857
- prefetched: new Set,
2858
- prerendered: new Set,
2859
- pending: new Set
2860
- };
2861
- }
2862
- initFromHints(prefetch = [], prerender = []) {
2863
- const newPrefetch = prefetch.filter((p) => !this.state.prefetched.has(p) && !this.state.prerendered.has(p)).slice(0, this.options.maxPrefetch);
2864
- const newPrerender = prerender.filter((p) => !this.state.prerendered.has(p)).slice(0, this.options.maxPrerender);
2865
- if (supportsSpeculationRules()) {
2866
- this.speculationScript = addSpeculationRules(newPrefetch, newPrerender);
2867
- newPrefetch.forEach((p) => {
2868
- this.state.prefetched.add(p);
2869
- this.options.onSpeculate(p, "prefetch");
2870
- });
2871
- newPrerender.forEach((p) => {
2872
- this.state.prerendered.add(p);
2873
- this.options.onSpeculate(p, "prerender");
2874
- });
2875
- } else {
2876
- newPrefetch.forEach((path) => {
2877
- const link = linkPrefetch(path);
2878
- if (link) {
2879
- this.prefetchLinks.set(path, link);
2880
- this.state.prefetched.add(path);
2881
- this.options.onSpeculate(path, "prefetch");
2882
- }
2883
- });
2884
- }
2885
- }
2886
- prefetch(path) {
2887
- if (this.state.prefetched.has(path) || this.state.prerendered.has(path)) {
2888
- return false;
2889
- }
2890
- if (this.state.prefetched.size >= this.options.maxPrefetch) {
2891
- return false;
2892
- }
2893
- if (supportsSpeculationRules()) {
2894
- const allPrefetch = [...this.state.prefetched, path];
2895
- const allPrerender = [...this.state.prerendered];
2896
- if (this.speculationScript) {
2897
- removeSpeculationRules(this.speculationScript);
2898
- }
2899
- this.speculationScript = addSpeculationRules(allPrefetch, allPrerender);
2900
- } else {
2901
- const link = linkPrefetch(path);
2902
- if (link) {
2903
- this.prefetchLinks.set(path, link);
2904
- }
2905
- }
2906
- this.state.prefetched.add(path);
2907
- this.options.onSpeculate(path, "prefetch");
2908
- return true;
2909
- }
2910
- watchHover(element) {
2911
- const path = new URL(element.href, window.location.href).pathname;
2912
- const handleMouseEnter = () => {
2913
- if (this.state.prefetched.has(path) || this.state.pending.has(path)) {
2914
- return;
2915
- }
2916
- this.state.pending.add(path);
2917
- const timer = setTimeout(() => {
2918
- this.prefetch(path);
2919
- this.state.pending.delete(path);
2920
- }, this.options.hoverDelay);
2921
- this.hoverTimers.set(element, timer);
2922
- };
2923
- const handleMouseLeave = () => {
2924
- const timer = this.hoverTimers.get(element);
2925
- if (timer) {
2926
- clearTimeout(timer);
2927
- this.hoverTimers.delete(element);
2928
- }
2929
- this.state.pending.delete(path);
2930
- };
2931
- element.addEventListener("mouseenter", handleMouseEnter);
2932
- element.addEventListener("mouseleave", handleMouseLeave);
2933
- return () => {
2934
- element.removeEventListener("mouseenter", handleMouseEnter);
2935
- element.removeEventListener("mouseleave", handleMouseLeave);
2936
- handleMouseLeave();
2937
- };
2938
- }
2939
- watchVisible(element) {
2940
- if (!this.options.prefetchOnVisible) {
2941
- return () => {};
2942
- }
2943
- const path = new URL(element.href, window.location.href).pathname;
2944
- const observer = new IntersectionObserver((entries) => {
2945
- entries.forEach((entry) => {
2946
- if (entry.isIntersecting) {
2947
- this.prefetch(path);
2948
- observer.disconnect();
2949
- this.observers.delete(element);
2950
- }
2951
- });
2952
- }, { threshold: this.options.visibilityThreshold });
2953
- observer.observe(element);
2954
- this.observers.set(element, observer);
2955
- return () => {
2956
- observer.disconnect();
2957
- this.observers.delete(element);
2958
- };
2959
- }
2960
- watchAllLinks() {
2961
- const links = document.querySelectorAll('a[href^="/"]');
2962
- const cleanups = [];
2963
- links.forEach((link) => {
2964
- if (link instanceof HTMLAnchorElement) {
2965
- cleanups.push(this.watchHover(link));
2966
- cleanups.push(this.watchVisible(link));
2967
- }
2968
- });
2969
- return () => {
2970
- cleanups.forEach((cleanup) => cleanup());
2971
- };
2972
- }
2973
- clear() {
2974
- if (this.speculationScript) {
2975
- removeSpeculationRules(this.speculationScript);
2976
- this.speculationScript = null;
2977
- }
2978
- this.prefetchLinks.forEach((link) => removePrefetch(link));
2979
- this.prefetchLinks.clear();
2980
- this.observers.forEach((observer) => observer.disconnect());
2981
- this.observers.clear();
2982
- this.hoverTimers.forEach((timer) => clearTimeout(timer));
2983
- this.hoverTimers.clear();
2984
- this.state.prefetched.clear();
2985
- this.state.prerendered.clear();
2986
- this.state.pending.clear();
2987
- }
2988
- getState() {
2989
- return {
2990
- prefetched: new Set(this.state.prefetched),
2991
- prerendered: new Set(this.state.prerendered),
2992
- pending: new Set(this.state.pending)
2993
- };
2994
- }
2995
- }
2996
- function createSpeculationHook(useState2, useEffect2, useRef) {
2997
- return function useSpeculation(options = {}) {
2998
- const managerRef = useRef(null);
2999
- const [state, setState] = useState2({
3000
- prefetched: new Set,
3001
- prerendered: new Set,
3002
- pending: new Set
3003
- });
3004
- useEffect2(() => {
3005
- managerRef.current = new SpeculationManager({
3006
- ...options,
3007
- onSpeculate: (path, type) => {
3008
- options.onSpeculate?.(path, type);
3009
- setState(managerRef.current.getState());
3010
- }
3011
- });
3012
- const cleanup = managerRef.current.watchAllLinks();
3013
- return () => {
3014
- cleanup();
3015
- managerRef.current?.clear();
3016
- };
3017
- }, []);
3018
- return {
3019
- state,
3020
- prefetch: (path) => managerRef.current?.prefetch(path),
3021
- initFromHints: (prefetch, prerender) => managerRef.current?.initFromHints(prefetch, prerender),
3022
- clear: () => managerRef.current?.clear()
3023
- };
3024
- };
3025
- }
3026
- function autoInitSpeculation() {
3027
- if (typeof window === "undefined")
3028
- return null;
3029
- const hints = window.__AEON_SPECULATION__;
3030
- const manager = new SpeculationManager;
3031
- if (hints) {
3032
- manager.initFromHints(hints.prefetch || [], hints.prerender || []);
3033
- }
3034
- manager.watchAllLinks();
3035
- return manager;
3036
- }
3037
- // src/router/esi-control.ts
3038
- function generateSchemaPrompt(schema) {
3039
- const schemaDescription = describeZodSchema(schema);
3040
- return `
3041
-
3042
- Respond with valid JSON matching this schema:
3043
- ${schemaDescription}
3044
-
3045
- Output ONLY the JSON, no markdown, no explanation.`;
3046
- }
3047
- function describeZodSchema(schema) {
3048
- const def = schema._def;
3049
- if (def.typeName === "ZodObject") {
3050
- const shape = def.shape;
3051
- const fields = Object.entries(shape).map(([key, fieldSchema]) => {
3052
- const fieldDef = fieldSchema._def;
3053
- return ` "${key}": ${describeZodType(fieldDef)}`;
3054
- });
3055
- return `{
3056
- ${fields.join(`,
3057
- `)}
3058
- }`;
3059
- }
3060
- return describeZodType(def);
3061
- }
3062
- function describeZodType(def) {
3063
- const typeName = def.typeName;
3064
- switch (typeName) {
3065
- case "ZodString":
3066
- return "string";
3067
- case "ZodNumber":
3068
- return "number";
3069
- case "ZodBoolean":
3070
- return "boolean";
3071
- case "ZodArray":
3072
- const innerType = def.type;
3073
- return `array of ${describeZodType(innerType._def)}`;
3074
- case "ZodEnum":
3075
- const values = def.values;
3076
- return `one of: ${values.map((v) => `"${v}"`).join(" | ")}`;
3077
- case "ZodLiteral":
3078
- return JSON.stringify(def.value);
3079
- case "ZodOptional":
3080
- const optionalType = def.innerType;
3081
- return `${describeZodType(optionalType._def)} (optional)`;
3082
- case "ZodNullable":
3083
- const nullableType = def.innerType;
3084
- return `${describeZodType(nullableType._def)} or null`;
3085
- case "ZodObject":
3086
- return "object";
3087
- default:
3088
- return "any";
3089
- }
3090
- }
3091
- function parseWithSchema(output, schema) {
3092
- let jsonStr = output.trim();
3093
- if (jsonStr.startsWith("```")) {
3094
- const match = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/);
3095
- if (match) {
3096
- jsonStr = match[1].trim();
3097
- }
3098
- }
3099
- let parsed;
3100
- try {
3101
- parsed = JSON.parse(jsonStr);
3102
- } catch (e) {
3103
- const jsonMatch = jsonStr.match(/\{[\s\S]*\}/);
3104
- if (jsonMatch) {
3105
- try {
3106
- parsed = JSON.parse(jsonMatch[0]);
3107
- } catch {
3108
- return {
3109
- success: false,
3110
- errors: [`Failed to parse JSON: ${e instanceof Error ? e.message : "Unknown error"}`]
3111
- };
3112
- }
3113
- } else {
3114
- return {
3115
- success: false,
3116
- errors: [`No valid JSON found in output`]
3117
- };
3118
- }
3119
- }
3120
- const result = schema.safeParse(parsed);
3121
- if (result.success) {
3122
- return { success: true, data: result.data };
3123
- }
3124
- return {
3125
- success: false,
3126
- errors: result.error.errors.map((e) => `${e.path.join(".")}: ${e.message}`)
3127
- };
3128
- }
3129
- function createControlProcessor(processESI) {
3130
- return {
3131
- async processWithSchema(prompt, schema, params, context) {
3132
- const fullPrompt = prompt + generateSchemaPrompt(schema);
3133
- const directive = {
3134
- id: `esi-schema-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
3135
- params: {
3136
- model: "llm",
3137
- ...params
3138
- },
3139
- content: {
3140
- type: "text",
3141
- value: fullPrompt
3142
- }
3143
- };
3144
- const result = await processESI(directive, context);
3145
- if (!result.success || !result.output) {
3146
- return {
3147
- ...result,
3148
- validationErrors: result.error ? [result.error] : ["No output"]
3149
- };
3150
- }
3151
- const parseResult = parseWithSchema(result.output, schema);
3152
- if (parseResult.success) {
3153
- return {
3154
- ...result,
3155
- data: parseResult.data,
3156
- rawOutput: result.output
3157
- };
3158
- }
3159
- return {
3160
- ...result,
3161
- rawOutput: result.output,
3162
- validationErrors: parseResult.errors
3163
- };
3164
- },
3165
- async processIf(directive, context) {
3166
- const schemaResult = await this.processWithSchema(directive.prompt, directive.schema, directive.params || {}, context);
3167
- let conditionMet = false;
3168
- if (schemaResult.data !== undefined) {
3169
- try {
3170
- conditionMet = directive.when(schemaResult.data, context);
3171
- } catch (e) {
3172
- conditionMet = false;
3173
- }
3174
- }
3175
- return {
3176
- id: directive.id,
3177
- conditionMet,
3178
- data: schemaResult.data,
3179
- inferenceResult: schemaResult
3180
- };
3181
- },
3182
- async processMatch(directive, context) {
3183
- const schemaResult = await this.processWithSchema(directive.prompt, directive.schema, directive.params || {}, context);
3184
- let matchedCase;
3185
- if (schemaResult.data !== undefined) {
3186
- for (const caseItem of directive.cases) {
3187
- try {
3188
- if (caseItem.match(schemaResult.data, context)) {
3189
- matchedCase = caseItem.id;
3190
- break;
3191
- }
3192
- } catch {}
3193
- }
3194
- if (!matchedCase && directive.defaultCase) {
3195
- matchedCase = directive.defaultCase;
3196
- }
3197
- }
3198
- return {
3199
- id: directive.id,
3200
- matchedCase,
3201
- data: schemaResult.data,
3202
- inferenceResult: schemaResult
3203
- };
3204
- }
3205
- };
3206
- }
3207
- function esiIf(prompt, schema, when, options = {}) {
3208
- return {
3209
- id: `esi-if-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
3210
- prompt,
3211
- schema,
3212
- when,
3213
- params: options
3214
- };
3215
- }
3216
- function esiMatch(prompt, schema, cases, defaultCase, options = {}) {
3217
- return {
3218
- id: `esi-match-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
3219
- prompt,
3220
- schema,
3221
- cases,
3222
- defaultCase,
3223
- params: options
3224
- };
3225
- }
3226
- // src/router/esi-control-react.tsx
3227
- var import_react2 = __toESM(require_react(), 1);
3228
- var jsx_dev_runtime2 = __toESM(require_jsx_dev_runtime(), 1);
3229
- var PresenceContext = import_react2.createContext(null);
3230
- function usePresenceForESI() {
3231
- const ctx = import_react2.useContext(PresenceContext);
3232
- return ctx || { users: [], localUser: null };
3233
- }
3234
- function ESIStructured({
3235
- children,
3236
- prompt,
3237
- schema,
3238
- render,
3239
- fallback,
3240
- loading = "...",
3241
- retryOnFail = false,
3242
- maxRetries = 2,
3243
- temperature,
3244
- maxTokens,
3245
- cacheTtl,
3246
- onSuccess,
3247
- onValidationError,
3248
- onError,
3249
- className
3250
- }) {
3251
- const { process: process2, enabled } = useESI();
3252
- const [result, setResult] = import_react2.useState(null);
3253
- const [isLoading, setIsLoading] = import_react2.useState(true);
3254
- const [retryCount, setRetryCount] = import_react2.useState(0);
3255
- const promptText = prompt || (typeof children === "string" ? children : String(children || ""));
3256
- const fullPrompt = promptText + generateSchemaPrompt(schema);
3257
- import_react2.useEffect(() => {
3258
- if (!enabled) {
3259
- setIsLoading(false);
3260
- return;
3261
- }
3262
- async function runInference() {
3263
- setIsLoading(true);
3264
- const directive = {
3265
- id: `esi-structured-${Date.now()}`,
3266
- params: {
3267
- model: "llm",
3268
- temperature,
3269
- maxTokens,
3270
- cacheTtl
3271
- },
3272
- content: {
3273
- type: "text",
3274
- value: fullPrompt
3275
- }
3276
- };
3277
- const inferenceResult = await process2(directive);
3278
- if (!inferenceResult.success || !inferenceResult.output) {
3279
- setResult({
3280
- ...inferenceResult,
3281
- validationErrors: [inferenceResult.error || "No output"]
3282
- });
3283
- onError?.(inferenceResult.error || "Inference failed");
3284
- setIsLoading(false);
3285
- return;
3286
- }
3287
- const parseResult = parseWithSchema(inferenceResult.output, schema);
3288
- if (parseResult.success) {
3289
- const schemaResult = {
3290
- ...inferenceResult,
3291
- data: parseResult.data,
3292
- rawOutput: inferenceResult.output
3293
- };
3294
- setResult(schemaResult);
3295
- onSuccess?.(parseResult.data);
3296
- } else {
3297
- if (retryOnFail && retryCount < maxRetries) {
3298
- setRetryCount((c) => c + 1);
3299
- } else {
3300
- const schemaResult = {
3301
- ...inferenceResult,
3302
- rawOutput: inferenceResult.output,
3303
- validationErrors: parseResult.errors
3304
- };
3305
- setResult(schemaResult);
3306
- onValidationError?.(parseResult.errors, inferenceResult.output);
3307
- }
3308
- }
3309
- setIsLoading(false);
3310
- }
3311
- runInference();
3312
- }, [fullPrompt, enabled, retryCount]);
3313
- if (isLoading) {
3314
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("span", {
3315
- className,
3316
- children: loading
3317
- }, undefined, false, undefined, this);
3318
- }
3319
- if (!result?.data) {
3320
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("span", {
3321
- className,
3322
- children: fallback
3323
- }, undefined, false, undefined, this);
3324
- }
3325
- if (render) {
3326
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("span", {
3327
- className,
3328
- children: render(result.data, {
3329
- cached: result.cached,
3330
- latencyMs: result.latencyMs
3331
- })
3332
- }, undefined, false, undefined, this);
3333
- }
3334
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("span", {
3335
- className,
3336
- children: JSON.stringify(result.data)
3337
- }, undefined, false, undefined, this);
3338
- }
3339
- function ESIIf({
3340
- children,
3341
- prompt,
3342
- schema,
3343
- when,
3344
- then: thenContent,
3345
- else: elseContent,
3346
- loading = null,
3347
- temperature,
3348
- cacheTtl,
3349
- onEvaluate,
3350
- className
3351
- }) {
3352
- const [conditionMet, setConditionMet] = import_react2.useState(null);
3353
- const [data, setData] = import_react2.useState(null);
3354
- const handleSuccess = import_react2.useCallback((result) => {
3355
- setData(result);
3356
- try {
3357
- const met = when(result, {});
3358
- setConditionMet(met);
3359
- onEvaluate?.(result, met);
3360
- } catch {
3361
- setConditionMet(false);
3362
- }
3363
- }, [when, onEvaluate]);
3364
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("span", {
3365
- className,
3366
- children: [
3367
- /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ESIStructured, {
3368
- prompt,
3369
- schema,
3370
- temperature,
3371
- cacheTtl,
3372
- loading,
3373
- onSuccess: handleSuccess,
3374
- render: () => null,
3375
- children
3376
- }, undefined, false, undefined, this),
3377
- conditionMet === true && thenContent,
3378
- conditionMet === false && elseContent
3379
- ]
3380
- }, undefined, true, undefined, this);
3381
- }
3382
- function ESICase({ children }) {
3383
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(jsx_dev_runtime2.Fragment, {
3384
- children
3385
- }, undefined, false, undefined, this);
3386
- }
3387
- function ESIDefault({ children }) {
3388
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(jsx_dev_runtime2.Fragment, {
3389
- children
3390
- }, undefined, false, undefined, this);
3391
- }
3392
- function ESIMatch({
3393
- children,
3394
- prompt,
3395
- schema,
3396
- loading = null,
3397
- temperature,
3398
- cacheTtl,
3399
- onMatch,
3400
- className
3401
- }) {
3402
- const [matchedIndex, setMatchedIndex] = import_react2.useState(null);
3403
- const [data, setData] = import_react2.useState(null);
3404
- const { cases, defaultCase, promptFromChildren } = import_react2.useMemo(() => {
3405
- const cases2 = [];
3406
- let defaultCase2 = null;
3407
- let promptFromChildren2 = "";
3408
- import_react2.Children.forEach(children, (child) => {
3409
- if (!import_react2.isValidElement(child)) {
3410
- if (typeof child === "string") {
3411
- promptFromChildren2 += child;
3412
- }
3413
- return;
3414
- }
3415
- if (child.type === ESICase) {
3416
- const props = child.props;
3417
- cases2.push({
3418
- match: props.match,
3419
- content: props.children
3420
- });
3421
- } else if (child.type === ESIDefault) {
3422
- defaultCase2 = child.props.children;
3423
- }
3424
- });
3425
- return { cases: cases2, defaultCase: defaultCase2, promptFromChildren: promptFromChildren2 };
3426
- }, [children]);
3427
- const handleSuccess = import_react2.useCallback((result) => {
3428
- setData(result);
3429
- for (let i = 0;i < cases.length; i++) {
3430
- try {
3431
- if (cases[i].match(result, {})) {
3432
- setMatchedIndex(i);
3433
- onMatch?.(result, i);
3434
- return;
3435
- }
3436
- } catch {}
3437
- }
3438
- setMatchedIndex(-1);
3439
- onMatch?.(result, -1);
3440
- }, [cases, onMatch]);
3441
- const finalPrompt = prompt || promptFromChildren;
3442
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("span", {
3443
- className,
3444
- children: [
3445
- /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ESIStructured, {
3446
- prompt: finalPrompt,
3447
- schema,
3448
- temperature,
3449
- cacheTtl,
3450
- loading,
3451
- onSuccess: handleSuccess,
3452
- render: () => null
3453
- }, undefined, false, undefined, this),
3454
- matchedIndex !== null && matchedIndex >= 0 && cases[matchedIndex]?.content,
3455
- matchedIndex === -1 && defaultCase
3456
- ]
3457
- }, undefined, true, undefined, this);
3458
- }
3459
- function defaultDescribeUsers(users) {
3460
- if (users.length === 0)
3461
- return "No other users are viewing this content.";
3462
- if (users.length === 1)
3463
- return `1 user is viewing: ${describeUser(users[0])}`;
3464
- const roles = [...new Set(users.map((u) => u.role).filter(Boolean))];
3465
- const roleStr = roles.length > 0 ? ` with roles: ${roles.join(", ")}` : "";
3466
- return `${users.length} users are viewing${roleStr}:
3467
- ${users.map(describeUser).join(`
3468
- `)}`;
3469
- }
3470
- function describeUser(user) {
3471
- const parts = [user.name || user.userId];
3472
- if (user.role)
3473
- parts.push(`(${user.role})`);
3474
- if (user.status)
3475
- parts.push(`[${user.status}]`);
3476
- return `- ${parts.join(" ")}`;
3477
- }
3478
- function ESICollaborative({
3479
- children,
3480
- prompt,
3481
- schema,
3482
- render,
3483
- fallback,
3484
- loading = "...",
3485
- describeUsers = defaultDescribeUsers,
3486
- reactToPresenceChange = true,
3487
- presenceDebounce = 2000,
3488
- temperature,
3489
- maxTokens,
3490
- cacheTtl,
3491
- onSuccess,
3492
- className
3493
- }) {
3494
- const presence = usePresenceForESI();
3495
- const [debouncedUsers, setDebouncedUsers] = import_react2.useState(presence.users);
3496
- const [result, setResult] = import_react2.useState(null);
3497
- import_react2.useEffect(() => {
3498
- if (!reactToPresenceChange)
3499
- return;
3500
- const timer = setTimeout(() => {
3501
- setDebouncedUsers(presence.users);
3502
- }, presenceDebounce);
3503
- return () => clearTimeout(timer);
3504
- }, [presence.users, reactToPresenceChange, presenceDebounce]);
3505
- const basePrompt = prompt || (typeof children === "string" ? children : String(children || ""));
3506
- const presenceDescription = describeUsers(debouncedUsers);
3507
- const collaborativePrompt = `[Audience Context]
3508
- ${presenceDescription}
3509
-
3510
- [Task]
3511
- ${basePrompt}
3512
-
3513
- Consider ALL viewers when generating your response. The content should be relevant and appropriate for everyone currently viewing.`;
3514
- const handleSuccess = import_react2.useCallback((data) => {
3515
- setResult(data);
3516
- onSuccess?.(data, debouncedUsers);
3517
- }, [debouncedUsers, onSuccess]);
3518
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ESIStructured, {
3519
- prompt: collaborativePrompt,
3520
- schema,
3521
- temperature,
3522
- maxTokens,
3523
- cacheTtl,
3524
- loading,
3525
- fallback,
3526
- onSuccess: handleSuccess,
3527
- className,
3528
- render: (data, meta) => {
3529
- if (render) {
3530
- return render(data, debouncedUsers);
3531
- }
3532
- return JSON.stringify(data);
3533
- }
3534
- }, undefined, false, undefined, this);
3535
- }
3536
- function ESIReflect({
3537
- children,
3538
- prompt,
3539
- schema,
3540
- until,
3541
- maxIterations = 3,
3542
- render,
3543
- showProgress = false,
3544
- fallback,
3545
- loading = "...",
3546
- onIteration,
3547
- onComplete,
3548
- className
3549
- }) {
3550
- const { process: process2, enabled } = useESI();
3551
- const [currentResult, setCurrentResult] = import_react2.useState(null);
3552
- const [iteration, setIteration] = import_react2.useState(0);
3553
- const [isComplete, setIsComplete] = import_react2.useState(false);
3554
- const [isLoading, setIsLoading] = import_react2.useState(true);
3555
- const basePrompt = prompt || (typeof children === "string" ? children : String(children || ""));
3556
- import_react2.useEffect(() => {
3557
- if (!enabled) {
3558
- setIsLoading(false);
3559
- return;
3560
- }
3561
- async function runReflection() {
3562
- setIsLoading(true);
3563
- let currentIteration = 0;
3564
- let lastResult = null;
3565
- let previousAttempts = [];
3566
- while (currentIteration < maxIterations) {
3567
- let reflectionPrompt = basePrompt;
3568
- if (currentIteration > 0 && lastResult) {
3569
- reflectionPrompt = `[Previous Attempt ${currentIteration}]
3570
- ${JSON.stringify(lastResult)}
3571
-
3572
- [Reflection]
3573
- The previous attempt did not meet the quality threshold. Please improve upon it.
3574
-
3575
- [Original Task]
3576
- ${basePrompt}`;
3577
- }
3578
- const fullPrompt = reflectionPrompt + generateSchemaPrompt(schema);
3579
- const directive = {
3580
- id: `esi-reflect-${Date.now()}-${currentIteration}`,
3581
- params: { model: "llm" },
3582
- content: { type: "text", value: fullPrompt }
3583
- };
3584
- const result = await process2(directive);
3585
- if (!result.success || !result.output) {
3586
- break;
3587
- }
3588
- const parseResult = parseWithSchema(result.output, schema);
3589
- if (!parseResult.success) {
3590
- currentIteration++;
3591
- continue;
3592
- }
3593
- lastResult = parseResult.data;
3594
- setCurrentResult(parseResult.data);
3595
- setIteration(currentIteration + 1);
3596
- onIteration?.(parseResult.data, currentIteration + 1);
3597
- if (until(parseResult.data, currentIteration + 1)) {
3598
- setIsComplete(true);
3599
- onComplete?.(parseResult.data, currentIteration + 1);
3600
- break;
3601
- }
3602
- previousAttempts.push(result.output);
3603
- currentIteration++;
3604
- }
3605
- if (!isComplete && lastResult) {
3606
- setIsComplete(true);
3607
- onComplete?.(lastResult, currentIteration);
3608
- }
3609
- setIsLoading(false);
3610
- }
3611
- runReflection();
3612
- }, [basePrompt, enabled, maxIterations]);
3613
- if (isLoading) {
3614
- if (showProgress && currentResult) {
3615
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("span", {
3616
- className,
3617
- children: [
3618
- render ? render(currentResult, iteration) : JSON.stringify(currentResult),
3619
- /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("span", {
3620
- children: [
3621
- " (refining... iteration ",
3622
- iteration,
3623
- ")"
3624
- ]
3625
- }, undefined, true, undefined, this)
3626
- ]
3627
- }, undefined, true, undefined, this);
3628
- }
3629
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("span", {
3630
- className,
3631
- children: loading
3632
- }, undefined, false, undefined, this);
3633
- }
3634
- if (!currentResult) {
3635
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("span", {
3636
- className,
3637
- children: fallback
3638
- }, undefined, false, undefined, this);
3639
- }
3640
- if (render) {
3641
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("span", {
3642
- className,
3643
- children: render(currentResult, iteration)
3644
- }, undefined, false, undefined, this);
3645
- }
3646
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("span", {
3647
- className,
3648
- children: JSON.stringify(currentResult)
3649
- }, undefined, false, undefined, this);
3650
- }
3651
- function ESIOptimize({
3652
- children,
3653
- prompt,
3654
- schema,
3655
- criteria = ["clarity", "relevance", "completeness", "conciseness"],
3656
- targetQuality = 0.85,
3657
- maxRounds = 3,
3658
- onlyWhenAlone = true,
3659
- render,
3660
- fallback,
3661
- loading = "...",
3662
- onImprove,
3663
- onOptimized,
3664
- className
3665
- }) {
3666
- const { process: process2, enabled } = useESI();
3667
- const presence = usePresenceForESI();
3668
- const [result, setResult] = import_react2.useState(null);
3669
- const [meta, setMeta] = import_react2.useState({
3670
- rounds: 0,
3671
- quality: 0,
3672
- improvements: [],
3673
- wasOptimized: false
3674
- });
3675
- const [isLoading, setIsLoading] = import_react2.useState(true);
3676
- const basePrompt = prompt || (typeof children === "string" ? children : String(children || ""));
3677
- const shouldOptimize = !onlyWhenAlone || presence.users.length <= 1;
3678
- import_react2.useEffect(() => {
3679
- if (!enabled) {
3680
- setIsLoading(false);
3681
- return;
3682
- }
3683
- async function runOptimization() {
3684
- setIsLoading(true);
3685
- const criteriaList = criteria.join(", ");
3686
- const firstPassPrompt = `${basePrompt}
3687
-
3688
- After generating your response, assess its quality on these criteria: ${criteriaList}
3689
-
3690
- ${generateSchemaPrompt(schema)}
3691
-
3692
- Additionally, include a self-assessment in this format:
3693
- {
3694
- "result": <your response matching the schema above>,
3695
- "selfAssessment": {
3696
- "quality": <0-1 score>,
3697
- "strengths": [<list of strengths>],
3698
- "weaknesses": [<list of weaknesses>],
3699
- "improvementSuggestions": [<specific improvements>]
3700
- }
3701
- }`;
3702
- let currentResult = null;
3703
- let currentQuality = 0;
3704
- let round = 0;
3705
- let improvements = [];
3706
- let lastWeaknesses = [];
3707
- const firstResult = await process2({
3708
- id: `esi-optimize-${Date.now()}-0`,
3709
- params: { model: "llm" },
3710
- content: { type: "text", value: firstPassPrompt }
3711
- });
3712
- if (!firstResult.success || !firstResult.output) {
3713
- setIsLoading(false);
3714
- return;
3715
- }
3716
- try {
3717
- const parsed = JSON.parse(extractJson(firstResult.output));
3718
- const validated = schema.safeParse(parsed.result);
3719
- if (validated.success) {
3720
- currentResult = validated.data;
3721
- currentQuality = parsed.selfAssessment?.quality || 0.5;
3722
- lastWeaknesses = parsed.selfAssessment?.weaknesses || [];
3723
- round = 1;
3724
- setResult(currentResult);
3725
- setMeta({
3726
- rounds: 1,
3727
- quality: currentQuality,
3728
- improvements: [],
3729
- wasOptimized: false
3730
- });
3731
- onImprove?.(currentResult, 1, currentQuality);
3732
- }
3733
- } catch {
3734
- const parseResult = parseWithSchema(firstResult.output, schema);
3735
- if (parseResult.success) {
3736
- currentResult = parseResult.data;
3737
- currentQuality = 0.6;
3738
- round = 1;
3739
- setResult(currentResult);
3740
- } else {
3741
- setIsLoading(false);
3742
- return;
3743
- }
3744
- }
3745
- if (shouldOptimize && currentQuality < targetQuality) {
3746
- while (round < maxRounds && currentQuality < targetQuality) {
3747
- const optimizePrompt = `You previously generated this response:
3748
- ${JSON.stringify(currentResult)}
3749
-
3750
- Quality score: ${currentQuality.toFixed(2)}
3751
- Weaknesses identified: ${lastWeaknesses.join(", ") || "none specified"}
3752
-
3753
- Please improve the response, focusing on: ${criteriaList}
3754
- Address the weaknesses and aim for a quality score above ${targetQuality}.
3755
-
3756
- ${generateSchemaPrompt(schema)}
3757
-
3758
- Include your improved self-assessment:
3759
- {
3760
- "result": <improved response>,
3761
- "selfAssessment": {
3762
- "quality": <0-1 score>,
3763
- "strengths": [...],
3764
- "weaknesses": [...],
3765
- "improvementSuggestions": [...]
3766
- },
3767
- "improvementsMade": [<what you improved>]
3768
- }`;
3769
- const improvedResult = await process2({
3770
- id: `esi-optimize-${Date.now()}-${round}`,
3771
- params: { model: "llm" },
3772
- content: { type: "text", value: optimizePrompt }
3773
- });
3774
- if (!improvedResult.success || !improvedResult.output) {
3775
- break;
3776
- }
3777
- try {
3778
- const parsed = JSON.parse(extractJson(improvedResult.output));
3779
- const validated = schema.safeParse(parsed.result);
3780
- if (validated.success) {
3781
- const newQuality = parsed.selfAssessment?.quality || currentQuality;
3782
- if (newQuality > currentQuality) {
3783
- currentResult = validated.data;
3784
- currentQuality = newQuality;
3785
- lastWeaknesses = parsed.selfAssessment?.weaknesses || [];
3786
- if (parsed.improvementsMade) {
3787
- improvements.push(...parsed.improvementsMade);
3788
- }
3789
- setResult(currentResult);
3790
- setMeta({
3791
- rounds: round + 1,
3792
- quality: currentQuality,
3793
- improvements,
3794
- wasOptimized: true
3795
- });
3796
- onImprove?.(currentResult, round + 1, currentQuality);
3797
- }
3798
- }
3799
- } catch {}
3800
- round++;
3801
- }
3802
- }
3803
- if (currentResult) {
3804
- setMeta((prev) => ({
3805
- ...prev,
3806
- rounds: round,
3807
- quality: currentQuality,
3808
- wasOptimized: round > 1
3809
- }));
3810
- onOptimized?.(currentResult, round, currentQuality);
3811
- }
3812
- setIsLoading(false);
3813
- }
3814
- runOptimization();
3815
- }, [basePrompt, enabled, shouldOptimize, targetQuality, maxRounds]);
3816
- if (isLoading) {
3817
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("span", {
3818
- className,
3819
- children: loading
3820
- }, undefined, false, undefined, this);
3821
- }
3822
- if (!result) {
3823
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("span", {
3824
- className,
3825
- children: fallback
3826
- }, undefined, false, undefined, this);
3827
- }
3828
- if (render) {
3829
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("span", {
3830
- className,
3831
- children: render(result, meta)
3832
- }, undefined, false, undefined, this);
3833
- }
3834
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV("span", {
3835
- className,
3836
- children: JSON.stringify(result)
3837
- }, undefined, false, undefined, this);
3838
- }
3839
- function extractJson(str) {
3840
- let cleaned = str.trim();
3841
- if (cleaned.startsWith("```")) {
3842
- const match = cleaned.match(/```(?:json)?\s*([\s\S]*?)```/);
3843
- if (match)
3844
- cleaned = match[1].trim();
3845
- }
3846
- const jsonMatch = cleaned.match(/\{[\s\S]*\}/);
3847
- if (jsonMatch)
3848
- return jsonMatch[0];
3849
- return cleaned;
3850
- }
3851
- function ESIAuto({
3852
- children,
3853
- prompt,
3854
- schema,
3855
- render,
3856
- collaborativeThreshold = 2,
3857
- optimizeSettings,
3858
- fallback,
3859
- loading,
3860
- className
3861
- }) {
3862
- const presence = usePresenceForESI();
3863
- const userCount = presence.users.length;
3864
- const mode = userCount >= collaborativeThreshold ? "collaborative" : userCount === 1 ? "optimized" : "basic";
3865
- if (mode === "collaborative") {
3866
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ESICollaborative, {
3867
- prompt,
3868
- schema,
3869
- fallback,
3870
- loading,
3871
- className,
3872
- render: render ? (data) => render(data, "collaborative") : undefined,
3873
- children
3874
- }, undefined, false, undefined, this);
3875
- }
3876
- if (mode === "optimized") {
3877
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ESIOptimize, {
3878
- prompt,
3879
- schema,
3880
- criteria: optimizeSettings?.criteria,
3881
- targetQuality: optimizeSettings?.targetQuality,
3882
- maxRounds: optimizeSettings?.maxRounds,
3883
- fallback,
3884
- loading,
3885
- className,
3886
- render: render ? (data) => render(data, "optimized") : undefined,
3887
- children
3888
- }, undefined, false, undefined, this);
3889
- }
3890
- return /* @__PURE__ */ jsx_dev_runtime2.jsxDEV(ESIStructured, {
3891
- prompt,
3892
- schema,
3893
- fallback,
3894
- loading,
3895
- className,
3896
- render: render ? (data) => render(data, "basic") : undefined,
3897
- children
3898
- }, undefined, false, undefined, this);
3899
- }
3900
- var ESIControl = {
3901
- Structured: ESIStructured,
3902
- If: ESIIf,
3903
- Match: ESIMatch,
3904
- Case: ESICase,
3905
- Default: ESIDefault,
3906
- Collaborative: ESICollaborative,
3907
- Reflect: ESIReflect,
3908
- Optimize: ESIOptimize,
3909
- Auto: ESIAuto
3910
- };
1
+ import {
2
+ CYRANO_TOOL_SUGGESTIONS,
3
+ DEFAULT_ESI_CONFIG,
4
+ DEFAULT_ROUTER_CONFIG,
5
+ ESI,
6
+ ESIABTest,
7
+ ESIAuto,
8
+ ESICase,
9
+ ESIClamp,
10
+ ESICollaborative,
11
+ ESIControl,
12
+ ESIDefault,
13
+ ESIEmbed,
14
+ ESIEmotion,
15
+ ESIEmotionGate,
16
+ ESIFirst,
17
+ ESIForEach,
18
+ ESIHide,
19
+ ESIIf,
20
+ ESIInfer,
21
+ ESIMatch,
22
+ ESIOptimize,
23
+ ESIProvider,
24
+ ESIReflect,
25
+ ESIScore,
26
+ ESISelect,
27
+ ESIShow,
28
+ ESIStructured,
29
+ ESITierGate,
30
+ ESITimeGate,
31
+ ESIUnless,
32
+ ESIVision,
33
+ ESIWhen,
34
+ EdgeWorkersESIProcessor,
35
+ HeuristicAdapter,
36
+ SpeculationManager,
37
+ addSpeculationHeaders,
38
+ autoInitSpeculation,
39
+ createContextMiddleware,
40
+ createControlProcessor,
41
+ createExhaustEntry,
42
+ createSpeculationHook,
43
+ esiContext,
44
+ esiCyrano,
45
+ esiEmbed,
46
+ esiEmotion,
47
+ esiHalo,
48
+ esiIf,
49
+ esiInfer,
50
+ esiMatch,
51
+ esiVision,
52
+ esiWithContext,
53
+ evaluateTrigger,
54
+ extractUserContext,
55
+ generateESIStateScript,
56
+ generateESIStateScriptFromContext,
57
+ generateSchemaPrompt,
58
+ getToolSuggestions,
59
+ parseWithSchema,
60
+ serializeToESIState,
61
+ setContextCookies,
62
+ supportsLinkPrefetch,
63
+ supportsSpeculationRules,
64
+ updateGlobalESIState,
65
+ useESI,
66
+ useESIEmotionState,
67
+ useESIFeature,
68
+ useESIInfer,
69
+ useESIPreferences,
70
+ useESITier,
71
+ useGlobalESIState
72
+ } from "../chunk-rg2gma51.js";
73
+ import"../chunk-tgx0r0vn.js";
3911
74
  export {
3912
75
  useGlobalESIState,
3913
76
  useESITier,
@@ -3947,21 +110,34 @@ export {
3947
110
  SpeculationManager,
3948
111
  HeuristicAdapter,
3949
112
  EdgeWorkersESIProcessor,
113
+ ESIWhen,
3950
114
  ESIVision,
115
+ ESIUnless,
116
+ ESITimeGate,
117
+ ESITierGate,
3951
118
  ESIStructured,
119
+ ESIShow,
120
+ ESISelect,
121
+ ESIScore,
3952
122
  ESIReflect,
3953
123
  ESIProvider,
3954
124
  ESIOptimize,
3955
125
  ESIMatch,
3956
126
  ESIInfer,
3957
127
  ESIIf,
128
+ ESIHide,
129
+ ESIForEach,
130
+ ESIFirst,
131
+ ESIEmotionGate,
3958
132
  ESIEmotion,
3959
133
  ESIEmbed,
3960
134
  ESIDefault,
3961
135
  ESIControl,
3962
136
  ESICollaborative,
137
+ ESIClamp,
3963
138
  ESICase,
3964
139
  ESIAuto,
140
+ ESIABTest,
3965
141
  ESI,
3966
142
  DEFAULT_ROUTER_CONFIG,
3967
143
  DEFAULT_ESI_CONFIG,