@xpert-ai/plugin-sdk 3.32.0 → 3.33.1
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/artifact-document.cjs.js +271 -30
- package/artifact-document.esm.js +271 -31
- package/docs/artifact-documents.md +10 -1
- package/package.json +2 -2
- package/src/artifact-document.d.ts +1 -0
- package/src/lib/artifact-document/host.d.ts +7 -2
- package/src/lib/artifact-document/protocol.d.ts +4 -0
- package/src/lib/artifact-document/scheduler.d.ts +31 -0
package/artifact-document.cjs.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
var v3 = require('zod/v3');
|
|
4
4
|
var _object_without_properties_loose = require('./_object_without_properties_loose.cjs.js');
|
|
5
|
+
var _extends = require('./_extends.cjs.js');
|
|
5
6
|
|
|
6
7
|
/** Wire namespace/version shared by the trusted host and its isolated document bootstrap. */ const ARTIFACT_DOCUMENT_CHANNEL = 'xpert.artifact-document';
|
|
7
8
|
const ARTIFACT_DOCUMENT_VERSION = 1;
|
|
@@ -17,7 +18,12 @@ const artifactDocumentControls = v3.z.record(artifactDocumentId, artifactDocumen
|
|
|
17
18
|
type: v3.z.literal('query'),
|
|
18
19
|
requestId: v3.z.string().min(1).max(80),
|
|
19
20
|
bindingId: artifactDocumentId,
|
|
20
|
-
controls: artifactDocumentControls
|
|
21
|
+
controls: artifactDocumentControls,
|
|
22
|
+
priority: v3.z.enum([
|
|
23
|
+
'interactive',
|
|
24
|
+
'initial',
|
|
25
|
+
'refresh'
|
|
26
|
+
]).optional()
|
|
21
27
|
}).strict();
|
|
22
28
|
/** Only public presentation context may cross into the untrusted frame. Never include credentials here. */ const artifactDocumentContext = v3.z.object({
|
|
23
29
|
bindingIds: v3.z.array(artifactDocumentId).max(64).refine((ids)=>new Set(ids).size === ids.length, 'Duplicate binding IDs'),
|
|
@@ -324,7 +330,10 @@ const ARTIFACT_DOCUMENT_RUNTIME = String.raw`
|
|
|
324
330
|
pending = new Map(),
|
|
325
331
|
listeners = new Map(),
|
|
326
332
|
lastControls = new Map(),
|
|
327
|
-
latest = new Map()
|
|
333
|
+
latest = new Map(),
|
|
334
|
+
inFlight = new Map(),
|
|
335
|
+
deliveryLocks = new Map()
|
|
336
|
+
let refreshing = false
|
|
328
337
|
let port,
|
|
329
338
|
context,
|
|
330
339
|
sequence = 0,
|
|
@@ -339,24 +348,33 @@ const ARTIFACT_DOCUMENT_RUNTIME = String.raw`
|
|
|
339
348
|
}
|
|
340
349
|
}
|
|
341
350
|
const fail = (code) => Object.assign(new Error(code), { code })
|
|
342
|
-
const query = async (bindingId, controls = {}) => {
|
|
351
|
+
const query = async (bindingId, controls = {}, priority, owner) => {
|
|
343
352
|
await ready
|
|
344
353
|
if (!context.bindingIds.includes(bindingId)) {
|
|
345
354
|
port.postMessage({ type: 'diagnostic', code: 'DOCUMENT_BINDING_DENIED' })
|
|
346
355
|
throw fail('DOCUMENT_BINDING_DENIED')
|
|
347
356
|
}
|
|
348
|
-
|
|
349
|
-
|
|
357
|
+
if (deliveryLocks.has(bindingId) && deliveryLocks.get(bindingId) !== owner) deliveryLocks.delete(bindingId)
|
|
358
|
+
const values = { ...context.defaults, ...controls },
|
|
359
|
+
key = JSON.stringify(Object.keys(values).sort().map(id => [id, values[id]])),
|
|
360
|
+
previous = inFlight.get(bindingId)
|
|
361
|
+
if (previous && previous.key === key) return previous.promise
|
|
362
|
+
priority = priority || (lastControls.has(bindingId) ? 'interactive' : 'initial')
|
|
363
|
+
const requestId = 'q' + ++sequence
|
|
350
364
|
lastControls.set(bindingId, values)
|
|
351
365
|
latest.set(bindingId, requestId)
|
|
352
|
-
|
|
366
|
+
const promise = new Promise((resolve, reject) => {
|
|
353
367
|
const timer = setTimeout(() => {
|
|
354
368
|
pending.delete(requestId)
|
|
355
|
-
reject(fail('
|
|
356
|
-
},
|
|
369
|
+
reject(fail('DOCUMENT_QUEUE_TIMEOUT'))
|
|
370
|
+
}, 185000)
|
|
357
371
|
pending.set(requestId, { resolve, reject, timer, bindingId })
|
|
358
|
-
port.postMessage({ type: 'query', requestId, bindingId, controls: values })
|
|
372
|
+
port.postMessage({ type: 'query', requestId, bindingId, controls: values, priority })
|
|
359
373
|
})
|
|
374
|
+
inFlight.set(bindingId, { key, promise })
|
|
375
|
+
try { return await promise } finally {
|
|
376
|
+
if (inFlight.get(bindingId)?.promise === promise) inFlight.delete(bindingId)
|
|
377
|
+
}
|
|
360
378
|
}
|
|
361
379
|
const subscribe = (id, fn) => {
|
|
362
380
|
if (typeof fn !== 'function') throw fail('DOCUMENT_INVALID_LISTENER')
|
|
@@ -365,7 +383,28 @@ const ARTIFACT_DOCUMENT_RUNTIME = String.raw`
|
|
|
365
383
|
listeners.set(id, set)
|
|
366
384
|
return () => set.delete(fn)
|
|
367
385
|
}
|
|
368
|
-
const refresh = async (id) => query(id, lastControls.get(id) || {})
|
|
386
|
+
const refresh = async (id) => query(id, lastControls.get(id) || {}, 'refresh')
|
|
387
|
+
const queryGroup = async (requests, priority) => {
|
|
388
|
+
await ready
|
|
389
|
+
const ids = requests.map(request => request.bindingId)
|
|
390
|
+
if (!ids.length) return { datasets: [], failures: [] }
|
|
391
|
+
if (ids.length > 64 || new Set(ids).size !== ids.length || ids.some(id => !context.bindingIds.includes(id)))
|
|
392
|
+
throw fail('DOCUMENT_BINDING_DENIED')
|
|
393
|
+
const owner = Symbol('query-group')
|
|
394
|
+
ids.forEach(id => deliveryLocks.set(id, owner))
|
|
395
|
+
const results = await Promise.allSettled(requests.map(request => query(request.bindingId, request.controls, priority, owner)))
|
|
396
|
+
const current = ids.every(id => deliveryLocks.get(id) === owner)
|
|
397
|
+
ids.forEach(id => { if (deliveryLocks.get(id) === owner) deliveryLocks.delete(id) })
|
|
398
|
+
if (!current) throw fail('DOCUMENT_QUERY_SUPERSEDED')
|
|
399
|
+
const datasets = [], failures = []
|
|
400
|
+
results.forEach((result, index) => {
|
|
401
|
+
if (result.status === 'fulfilled') { datasets.push(result.value); emit(ids[index], result.value) }
|
|
402
|
+
else failures.push({ bindingId: ids[index], code: result.reason?.code || 'DOCUMENT_QUERY_FAILED' })
|
|
403
|
+
})
|
|
404
|
+
return { datasets, failures }
|
|
405
|
+
}
|
|
406
|
+
// Subscribers see successful members of one filter round together, after it settles.
|
|
407
|
+
const queryMany = (ids, controls = {}) => queryGroup(ids.map(bindingId => ({ bindingId, controls })), 'interactive')
|
|
369
408
|
const bindSelect = (element, config) => {
|
|
370
409
|
if (
|
|
371
410
|
!element ||
|
|
@@ -417,7 +456,7 @@ const ARTIFACT_DOCUMENT_RUNTIME = String.raw`
|
|
|
417
456
|
}
|
|
418
457
|
}
|
|
419
458
|
Object.defineProperty(window, 'xpertLiveArtifact', {
|
|
420
|
-
value: Object.freeze({ ready: () => ready, query, subscribe, refresh, bindSelect }),
|
|
459
|
+
value: Object.freeze({ ready: () => ready, query, queryMany, subscribe, refresh, bindSelect }),
|
|
421
460
|
writable: false,
|
|
422
461
|
configurable: false
|
|
423
462
|
})
|
|
@@ -441,7 +480,23 @@ const ARTIFACT_DOCUMENT_RUNTIME = String.raw`
|
|
|
441
480
|
port.onmessage = (event) => {
|
|
442
481
|
const data = event.data
|
|
443
482
|
if (data.type === 'refresh') {
|
|
444
|
-
|
|
483
|
+
if (data.bindingId) { refresh(data.bindingId).catch(console.error); return }
|
|
484
|
+
if (refreshing) return
|
|
485
|
+
refreshing = true
|
|
486
|
+
queryGroup([...new Set([...listeners.keys(), ...lastControls.keys()])].map(bindingId => ({ bindingId, controls: lastControls.get(bindingId) || {} })), 'refresh')
|
|
487
|
+
.catch(error => { if (error.code !== 'DOCUMENT_QUERY_SUPERSEDED') console.error(error) })
|
|
488
|
+
.finally(() => { refreshing = false })
|
|
489
|
+
return
|
|
490
|
+
}
|
|
491
|
+
if (data.type === 'query-state') {
|
|
492
|
+
const entry = pending.get(data.requestId)
|
|
493
|
+
if (entry && data.state === 'running') {
|
|
494
|
+
clearTimeout(entry.timer)
|
|
495
|
+
entry.timer = setTimeout(() => {
|
|
496
|
+
pending.delete(data.requestId)
|
|
497
|
+
entry.reject(fail('DOCUMENT_QUERY_TIMEOUT'))
|
|
498
|
+
}, 50000)
|
|
499
|
+
}
|
|
445
500
|
return
|
|
446
501
|
}
|
|
447
502
|
if (data.type !== 'result') return
|
|
@@ -454,7 +509,7 @@ const ARTIFACT_DOCUMENT_RUNTIME = String.raw`
|
|
|
454
509
|
return
|
|
455
510
|
}
|
|
456
511
|
if (data.ok) {
|
|
457
|
-
emit(entry.bindingId, data.dataset)
|
|
512
|
+
if (!deliveryLocks.has(entry.bindingId)) emit(entry.bindingId, data.dataset)
|
|
458
513
|
entry.resolve(data.dataset)
|
|
459
514
|
} else entry.reject(fail(data.code || 'DOCUMENT_QUERY_FAILED'))
|
|
460
515
|
}
|
|
@@ -465,9 +520,154 @@ const ARTIFACT_DOCUMENT_RUNTIME = String.raw`
|
|
|
465
520
|
})()
|
|
466
521
|
`;
|
|
467
522
|
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
523
|
+
const failure = (code)=>Object.assign(new Error(code), {
|
|
524
|
+
code
|
|
525
|
+
});
|
|
526
|
+
const keyOf = (input)=>JSON.stringify([
|
|
527
|
+
input.bindingId,
|
|
528
|
+
Object.keys(input.controls).sort().map((key)=>[
|
|
529
|
+
key,
|
|
530
|
+
input.controls[key]
|
|
531
|
+
])
|
|
532
|
+
]);
|
|
533
|
+
const priorities = {
|
|
534
|
+
interactive: 0,
|
|
535
|
+
initial: 1,
|
|
536
|
+
refresh: 2
|
|
537
|
+
};
|
|
538
|
+
const QUEUE_TIMEOUT = 180000, EXECUTION_TIMEOUT = 45000, WINDOW = 60000;
|
|
539
|
+
/** One trusted Artifact/version/actor generation. Queue time never consumes execution time.
|
|
540
|
+
* Slots remain occupied until the underlying execution settles, even after timeout/abort.
|
|
541
|
+
* Callers must propagate the signal when supported; disposal alone cannot cancel database work. */ function createArtifactQueryScheduler(options) {
|
|
542
|
+
const bounded = (value, fallback, max)=>Number.isFinite(value) ? Math.max(1, Math.min(max, Math.floor(value))) : fallback;
|
|
543
|
+
const concurrency = bounded(options.concurrency, 4, 8);
|
|
544
|
+
const dispatchLimit = bounded(options.dispatchesPerMinute, 60, 1024);
|
|
545
|
+
const queued = [], running = new Set(), latest = new Map();
|
|
546
|
+
const dispatches = [];
|
|
547
|
+
let disposed = false, wake;
|
|
548
|
+
const observe = (fn, value)=>{
|
|
549
|
+
try {
|
|
550
|
+
fn == null ? void 0 : fn(value);
|
|
551
|
+
} catch (e) {
|
|
552
|
+
/* observer only */ }
|
|
553
|
+
};
|
|
554
|
+
const busy = ()=>observe(options.onBusy, !disposed && (queued.length > 0 || running.size > 0));
|
|
555
|
+
const transition = (task, state, code)=>{
|
|
556
|
+
task.state = _extends._extends({}, task.state, {
|
|
557
|
+
state
|
|
558
|
+
}, state === 'running' ? {
|
|
559
|
+
startedAt: Date.now()
|
|
560
|
+
} : state !== 'queued' ? {
|
|
561
|
+
finishedAt: Date.now()
|
|
562
|
+
} : {}, code ? {
|
|
563
|
+
code
|
|
564
|
+
} : {});
|
|
565
|
+
observe(options.onState, _extends._extends({}, task.state));
|
|
566
|
+
};
|
|
567
|
+
const reject = (task, code)=>{
|
|
568
|
+
if (task.settled) return;
|
|
569
|
+
task.settled = true;
|
|
570
|
+
clearTimeout(task.timer);
|
|
571
|
+
task.controller.abort();
|
|
572
|
+
transition(task, code === 'DOCUMENT_QUERY_SUPERSEDED' ? 'superseded' : 'failed', code);
|
|
573
|
+
task.reject(failure(code));
|
|
574
|
+
if (latest.get(task.input.bindingId) === task) latest.delete(task.input.bindingId);
|
|
575
|
+
};
|
|
576
|
+
const pump = ()=>{
|
|
577
|
+
clearTimeout(wake);
|
|
578
|
+
if (disposed) return;
|
|
579
|
+
const now = Date.now();
|
|
580
|
+
while(dispatches.length && dispatches[0] <= now - WINDOW)dispatches.shift();
|
|
581
|
+
while(queued.length && running.size < concurrency && dispatches.length < dispatchLimit){
|
|
582
|
+
queued.sort((a, b)=>a.priority - b.priority || a.state.queuedAt - b.state.queuedAt);
|
|
583
|
+
const task = queued.shift();
|
|
584
|
+
clearTimeout(task.timer);
|
|
585
|
+
running.add(task);
|
|
586
|
+
dispatches.push(Date.now());
|
|
587
|
+
transition(task, 'running');
|
|
588
|
+
task.timer = setTimeout(()=>reject(task, 'DOCUMENT_QUERY_TIMEOUT'), EXECUTION_TIMEOUT);
|
|
589
|
+
Promise.resolve().then(()=>options.execute(task.input, task.controller.signal)).then((result)=>{
|
|
590
|
+
if (disposed || task.settled) return;
|
|
591
|
+
task.settled = true;
|
|
592
|
+
transition(task, 'succeeded');
|
|
593
|
+
task.resolve(result);
|
|
594
|
+
}, ()=>reject(task, 'DOCUMENT_QUERY_FAILED')).finally(()=>{
|
|
595
|
+
clearTimeout(task.timer);
|
|
596
|
+
running.delete(task);
|
|
597
|
+
if (latest.get(task.input.bindingId) === task) latest.delete(task.input.bindingId);
|
|
598
|
+
pump();
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
if (queued.length && dispatches.length >= dispatchLimit) wake = setTimeout(pump, Math.max(1, dispatches[0] + WINDOW - Date.now()));
|
|
602
|
+
busy();
|
|
603
|
+
};
|
|
604
|
+
return {
|
|
605
|
+
query (input, priority = 'interactive') {
|
|
606
|
+
if (disposed) return Promise.reject(failure('DOCUMENT_DISPOSED'));
|
|
607
|
+
const key = keyOf(input), previous = latest.get(input.bindingId);
|
|
608
|
+
if ((previous == null ? void 0 : previous.key) === key && !previous.settled) {
|
|
609
|
+
previous.priority = Math.min(previous.priority, priorities[priority]);
|
|
610
|
+
return previous.promise;
|
|
611
|
+
}
|
|
612
|
+
if (previous) {
|
|
613
|
+
const index = queued.indexOf(previous);
|
|
614
|
+
if (index >= 0) queued.splice(index, 1);
|
|
615
|
+
reject(previous, 'DOCUMENT_QUERY_SUPERSEDED');
|
|
616
|
+
}
|
|
617
|
+
if (queued.length >= 64) return Promise.reject(failure('DOCUMENT_QUEUE_LIMIT'));
|
|
618
|
+
let resolve, rejectPromise;
|
|
619
|
+
const promise = new Promise((yes, no)=>{
|
|
620
|
+
resolve = yes;
|
|
621
|
+
rejectPromise = no;
|
|
622
|
+
});
|
|
623
|
+
const task = {
|
|
624
|
+
input: {
|
|
625
|
+
bindingId: input.bindingId,
|
|
626
|
+
controls: _extends._extends({}, input.controls)
|
|
627
|
+
},
|
|
628
|
+
key,
|
|
629
|
+
priority: priorities[priority],
|
|
630
|
+
controller: new AbortController(),
|
|
631
|
+
promise,
|
|
632
|
+
resolve,
|
|
633
|
+
reject: rejectPromise,
|
|
634
|
+
state: _extends._extends({}, input, {
|
|
635
|
+
controls: _extends._extends({}, input.controls),
|
|
636
|
+
state: 'queued',
|
|
637
|
+
queuedAt: Date.now()
|
|
638
|
+
}),
|
|
639
|
+
settled: false
|
|
640
|
+
};
|
|
641
|
+
task.timer = setTimeout(()=>{
|
|
642
|
+
const index = queued.indexOf(task);
|
|
643
|
+
if (index >= 0) queued.splice(index, 1);
|
|
644
|
+
reject(task, 'DOCUMENT_QUEUE_TIMEOUT');
|
|
645
|
+
pump();
|
|
646
|
+
}, QUEUE_TIMEOUT);
|
|
647
|
+
latest.set(input.bindingId, task);
|
|
648
|
+
queued.push(task);
|
|
649
|
+
transition(task, 'queued');
|
|
650
|
+
pump();
|
|
651
|
+
return promise;
|
|
652
|
+
},
|
|
653
|
+
get busy () {
|
|
654
|
+
return queued.length > 0 || running.size > 0;
|
|
655
|
+
},
|
|
656
|
+
dispose () {
|
|
657
|
+
if (disposed) return;
|
|
658
|
+
disposed = true;
|
|
659
|
+
clearTimeout(wake);
|
|
660
|
+
for (const task of [
|
|
661
|
+
...queued,
|
|
662
|
+
...running
|
|
663
|
+
])reject(task, 'DOCUMENT_DISPOSED');
|
|
664
|
+
queued.length = 0;
|
|
665
|
+
latest.clear();
|
|
666
|
+
busy();
|
|
667
|
+
}
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
|
|
471
671
|
const readySchema = v3.z.object({
|
|
472
672
|
channel: v3.z.literal(ARTIFACT_DOCUMENT_CHANNEL),
|
|
473
673
|
version: v3.z.literal(ARTIFACT_DOCUMENT_VERSION),
|
|
@@ -488,8 +688,10 @@ const diagnosticSchema = v3.z.object({
|
|
|
488
688
|
const source = renderArtifactDocument(options.html, sessionId, options.dependencies, options.networkPolicy);
|
|
489
689
|
const channel = new MessageChannel();
|
|
490
690
|
const bindingIds = new Set(context.bindingIds);
|
|
691
|
+
const admissionLimit = Number.isFinite(options.dispatchesPerMinute) ? Math.max(256, Math.min(1024, options.dispatchesPerMinute)) : 256;
|
|
491
692
|
const requestIds = new Set();
|
|
492
|
-
const activeIds = new
|
|
693
|
+
const activeIds = new Map();
|
|
694
|
+
const executingIds = new Set();
|
|
493
695
|
const latest = new Map();
|
|
494
696
|
const hostWindow = frame.ownerDocument.defaultView;
|
|
495
697
|
let connected = false, disposed = false, requests = 0, started = Date.now();
|
|
@@ -514,6 +716,34 @@ const diagnosticSchema = v3.z.object({
|
|
|
514
716
|
});
|
|
515
717
|
observe(options.onError, code);
|
|
516
718
|
};
|
|
719
|
+
const scheduler = createArtifactQueryScheduler({
|
|
720
|
+
concurrency: options.concurrency,
|
|
721
|
+
dispatchesPerMinute: options.dispatchesPerMinute,
|
|
722
|
+
execute: async (input, signal)=>{
|
|
723
|
+
if (signal.aborted) throw new Error('DOCUMENT_QUERY_SUPERSEDED');
|
|
724
|
+
const request = [
|
|
725
|
+
...activeIds.values()
|
|
726
|
+
].find((item)=>item.bindingId === input.bindingId && Object.keys(item.controls).length === Object.keys(input.controls).length && Object.keys(input.controls).every((key)=>item.controls[key] === input.controls[key]));
|
|
727
|
+
if (!request) throw new Error('DOCUMENT_QUERY_SUPERSEDED');
|
|
728
|
+
executingIds.add(request.requestId);
|
|
729
|
+
try {
|
|
730
|
+
return await options.query(request, signal);
|
|
731
|
+
} finally{
|
|
732
|
+
executingIds.delete(request.requestId);
|
|
733
|
+
}
|
|
734
|
+
},
|
|
735
|
+
onBusy: (value)=>observe(options.onBusy, value),
|
|
736
|
+
onState: (state)=>{
|
|
737
|
+
observe(options.onQueryState, state);
|
|
738
|
+
if (state.state === 'running') {
|
|
739
|
+
for (const input of activeIds.values())if (input.bindingId === state.bindingId) post({
|
|
740
|
+
type: 'query-state',
|
|
741
|
+
requestId: input.requestId,
|
|
742
|
+
state: 'running'
|
|
743
|
+
});
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
});
|
|
517
747
|
channel.port1.onmessage = async (event)=>{
|
|
518
748
|
if (disposed) return;
|
|
519
749
|
const diagnostic = diagnosticSchema.safeParse(event.data);
|
|
@@ -530,7 +760,8 @@ const diagnosticSchema = v3.z.object({
|
|
|
530
760
|
type: parsed.data.type,
|
|
531
761
|
requestId: parsed.data.requestId,
|
|
532
762
|
bindingId: parsed.data.bindingId,
|
|
533
|
-
controls: parsed.data.controls
|
|
763
|
+
controls: parsed.data.controls,
|
|
764
|
+
priority: parsed.data.priority
|
|
534
765
|
};
|
|
535
766
|
if (!bindingIds.has(input.bindingId)) {
|
|
536
767
|
reject(input.requestId, 'DOCUMENT_BINDING_DENIED');
|
|
@@ -542,20 +773,24 @@ const diagnosticSchema = v3.z.object({
|
|
|
542
773
|
requestIds.clear();
|
|
543
774
|
}
|
|
544
775
|
// Keep in-flight IDs protected even after the one-minute replay/rate window rolls over.
|
|
545
|
-
if (activeIds.has(input.requestId) || requestIds.has(input.requestId)) {
|
|
776
|
+
if (activeIds.has(input.requestId) || executingIds.has(input.requestId) || requestIds.has(input.requestId)) {
|
|
546
777
|
reject(input.requestId, 'DOCUMENT_REQUEST_REPLAY');
|
|
547
778
|
return;
|
|
548
779
|
}
|
|
549
|
-
if (activeIds.size >=
|
|
780
|
+
if (activeIds.size >= 128 || ++requests > admissionLimit) {
|
|
550
781
|
reject(input.requestId, 'DOCUMENT_QUERY_LIMIT');
|
|
551
782
|
return;
|
|
552
783
|
}
|
|
553
784
|
requestIds.add(input.requestId);
|
|
554
|
-
activeIds.
|
|
785
|
+
activeIds.set(input.requestId, input);
|
|
555
786
|
latest.set(input.bindingId, input.requestId);
|
|
556
|
-
|
|
787
|
+
post({
|
|
788
|
+
type: 'query-state',
|
|
789
|
+
requestId: input.requestId,
|
|
790
|
+
state: 'queued'
|
|
791
|
+
});
|
|
557
792
|
try {
|
|
558
|
-
const dataset = await
|
|
793
|
+
const dataset = await scheduler.query(input, input.priority);
|
|
559
794
|
if (!disposed) {
|
|
560
795
|
post({
|
|
561
796
|
type: 'result',
|
|
@@ -565,19 +800,19 @@ const diagnosticSchema = v3.z.object({
|
|
|
565
800
|
});
|
|
566
801
|
if (latest.get(input.bindingId) === input.requestId) observe(options.onResult, dataset);
|
|
567
802
|
}
|
|
568
|
-
} catch (
|
|
803
|
+
} catch (error) {
|
|
569
804
|
if (!disposed) {
|
|
805
|
+
const code = error instanceof Error && /^DOCUMENT_[A-Z_]+$/.test(error.message) ? error.message : 'DOCUMENT_QUERY_FAILED';
|
|
570
806
|
post({
|
|
571
807
|
type: 'result',
|
|
572
808
|
requestId: input.requestId,
|
|
573
809
|
ok: false,
|
|
574
|
-
code
|
|
810
|
+
code
|
|
575
811
|
});
|
|
576
|
-
if (latest.get(input.bindingId) === input.requestId) observe(options.onError,
|
|
812
|
+
if (latest.get(input.bindingId) === input.requestId) observe(options.onError, code);
|
|
577
813
|
}
|
|
578
814
|
} finally{
|
|
579
815
|
activeIds.delete(input.requestId);
|
|
580
|
-
if (!disposed) observe(options.onBusy, activeIds.size > 0);
|
|
581
816
|
}
|
|
582
817
|
};
|
|
583
818
|
const ready = (event)=>{
|
|
@@ -600,14 +835,19 @@ const diagnosticSchema = v3.z.object({
|
|
|
600
835
|
channel.port1.start();
|
|
601
836
|
frame.srcdoc = source;
|
|
602
837
|
return {
|
|
603
|
-
refresh () {
|
|
604
|
-
|
|
838
|
+
refresh (bindingId) {
|
|
839
|
+
if (bindingId !== undefined && !bindingIds.has(bindingId)) throw new Error('DOCUMENT_BINDING_DENIED');
|
|
840
|
+
post(_extends._extends({
|
|
605
841
|
type: 'refresh'
|
|
606
|
-
}
|
|
842
|
+
}, bindingId ? {
|
|
843
|
+
bindingId
|
|
844
|
+
} : {}));
|
|
607
845
|
},
|
|
608
846
|
dispose () {
|
|
609
847
|
if (disposed) return;
|
|
610
848
|
disposed = true;
|
|
849
|
+
scheduler.dispose();
|
|
850
|
+
activeIds.clear();
|
|
611
851
|
hostWindow.removeEventListener('message', ready);
|
|
612
852
|
channel.port1.close();
|
|
613
853
|
channel.port2.close();
|
|
@@ -638,6 +878,7 @@ exports.artifactDocumentId = artifactDocumentId;
|
|
|
638
878
|
exports.artifactDocumentNetworkPolicy = artifactDocumentNetworkPolicy;
|
|
639
879
|
exports.artifactDocumentQuery = artifactDocumentQuery;
|
|
640
880
|
exports.artifactDocumentValue = artifactDocumentValue;
|
|
881
|
+
exports.createArtifactQueryScheduler = createArtifactQueryScheduler;
|
|
641
882
|
exports.installArtifactDocumentFramePolicy = installArtifactDocumentFramePolicy;
|
|
642
883
|
exports.isArtifactDocumentResourceAllowed = isArtifactDocumentResourceAllowed;
|
|
643
884
|
exports.mountArtifactDocument = mountArtifactDocument;
|
package/artifact-document.esm.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod/v3';
|
|
2
2
|
import { _ as _object_without_properties_loose } from './_object_without_properties_loose.esm.js';
|
|
3
|
+
import { _ as _extends } from './_extends.esm.js';
|
|
3
4
|
|
|
4
5
|
/** Wire namespace/version shared by the trusted host and its isolated document bootstrap. */ const ARTIFACT_DOCUMENT_CHANNEL = 'xpert.artifact-document';
|
|
5
6
|
const ARTIFACT_DOCUMENT_VERSION = 1;
|
|
@@ -15,7 +16,12 @@ const artifactDocumentControls = z.record(artifactDocumentId, artifactDocumentVa
|
|
|
15
16
|
type: z.literal('query'),
|
|
16
17
|
requestId: z.string().min(1).max(80),
|
|
17
18
|
bindingId: artifactDocumentId,
|
|
18
|
-
controls: artifactDocumentControls
|
|
19
|
+
controls: artifactDocumentControls,
|
|
20
|
+
priority: z.enum([
|
|
21
|
+
'interactive',
|
|
22
|
+
'initial',
|
|
23
|
+
'refresh'
|
|
24
|
+
]).optional()
|
|
19
25
|
}).strict();
|
|
20
26
|
/** Only public presentation context may cross into the untrusted frame. Never include credentials here. */ const artifactDocumentContext = z.object({
|
|
21
27
|
bindingIds: z.array(artifactDocumentId).max(64).refine((ids)=>new Set(ids).size === ids.length, 'Duplicate binding IDs'),
|
|
@@ -322,7 +328,10 @@ const ARTIFACT_DOCUMENT_RUNTIME = String.raw`
|
|
|
322
328
|
pending = new Map(),
|
|
323
329
|
listeners = new Map(),
|
|
324
330
|
lastControls = new Map(),
|
|
325
|
-
latest = new Map()
|
|
331
|
+
latest = new Map(),
|
|
332
|
+
inFlight = new Map(),
|
|
333
|
+
deliveryLocks = new Map()
|
|
334
|
+
let refreshing = false
|
|
326
335
|
let port,
|
|
327
336
|
context,
|
|
328
337
|
sequence = 0,
|
|
@@ -337,24 +346,33 @@ const ARTIFACT_DOCUMENT_RUNTIME = String.raw`
|
|
|
337
346
|
}
|
|
338
347
|
}
|
|
339
348
|
const fail = (code) => Object.assign(new Error(code), { code })
|
|
340
|
-
const query = async (bindingId, controls = {}) => {
|
|
349
|
+
const query = async (bindingId, controls = {}, priority, owner) => {
|
|
341
350
|
await ready
|
|
342
351
|
if (!context.bindingIds.includes(bindingId)) {
|
|
343
352
|
port.postMessage({ type: 'diagnostic', code: 'DOCUMENT_BINDING_DENIED' })
|
|
344
353
|
throw fail('DOCUMENT_BINDING_DENIED')
|
|
345
354
|
}
|
|
346
|
-
|
|
347
|
-
|
|
355
|
+
if (deliveryLocks.has(bindingId) && deliveryLocks.get(bindingId) !== owner) deliveryLocks.delete(bindingId)
|
|
356
|
+
const values = { ...context.defaults, ...controls },
|
|
357
|
+
key = JSON.stringify(Object.keys(values).sort().map(id => [id, values[id]])),
|
|
358
|
+
previous = inFlight.get(bindingId)
|
|
359
|
+
if (previous && previous.key === key) return previous.promise
|
|
360
|
+
priority = priority || (lastControls.has(bindingId) ? 'interactive' : 'initial')
|
|
361
|
+
const requestId = 'q' + ++sequence
|
|
348
362
|
lastControls.set(bindingId, values)
|
|
349
363
|
latest.set(bindingId, requestId)
|
|
350
|
-
|
|
364
|
+
const promise = new Promise((resolve, reject) => {
|
|
351
365
|
const timer = setTimeout(() => {
|
|
352
366
|
pending.delete(requestId)
|
|
353
|
-
reject(fail('
|
|
354
|
-
},
|
|
367
|
+
reject(fail('DOCUMENT_QUEUE_TIMEOUT'))
|
|
368
|
+
}, 185000)
|
|
355
369
|
pending.set(requestId, { resolve, reject, timer, bindingId })
|
|
356
|
-
port.postMessage({ type: 'query', requestId, bindingId, controls: values })
|
|
370
|
+
port.postMessage({ type: 'query', requestId, bindingId, controls: values, priority })
|
|
357
371
|
})
|
|
372
|
+
inFlight.set(bindingId, { key, promise })
|
|
373
|
+
try { return await promise } finally {
|
|
374
|
+
if (inFlight.get(bindingId)?.promise === promise) inFlight.delete(bindingId)
|
|
375
|
+
}
|
|
358
376
|
}
|
|
359
377
|
const subscribe = (id, fn) => {
|
|
360
378
|
if (typeof fn !== 'function') throw fail('DOCUMENT_INVALID_LISTENER')
|
|
@@ -363,7 +381,28 @@ const ARTIFACT_DOCUMENT_RUNTIME = String.raw`
|
|
|
363
381
|
listeners.set(id, set)
|
|
364
382
|
return () => set.delete(fn)
|
|
365
383
|
}
|
|
366
|
-
const refresh = async (id) => query(id, lastControls.get(id) || {})
|
|
384
|
+
const refresh = async (id) => query(id, lastControls.get(id) || {}, 'refresh')
|
|
385
|
+
const queryGroup = async (requests, priority) => {
|
|
386
|
+
await ready
|
|
387
|
+
const ids = requests.map(request => request.bindingId)
|
|
388
|
+
if (!ids.length) return { datasets: [], failures: [] }
|
|
389
|
+
if (ids.length > 64 || new Set(ids).size !== ids.length || ids.some(id => !context.bindingIds.includes(id)))
|
|
390
|
+
throw fail('DOCUMENT_BINDING_DENIED')
|
|
391
|
+
const owner = Symbol('query-group')
|
|
392
|
+
ids.forEach(id => deliveryLocks.set(id, owner))
|
|
393
|
+
const results = await Promise.allSettled(requests.map(request => query(request.bindingId, request.controls, priority, owner)))
|
|
394
|
+
const current = ids.every(id => deliveryLocks.get(id) === owner)
|
|
395
|
+
ids.forEach(id => { if (deliveryLocks.get(id) === owner) deliveryLocks.delete(id) })
|
|
396
|
+
if (!current) throw fail('DOCUMENT_QUERY_SUPERSEDED')
|
|
397
|
+
const datasets = [], failures = []
|
|
398
|
+
results.forEach((result, index) => {
|
|
399
|
+
if (result.status === 'fulfilled') { datasets.push(result.value); emit(ids[index], result.value) }
|
|
400
|
+
else failures.push({ bindingId: ids[index], code: result.reason?.code || 'DOCUMENT_QUERY_FAILED' })
|
|
401
|
+
})
|
|
402
|
+
return { datasets, failures }
|
|
403
|
+
}
|
|
404
|
+
// Subscribers see successful members of one filter round together, after it settles.
|
|
405
|
+
const queryMany = (ids, controls = {}) => queryGroup(ids.map(bindingId => ({ bindingId, controls })), 'interactive')
|
|
367
406
|
const bindSelect = (element, config) => {
|
|
368
407
|
if (
|
|
369
408
|
!element ||
|
|
@@ -415,7 +454,7 @@ const ARTIFACT_DOCUMENT_RUNTIME = String.raw`
|
|
|
415
454
|
}
|
|
416
455
|
}
|
|
417
456
|
Object.defineProperty(window, 'xpertLiveArtifact', {
|
|
418
|
-
value: Object.freeze({ ready: () => ready, query, subscribe, refresh, bindSelect }),
|
|
457
|
+
value: Object.freeze({ ready: () => ready, query, queryMany, subscribe, refresh, bindSelect }),
|
|
419
458
|
writable: false,
|
|
420
459
|
configurable: false
|
|
421
460
|
})
|
|
@@ -439,7 +478,23 @@ const ARTIFACT_DOCUMENT_RUNTIME = String.raw`
|
|
|
439
478
|
port.onmessage = (event) => {
|
|
440
479
|
const data = event.data
|
|
441
480
|
if (data.type === 'refresh') {
|
|
442
|
-
|
|
481
|
+
if (data.bindingId) { refresh(data.bindingId).catch(console.error); return }
|
|
482
|
+
if (refreshing) return
|
|
483
|
+
refreshing = true
|
|
484
|
+
queryGroup([...new Set([...listeners.keys(), ...lastControls.keys()])].map(bindingId => ({ bindingId, controls: lastControls.get(bindingId) || {} })), 'refresh')
|
|
485
|
+
.catch(error => { if (error.code !== 'DOCUMENT_QUERY_SUPERSEDED') console.error(error) })
|
|
486
|
+
.finally(() => { refreshing = false })
|
|
487
|
+
return
|
|
488
|
+
}
|
|
489
|
+
if (data.type === 'query-state') {
|
|
490
|
+
const entry = pending.get(data.requestId)
|
|
491
|
+
if (entry && data.state === 'running') {
|
|
492
|
+
clearTimeout(entry.timer)
|
|
493
|
+
entry.timer = setTimeout(() => {
|
|
494
|
+
pending.delete(data.requestId)
|
|
495
|
+
entry.reject(fail('DOCUMENT_QUERY_TIMEOUT'))
|
|
496
|
+
}, 50000)
|
|
497
|
+
}
|
|
443
498
|
return
|
|
444
499
|
}
|
|
445
500
|
if (data.type !== 'result') return
|
|
@@ -452,7 +507,7 @@ const ARTIFACT_DOCUMENT_RUNTIME = String.raw`
|
|
|
452
507
|
return
|
|
453
508
|
}
|
|
454
509
|
if (data.ok) {
|
|
455
|
-
emit(entry.bindingId, data.dataset)
|
|
510
|
+
if (!deliveryLocks.has(entry.bindingId)) emit(entry.bindingId, data.dataset)
|
|
456
511
|
entry.resolve(data.dataset)
|
|
457
512
|
} else entry.reject(fail(data.code || 'DOCUMENT_QUERY_FAILED'))
|
|
458
513
|
}
|
|
@@ -463,9 +518,154 @@ const ARTIFACT_DOCUMENT_RUNTIME = String.raw`
|
|
|
463
518
|
})()
|
|
464
519
|
`;
|
|
465
520
|
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
521
|
+
const failure = (code)=>Object.assign(new Error(code), {
|
|
522
|
+
code
|
|
523
|
+
});
|
|
524
|
+
const keyOf = (input)=>JSON.stringify([
|
|
525
|
+
input.bindingId,
|
|
526
|
+
Object.keys(input.controls).sort().map((key)=>[
|
|
527
|
+
key,
|
|
528
|
+
input.controls[key]
|
|
529
|
+
])
|
|
530
|
+
]);
|
|
531
|
+
const priorities = {
|
|
532
|
+
interactive: 0,
|
|
533
|
+
initial: 1,
|
|
534
|
+
refresh: 2
|
|
535
|
+
};
|
|
536
|
+
const QUEUE_TIMEOUT = 180000, EXECUTION_TIMEOUT = 45000, WINDOW = 60000;
|
|
537
|
+
/** One trusted Artifact/version/actor generation. Queue time never consumes execution time.
|
|
538
|
+
* Slots remain occupied until the underlying execution settles, even after timeout/abort.
|
|
539
|
+
* Callers must propagate the signal when supported; disposal alone cannot cancel database work. */ function createArtifactQueryScheduler(options) {
|
|
540
|
+
const bounded = (value, fallback, max)=>Number.isFinite(value) ? Math.max(1, Math.min(max, Math.floor(value))) : fallback;
|
|
541
|
+
const concurrency = bounded(options.concurrency, 4, 8);
|
|
542
|
+
const dispatchLimit = bounded(options.dispatchesPerMinute, 60, 1024);
|
|
543
|
+
const queued = [], running = new Set(), latest = new Map();
|
|
544
|
+
const dispatches = [];
|
|
545
|
+
let disposed = false, wake;
|
|
546
|
+
const observe = (fn, value)=>{
|
|
547
|
+
try {
|
|
548
|
+
fn == null ? void 0 : fn(value);
|
|
549
|
+
} catch (e) {
|
|
550
|
+
/* observer only */ }
|
|
551
|
+
};
|
|
552
|
+
const busy = ()=>observe(options.onBusy, !disposed && (queued.length > 0 || running.size > 0));
|
|
553
|
+
const transition = (task, state, code)=>{
|
|
554
|
+
task.state = _extends({}, task.state, {
|
|
555
|
+
state
|
|
556
|
+
}, state === 'running' ? {
|
|
557
|
+
startedAt: Date.now()
|
|
558
|
+
} : state !== 'queued' ? {
|
|
559
|
+
finishedAt: Date.now()
|
|
560
|
+
} : {}, code ? {
|
|
561
|
+
code
|
|
562
|
+
} : {});
|
|
563
|
+
observe(options.onState, _extends({}, task.state));
|
|
564
|
+
};
|
|
565
|
+
const reject = (task, code)=>{
|
|
566
|
+
if (task.settled) return;
|
|
567
|
+
task.settled = true;
|
|
568
|
+
clearTimeout(task.timer);
|
|
569
|
+
task.controller.abort();
|
|
570
|
+
transition(task, code === 'DOCUMENT_QUERY_SUPERSEDED' ? 'superseded' : 'failed', code);
|
|
571
|
+
task.reject(failure(code));
|
|
572
|
+
if (latest.get(task.input.bindingId) === task) latest.delete(task.input.bindingId);
|
|
573
|
+
};
|
|
574
|
+
const pump = ()=>{
|
|
575
|
+
clearTimeout(wake);
|
|
576
|
+
if (disposed) return;
|
|
577
|
+
const now = Date.now();
|
|
578
|
+
while(dispatches.length && dispatches[0] <= now - WINDOW)dispatches.shift();
|
|
579
|
+
while(queued.length && running.size < concurrency && dispatches.length < dispatchLimit){
|
|
580
|
+
queued.sort((a, b)=>a.priority - b.priority || a.state.queuedAt - b.state.queuedAt);
|
|
581
|
+
const task = queued.shift();
|
|
582
|
+
clearTimeout(task.timer);
|
|
583
|
+
running.add(task);
|
|
584
|
+
dispatches.push(Date.now());
|
|
585
|
+
transition(task, 'running');
|
|
586
|
+
task.timer = setTimeout(()=>reject(task, 'DOCUMENT_QUERY_TIMEOUT'), EXECUTION_TIMEOUT);
|
|
587
|
+
Promise.resolve().then(()=>options.execute(task.input, task.controller.signal)).then((result)=>{
|
|
588
|
+
if (disposed || task.settled) return;
|
|
589
|
+
task.settled = true;
|
|
590
|
+
transition(task, 'succeeded');
|
|
591
|
+
task.resolve(result);
|
|
592
|
+
}, ()=>reject(task, 'DOCUMENT_QUERY_FAILED')).finally(()=>{
|
|
593
|
+
clearTimeout(task.timer);
|
|
594
|
+
running.delete(task);
|
|
595
|
+
if (latest.get(task.input.bindingId) === task) latest.delete(task.input.bindingId);
|
|
596
|
+
pump();
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
if (queued.length && dispatches.length >= dispatchLimit) wake = setTimeout(pump, Math.max(1, dispatches[0] + WINDOW - Date.now()));
|
|
600
|
+
busy();
|
|
601
|
+
};
|
|
602
|
+
return {
|
|
603
|
+
query (input, priority = 'interactive') {
|
|
604
|
+
if (disposed) return Promise.reject(failure('DOCUMENT_DISPOSED'));
|
|
605
|
+
const key = keyOf(input), previous = latest.get(input.bindingId);
|
|
606
|
+
if ((previous == null ? void 0 : previous.key) === key && !previous.settled) {
|
|
607
|
+
previous.priority = Math.min(previous.priority, priorities[priority]);
|
|
608
|
+
return previous.promise;
|
|
609
|
+
}
|
|
610
|
+
if (previous) {
|
|
611
|
+
const index = queued.indexOf(previous);
|
|
612
|
+
if (index >= 0) queued.splice(index, 1);
|
|
613
|
+
reject(previous, 'DOCUMENT_QUERY_SUPERSEDED');
|
|
614
|
+
}
|
|
615
|
+
if (queued.length >= 64) return Promise.reject(failure('DOCUMENT_QUEUE_LIMIT'));
|
|
616
|
+
let resolve, rejectPromise;
|
|
617
|
+
const promise = new Promise((yes, no)=>{
|
|
618
|
+
resolve = yes;
|
|
619
|
+
rejectPromise = no;
|
|
620
|
+
});
|
|
621
|
+
const task = {
|
|
622
|
+
input: {
|
|
623
|
+
bindingId: input.bindingId,
|
|
624
|
+
controls: _extends({}, input.controls)
|
|
625
|
+
},
|
|
626
|
+
key,
|
|
627
|
+
priority: priorities[priority],
|
|
628
|
+
controller: new AbortController(),
|
|
629
|
+
promise,
|
|
630
|
+
resolve,
|
|
631
|
+
reject: rejectPromise,
|
|
632
|
+
state: _extends({}, input, {
|
|
633
|
+
controls: _extends({}, input.controls),
|
|
634
|
+
state: 'queued',
|
|
635
|
+
queuedAt: Date.now()
|
|
636
|
+
}),
|
|
637
|
+
settled: false
|
|
638
|
+
};
|
|
639
|
+
task.timer = setTimeout(()=>{
|
|
640
|
+
const index = queued.indexOf(task);
|
|
641
|
+
if (index >= 0) queued.splice(index, 1);
|
|
642
|
+
reject(task, 'DOCUMENT_QUEUE_TIMEOUT');
|
|
643
|
+
pump();
|
|
644
|
+
}, QUEUE_TIMEOUT);
|
|
645
|
+
latest.set(input.bindingId, task);
|
|
646
|
+
queued.push(task);
|
|
647
|
+
transition(task, 'queued');
|
|
648
|
+
pump();
|
|
649
|
+
return promise;
|
|
650
|
+
},
|
|
651
|
+
get busy () {
|
|
652
|
+
return queued.length > 0 || running.size > 0;
|
|
653
|
+
},
|
|
654
|
+
dispose () {
|
|
655
|
+
if (disposed) return;
|
|
656
|
+
disposed = true;
|
|
657
|
+
clearTimeout(wake);
|
|
658
|
+
for (const task of [
|
|
659
|
+
...queued,
|
|
660
|
+
...running
|
|
661
|
+
])reject(task, 'DOCUMENT_DISPOSED');
|
|
662
|
+
queued.length = 0;
|
|
663
|
+
latest.clear();
|
|
664
|
+
busy();
|
|
665
|
+
}
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
|
|
469
669
|
const readySchema = z.object({
|
|
470
670
|
channel: z.literal(ARTIFACT_DOCUMENT_CHANNEL),
|
|
471
671
|
version: z.literal(ARTIFACT_DOCUMENT_VERSION),
|
|
@@ -486,8 +686,10 @@ const diagnosticSchema = z.object({
|
|
|
486
686
|
const source = renderArtifactDocument(options.html, sessionId, options.dependencies, options.networkPolicy);
|
|
487
687
|
const channel = new MessageChannel();
|
|
488
688
|
const bindingIds = new Set(context.bindingIds);
|
|
689
|
+
const admissionLimit = Number.isFinite(options.dispatchesPerMinute) ? Math.max(256, Math.min(1024, options.dispatchesPerMinute)) : 256;
|
|
489
690
|
const requestIds = new Set();
|
|
490
|
-
const activeIds = new
|
|
691
|
+
const activeIds = new Map();
|
|
692
|
+
const executingIds = new Set();
|
|
491
693
|
const latest = new Map();
|
|
492
694
|
const hostWindow = frame.ownerDocument.defaultView;
|
|
493
695
|
let connected = false, disposed = false, requests = 0, started = Date.now();
|
|
@@ -512,6 +714,34 @@ const diagnosticSchema = z.object({
|
|
|
512
714
|
});
|
|
513
715
|
observe(options.onError, code);
|
|
514
716
|
};
|
|
717
|
+
const scheduler = createArtifactQueryScheduler({
|
|
718
|
+
concurrency: options.concurrency,
|
|
719
|
+
dispatchesPerMinute: options.dispatchesPerMinute,
|
|
720
|
+
execute: async (input, signal)=>{
|
|
721
|
+
if (signal.aborted) throw new Error('DOCUMENT_QUERY_SUPERSEDED');
|
|
722
|
+
const request = [
|
|
723
|
+
...activeIds.values()
|
|
724
|
+
].find((item)=>item.bindingId === input.bindingId && Object.keys(item.controls).length === Object.keys(input.controls).length && Object.keys(input.controls).every((key)=>item.controls[key] === input.controls[key]));
|
|
725
|
+
if (!request) throw new Error('DOCUMENT_QUERY_SUPERSEDED');
|
|
726
|
+
executingIds.add(request.requestId);
|
|
727
|
+
try {
|
|
728
|
+
return await options.query(request, signal);
|
|
729
|
+
} finally{
|
|
730
|
+
executingIds.delete(request.requestId);
|
|
731
|
+
}
|
|
732
|
+
},
|
|
733
|
+
onBusy: (value)=>observe(options.onBusy, value),
|
|
734
|
+
onState: (state)=>{
|
|
735
|
+
observe(options.onQueryState, state);
|
|
736
|
+
if (state.state === 'running') {
|
|
737
|
+
for (const input of activeIds.values())if (input.bindingId === state.bindingId) post({
|
|
738
|
+
type: 'query-state',
|
|
739
|
+
requestId: input.requestId,
|
|
740
|
+
state: 'running'
|
|
741
|
+
});
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
});
|
|
515
745
|
channel.port1.onmessage = async (event)=>{
|
|
516
746
|
if (disposed) return;
|
|
517
747
|
const diagnostic = diagnosticSchema.safeParse(event.data);
|
|
@@ -528,7 +758,8 @@ const diagnosticSchema = z.object({
|
|
|
528
758
|
type: parsed.data.type,
|
|
529
759
|
requestId: parsed.data.requestId,
|
|
530
760
|
bindingId: parsed.data.bindingId,
|
|
531
|
-
controls: parsed.data.controls
|
|
761
|
+
controls: parsed.data.controls,
|
|
762
|
+
priority: parsed.data.priority
|
|
532
763
|
};
|
|
533
764
|
if (!bindingIds.has(input.bindingId)) {
|
|
534
765
|
reject(input.requestId, 'DOCUMENT_BINDING_DENIED');
|
|
@@ -540,20 +771,24 @@ const diagnosticSchema = z.object({
|
|
|
540
771
|
requestIds.clear();
|
|
541
772
|
}
|
|
542
773
|
// Keep in-flight IDs protected even after the one-minute replay/rate window rolls over.
|
|
543
|
-
if (activeIds.has(input.requestId) || requestIds.has(input.requestId)) {
|
|
774
|
+
if (activeIds.has(input.requestId) || executingIds.has(input.requestId) || requestIds.has(input.requestId)) {
|
|
544
775
|
reject(input.requestId, 'DOCUMENT_REQUEST_REPLAY');
|
|
545
776
|
return;
|
|
546
777
|
}
|
|
547
|
-
if (activeIds.size >=
|
|
778
|
+
if (activeIds.size >= 128 || ++requests > admissionLimit) {
|
|
548
779
|
reject(input.requestId, 'DOCUMENT_QUERY_LIMIT');
|
|
549
780
|
return;
|
|
550
781
|
}
|
|
551
782
|
requestIds.add(input.requestId);
|
|
552
|
-
activeIds.
|
|
783
|
+
activeIds.set(input.requestId, input);
|
|
553
784
|
latest.set(input.bindingId, input.requestId);
|
|
554
|
-
|
|
785
|
+
post({
|
|
786
|
+
type: 'query-state',
|
|
787
|
+
requestId: input.requestId,
|
|
788
|
+
state: 'queued'
|
|
789
|
+
});
|
|
555
790
|
try {
|
|
556
|
-
const dataset = await
|
|
791
|
+
const dataset = await scheduler.query(input, input.priority);
|
|
557
792
|
if (!disposed) {
|
|
558
793
|
post({
|
|
559
794
|
type: 'result',
|
|
@@ -563,19 +798,19 @@ const diagnosticSchema = z.object({
|
|
|
563
798
|
});
|
|
564
799
|
if (latest.get(input.bindingId) === input.requestId) observe(options.onResult, dataset);
|
|
565
800
|
}
|
|
566
|
-
} catch (
|
|
801
|
+
} catch (error) {
|
|
567
802
|
if (!disposed) {
|
|
803
|
+
const code = error instanceof Error && /^DOCUMENT_[A-Z_]+$/.test(error.message) ? error.message : 'DOCUMENT_QUERY_FAILED';
|
|
568
804
|
post({
|
|
569
805
|
type: 'result',
|
|
570
806
|
requestId: input.requestId,
|
|
571
807
|
ok: false,
|
|
572
|
-
code
|
|
808
|
+
code
|
|
573
809
|
});
|
|
574
|
-
if (latest.get(input.bindingId) === input.requestId) observe(options.onError,
|
|
810
|
+
if (latest.get(input.bindingId) === input.requestId) observe(options.onError, code);
|
|
575
811
|
}
|
|
576
812
|
} finally{
|
|
577
813
|
activeIds.delete(input.requestId);
|
|
578
|
-
if (!disposed) observe(options.onBusy, activeIds.size > 0);
|
|
579
814
|
}
|
|
580
815
|
};
|
|
581
816
|
const ready = (event)=>{
|
|
@@ -598,14 +833,19 @@ const diagnosticSchema = z.object({
|
|
|
598
833
|
channel.port1.start();
|
|
599
834
|
frame.srcdoc = source;
|
|
600
835
|
return {
|
|
601
|
-
refresh () {
|
|
602
|
-
|
|
836
|
+
refresh (bindingId) {
|
|
837
|
+
if (bindingId !== undefined && !bindingIds.has(bindingId)) throw new Error('DOCUMENT_BINDING_DENIED');
|
|
838
|
+
post(_extends({
|
|
603
839
|
type: 'refresh'
|
|
604
|
-
}
|
|
840
|
+
}, bindingId ? {
|
|
841
|
+
bindingId
|
|
842
|
+
} : {}));
|
|
605
843
|
},
|
|
606
844
|
dispose () {
|
|
607
845
|
if (disposed) return;
|
|
608
846
|
disposed = true;
|
|
847
|
+
scheduler.dispose();
|
|
848
|
+
activeIds.clear();
|
|
609
849
|
hostWindow.removeEventListener('message', ready);
|
|
610
850
|
channel.port1.close();
|
|
611
851
|
channel.port2.close();
|
|
@@ -622,4 +862,4 @@ const diagnosticSchema = z.object({
|
|
|
622
862
|
hostDocument.head.prepend(meta);
|
|
623
863
|
}
|
|
624
864
|
|
|
625
|
-
export { ARTIFACT_DOCUMENT_CHANNEL, ARTIFACT_DOCUMENT_CSP, ARTIFACT_DOCUMENT_VERSION, artifactDocumentContext, artifactDocumentControls, artifactDocumentCsp, artifactDocumentDependencyAssets, artifactDocumentDependencyLock, artifactDocumentDependencyLocks, artifactDocumentHtml, artifactDocumentId, artifactDocumentNetworkPolicy, artifactDocumentQuery, artifactDocumentValue, installArtifactDocumentFramePolicy, isArtifactDocumentResourceAllowed, mountArtifactDocument, renderArtifactDocument, renderArtifactDocumentDependencies, verifyArtifactDocumentDependencies };
|
|
865
|
+
export { ARTIFACT_DOCUMENT_CHANNEL, ARTIFACT_DOCUMENT_CSP, ARTIFACT_DOCUMENT_VERSION, artifactDocumentContext, artifactDocumentControls, artifactDocumentCsp, artifactDocumentDependencyAssets, artifactDocumentDependencyLock, artifactDocumentDependencyLocks, artifactDocumentHtml, artifactDocumentId, artifactDocumentNetworkPolicy, artifactDocumentQuery, artifactDocumentValue, createArtifactQueryScheduler, installArtifactDocumentFramePolicy, isArtifactDocumentResourceAllowed, mountArtifactDocument, renderArtifactDocument, renderArtifactDocumentDependencies, verifyArtifactDocumentDependencies };
|
|
@@ -46,7 +46,11 @@ Node 内置模块或安全上下文,因此浏览器 HTTPS、普通 HTTP 内网
|
|
|
46
46
|
由该版本的内容摘要覆盖。只存版本号或 hash、再从当前插件目录寻找代码,不能保证历史可用性。
|
|
47
47
|
读取时验证版本内容摘要及每项依赖锁;修改页面默认继承原快照,升级依赖必须显式生成新版本。
|
|
48
48
|
|
|
49
|
-
SDK 使用独立 MessageChannel,只接受当前 iframe、当前挂载随机标识的一次初始化请求;旧文档的延迟消息不能初始化新挂载。每条查询严格解析、检查 Binding
|
|
49
|
+
SDK 使用独立 MessageChannel,只接受当前 iframe、当前挂载随机标识的一次初始化请求;旧文档的延迟消息不能初始化新挂载。每条查询严格解析、检查 Binding 白名单和请求重放。默认 4 路并发,可信宿主可配置 1–8 路;每个挂载默认每滚动分钟启动最多 60 次执行,超过预算的合法请求进入队列。最多保留 64 个排队任务,排队期限 180 秒,执行期限 45 秒,文档最多声明 64 个 Binding。
|
|
50
|
+
|
|
51
|
+
`createArtifactQueryScheduler` 供 HTML 宿主与其他 Artifact 渲染器复用。相同 Binding/控件的进行中请求复用 Promise;新参数替换旧待执行请求,交互优先于初次加载和刷新。超时或终止发出 AbortSignal,但底层执行实际结束前不释放并发槽。关闭文档清空队列、停止后续派发并丢弃迟到结果;只有调用方将 signal 传到后端时才具备真实 I/O 取消。不得以丢弃响应冒充数据库查询取消。
|
|
52
|
+
|
|
53
|
+
`onQueryState` 提供 queued/running/succeeded/failed/superseded 及排队、开始、结束时间。`onBusy` 包含排队与尚未结束的底层执行。可信、无数据源 I/O 的快照验证宿主可以配置独立的有限回放预算 `dispatchesPerMinute`(最多 1024);生产看板保留 60。作者 HTML 不能调整并发或预算。
|
|
50
54
|
|
|
51
55
|
## 文档 SDK
|
|
52
56
|
|
|
@@ -63,10 +67,15 @@ await live.ready()
|
|
|
63
67
|
await live.query('sales', { region: null })
|
|
64
68
|
// 筛选值是声明的 controlId;刷新沿用此 Binding 最近一次请求的控件值。
|
|
65
69
|
await live.refresh('sales')
|
|
70
|
+
// 多来源共享筛选:本轮结束后,一起交付成功的订阅结果;失败项须明确显示不可用。
|
|
71
|
+
const round = await live.queryMany(['sales', 'margin'], { region: 'east' })
|
|
72
|
+
renderUnavailable(round.failures)
|
|
66
73
|
```
|
|
67
74
|
|
|
68
75
|
订阅会接收普通查询和宿主刷新结果。同一 Binding 的旧响应不会覆盖新响应。页面自行处理 loading/error/empty 和数据完整性;可信宿主独立显示新鲜度、部分结果及错误状态。
|
|
69
76
|
|
|
77
|
+
`queryMany` 返回 `{ datasets, failures }`,失败项包含 `bindingId` 和稳定错误码。新一轮共享筛选使旧轮次失效;旧轮次不会补写新控件结果。全页宿主刷新使用分组交付并合并重复刷新,单来源 `host.refresh(bindingId)` 保留独立刷新。旧 HTML 的多个独立 `query` 调用仍独立交付;需要多来源同时更新的作者代码应显式使用 `queryMany`,不要将旧数据作为失败项的新结果。
|
|
78
|
+
|
|
70
79
|
`bindSelect` 是可选的通用 Dataset 控件适配器:从已收到的数据行收集唯一值、保留筛选前的候选值、维持选择并发起查询。option.value 使用 JSON 编码以保留标量类型,页面不应再添加第二个 change handler。`allValue` 默认 null,可显式指定声明的全选值。它不会额外查询隐藏数据,也不会把候选列表当作授权;字段和参数访问始终由后端校验。查询失败触发冒泡的 `xpert-query-error` 事件。其他控件可直接使用 query。
|
|
71
80
|
|
|
72
81
|
## 隔离边界
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xpert-ai/plugin-sdk",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.33.1",
|
|
4
4
|
"license": "AGPL-3.0",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -74,7 +74,7 @@
|
|
|
74
74
|
},
|
|
75
75
|
"dependencies": {
|
|
76
76
|
"@langchain/openai": "0.6.9",
|
|
77
|
-
"@xpert-ai/contracts": "3.
|
|
77
|
+
"@xpert-ai/contracts": "3.33.1",
|
|
78
78
|
"express": "^4.22.1",
|
|
79
79
|
"js-tiktoken": "^1.0.21"
|
|
80
80
|
},
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type ArtifactQueryState } from './scheduler';
|
|
1
2
|
import { type ArtifactDocumentContext, type ArtifactDocumentQuery } from './protocol';
|
|
2
3
|
import type { ArtifactDocumentDependencyAsset } from './dependencies';
|
|
3
4
|
import type { ArtifactDocumentNetworkPolicy } from './network';
|
|
@@ -12,7 +13,11 @@ export interface ArtifactDocumentHostOptions<T> {
|
|
|
12
13
|
/** Public binding IDs and presentation defaults for this document generation. */
|
|
13
14
|
context: ArtifactDocumentContext;
|
|
14
15
|
/** Resolve against saved Bindings on the server with the current user's access; never execute a query definition from HTML. */
|
|
15
|
-
query(input: ArtifactDocumentQuery): Promise<T>;
|
|
16
|
+
query(input: ArtifactDocumentQuery, signal?: AbortSignal): Promise<T>;
|
|
17
|
+
concurrency?: number;
|
|
18
|
+
/** Trusted host policy, never supplied by authored HTML. Defaults to 60 live executions/minute. */
|
|
19
|
+
dispatchesPerMinute?: number;
|
|
20
|
+
onQueryState?(state: ArtifactQueryState): void;
|
|
16
21
|
/** Latest result for a Binding, suitable for host-owned freshness/partial-result indicators. */
|
|
17
22
|
onResult?(result: T): void;
|
|
18
23
|
/** Stable protocol/query error code; private backend error details are never sent into the document. */
|
|
@@ -23,7 +28,7 @@ export interface ArtifactDocumentHostOptions<T> {
|
|
|
23
28
|
/** Lifecycle handle for one mount; dispose before replacing the document or its trusted query scope. */
|
|
24
29
|
export interface ArtifactDocumentHost {
|
|
25
30
|
/** Requeries subscribed/previously queried bindings using their last controls. */
|
|
26
|
-
refresh(): void;
|
|
31
|
+
refresh(bindingId?: string): void;
|
|
27
32
|
/** Closes the query channel and discards late results; backend cancellation remains the caller's responsibility. */
|
|
28
33
|
dispose(): void;
|
|
29
34
|
}
|
|
@@ -12,16 +12,19 @@ export declare const artifactDocumentQuery: z.ZodObject<{
|
|
|
12
12
|
requestId: z.ZodString;
|
|
13
13
|
bindingId: z.ZodString;
|
|
14
14
|
controls: z.ZodEffects<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodString, z.ZodNumber, z.ZodBoolean, z.ZodNull]>>, Record<string, string | number | boolean>, Record<string, string | number | boolean>>;
|
|
15
|
+
priority: z.ZodOptional<z.ZodEnum<["interactive", "initial", "refresh"]>>;
|
|
15
16
|
}, "strict", z.ZodTypeAny, {
|
|
16
17
|
type?: "query";
|
|
17
18
|
controls?: Record<string, string | number | boolean>;
|
|
18
19
|
requestId?: string;
|
|
19
20
|
bindingId?: string;
|
|
21
|
+
priority?: "interactive" | "initial" | "refresh";
|
|
20
22
|
}, {
|
|
21
23
|
type?: "query";
|
|
22
24
|
controls?: Record<string, string | number | boolean>;
|
|
23
25
|
requestId?: string;
|
|
24
26
|
bindingId?: string;
|
|
27
|
+
priority?: "interactive" | "initial" | "refresh";
|
|
25
28
|
}>;
|
|
26
29
|
/** Flat UI filter values keyed by declared control IDs; validated again by the backend Binding. */
|
|
27
30
|
export type ArtifactDocumentControls = Record<string, string | number | boolean | null>;
|
|
@@ -31,6 +34,7 @@ export interface ArtifactDocumentQuery {
|
|
|
31
34
|
requestId: string;
|
|
32
35
|
bindingId: string;
|
|
33
36
|
controls: ArtifactDocumentControls;
|
|
37
|
+
priority?: 'interactive' | 'initial' | 'refresh';
|
|
34
38
|
}
|
|
35
39
|
/** Only public presentation context may cross into the untrusted frame. Never include credentials here. */
|
|
36
40
|
export declare const artifactDocumentContext: z.ZodObject<{
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ArtifactDocumentControls } from './protocol';
|
|
2
|
+
export type ArtifactQueryPriority = 'interactive' | 'initial' | 'refresh';
|
|
3
|
+
export interface ArtifactQueryInput {
|
|
4
|
+
bindingId: string;
|
|
5
|
+
controls: ArtifactDocumentControls;
|
|
6
|
+
}
|
|
7
|
+
export interface ArtifactQueryState {
|
|
8
|
+
bindingId: string;
|
|
9
|
+
controls: ArtifactDocumentControls;
|
|
10
|
+
state: 'queued' | 'running' | 'succeeded' | 'failed' | 'superseded';
|
|
11
|
+
queuedAt: number;
|
|
12
|
+
startedAt?: number;
|
|
13
|
+
finishedAt?: number;
|
|
14
|
+
code?: string;
|
|
15
|
+
}
|
|
16
|
+
export interface ArtifactQuerySchedulerOptions<T> {
|
|
17
|
+
execute(input: ArtifactQueryInput, signal: AbortSignal): Promise<T>;
|
|
18
|
+
concurrency?: number;
|
|
19
|
+
/** Trusted executor budget. Live integrations should retain 60; bounded snapshot replay may use up to 1024. */
|
|
20
|
+
dispatchesPerMinute?: number;
|
|
21
|
+
onState?(state: ArtifactQueryState): void;
|
|
22
|
+
onBusy?(busy: boolean): void;
|
|
23
|
+
}
|
|
24
|
+
/** One trusted Artifact/version/actor generation. Queue time never consumes execution time.
|
|
25
|
+
* Slots remain occupied until the underlying execution settles, even after timeout/abort.
|
|
26
|
+
* Callers must propagate the signal when supported; disposal alone cannot cancel database work. */
|
|
27
|
+
export declare function createArtifactQueryScheduler<T>(options: ArtifactQuerySchedulerOptions<T>): {
|
|
28
|
+
query(input: ArtifactQueryInput, priority?: ArtifactQueryPriority): Promise<T>;
|
|
29
|
+
readonly busy: boolean;
|
|
30
|
+
dispose(): void;
|
|
31
|
+
};
|