@sola-air-ui/core 1.0.2 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/sola-core.iife.js +597 -0
- package/dist/sola-core.iife.min.js +4 -0
- package/package.json +40 -32
- package/src/index.js +4 -61
- package/src/sentinel.js +179 -0
- package/build.js +0 -33
|
@@ -0,0 +1,597 @@
|
|
|
1
|
+
/* @sola-air-ui/core — IIFE build for ServiceNow and no-bundler environments */
|
|
2
|
+
var SolaCore = (() => {
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
|
|
21
|
+
// src/index.js
|
|
22
|
+
var src_exports = {};
|
|
23
|
+
__export(src_exports, {
|
|
24
|
+
SolaSentinel: () => SolaSentinel,
|
|
25
|
+
__flush_destroys: () => __flush_destroys,
|
|
26
|
+
__flush_mounts: () => __flush_mounts,
|
|
27
|
+
configureData: () => configureData,
|
|
28
|
+
configureIntent: () => configureIntent,
|
|
29
|
+
createData: () => createData,
|
|
30
|
+
createDerived: () => createDerived,
|
|
31
|
+
createEffect: () => createEffect,
|
|
32
|
+
createIntent: () => createIntent,
|
|
33
|
+
createSentinel: () => createSentinel,
|
|
34
|
+
createSignal: () => createSignal,
|
|
35
|
+
createTopicSignal: () => createTopicSignal,
|
|
36
|
+
flushSync: () => flushSync,
|
|
37
|
+
onDestroy: () => onDestroy,
|
|
38
|
+
onMount: () => onMount,
|
|
39
|
+
popContext: () => popContext,
|
|
40
|
+
pushContext: () => pushContext,
|
|
41
|
+
signalMesh: () => signalMesh
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// src/sentinel.js
|
|
45
|
+
var FIELD_BUFFER_MAX_EVENTS = 50;
|
|
46
|
+
var FIELD_BUFFER_WINDOW_MS = 6e4;
|
|
47
|
+
var FIELD_TEXT_PREVIEW_MAX_CHARS = 200;
|
|
48
|
+
function now() {
|
|
49
|
+
return typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
50
|
+
}
|
|
51
|
+
var SolaSentinel = class {
|
|
52
|
+
constructor(name = "default", options = {}) {
|
|
53
|
+
this.name = name;
|
|
54
|
+
this.thresholdMs = options.thresholdMs || 600;
|
|
55
|
+
this.maxRageClicks = options.maxRageClicks || 3;
|
|
56
|
+
this.clickHistory = [];
|
|
57
|
+
this.subscribers = /* @__PURE__ */ new Set();
|
|
58
|
+
this.frictionEvents = [];
|
|
59
|
+
this.flowIndex = 99.8;
|
|
60
|
+
this.fieldHistory = [];
|
|
61
|
+
this.lastActivityAt = 0;
|
|
62
|
+
this.lastSuggestedAt = -Infinity;
|
|
63
|
+
this.idleThresholdMs = options.idleThresholdMs ?? 1500;
|
|
64
|
+
this.minSuggestIntervalMs = options.minSuggestIntervalMs ?? 8e3;
|
|
65
|
+
this.minEventsForSuggestion = options.minEventsForSuggestion ?? 2;
|
|
66
|
+
}
|
|
67
|
+
recordClick(actionId, target = "button") {
|
|
68
|
+
const ts = now();
|
|
69
|
+
this.clickHistory.push({ actionId, target, timestamp: ts });
|
|
70
|
+
this.clickHistory = this.clickHistory.filter((c) => ts - c.timestamp < 2e3);
|
|
71
|
+
const recent = this.clickHistory.filter((c) => c.actionId === actionId && ts - c.timestamp < this.thresholdMs);
|
|
72
|
+
if (recent.length >= this.maxRageClicks) {
|
|
73
|
+
this.triggerFrictionAlert({
|
|
74
|
+
type: "RAGE_CLICK",
|
|
75
|
+
actionId,
|
|
76
|
+
target,
|
|
77
|
+
count: recent.length,
|
|
78
|
+
timestamp: ts,
|
|
79
|
+
severity: "HIGH",
|
|
80
|
+
message: `Rage-click burst: ${recent.length} taps in ${Math.round(ts - recent[0].timestamp)}ms`
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
recordSignalDrop(topic, error) {
|
|
85
|
+
this.triggerFrictionAlert({
|
|
86
|
+
type: "SIGNAL_TIMEOUT",
|
|
87
|
+
topic,
|
|
88
|
+
error: error?.message || String(error),
|
|
89
|
+
timestamp: now(),
|
|
90
|
+
severity: "CRITICAL",
|
|
91
|
+
message: `Signal channel "${topic}" breached SLA timeout (504 Gateway Stall)`
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
triggerFrictionAlert(event) {
|
|
95
|
+
this.frictionEvents.unshift(event);
|
|
96
|
+
if (this.frictionEvents.length > 50) this.frictionEvents.pop();
|
|
97
|
+
this._recomputeFlowIndex(event.timestamp);
|
|
98
|
+
this.subscribers.forEach((cb) => {
|
|
99
|
+
try {
|
|
100
|
+
cb(event, this);
|
|
101
|
+
} catch (e) {
|
|
102
|
+
console.error(e);
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
onFriction(cb) {
|
|
107
|
+
this.subscribers.add(cb);
|
|
108
|
+
return () => this.subscribers.delete(cb);
|
|
109
|
+
}
|
|
110
|
+
// ─── Flow index ───
|
|
111
|
+
// A real computed score, not a fixed decrement: severity- and recency-weighted
|
|
112
|
+
// friction events, the share of field visits that were backtracks, plus how
|
|
113
|
+
// erratic the pacing between field events is (a proxy for hesitation).
|
|
114
|
+
_recomputeFlowIndex(ts = now()) {
|
|
115
|
+
let score = 99.8;
|
|
116
|
+
const recentFriction = this.frictionEvents.filter((e) => ts - e.timestamp < 12e4);
|
|
117
|
+
score -= recentFriction.reduce((sum, e) => {
|
|
118
|
+
const severityWeight = e.severity === "CRITICAL" ? 6 : e.severity === "HIGH" ? 3.8 : 2;
|
|
119
|
+
const recencyWeight = Math.max(0.3, 1 - (ts - e.timestamp) / 12e4);
|
|
120
|
+
return sum + severityWeight * recencyWeight;
|
|
121
|
+
}, 0);
|
|
122
|
+
const focusEvents = this.fieldHistory.filter((e) => e.type === "focus");
|
|
123
|
+
if (focusEvents.length > 0) {
|
|
124
|
+
const revisitRatio = focusEvents.filter((e) => e.revisit).length / focusEvents.length;
|
|
125
|
+
score -= revisitRatio * 15;
|
|
126
|
+
}
|
|
127
|
+
if (this.fieldHistory.length >= 3) {
|
|
128
|
+
const gaps = [];
|
|
129
|
+
for (let i = 1; i < this.fieldHistory.length; i++) {
|
|
130
|
+
gaps.push(this.fieldHistory[i].timestamp - this.fieldHistory[i - 1].timestamp);
|
|
131
|
+
}
|
|
132
|
+
const mean = gaps.reduce((a, b) => a + b, 0) / gaps.length;
|
|
133
|
+
const variance = gaps.reduce((sum, g) => sum + (g - mean) ** 2, 0) / gaps.length;
|
|
134
|
+
score -= Math.min(10, Math.sqrt(variance) / 500);
|
|
135
|
+
}
|
|
136
|
+
this.flowIndex = Math.max(0, Math.min(99.8, Number(score.toFixed(1))));
|
|
137
|
+
return this.flowIndex;
|
|
138
|
+
}
|
|
139
|
+
// ─── Ambient field observation ───
|
|
140
|
+
_pushFieldEvent(event) {
|
|
141
|
+
this.fieldHistory.push(event);
|
|
142
|
+
this.fieldHistory = this.fieldHistory.filter((e) => event.timestamp - e.timestamp < FIELD_BUFFER_WINDOW_MS).slice(-FIELD_BUFFER_MAX_EVENTS);
|
|
143
|
+
this.lastActivityAt = event.timestamp;
|
|
144
|
+
this._recomputeFlowIndex(event.timestamp);
|
|
145
|
+
}
|
|
146
|
+
recordFieldFocus(fieldId, ts = now()) {
|
|
147
|
+
const revisit = this.fieldHistory.some((e) => e.type === "blur" && e.fieldId === fieldId);
|
|
148
|
+
this._pushFieldEvent({ type: "focus", fieldId, revisit, timestamp: ts });
|
|
149
|
+
return revisit;
|
|
150
|
+
}
|
|
151
|
+
recordFieldBlur(fieldId, value, ts = now()) {
|
|
152
|
+
const text = String(value ?? "");
|
|
153
|
+
const preview = text.length > FIELD_TEXT_PREVIEW_MAX_CHARS ? text.slice(-FIELD_TEXT_PREVIEW_MAX_CHARS) : text;
|
|
154
|
+
this._pushFieldEvent({ type: "blur", fieldId, valuePreview: preview, valueLength: text.length, timestamp: ts });
|
|
155
|
+
}
|
|
156
|
+
// ─── Significance gate ───
|
|
157
|
+
// Fires at most once per `minSuggestIntervalMs`, only after `idleThresholdMs`
|
|
158
|
+
// of inactivity following new activity — never on every keystroke.
|
|
159
|
+
checkSignificance(ts = now()) {
|
|
160
|
+
if (this.fieldHistory.length < this.minEventsForSuggestion) return false;
|
|
161
|
+
if (this.lastActivityAt <= this.lastSuggestedAt) return false;
|
|
162
|
+
if (ts - this.lastActivityAt < this.idleThresholdMs) return false;
|
|
163
|
+
if (ts - this.lastSuggestedAt < this.minSuggestIntervalMs) return false;
|
|
164
|
+
this.lastSuggestedAt = ts;
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
// ─── Prompt builder ───
|
|
168
|
+
// Compact natural-language description of recent field activity, oldest first.
|
|
169
|
+
buildPrompt() {
|
|
170
|
+
if (this.fieldHistory.length === 0) return null;
|
|
171
|
+
const lines = this.fieldHistory.map((e) => {
|
|
172
|
+
if (e.type === "focus") {
|
|
173
|
+
return e.revisit ? `User returned to field "${e.fieldId}".` : `User focused field "${e.fieldId}".`;
|
|
174
|
+
}
|
|
175
|
+
if (e.valueLength === 0) return `User left field "${e.fieldId}" empty.`;
|
|
176
|
+
return `Field "${e.fieldId}" now contains: "${e.valuePreview}"`;
|
|
177
|
+
});
|
|
178
|
+
return [
|
|
179
|
+
"You are an ambient UX assistant embedded in a form.",
|
|
180
|
+
"Recent user activity, oldest first:",
|
|
181
|
+
...lines,
|
|
182
|
+
"",
|
|
183
|
+
"Based only on this activity, suggest exactly one concise, specific next-step action the user might want.",
|
|
184
|
+
'Respond as compact JSON only: {"label": string (<=60 chars), "action": string (<=140 chars), "confidence": number 0-1}.',
|
|
185
|
+
'If nothing useful can be suggested, respond {"label": null}.'
|
|
186
|
+
].join("\n");
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
function createSentinel(name, options) {
|
|
190
|
+
return new SolaSentinel(name, options);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// src/index.js
|
|
194
|
+
var effectStack = [];
|
|
195
|
+
var pendingEffects = /* @__PURE__ */ new Set();
|
|
196
|
+
var isFlushing = false;
|
|
197
|
+
function flushSync() {
|
|
198
|
+
while (pendingEffects.size > 0) {
|
|
199
|
+
const effects = [...pendingEffects];
|
|
200
|
+
pendingEffects.clear();
|
|
201
|
+
for (const effect of effects) {
|
|
202
|
+
effect.execute();
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
isFlushing = false;
|
|
206
|
+
}
|
|
207
|
+
function scheduleFlush() {
|
|
208
|
+
if (!isFlushing) {
|
|
209
|
+
isFlushing = true;
|
|
210
|
+
queueMicrotask(flushSync);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
function createSignal(initialValue) {
|
|
214
|
+
let value = initialValue;
|
|
215
|
+
const subscribers = /* @__PURE__ */ new Set();
|
|
216
|
+
const read = () => {
|
|
217
|
+
const currentEffect = effectStack[effectStack.length - 1];
|
|
218
|
+
if (currentEffect) {
|
|
219
|
+
subscribers.add(currentEffect);
|
|
220
|
+
currentEffect.dependencies.add(subscribers);
|
|
221
|
+
}
|
|
222
|
+
return value;
|
|
223
|
+
};
|
|
224
|
+
const write = (newValue) => {
|
|
225
|
+
if (value !== newValue) {
|
|
226
|
+
value = newValue;
|
|
227
|
+
for (const sub of [...subscribers]) {
|
|
228
|
+
pendingEffects.add(sub);
|
|
229
|
+
}
|
|
230
|
+
scheduleFlush();
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
return [read, write];
|
|
234
|
+
}
|
|
235
|
+
function createEffect(fn) {
|
|
236
|
+
const effect = {
|
|
237
|
+
execute() {
|
|
238
|
+
cleanup();
|
|
239
|
+
effectStack.push(effect);
|
|
240
|
+
try {
|
|
241
|
+
fn();
|
|
242
|
+
} finally {
|
|
243
|
+
effectStack.pop();
|
|
244
|
+
}
|
|
245
|
+
},
|
|
246
|
+
dependencies: /* @__PURE__ */ new Set(),
|
|
247
|
+
cleanup
|
|
248
|
+
};
|
|
249
|
+
function cleanup() {
|
|
250
|
+
for (const dep of effect.dependencies) {
|
|
251
|
+
dep.delete(effect);
|
|
252
|
+
}
|
|
253
|
+
effect.dependencies.clear();
|
|
254
|
+
}
|
|
255
|
+
effectStack.push(effect);
|
|
256
|
+
try {
|
|
257
|
+
fn();
|
|
258
|
+
} finally {
|
|
259
|
+
effectStack.pop();
|
|
260
|
+
}
|
|
261
|
+
return cleanup;
|
|
262
|
+
}
|
|
263
|
+
function createDerived(fn) {
|
|
264
|
+
let cachedValue;
|
|
265
|
+
let dirty = true;
|
|
266
|
+
const subscribers = /* @__PURE__ */ new Set();
|
|
267
|
+
let innerDependencies = /* @__PURE__ */ new Set();
|
|
268
|
+
const markDirty = {
|
|
269
|
+
execute() {
|
|
270
|
+
if (!dirty) {
|
|
271
|
+
dirty = true;
|
|
272
|
+
for (const sub of [...subscribers]) {
|
|
273
|
+
pendingEffects.add(sub);
|
|
274
|
+
}
|
|
275
|
+
scheduleFlush();
|
|
276
|
+
}
|
|
277
|
+
},
|
|
278
|
+
dependencies: innerDependencies,
|
|
279
|
+
cleanup() {
|
|
280
|
+
for (const dep of innerDependencies) {
|
|
281
|
+
dep.delete(markDirty);
|
|
282
|
+
}
|
|
283
|
+
innerDependencies.clear();
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
const read = () => {
|
|
287
|
+
const currentEffect = effectStack[effectStack.length - 1];
|
|
288
|
+
if (currentEffect) {
|
|
289
|
+
subscribers.add(currentEffect);
|
|
290
|
+
currentEffect.dependencies.add(subscribers);
|
|
291
|
+
}
|
|
292
|
+
if (dirty) {
|
|
293
|
+
markDirty.cleanup();
|
|
294
|
+
innerDependencies = /* @__PURE__ */ new Set();
|
|
295
|
+
markDirty.dependencies = innerDependencies;
|
|
296
|
+
effectStack.push(markDirty);
|
|
297
|
+
try {
|
|
298
|
+
cachedValue = fn();
|
|
299
|
+
} finally {
|
|
300
|
+
effectStack.pop();
|
|
301
|
+
}
|
|
302
|
+
dirty = false;
|
|
303
|
+
}
|
|
304
|
+
return cachedValue;
|
|
305
|
+
};
|
|
306
|
+
return read;
|
|
307
|
+
}
|
|
308
|
+
var contextStack = [];
|
|
309
|
+
var activeContext = null;
|
|
310
|
+
function pushContext() {
|
|
311
|
+
const ctx = { mounts: [], destroys: [] };
|
|
312
|
+
contextStack.push(ctx);
|
|
313
|
+
activeContext = ctx;
|
|
314
|
+
return ctx;
|
|
315
|
+
}
|
|
316
|
+
function popContext(ctx) {
|
|
317
|
+
const idx = contextStack.lastIndexOf(ctx);
|
|
318
|
+
if (idx !== -1) {
|
|
319
|
+
contextStack.splice(idx, 1);
|
|
320
|
+
}
|
|
321
|
+
activeContext = contextStack.length > 0 ? contextStack[contextStack.length - 1] : null;
|
|
322
|
+
}
|
|
323
|
+
function onMount(fn) {
|
|
324
|
+
if (activeContext) {
|
|
325
|
+
activeContext.mounts.push(fn);
|
|
326
|
+
} else {
|
|
327
|
+
fn();
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
function onDestroy(fn) {
|
|
331
|
+
if (activeContext) {
|
|
332
|
+
activeContext.destroys.push(fn);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
function __flush_mounts() {
|
|
336
|
+
if (activeContext && activeContext.mounts.length > 0) {
|
|
337
|
+
const cbs = [...activeContext.mounts];
|
|
338
|
+
activeContext.mounts = [];
|
|
339
|
+
for (const cb of cbs) {
|
|
340
|
+
cb();
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
function __flush_destroys() {
|
|
345
|
+
if (activeContext && activeContext.destroys.length > 0) {
|
|
346
|
+
const cbs = [...activeContext.destroys];
|
|
347
|
+
activeContext.destroys = [];
|
|
348
|
+
for (const cb of cbs) {
|
|
349
|
+
cb();
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
var defaultIntentConfig = {
|
|
354
|
+
provider: "local",
|
|
355
|
+
endpoint: "/api/intent",
|
|
356
|
+
model: "gemini-2.5-flash",
|
|
357
|
+
stream: false
|
|
358
|
+
};
|
|
359
|
+
var globalIntentConfig = { ...defaultIntentConfig };
|
|
360
|
+
function configureIntent(config) {
|
|
361
|
+
globalIntentConfig = { ...globalIntentConfig, ...config };
|
|
362
|
+
}
|
|
363
|
+
async function _consumeSSE(response, onToken, onDone, onError) {
|
|
364
|
+
const reader = response.body.getReader();
|
|
365
|
+
const decoder = new TextDecoder();
|
|
366
|
+
let buf = "";
|
|
367
|
+
try {
|
|
368
|
+
while (true) {
|
|
369
|
+
const { done, value } = await reader.read();
|
|
370
|
+
if (done) break;
|
|
371
|
+
buf += decoder.decode(value, { stream: true });
|
|
372
|
+
const lines = buf.split("\n");
|
|
373
|
+
buf = lines.pop();
|
|
374
|
+
for (const line of lines) {
|
|
375
|
+
if (!line.startsWith("data: ")) continue;
|
|
376
|
+
const payload = line.slice(6).trim();
|
|
377
|
+
if (payload === "[DONE]") {
|
|
378
|
+
onDone();
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
try {
|
|
382
|
+
const parsed = JSON.parse(payload);
|
|
383
|
+
const token = parsed.token ?? parsed.delta ?? parsed.content ?? "";
|
|
384
|
+
if (token) onToken(token);
|
|
385
|
+
} catch {
|
|
386
|
+
if (payload) onToken(payload);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
onDone();
|
|
391
|
+
} catch (err) {
|
|
392
|
+
if (err.name !== "AbortError") onError(err);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
function createIntent(promptFn, options = {}) {
|
|
396
|
+
const config = { ...globalIntentConfig, ...options };
|
|
397
|
+
const [read, write] = createSignal(options.initial ?? null);
|
|
398
|
+
const [loading, setLoading] = createSignal(false);
|
|
399
|
+
const [error, setError] = createSignal(null);
|
|
400
|
+
let abortController = null;
|
|
401
|
+
onDestroy(() => {
|
|
402
|
+
if (abortController) abortController.abort();
|
|
403
|
+
});
|
|
404
|
+
createEffect(() => {
|
|
405
|
+
const prompt = typeof promptFn === "function" ? promptFn() : promptFn;
|
|
406
|
+
if (!prompt) return;
|
|
407
|
+
if (abortController) abortController.abort();
|
|
408
|
+
abortController = new AbortController();
|
|
409
|
+
write(null);
|
|
410
|
+
setError(null);
|
|
411
|
+
setLoading(true);
|
|
412
|
+
const body = JSON.stringify({
|
|
413
|
+
messages: [{ role: "user", content: prompt }],
|
|
414
|
+
model: config.model,
|
|
415
|
+
provider: config.provider,
|
|
416
|
+
stream: config.stream
|
|
417
|
+
});
|
|
418
|
+
fetch(config.endpoint, {
|
|
419
|
+
method: "POST",
|
|
420
|
+
headers: { "Content-Type": "application/json" },
|
|
421
|
+
body,
|
|
422
|
+
signal: abortController.signal
|
|
423
|
+
}).then((res) => {
|
|
424
|
+
if (!res.ok) throw new Error(`Intent failed: ${res.status}`);
|
|
425
|
+
if (config.stream) {
|
|
426
|
+
let accumulated = "";
|
|
427
|
+
return _consumeSSE(
|
|
428
|
+
res,
|
|
429
|
+
(token) => {
|
|
430
|
+
accumulated += token;
|
|
431
|
+
write(accumulated);
|
|
432
|
+
},
|
|
433
|
+
() => setLoading(false),
|
|
434
|
+
(err) => {
|
|
435
|
+
setError(err.message);
|
|
436
|
+
setLoading(false);
|
|
437
|
+
}
|
|
438
|
+
);
|
|
439
|
+
}
|
|
440
|
+
return res.json().then((data) => {
|
|
441
|
+
if (data?.components?.length > 0) write(data.components[0]);
|
|
442
|
+
else if (data?.result != null) write(data.result);
|
|
443
|
+
else write(data);
|
|
444
|
+
setLoading(false);
|
|
445
|
+
});
|
|
446
|
+
}).catch((err) => {
|
|
447
|
+
if (err.name !== "AbortError") {
|
|
448
|
+
console.error("[Sola Intent Error]", err);
|
|
449
|
+
setError(err.message);
|
|
450
|
+
setLoading(false);
|
|
451
|
+
}
|
|
452
|
+
});
|
|
453
|
+
});
|
|
454
|
+
const accessor = read;
|
|
455
|
+
accessor.loading = loading;
|
|
456
|
+
accessor.error = error;
|
|
457
|
+
return accessor;
|
|
458
|
+
}
|
|
459
|
+
var defaultDataConfig = {
|
|
460
|
+
relayEndpoint: "http://localhost:4040/api/query",
|
|
461
|
+
refresh: null
|
|
462
|
+
// e.g. '30s', '1m', '5m'
|
|
463
|
+
};
|
|
464
|
+
var globalDataConfig = { ...defaultDataConfig };
|
|
465
|
+
function configureData(config) {
|
|
466
|
+
globalDataConfig = { ...globalDataConfig, ...config };
|
|
467
|
+
}
|
|
468
|
+
function parseInterval(str) {
|
|
469
|
+
if (!str) return null;
|
|
470
|
+
const match = str.match(/^(\d+)(s|m|h)$/);
|
|
471
|
+
if (!match) return null;
|
|
472
|
+
const val = parseInt(match[1]);
|
|
473
|
+
switch (match[2]) {
|
|
474
|
+
case "s":
|
|
475
|
+
return val * 1e3;
|
|
476
|
+
case "m":
|
|
477
|
+
return val * 60 * 1e3;
|
|
478
|
+
case "h":
|
|
479
|
+
return val * 3600 * 1e3;
|
|
480
|
+
}
|
|
481
|
+
return null;
|
|
482
|
+
}
|
|
483
|
+
function createData(source, options = {}) {
|
|
484
|
+
const config = { ...globalDataConfig, ...options };
|
|
485
|
+
const [read, write] = createSignal({ loading: true, data: null, error: null });
|
|
486
|
+
let abortController = null;
|
|
487
|
+
let refreshTimer = null;
|
|
488
|
+
function fetchData() {
|
|
489
|
+
if (abortController) abortController.abort();
|
|
490
|
+
abortController = new AbortController();
|
|
491
|
+
write({ loading: true, data: read().data, error: null });
|
|
492
|
+
fetch(config.relayEndpoint, {
|
|
493
|
+
method: "POST",
|
|
494
|
+
headers: { "Content-Type": "application/json" },
|
|
495
|
+
body: JSON.stringify({
|
|
496
|
+
source,
|
|
497
|
+
query: config.query || null,
|
|
498
|
+
filters: config.filters || null,
|
|
499
|
+
sort: config.sort || null,
|
|
500
|
+
limit: config.limit || null,
|
|
501
|
+
offset: config.offset || null
|
|
502
|
+
}),
|
|
503
|
+
signal: abortController.signal
|
|
504
|
+
}).then((res) => {
|
|
505
|
+
if (!res.ok) throw new Error(`Data fetch failed: ${res.status}`);
|
|
506
|
+
return res.json();
|
|
507
|
+
}).then((data) => {
|
|
508
|
+
write({ loading: false, data: data.rows || data, error: null });
|
|
509
|
+
}).catch((err) => {
|
|
510
|
+
if (err.name !== "AbortError") {
|
|
511
|
+
console.error("[Sola Data Error]", err);
|
|
512
|
+
write({ loading: false, data: null, error: err.message });
|
|
513
|
+
}
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
fetchData();
|
|
517
|
+
const interval = parseInterval(config.refresh);
|
|
518
|
+
if (interval) {
|
|
519
|
+
refreshTimer = setInterval(fetchData, interval);
|
|
520
|
+
}
|
|
521
|
+
const accessor = () => read();
|
|
522
|
+
accessor.refetch = fetchData;
|
|
523
|
+
accessor.stop = () => {
|
|
524
|
+
if (refreshTimer) clearInterval(refreshTimer);
|
|
525
|
+
if (abortController) abortController.abort();
|
|
526
|
+
};
|
|
527
|
+
return accessor;
|
|
528
|
+
}
|
|
529
|
+
var SignalMeshEngine = class {
|
|
530
|
+
constructor() {
|
|
531
|
+
this.topics = /* @__PURE__ */ new Map();
|
|
532
|
+
this.telemetrySubscribers = /* @__PURE__ */ new Set();
|
|
533
|
+
this.cycleStack = /* @__PURE__ */ new Set();
|
|
534
|
+
}
|
|
535
|
+
topic(name, initialValue) {
|
|
536
|
+
if (!this.topics.has(name)) {
|
|
537
|
+
const [read2, write2] = createSignal(initialValue);
|
|
538
|
+
this.topics.set(name, { read: read2, write: write2, value: initialValue, subscribers: /* @__PURE__ */ new Set() });
|
|
539
|
+
}
|
|
540
|
+
const entry = this.topics.get(name);
|
|
541
|
+
const read = () => entry.read();
|
|
542
|
+
const write = (next, originId = "signal") => {
|
|
543
|
+
const nextVal = typeof next === "function" ? next(entry.value) : next;
|
|
544
|
+
if (entry.value === nextVal) return;
|
|
545
|
+
if (this.cycleStack.has(name)) {
|
|
546
|
+
console.warn(`[Sola Signal Mesh] Cycle detected on topic "${name}". Aborting cyclic dispatch.`);
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
const prev = entry.value;
|
|
550
|
+
entry.value = nextVal;
|
|
551
|
+
entry.write(nextVal);
|
|
552
|
+
const event = {
|
|
553
|
+
topic: name,
|
|
554
|
+
value: nextVal,
|
|
555
|
+
prevValue: prev,
|
|
556
|
+
timestamp: typeof performance !== "undefined" ? performance.now() : Date.now(),
|
|
557
|
+
originWidgetId: originId
|
|
558
|
+
};
|
|
559
|
+
this.telemetrySubscribers.forEach((cb) => {
|
|
560
|
+
try {
|
|
561
|
+
cb(event);
|
|
562
|
+
} catch (e) {
|
|
563
|
+
console.error(e);
|
|
564
|
+
}
|
|
565
|
+
});
|
|
566
|
+
this.cycleStack.add(name);
|
|
567
|
+
try {
|
|
568
|
+
entry.subscribers.forEach((sub) => {
|
|
569
|
+
try {
|
|
570
|
+
sub(nextVal, event);
|
|
571
|
+
} catch (e) {
|
|
572
|
+
console.error(e);
|
|
573
|
+
}
|
|
574
|
+
});
|
|
575
|
+
} finally {
|
|
576
|
+
this.cycleStack.delete(name);
|
|
577
|
+
}
|
|
578
|
+
};
|
|
579
|
+
return [read, write];
|
|
580
|
+
}
|
|
581
|
+
subscribe(name, fn) {
|
|
582
|
+
if (!this.topics.has(name)) {
|
|
583
|
+
this.topic(name, void 0);
|
|
584
|
+
}
|
|
585
|
+
const entry = this.topics.get(name);
|
|
586
|
+
entry.subscribers.add(fn);
|
|
587
|
+
return () => entry.subscribers.delete(fn);
|
|
588
|
+
}
|
|
589
|
+
onTelemetry(fn) {
|
|
590
|
+
this.telemetrySubscribers.add(fn);
|
|
591
|
+
return () => this.telemetrySubscribers.delete(fn);
|
|
592
|
+
}
|
|
593
|
+
};
|
|
594
|
+
var signalMesh = new SignalMeshEngine();
|
|
595
|
+
var createTopicSignal = (topic, initialVal) => signalMesh.topic(topic, initialVal);
|
|
596
|
+
return __toCommonJS(src_exports);
|
|
597
|
+
})();
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/* @sola-air-ui/core v1.0.2 | MIT */
|
|
2
|
+
var SolaCore=(()=>{var I=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var $=Object.prototype.hasOwnProperty;var N=(s,t)=>{for(var e in t)I(s,e,{get:t[e],enumerable:!0})},O=(s,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of L(t))!$.call(s,i)&&i!==e&&I(s,i,{get:()=>t[i],enumerable:!(n=R(t,i))||n.enumerable});return s};var W=s=>O(I({},"__esModule",{value:!0}),s);var et={};N(et,{SolaSentinel:()=>E,__flush_destroys:()=>j,__flush_mounts:()=>V,configureData:()=>Y,configureIntent:()=>G,createData:()=>Z,createDerived:()=>U,createEffect:()=>D,createIntent:()=>z,createSentinel:()=>C,createSignal:()=>S,createTopicSignal:()=>tt,flushSync:()=>M,onDestroy:()=>k,onMount:()=>B,popContext:()=>P,pushContext:()=>X,signalMesh:()=>T});function y(){return typeof performance<"u"?performance.now():Date.now()}var E=class{constructor(t="default",e={}){this.name=t,this.thresholdMs=e.thresholdMs||600,this.maxRageClicks=e.maxRageClicks||3,this.clickHistory=[],this.subscribers=new Set,this.frictionEvents=[],this.flowIndex=99.8,this.fieldHistory=[],this.lastActivityAt=0,this.lastSuggestedAt=-1/0,this.idleThresholdMs=e.idleThresholdMs??1500,this.minSuggestIntervalMs=e.minSuggestIntervalMs??8e3,this.minEventsForSuggestion=e.minEventsForSuggestion??2}recordClick(t,e="button"){let n=y();this.clickHistory.push({actionId:t,target:e,timestamp:n}),this.clickHistory=this.clickHistory.filter(r=>n-r.timestamp<2e3);let i=this.clickHistory.filter(r=>r.actionId===t&&n-r.timestamp<this.thresholdMs);i.length>=this.maxRageClicks&&this.triggerFrictionAlert({type:"RAGE_CLICK",actionId:t,target:e,count:i.length,timestamp:n,severity:"HIGH",message:`Rage-click burst: ${i.length} taps in ${Math.round(n-i[0].timestamp)}ms`})}recordSignalDrop(t,e){this.triggerFrictionAlert({type:"SIGNAL_TIMEOUT",topic:t,error:e?.message||String(e),timestamp:y(),severity:"CRITICAL",message:`Signal channel "${t}" breached SLA timeout (504 Gateway Stall)`})}triggerFrictionAlert(t){this.frictionEvents.unshift(t),this.frictionEvents.length>50&&this.frictionEvents.pop(),this._recomputeFlowIndex(t.timestamp),this.subscribers.forEach(e=>{try{e(t,this)}catch(n){console.error(n)}})}onFriction(t){return this.subscribers.add(t),()=>this.subscribers.delete(t)}_recomputeFlowIndex(t=y()){let e=99.8,n=this.frictionEvents.filter(r=>t-r.timestamp<12e4);e-=n.reduce((r,o)=>{let c=o.severity==="CRITICAL"?6:o.severity==="HIGH"?3.8:2,l=Math.max(.3,1-(t-o.timestamp)/12e4);return r+c*l},0);let i=this.fieldHistory.filter(r=>r.type==="focus");if(i.length>0){let r=i.filter(o=>o.revisit).length/i.length;e-=r*15}if(this.fieldHistory.length>=3){let r=[];for(let l=1;l<this.fieldHistory.length;l++)r.push(this.fieldHistory[l].timestamp-this.fieldHistory[l-1].timestamp);let o=r.reduce((l,u)=>l+u,0)/r.length,c=r.reduce((l,u)=>l+(u-o)**2,0)/r.length;e-=Math.min(10,Math.sqrt(c)/500)}return this.flowIndex=Math.max(0,Math.min(99.8,Number(e.toFixed(1)))),this.flowIndex}_pushFieldEvent(t){this.fieldHistory.push(t),this.fieldHistory=this.fieldHistory.filter(e=>t.timestamp-e.timestamp<6e4).slice(-50),this.lastActivityAt=t.timestamp,this._recomputeFlowIndex(t.timestamp)}recordFieldFocus(t,e=y()){let n=this.fieldHistory.some(i=>i.type==="blur"&&i.fieldId===t);return this._pushFieldEvent({type:"focus",fieldId:t,revisit:n,timestamp:e}),n}recordFieldBlur(t,e,n=y()){let i=String(e??""),r=i.length>200?i.slice(-200):i;this._pushFieldEvent({type:"blur",fieldId:t,valuePreview:r,valueLength:i.length,timestamp:n})}checkSignificance(t=y()){return this.fieldHistory.length<this.minEventsForSuggestion||this.lastActivityAt<=this.lastSuggestedAt||t-this.lastActivityAt<this.idleThresholdMs||t-this.lastSuggestedAt<this.minSuggestIntervalMs?!1:(this.lastSuggestedAt=t,!0)}buildPrompt(){return this.fieldHistory.length===0?null:["You are an ambient UX assistant embedded in a form.","Recent user activity, oldest first:",...this.fieldHistory.map(e=>e.type==="focus"?e.revisit?`User returned to field "${e.fieldId}".`:`User focused field "${e.fieldId}".`:e.valueLength===0?`User left field "${e.fieldId}" empty.`:`Field "${e.fieldId}" now contains: "${e.valuePreview}"`),"","Based only on this activity, suggest exactly one concise, specific next-step action the user might want.",'Respond as compact JSON only: {"label": string (<=60 chars), "action": string (<=140 chars), "confidence": number 0-1}.','If nothing useful can be suggested, respond {"label": null}.'].join(`
|
|
3
|
+
`)}};function C(s,t){return new E(s,t)}var p=[],v=new Set,x=!1;function M(){for(;v.size>0;){let s=[...v];v.clear();for(let t of s)t.execute()}x=!1}function H(){x||(x=!0,queueMicrotask(M))}function S(s){let t=s,e=new Set;return[()=>{let r=p[p.length-1];return r&&(e.add(r),r.dependencies.add(e)),t},r=>{if(t!==r){t=r;for(let o of[...e])v.add(o);H()}}]}function D(s){let t={execute(){e(),p.push(t);try{s()}finally{p.pop()}},dependencies:new Set,cleanup:e};function e(){for(let n of t.dependencies)n.delete(t);t.dependencies.clear()}p.push(t);try{s()}finally{p.pop()}return e}function U(s){let t,e=!0,n=new Set,i=new Set,r={execute(){if(!e){e=!0;for(let c of[...n])v.add(c);H()}},dependencies:i,cleanup(){for(let c of i)c.delete(r);i.clear()}};return()=>{let c=p[p.length-1];if(c&&(n.add(c),c.dependencies.add(n)),e){r.cleanup(),i=new Set,r.dependencies=i,p.push(r);try{t=s()}finally{p.pop()}e=!1}return t}}var b=[],f=null;function X(){let s={mounts:[],destroys:[]};return b.push(s),f=s,s}function P(s){let t=b.lastIndexOf(s);t!==-1&&b.splice(t,1),f=b.length>0?b[b.length-1]:null}function B(s){f?f.mounts.push(s):s()}function k(s){f&&f.destroys.push(s)}function V(){if(f&&f.mounts.length>0){let s=[...f.mounts];f.mounts=[];for(let t of s)t()}}function j(){if(f&&f.destroys.length>0){let s=[...f.destroys];f.destroys=[];for(let t of s)t()}}var q={provider:"local",endpoint:"/api/intent",model:"gemini-2.5-flash",stream:!1},_={...q};function G(s){_={..._,...s}}async function J(s,t,e,n){let i=s.body.getReader(),r=new TextDecoder,o="";try{for(;;){let{done:c,value:l}=await i.read();if(c)break;o+=r.decode(l,{stream:!0});let u=o.split(`
|
|
4
|
+
`);o=u.pop();for(let a of u){if(!a.startsWith("data: "))continue;let d=a.slice(6).trim();if(d==="[DONE]"){e();return}try{let g=JSON.parse(d),h=g.token??g.delta??g.content??"";h&&t(h)}catch{d&&t(d)}}}e()}catch(c){c.name!=="AbortError"&&n(c)}}function z(s,t={}){let e={..._,...t},[n,i]=S(t.initial??null),[r,o]=S(!1),[c,l]=S(null),u=null;k(()=>{u&&u.abort()}),D(()=>{let d=typeof s=="function"?s():s;if(!d)return;u&&u.abort(),u=new AbortController,i(null),l(null),o(!0);let g=JSON.stringify({messages:[{role:"user",content:d}],model:e.model,provider:e.provider,stream:e.stream});fetch(e.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:g,signal:u.signal}).then(h=>{if(!h.ok)throw new Error(`Intent failed: ${h.status}`);if(e.stream){let m="";return J(h,w=>{m+=w,i(m)},()=>o(!1),w=>{l(w.message),o(!1)})}return h.json().then(m=>{m?.components?.length>0?i(m.components[0]):m?.result!=null?i(m.result):i(m),o(!1)})}).catch(h=>{h.name!=="AbortError"&&(console.error("[Sola Intent Error]",h),l(h.message),o(!1))})});let a=n;return a.loading=r,a.error=c,a}var K={relayEndpoint:"http://localhost:4040/api/query",refresh:null},A={...K};function Y(s){A={...A,...s}}function Q(s){if(!s)return null;let t=s.match(/^(\d+)(s|m|h)$/);if(!t)return null;let e=parseInt(t[1]);switch(t[2]){case"s":return e*1e3;case"m":return e*60*1e3;case"h":return e*3600*1e3}return null}function Z(s,t={}){let e={...A,...t},[n,i]=S({loading:!0,data:null,error:null}),r=null,o=null;function c(){r&&r.abort(),r=new AbortController,i({loading:!0,data:n().data,error:null}),fetch(e.relayEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:s,query:e.query||null,filters:e.filters||null,sort:e.sort||null,limit:e.limit||null,offset:e.offset||null}),signal:r.signal}).then(a=>{if(!a.ok)throw new Error(`Data fetch failed: ${a.status}`);return a.json()}).then(a=>{i({loading:!1,data:a.rows||a,error:null})}).catch(a=>{a.name!=="AbortError"&&(console.error("[Sola Data Error]",a),i({loading:!1,data:null,error:a.message}))})}c();let l=Q(e.refresh);l&&(o=setInterval(c,l));let u=()=>n();return u.refetch=c,u.stop=()=>{o&&clearInterval(o),r&&r.abort()},u}var F=class{constructor(){this.topics=new Map,this.telemetrySubscribers=new Set,this.cycleStack=new Set}topic(t,e){if(!this.topics.has(t)){let[o,c]=S(e);this.topics.set(t,{read:o,write:c,value:e,subscribers:new Set})}let n=this.topics.get(t);return[()=>n.read(),(o,c="signal")=>{let l=typeof o=="function"?o(n.value):o;if(n.value===l)return;if(this.cycleStack.has(t)){console.warn(`[Sola Signal Mesh] Cycle detected on topic "${t}". Aborting cyclic dispatch.`);return}let u=n.value;n.value=l,n.write(l);let a={topic:t,value:l,prevValue:u,timestamp:typeof performance<"u"?performance.now():Date.now(),originWidgetId:c};this.telemetrySubscribers.forEach(d=>{try{d(a)}catch(g){console.error(g)}}),this.cycleStack.add(t);try{n.subscribers.forEach(d=>{try{d(l,a)}catch(g){console.error(g)}})}finally{this.cycleStack.delete(t)}}]}subscribe(t,e){this.topics.has(t)||this.topic(t,void 0);let n=this.topics.get(t);return n.subscribers.add(e),()=>n.subscribers.delete(e)}onTelemetry(t){return this.telemetrySubscribers.add(t),()=>this.telemetrySubscribers.delete(t)}},T=new F,tt=(s,t)=>T.topic(s,t);return W(et);})();
|
package/package.json
CHANGED
|
@@ -1,32 +1,40 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@sola-air-ui/core",
|
|
3
|
-
"version": "1.0
|
|
4
|
-
"description": "Zero-VDOM reactivity engine — signals, effects, lifecycle, and intent primitives",
|
|
5
|
-
"type": "module",
|
|
6
|
-
"main": "./src/index.js",
|
|
7
|
-
"exports": {
|
|
8
|
-
".": "./src/index.js",
|
|
9
|
-
"./iife": "./dist/sola-core.iife.js"
|
|
10
|
-
},
|
|
11
|
-
"scripts": {
|
|
12
|
-
"build": "node build.js"
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
"
|
|
17
|
-
"
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
"
|
|
21
|
-
|
|
22
|
-
"
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
"
|
|
26
|
-
"
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@sola-air-ui/core",
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Zero-VDOM reactivity engine — signals, effects, lifecycle, and intent primitives",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./src/index.js",
|
|
9
|
+
"./iife": "./dist/sola-core.iife.js"
|
|
10
|
+
},
|
|
11
|
+
"scripts": {
|
|
12
|
+
"build": "node build.js",
|
|
13
|
+
"prepare": "node build.js"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"src",
|
|
17
|
+
"dist"
|
|
18
|
+
],
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"esbuild": "^0.21.5"
|
|
21
|
+
},
|
|
22
|
+
"keywords": [
|
|
23
|
+
"sola",
|
|
24
|
+
"reactivity",
|
|
25
|
+
"signals",
|
|
26
|
+
"zero-vdom",
|
|
27
|
+
"ui",
|
|
28
|
+
"frontend"
|
|
29
|
+
],
|
|
30
|
+
"license": "MIT",
|
|
31
|
+
"homepage": "https://sola-air.dev",
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "https://github.com/rbm3267/sola-air"
|
|
35
|
+
},
|
|
36
|
+
"publishConfig": {
|
|
37
|
+
"access": "public",
|
|
38
|
+
"registry": "https://registry.npmjs.org/"
|
|
39
|
+
}
|
|
40
|
+
}
|
package/src/index.js
CHANGED
|
@@ -476,65 +476,8 @@ class SignalMeshEngine {
|
|
|
476
476
|
export const signalMesh = new SignalMeshEngine();
|
|
477
477
|
export const createTopicSignal = (topic, initialVal) => signalMesh.topic(topic, initialVal);
|
|
478
478
|
|
|
479
|
-
// ─── Sola Sentinel & Intent Telemetry Observer ───
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
this.thresholdMs = options.thresholdMs || 600;
|
|
484
|
-
this.maxRageClicks = options.maxRageClicks || 3;
|
|
485
|
-
this.clickHistory = [];
|
|
486
|
-
this.subscribers = new Set();
|
|
487
|
-
this.frictionEvents = [];
|
|
488
|
-
this.flowIndex = 99.8;
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
recordClick(actionId, target = 'button') {
|
|
492
|
-
const now = typeof performance !== 'undefined' ? performance.now() : Date.now();
|
|
493
|
-
this.clickHistory.push({ actionId, target, timestamp: now });
|
|
494
|
-
this.clickHistory = this.clickHistory.filter(c => now - c.timestamp < 2000);
|
|
495
|
-
|
|
496
|
-
const recent = this.clickHistory.filter(c => c.actionId === actionId && now - c.timestamp < this.thresholdMs);
|
|
497
|
-
if (recent.length >= this.maxRageClicks) {
|
|
498
|
-
this.triggerFrictionAlert({
|
|
499
|
-
type: 'RAGE_CLICK',
|
|
500
|
-
actionId,
|
|
501
|
-
target,
|
|
502
|
-
count: recent.length,
|
|
503
|
-
timestamp: now,
|
|
504
|
-
severity: 'HIGH',
|
|
505
|
-
message: `Rage-click burst: ${recent.length} taps in ${Math.round(now - recent[0].timestamp)}ms`
|
|
506
|
-
});
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
recordSignalDrop(topic, error) {
|
|
511
|
-
this.triggerFrictionAlert({
|
|
512
|
-
type: 'SIGNAL_TIMEOUT',
|
|
513
|
-
topic,
|
|
514
|
-
error: error?.message || String(error),
|
|
515
|
-
timestamp: typeof performance !== 'undefined' ? performance.now() : Date.now(),
|
|
516
|
-
severity: 'CRITICAL',
|
|
517
|
-
message: `Signal channel "${topic}" breached SLA timeout (504 Gateway Stall)`
|
|
518
|
-
});
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
triggerFrictionAlert(event) {
|
|
522
|
-
this.frictionEvents.unshift(event);
|
|
523
|
-
if (this.frictionEvents.length > 50) this.frictionEvents.pop();
|
|
524
|
-
this.flowIndex = Math.max(68.5, Number((this.flowIndex - 3.8).toFixed(1)));
|
|
525
|
-
|
|
526
|
-
this.subscribers.forEach(cb => {
|
|
527
|
-
try { cb(event, this); } catch(e) { console.error(e); }
|
|
528
|
-
});
|
|
529
|
-
}
|
|
530
|
-
|
|
531
|
-
onFriction(cb) {
|
|
532
|
-
this.subscribers.add(cb);
|
|
533
|
-
return () => this.subscribers.delete(cb);
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
export function createSentinel(name, options) {
|
|
538
|
-
return new SolaSentinel(name, options);
|
|
539
|
-
}
|
|
479
|
+
// ─── Sola Sentinel & Ambient Intent Telemetry Observer ───
|
|
480
|
+
// Moved to sentinel.js — friction/rage-click detection, plus ambient
|
|
481
|
+
// field-behavior capture, significance gating, and prompt building.
|
|
482
|
+
export { SolaSentinel, createSentinel } from './sentinel.js';
|
|
540
483
|
|
package/src/sentinel.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// ─── Sola Sentinel & Ambient Intent Telemetry Observer ───
|
|
2
|
+
// Rage-click / signal-drop friction detection, plus ambient field-level
|
|
3
|
+
// behavior capture (focus, revisit, blur-with-value) feeding a debounced
|
|
4
|
+
// significance gate and a prompt builder for $intent-driven suggestions.
|
|
5
|
+
|
|
6
|
+
const FIELD_BUFFER_MAX_EVENTS = 50;
|
|
7
|
+
const FIELD_BUFFER_WINDOW_MS = 60_000;
|
|
8
|
+
const FIELD_TEXT_PREVIEW_MAX_CHARS = 200;
|
|
9
|
+
|
|
10
|
+
function now() {
|
|
11
|
+
return typeof performance !== 'undefined' ? performance.now() : Date.now();
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export class SolaSentinel {
|
|
15
|
+
constructor(name = 'default', options = {}) {
|
|
16
|
+
this.name = name;
|
|
17
|
+
this.thresholdMs = options.thresholdMs || 600;
|
|
18
|
+
this.maxRageClicks = options.maxRageClicks || 3;
|
|
19
|
+
this.clickHistory = [];
|
|
20
|
+
this.subscribers = new Set();
|
|
21
|
+
this.frictionEvents = [];
|
|
22
|
+
this.flowIndex = 99.8;
|
|
23
|
+
|
|
24
|
+
// Ambient field-behavior observation
|
|
25
|
+
this.fieldHistory = [];
|
|
26
|
+
this.lastActivityAt = 0;
|
|
27
|
+
this.lastSuggestedAt = -Infinity;
|
|
28
|
+
this.idleThresholdMs = options.idleThresholdMs ?? 1500;
|
|
29
|
+
this.minSuggestIntervalMs = options.minSuggestIntervalMs ?? 8000;
|
|
30
|
+
this.minEventsForSuggestion = options.minEventsForSuggestion ?? 2;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
recordClick(actionId, target = 'button') {
|
|
34
|
+
const ts = now();
|
|
35
|
+
this.clickHistory.push({ actionId, target, timestamp: ts });
|
|
36
|
+
this.clickHistory = this.clickHistory.filter(c => ts - c.timestamp < 2000);
|
|
37
|
+
|
|
38
|
+
const recent = this.clickHistory.filter(c => c.actionId === actionId && ts - c.timestamp < this.thresholdMs);
|
|
39
|
+
if (recent.length >= this.maxRageClicks) {
|
|
40
|
+
this.triggerFrictionAlert({
|
|
41
|
+
type: 'RAGE_CLICK',
|
|
42
|
+
actionId,
|
|
43
|
+
target,
|
|
44
|
+
count: recent.length,
|
|
45
|
+
timestamp: ts,
|
|
46
|
+
severity: 'HIGH',
|
|
47
|
+
message: `Rage-click burst: ${recent.length} taps in ${Math.round(ts - recent[0].timestamp)}ms`
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
recordSignalDrop(topic, error) {
|
|
53
|
+
this.triggerFrictionAlert({
|
|
54
|
+
type: 'SIGNAL_TIMEOUT',
|
|
55
|
+
topic,
|
|
56
|
+
error: error?.message || String(error),
|
|
57
|
+
timestamp: now(),
|
|
58
|
+
severity: 'CRITICAL',
|
|
59
|
+
message: `Signal channel "${topic}" breached SLA timeout (504 Gateway Stall)`
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
triggerFrictionAlert(event) {
|
|
64
|
+
this.frictionEvents.unshift(event);
|
|
65
|
+
if (this.frictionEvents.length > 50) this.frictionEvents.pop();
|
|
66
|
+
this._recomputeFlowIndex(event.timestamp);
|
|
67
|
+
|
|
68
|
+
this.subscribers.forEach(cb => {
|
|
69
|
+
try { cb(event, this); } catch (e) { console.error(e); }
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
onFriction(cb) {
|
|
74
|
+
this.subscribers.add(cb);
|
|
75
|
+
return () => this.subscribers.delete(cb);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// ─── Flow index ───
|
|
79
|
+
// A real computed score, not a fixed decrement: severity- and recency-weighted
|
|
80
|
+
// friction events, the share of field visits that were backtracks, plus how
|
|
81
|
+
// erratic the pacing between field events is (a proxy for hesitation).
|
|
82
|
+
_recomputeFlowIndex(ts = now()) {
|
|
83
|
+
let score = 99.8;
|
|
84
|
+
|
|
85
|
+
const recentFriction = this.frictionEvents.filter(e => ts - e.timestamp < 120_000);
|
|
86
|
+
score -= recentFriction.reduce((sum, e) => {
|
|
87
|
+
const severityWeight = e.severity === 'CRITICAL' ? 6 : e.severity === 'HIGH' ? 3.8 : 2;
|
|
88
|
+
const recencyWeight = Math.max(0.3, 1 - (ts - e.timestamp) / 120_000);
|
|
89
|
+
return sum + severityWeight * recencyWeight;
|
|
90
|
+
}, 0);
|
|
91
|
+
|
|
92
|
+
const focusEvents = this.fieldHistory.filter(e => e.type === 'focus');
|
|
93
|
+
if (focusEvents.length > 0) {
|
|
94
|
+
const revisitRatio = focusEvents.filter(e => e.revisit).length / focusEvents.length;
|
|
95
|
+
score -= revisitRatio * 15;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (this.fieldHistory.length >= 3) {
|
|
99
|
+
const gaps = [];
|
|
100
|
+
for (let i = 1; i < this.fieldHistory.length; i++) {
|
|
101
|
+
gaps.push(this.fieldHistory[i].timestamp - this.fieldHistory[i - 1].timestamp);
|
|
102
|
+
}
|
|
103
|
+
const mean = gaps.reduce((a, b) => a + b, 0) / gaps.length;
|
|
104
|
+
const variance = gaps.reduce((sum, g) => sum + (g - mean) ** 2, 0) / gaps.length;
|
|
105
|
+
score -= Math.min(10, Math.sqrt(variance) / 500);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
this.flowIndex = Math.max(0, Math.min(99.8, Number(score.toFixed(1))));
|
|
109
|
+
return this.flowIndex;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// ─── Ambient field observation ───
|
|
113
|
+
|
|
114
|
+
_pushFieldEvent(event) {
|
|
115
|
+
this.fieldHistory.push(event);
|
|
116
|
+
this.fieldHistory = this.fieldHistory
|
|
117
|
+
.filter(e => event.timestamp - e.timestamp < FIELD_BUFFER_WINDOW_MS)
|
|
118
|
+
.slice(-FIELD_BUFFER_MAX_EVENTS);
|
|
119
|
+
this.lastActivityAt = event.timestamp;
|
|
120
|
+
this._recomputeFlowIndex(event.timestamp);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
recordFieldFocus(fieldId, ts = now()) {
|
|
124
|
+
const revisit = this.fieldHistory.some(e => e.type === 'blur' && e.fieldId === fieldId);
|
|
125
|
+
this._pushFieldEvent({ type: 'focus', fieldId, revisit, timestamp: ts });
|
|
126
|
+
return revisit;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
recordFieldBlur(fieldId, value, ts = now()) {
|
|
130
|
+
const text = String(value ?? '');
|
|
131
|
+
const preview = text.length > FIELD_TEXT_PREVIEW_MAX_CHARS
|
|
132
|
+
? text.slice(-FIELD_TEXT_PREVIEW_MAX_CHARS)
|
|
133
|
+
: text;
|
|
134
|
+
this._pushFieldEvent({ type: 'blur', fieldId, valuePreview: preview, valueLength: text.length, timestamp: ts });
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// ─── Significance gate ───
|
|
138
|
+
// Fires at most once per `minSuggestIntervalMs`, only after `idleThresholdMs`
|
|
139
|
+
// of inactivity following new activity — never on every keystroke.
|
|
140
|
+
checkSignificance(ts = now()) {
|
|
141
|
+
if (this.fieldHistory.length < this.minEventsForSuggestion) return false;
|
|
142
|
+
if (this.lastActivityAt <= this.lastSuggestedAt) return false;
|
|
143
|
+
if (ts - this.lastActivityAt < this.idleThresholdMs) return false;
|
|
144
|
+
if (ts - this.lastSuggestedAt < this.minSuggestIntervalMs) return false;
|
|
145
|
+
|
|
146
|
+
this.lastSuggestedAt = ts;
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ─── Prompt builder ───
|
|
151
|
+
// Compact natural-language description of recent field activity, oldest first.
|
|
152
|
+
buildPrompt() {
|
|
153
|
+
if (this.fieldHistory.length === 0) return null;
|
|
154
|
+
|
|
155
|
+
const lines = this.fieldHistory.map(e => {
|
|
156
|
+
if (e.type === 'focus') {
|
|
157
|
+
return e.revisit
|
|
158
|
+
? `User returned to field "${e.fieldId}".`
|
|
159
|
+
: `User focused field "${e.fieldId}".`;
|
|
160
|
+
}
|
|
161
|
+
if (e.valueLength === 0) return `User left field "${e.fieldId}" empty.`;
|
|
162
|
+
return `Field "${e.fieldId}" now contains: "${e.valuePreview}"`;
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
return [
|
|
166
|
+
'You are an ambient UX assistant embedded in a form.',
|
|
167
|
+
'Recent user activity, oldest first:',
|
|
168
|
+
...lines,
|
|
169
|
+
'',
|
|
170
|
+
'Based only on this activity, suggest exactly one concise, specific next-step action the user might want.',
|
|
171
|
+
'Respond as compact JSON only: {"label": string (<=60 chars), "action": string (<=140 chars), "confidence": number 0-1}.',
|
|
172
|
+
'If nothing useful can be suggested, respond {"label": null}.'
|
|
173
|
+
].join('\n');
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function createSentinel(name, options) {
|
|
178
|
+
return new SolaSentinel(name, options);
|
|
179
|
+
}
|
package/build.js
DELETED
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
import { build } from 'esbuild';
|
|
2
|
-
import { mkdirSync } from 'fs';
|
|
3
|
-
|
|
4
|
-
mkdirSync('./dist', { recursive: true });
|
|
5
|
-
|
|
6
|
-
await build({
|
|
7
|
-
entryPoints: ['./src/index.js'],
|
|
8
|
-
bundle: true,
|
|
9
|
-
format: 'iife',
|
|
10
|
-
globalName: 'SolaCore',
|
|
11
|
-
outfile: './dist/sola-core.iife.js',
|
|
12
|
-
minify: false,
|
|
13
|
-
target: ['es2020'],
|
|
14
|
-
banner: {
|
|
15
|
-
js: '/* @sola-air-ui/core — IIFE build for ServiceNow and no-bundler environments */'
|
|
16
|
-
}
|
|
17
|
-
});
|
|
18
|
-
|
|
19
|
-
// Also emit a minified version
|
|
20
|
-
await build({
|
|
21
|
-
entryPoints: ['./src/index.js'],
|
|
22
|
-
bundle: true,
|
|
23
|
-
format: 'iife',
|
|
24
|
-
globalName: 'SolaCore',
|
|
25
|
-
outfile: './dist/sola-core.iife.min.js',
|
|
26
|
-
minify: true,
|
|
27
|
-
target: ['es2020'],
|
|
28
|
-
banner: {
|
|
29
|
-
js: '/* @sola-air-ui/core v1.0.2 | MIT */'
|
|
30
|
-
}
|
|
31
|
-
});
|
|
32
|
-
|
|
33
|
-
console.log('Built dist/sola-core.iife.js and dist/sola-core.iife.min.js');
|