@smilodon/core 1.10.0 → 1.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +130 -371
  2. package/dist/index.cjs +1931 -24
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.js +1931 -25
  5. package/dist/index.js.map +1 -1
  6. package/dist/index.min.js +1 -1
  7. package/dist/index.min.js.map +1 -1
  8. package/dist/index.umd.js +1931 -24
  9. package/dist/index.umd.js.map +1 -1
  10. package/dist/index.umd.min.js +1 -1
  11. package/dist/index.umd.min.js.map +1 -1
  12. package/dist/types/src/components/enhanced-select.d.ts +71 -7
  13. package/dist/types/src/components/native-select.d.ts +1 -1
  14. package/dist/types/src/components/select-option.d.ts +2 -2
  15. package/dist/types/src/config/global-config.d.ts +5 -3
  16. package/dist/types/src/data-loading/public-config.d.ts +3 -0
  17. package/dist/types/src/data-loading/public-types.d.ts +171 -0
  18. package/dist/types/src/data-loading/request-coordinator.d.ts +236 -0
  19. package/dist/types/src/index.d.ts +2 -0
  20. package/dist/types/src/native-types.d.ts +5 -0
  21. package/dist/types/src/renderers/contracts.d.ts +1 -1
  22. package/dist/types/src/types/limitation.d.ts +6 -0
  23. package/dist/types/src/types.d.ts +2 -6
  24. package/dist/types/src/utils/custom-option-pool.d.ts +1 -1
  25. package/package.json +7 -4
  26. package/dist/types/src/themes/importer.d.ts +0 -112
  27. package/dist/types/tests/accessibility-contract.spec.d.ts +0 -1
  28. package/dist/types/tests/capabilities-tracking.spec.d.ts +0 -1
  29. package/dist/types/tests/csp.spec.d.ts +0 -5
  30. package/dist/types/tests/enhanced-option-renderer.spec.d.ts +0 -1
  31. package/dist/types/tests/enhanced-select-accessibility-integration.spec.d.ts +0 -1
  32. package/dist/types/tests/enhanced-select-active-authority.spec.d.ts +0 -1
  33. package/dist/types/tests/enhanced-select-active-parity.spec.d.ts +0 -1
  34. package/dist/types/tests/enhanced-select-authority.spec.d.ts +0 -1
  35. package/dist/types/tests/enhanced-select-compatibility-projection.spec.d.ts +0 -1
  36. package/dist/types/tests/enhanced-select-selection-parity.spec.d.ts +0 -1
  37. package/dist/types/tests/enhanced-select-virtualization-integration.spec.d.ts +0 -1
  38. package/dist/types/tests/interaction.spec.d.ts +0 -1
  39. package/dist/types/tests/item-adapter.spec.d.ts +0 -1
  40. package/dist/types/tests/item-registry.spec.d.ts +0 -1
  41. package/dist/types/tests/lifecycle.spec.d.ts +0 -1
  42. package/dist/types/tests/memory-lifecycle.spec.d.ts +0 -1
  43. package/dist/types/tests/select-accessibility.spec.d.ts +0 -1
  44. package/dist/types/tests/select-selection.spec.d.ts +0 -1
  45. package/dist/types/tests/setup.d.ts +0 -6
  46. package/dist/types/tests/shadow-dom.spec.d.ts +0 -5
  47. package/dist/types/tests/smoke.spec.d.ts +0 -1
  48. package/dist/types/tests/stress.spec.d.ts +0 -5
  49. package/dist/types/tests/styling-contract.spec.d.ts +0 -1
  50. package/dist/types/tests/virtualization-contract.spec.d.ts +0 -1
  51. package/dist/types/tests/virtualizer.spec.d.ts +0 -1
  52. package/dist/types/tests/web-accessibility-effects.spec.d.ts +0 -1
package/dist/index.cjs CHANGED
@@ -2249,6 +2249,96 @@ function resetSelectConfig() {
2249
2249
  selectConfig.resetConfig();
2250
2250
  }
2251
2251
 
2252
+ const DEFAULT_CONFIG = {
2253
+ protocol: 'legacy',
2254
+ searchMode: 'local',
2255
+ paginationMode: 'page',
2256
+ firstPage: 1,
2257
+ };
2258
+ const ALLOWED_FIELDS = new Set([
2259
+ 'protocol',
2260
+ 'searchMode',
2261
+ 'paginationMode',
2262
+ 'firstPage',
2263
+ 'fetchLimit',
2264
+ ]);
2265
+ function issue(path, code, message) {
2266
+ return { path, code, message };
2267
+ }
2268
+ function isRecord$1(value) {
2269
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
2270
+ return false;
2271
+ const prototype = Object.getPrototypeOf(value);
2272
+ return prototype === Object.prototype || prototype === null;
2273
+ }
2274
+ function validatePositiveSafeInteger(candidate, key, issues) {
2275
+ const value = candidate[key];
2276
+ if (value === undefined)
2277
+ return;
2278
+ if (typeof value !== 'number') {
2279
+ issues.push(issue(key, 'invalid-type', `${key} must be a number.`));
2280
+ return;
2281
+ }
2282
+ if (!Number.isSafeInteger(value) || value <= 0) {
2283
+ issues.push(issue(key, 'invalid-positive-integer', `${key} must be a positive safe integer.`));
2284
+ }
2285
+ }
2286
+ /** Validate a complete effective per-instance data-loading configuration. */
2287
+ function validateDataLoadingConfig(candidate) {
2288
+ if (!isRecord$1(candidate)) {
2289
+ return {
2290
+ valid: false,
2291
+ issues: [issue('dataLoading', 'invalid-type', 'dataLoading must be a plain object.')],
2292
+ };
2293
+ }
2294
+ const issues = [];
2295
+ for (const key of Object.keys(candidate).filter((candidateKey) => !ALLOWED_FIELDS.has(candidateKey)).sort()) {
2296
+ issues.push(issue(key, 'unknown-field', `Unknown dataLoading field: ${key}.`));
2297
+ }
2298
+ const protocolValue = candidate.protocol;
2299
+ const protocol = protocolValue === undefined ? DEFAULT_CONFIG.protocol : protocolValue;
2300
+ if (typeof protocol !== 'string') {
2301
+ issues.push(issue('protocol', 'invalid-type', 'protocol must be a string.'));
2302
+ }
2303
+ else if (protocol !== 'legacy' && protocol !== 'acknowledged') {
2304
+ issues.push(issue('protocol', 'invalid-value', 'protocol must be legacy or acknowledged.'));
2305
+ }
2306
+ const searchModeValue = candidate.searchMode;
2307
+ const searchMode = searchModeValue === undefined ? DEFAULT_CONFIG.searchMode : searchModeValue;
2308
+ if (typeof searchMode !== 'string') {
2309
+ issues.push(issue('searchMode', 'invalid-type', 'searchMode must be a string.'));
2310
+ }
2311
+ else if (searchMode !== 'local' && searchMode !== 'remote' && searchMode !== 'hybrid') {
2312
+ issues.push(issue('searchMode', 'invalid-value', 'searchMode must be local, remote, or hybrid.'));
2313
+ }
2314
+ const paginationModeValue = candidate.paginationMode;
2315
+ const paginationMode = paginationModeValue === undefined ? DEFAULT_CONFIG.paginationMode : paginationModeValue;
2316
+ if (typeof paginationMode !== 'string') {
2317
+ issues.push(issue('paginationMode', 'invalid-type', 'paginationMode must be a string.'));
2318
+ }
2319
+ else if (paginationMode !== 'page' && paginationMode !== 'cursor') {
2320
+ issues.push(issue('paginationMode', 'invalid-value', 'paginationMode must be page or cursor.'));
2321
+ }
2322
+ validatePositiveSafeInteger(candidate, 'firstPage', issues);
2323
+ validatePositiveSafeInteger(candidate, 'fetchLimit', issues);
2324
+ if (protocol === 'legacy' && (searchMode === 'remote' || searchMode === 'hybrid')) {
2325
+ issues.push(issue('searchMode', 'requires-acknowledged-protocol', 'Remote and hybrid search require the acknowledged protocol.'));
2326
+ }
2327
+ if (protocol === 'legacy' && paginationMode === 'cursor') {
2328
+ issues.push(issue('paginationMode', 'requires-acknowledged-protocol', 'Cursor pagination requires the acknowledged protocol.'));
2329
+ }
2330
+ if (issues.length > 0)
2331
+ return { valid: false, issues };
2332
+ const resolved = {
2333
+ protocol: protocol,
2334
+ searchMode: searchMode,
2335
+ paginationMode: paginationMode,
2336
+ firstPage: candidate.firstPage === undefined ? DEFAULT_CONFIG.firstPage : candidate.firstPage,
2337
+ ...(candidate.fetchLimit === undefined ? {} : { fetchLimit: candidate.fetchLimit }),
2338
+ };
2339
+ return { valid: true, value: resolved };
2340
+ }
2341
+
2252
2342
  /** Returns whether a selected key remains in the filtered result set. */
2253
2343
  /**
2254
2344
  * Returns keys in the half-open index range [startIndex, endIndex), clamped to
@@ -3050,6 +3140,798 @@ function arraysEqualByValue(a, b) {
3050
3140
  return true;
3051
3141
  }
3052
3142
 
3143
+ /**
3144
+ * DOM-independent coordinator for the opt-in acknowledged data-loading
3145
+ * protocol. This module is intentionally not re-exported from the package
3146
+ * entry point; public component/adapter integration is a later increment.
3147
+ */
3148
+ const DEFAULT_MAX_CURSOR_PAGES = 256;
3149
+ const HARD_MAX_CURSOR_PAGES = 4096;
3150
+ const DEFAULT_MAX_CURSOR_TOKEN_BYTES = 1024;
3151
+ const HARD_MAX_CURSOR_TOKEN_BYTES = 4096;
3152
+ let coordinatorInstanceSequence = 0;
3153
+ function isRecord(value) {
3154
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
3155
+ return false;
3156
+ const prototype = Object.getPrototypeOf(value);
3157
+ return prototype === Object.prototype || prototype === null;
3158
+ }
3159
+ function isPositiveSafeInteger(value) {
3160
+ return Number.isSafeInteger(value) && value > 0;
3161
+ }
3162
+ function isNonNegativeSafeInteger(value) {
3163
+ return Number.isSafeInteger(value) && value >= 0;
3164
+ }
3165
+ function isCursor(value) {
3166
+ return typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value));
3167
+ }
3168
+ /** Count UTF-8 bytes without depending on DOM APIs or Node Buffer. */
3169
+ function cursorTokenByteLength(cursor) {
3170
+ const token = String(cursor);
3171
+ let bytes = 0;
3172
+ for (const character of token) {
3173
+ const codePoint = character.codePointAt(0);
3174
+ if (codePoint <= 0x7f)
3175
+ bytes += 1;
3176
+ else if (codePoint <= 0x7ff)
3177
+ bytes += 2;
3178
+ else if (codePoint <= 0xffff)
3179
+ bytes += 3;
3180
+ else
3181
+ bytes += 4;
3182
+ }
3183
+ return bytes;
3184
+ }
3185
+ function parseRequestId(value) {
3186
+ const match = /^data-(\d+)-generation-(\d+)-request-(\d+)-([a-z0-9]+)$/.exec(value);
3187
+ if (!match)
3188
+ return null;
3189
+ const [, instanceText, generationText, sequenceText, check] = match;
3190
+ const instanceId = Number(instanceText);
3191
+ const queryGeneration = Number(generationText);
3192
+ const sequence = Number(sequenceText);
3193
+ if (!Number.isSafeInteger(instanceId) || instanceId < 1 ||
3194
+ !Number.isSafeInteger(queryGeneration) || queryGeneration < 0 ||
3195
+ !Number.isSafeInteger(sequence) || sequence < 1)
3196
+ return null;
3197
+ return Object.freeze({ instanceId, queryGeneration, sequence, check });
3198
+ }
3199
+ function requestIdCheck(secret, instanceId, queryGeneration, sequence) {
3200
+ // A compact keyed check distinguishes IDs actually minted by this instance
3201
+ // from arbitrary strings without retaining a registry of historical IDs.
3202
+ let hash = 14695981039346656037n;
3203
+ const mask = (1n << 64n) - 1n;
3204
+ const input = `${secret}:${instanceId}:${queryGeneration}:${sequence}`;
3205
+ for (let index = 0; index < input.length; index += 1) {
3206
+ hash ^= BigInt(input.charCodeAt(index));
3207
+ hash = (hash * 1099511628211n) & mask;
3208
+ }
3209
+ return hash.toString(36);
3210
+ }
3211
+ function isQueryMode(value) {
3212
+ return value === 'local' || value === 'remote' || value === 'hybrid';
3213
+ }
3214
+ function isPaginationMode(value) {
3215
+ return value === 'page' || value === 'cursor';
3216
+ }
3217
+ function frozenPosition(position) {
3218
+ return Object.freeze({ ...position });
3219
+ }
3220
+ function exactKeys(record, allowed) {
3221
+ return Object.keys(record).every((key) => allowed.includes(key));
3222
+ }
3223
+ function asFrozenItems(items) {
3224
+ return Object.freeze(Array.from(items));
3225
+ }
3226
+ function immutableActions(actions) {
3227
+ return Object.freeze(actions.slice());
3228
+ }
3229
+ function configInput(config = {}) {
3230
+ const root = isRecord(config) ? config : {};
3231
+ const dataLoading = isRecord(root.dataLoading) ? root.dataLoading : {};
3232
+ const infiniteScroll = isRecord(root.infiniteScroll) ? root.infiniteScroll : {};
3233
+ return {
3234
+ protocol: dataLoading.protocol === undefined ? 'legacy' : dataLoading.protocol,
3235
+ searchMode: dataLoading.searchMode === undefined ? 'local' : dataLoading.searchMode,
3236
+ paginationMode: dataLoading.paginationMode === undefined ? 'page' : dataLoading.paginationMode,
3237
+ firstPage: dataLoading.firstPage === undefined ? 1 : dataLoading.firstPage,
3238
+ initialPage: infiniteScroll.initialPage === undefined ? 1 : infiniteScroll.initialPage,
3239
+ fetchLimit: dataLoading.fetchLimit,
3240
+ maxCursorPages: dataLoading.maxCursorPages === undefined
3241
+ ? DEFAULT_MAX_CURSOR_PAGES
3242
+ : dataLoading.maxCursorPages,
3243
+ maxCursorTokenBytes: dataLoading.maxCursorTokenBytes === undefined
3244
+ ? DEFAULT_MAX_CURSOR_TOKEN_BYTES
3245
+ : dataLoading.maxCursorTokenBytes,
3246
+ pageSize: infiniteScroll.pageSize,
3247
+ };
3248
+ }
3249
+ function validateDataCoordinatorConfig(config = {}) {
3250
+ const input = configInput(config);
3251
+ const errors = [];
3252
+ const add = (field, message) => errors.push(Object.freeze({ field, message }));
3253
+ const rawConfig = config;
3254
+ if (!isRecord(rawConfig))
3255
+ add('config', 'must be a plain object');
3256
+ else {
3257
+ if (rawConfig.dataLoading !== undefined && !isRecord(rawConfig.dataLoading)) {
3258
+ add('dataLoading', 'must be a plain object when supplied');
3259
+ }
3260
+ if (rawConfig.infiniteScroll !== undefined && !isRecord(rawConfig.infiniteScroll)) {
3261
+ add('infiniteScroll', 'must be a plain object when supplied');
3262
+ }
3263
+ }
3264
+ if (input.protocol !== 'legacy' && input.protocol !== 'acknowledged') {
3265
+ add('dataLoading.protocol', 'must be legacy or acknowledged');
3266
+ }
3267
+ if (!isQueryMode(input.searchMode)) {
3268
+ add('dataLoading.searchMode', 'must be local, remote, or hybrid');
3269
+ }
3270
+ if (!isPaginationMode(input.paginationMode)) {
3271
+ add('dataLoading.paginationMode', 'must be page or cursor');
3272
+ }
3273
+ if (!isPositiveSafeInteger(input.firstPage)) {
3274
+ add('dataLoading.firstPage', 'must be a positive safe integer');
3275
+ }
3276
+ if (!isPositiveSafeInteger(input.initialPage)) {
3277
+ add('infiniteScroll.initialPage', 'must be a positive safe integer');
3278
+ }
3279
+ if (input.protocol === 'acknowledged' &&
3280
+ input.searchMode === 'local' &&
3281
+ input.paginationMode === 'page' &&
3282
+ input.initialPage === Number.MAX_SAFE_INTEGER) {
3283
+ add('infiniteScroll.initialPage', 'must leave room for the next acknowledged page number');
3284
+ }
3285
+ if (input.fetchLimit !== undefined && !isPositiveSafeInteger(input.fetchLimit)) {
3286
+ add('dataLoading.fetchLimit', 'must be a positive safe integer when supplied');
3287
+ }
3288
+ if (!isPositiveSafeInteger(input.maxCursorPages) || input.maxCursorPages > HARD_MAX_CURSOR_PAGES) {
3289
+ add('dataLoading.maxCursorPages', `must be a positive safe integer no greater than ${HARD_MAX_CURSOR_PAGES}`);
3290
+ }
3291
+ if (!isPositiveSafeInteger(input.maxCursorTokenBytes) || input.maxCursorTokenBytes > HARD_MAX_CURSOR_TOKEN_BYTES) {
3292
+ add('dataLoading.maxCursorTokenBytes', `must be a positive safe integer no greater than ${HARD_MAX_CURSOR_TOKEN_BYTES}`);
3293
+ }
3294
+ if (input.pageSize !== undefined && !isPositiveSafeInteger(input.pageSize)) {
3295
+ add('infiniteScroll.pageSize', 'must be a positive safe integer when supplied');
3296
+ }
3297
+ if (input.protocol === 'legacy' &&
3298
+ (input.searchMode === 'remote' || input.searchMode === 'hybrid' || input.paginationMode === 'cursor')) {
3299
+ add('dataLoading.protocol', 'remote/hybrid search and cursor pagination require acknowledged protocol');
3300
+ }
3301
+ const resolvedFetchLimit = typeof input.fetchLimit === 'number' ? input.fetchLimit : typeof input.pageSize === 'number' ? input.pageSize : undefined;
3302
+ if (input.protocol === 'acknowledged' && resolvedFetchLimit === undefined) {
3303
+ add('dataLoading.fetchLimit', 'acknowledged requests require fetchLimit or an effective infiniteScroll.pageSize');
3304
+ }
3305
+ if (errors.length > 0) {
3306
+ return Object.freeze({ valid: false, errors: Object.freeze(errors) });
3307
+ }
3308
+ return Object.freeze({
3309
+ valid: true,
3310
+ value: Object.freeze({
3311
+ protocol: input.protocol,
3312
+ searchMode: input.searchMode,
3313
+ paginationMode: input.paginationMode,
3314
+ firstPage: input.firstPage,
3315
+ initialPage: input.initialPage,
3316
+ fetchLimit: resolvedFetchLimit,
3317
+ maxCursorPages: input.maxCursorPages,
3318
+ maxCursorTokenBytes: input.maxCursorTokenBytes,
3319
+ }),
3320
+ });
3321
+ }
3322
+ function copyCoordinatorConfig(config = {}) {
3323
+ return {
3324
+ dataLoading: config.dataLoading ? { ...config.dataLoading } : {},
3325
+ infiniteScroll: config.infiniteScroll ? { ...config.infiniteScroll } : {},
3326
+ };
3327
+ }
3328
+ function mergeCoordinatorConfig(current, update) {
3329
+ return {
3330
+ dataLoading: { ...(current.dataLoading ?? {}), ...(update.dataLoading ?? {}) },
3331
+ infiniteScroll: { ...(current.infiniteScroll ?? {}), ...(update.infiniteScroll ?? {}) },
3332
+ };
3333
+ }
3334
+ /**
3335
+ * Owns request identity and pagination state only. It has no DOM, framework,
3336
+ * observer, timer, or network dependencies. Returned actions are instructions
3337
+ * for a future facade/host boundary; cancellation never performs transport.
3338
+ */
3339
+ class DataRequestCoordinator {
3340
+ constructor(options = {}) {
3341
+ this.instanceId = ++coordinatorInstanceSequence;
3342
+ this.requestIdSecret = Math.random().toString(36).slice(2) || '0';
3343
+ this.requestSequence = 0;
3344
+ this.connected = false;
3345
+ this.hasConnected = false;
3346
+ this.queryGeneration = 0;
3347
+ this.active = null;
3348
+ this.status = 'idle';
3349
+ /**
3350
+ * Exact cycle detection for the current pagination epoch. One cursor is
3351
+ * retained per accepted advancement; there is intentionally no LRU eviction.
3352
+ */
3353
+ this.committedCursors = new Set();
3354
+ this.generationHasAcceptedResult = false;
3355
+ this.retryAvailable = false;
3356
+ this.error = null;
3357
+ this.resourceLimit = null;
3358
+ this.sentinelBlocked = false;
3359
+ this.sentinelIntersecting = false;
3360
+ const initialConfig = options.config === undefined ? {} : options.config;
3361
+ const validation = validateDataCoordinatorConfig(initialConfig);
3362
+ if (!validation.valid) {
3363
+ throw new TypeError(validation.errors.map(({ field, message }) => `${field}: ${message}`).join('; '));
3364
+ }
3365
+ this.rawConfig = copyCoordinatorConfig(initialConfig);
3366
+ this.config = validation.value;
3367
+ this.query = options.initialQuery ?? '';
3368
+ this.items = asFrozenItems(options.initialItems ?? []);
3369
+ const remote = this.isRemoteMode();
3370
+ this.hasMore = remote ? false : options.hasMore ?? false;
3371
+ this.nextEligiblePosition = this.initialPosition();
3372
+ this.lastCommittedPage = this.config.paginationMode === 'page' && !remote
3373
+ ? this.config.initialPage
3374
+ : undefined;
3375
+ this.needsInitialRemoteSearch = remote;
3376
+ }
3377
+ getSnapshot() {
3378
+ const activeRequest = this.active?.request ?? null;
3379
+ const nextPosition = frozenPosition(this.nextEligiblePosition);
3380
+ return Object.freeze({
3381
+ status: this.status,
3382
+ connected: this.connected,
3383
+ busy: this.active !== null,
3384
+ query: this.query,
3385
+ normalizedQuery: this.query.trim(),
3386
+ queryGeneration: this.queryGeneration,
3387
+ items: asFrozenItems(this.items),
3388
+ hasMore: this.hasMore,
3389
+ activeRequest,
3390
+ lastCommittedPage: this.lastCommittedPage,
3391
+ nextEligiblePosition: nextPosition,
3392
+ error: this.error ? Object.freeze({ ...this.error }) : null,
3393
+ resourceLimit: this.resourceLimit,
3394
+ sentinelBlocked: this.sentinelBlocked,
3395
+ sentinelIntersecting: this.sentinelIntersecting,
3396
+ });
3397
+ }
3398
+ /** Connect once, dispatching the initial remote/hybrid query when required. */
3399
+ connect(query = this.query) {
3400
+ if (this.connected)
3401
+ return immutableActions([]);
3402
+ const actions = [];
3403
+ if (query !== this.query)
3404
+ actions.push(...this.setQuery(query));
3405
+ if (this.hasConnected)
3406
+ this.queryGeneration += 1;
3407
+ this.connected = true;
3408
+ this.hasConnected = true;
3409
+ if (this.isRemoteMode() && this.needsInitialRemoteSearch) {
3410
+ this.resetPaginationForRemoteQuery(true);
3411
+ const request = this.createSearchRequest();
3412
+ if (request)
3413
+ actions.push(Object.freeze({ type: 'request', request }));
3414
+ }
3415
+ return immutableActions(actions);
3416
+ }
3417
+ /**
3418
+ * Advance the request transition from synchronous `requested` to `loading`
3419
+ * immediately before a future facade dispatches event/callback notifications.
3420
+ */
3421
+ markNotificationsDispatched(requestId) {
3422
+ if (!this.active || this.active.request.requestId !== requestId || this.active.phase !== 'requested') {
3423
+ return false;
3424
+ }
3425
+ this.active.phase = 'loading';
3426
+ this.status = 'loading';
3427
+ return true;
3428
+ }
3429
+ setQuery(query) {
3430
+ if (typeof query !== 'string' || query === this.query)
3431
+ return immutableActions([]);
3432
+ const actions = [];
3433
+ const cancellation = this.invalidateActive('query-changed');
3434
+ if (cancellation)
3435
+ actions.push(cancellation);
3436
+ this.query = query;
3437
+ this.queryGeneration += 1;
3438
+ this.error = null;
3439
+ this.status = 'idle';
3440
+ this.generationHasAcceptedResult = false;
3441
+ this.retryAvailable = false;
3442
+ this.retryPosition = undefined;
3443
+ this.retryKind = undefined;
3444
+ this.committedCursors.clear();
3445
+ this.resourceLimit = null;
3446
+ this.sentinelBlocked = false;
3447
+ if (this.isRemoteMode()) {
3448
+ this.resetPaginationForRemoteQuery(true);
3449
+ this.needsInitialRemoteSearch = true;
3450
+ if (this.connected) {
3451
+ const request = this.createSearchRequest();
3452
+ if (request)
3453
+ actions.push(Object.freeze({ type: 'request', request }));
3454
+ }
3455
+ }
3456
+ else {
3457
+ this.lastCommittedPage = this.config.paginationMode === 'page' ? this.config.initialPage : undefined;
3458
+ this.nextEligiblePosition = this.initialPosition();
3459
+ this.needsInitialRemoteSearch = false;
3460
+ }
3461
+ return immutableActions(actions);
3462
+ }
3463
+ /** Update effective config; non-protocol changes do not rewrite active requests. */
3464
+ updateConfig(update) {
3465
+ const rawUpdate = update;
3466
+ if (!isRecord(rawUpdate) ||
3467
+ (rawUpdate.dataLoading !== undefined && !isRecord(rawUpdate.dataLoading)) ||
3468
+ (rawUpdate.infiniteScroll !== undefined && !isRecord(rawUpdate.infiniteScroll))) {
3469
+ return Object.freeze({
3470
+ status: 'invalid',
3471
+ errors: Object.freeze([
3472
+ Object.freeze({ field: 'config', message: 'update and nested config groups must be plain objects' }),
3473
+ ]),
3474
+ });
3475
+ }
3476
+ const candidate = mergeCoordinatorConfig(this.rawConfig, update);
3477
+ const validation = validateDataCoordinatorConfig(candidate);
3478
+ if (!validation.valid)
3479
+ return Object.freeze({ status: 'invalid', errors: validation.errors });
3480
+ const previous = this.config;
3481
+ const next = validation.value;
3482
+ const protocolChanged = previous.protocol !== next.protocol ||
3483
+ previous.searchMode !== next.searchMode ||
3484
+ previous.paginationMode !== next.paginationMode;
3485
+ this.rawConfig = copyCoordinatorConfig(candidate);
3486
+ this.config = next;
3487
+ if (!protocolChanged) {
3488
+ this.refreshCursorDepthLimit();
3489
+ return Object.freeze({ status: 'accepted', actions: immutableActions([]) });
3490
+ }
3491
+ const actions = [];
3492
+ const cancellation = this.invalidateActive('config-changed');
3493
+ if (cancellation)
3494
+ actions.push(cancellation);
3495
+ this.queryGeneration += 1;
3496
+ this.error = null;
3497
+ this.status = 'idle';
3498
+ this.generationHasAcceptedResult = false;
3499
+ this.retryAvailable = false;
3500
+ this.retryPosition = undefined;
3501
+ this.retryKind = undefined;
3502
+ this.committedCursors.clear();
3503
+ this.resourceLimit = null;
3504
+ this.sentinelBlocked = false;
3505
+ this.hasMore = this.isRemoteMode() ? false : this.hasMore;
3506
+ this.lastCommittedPage = this.config.paginationMode === 'page' && !this.isRemoteMode()
3507
+ ? this.config.initialPage
3508
+ : undefined;
3509
+ this.nextEligiblePosition = this.initialPosition();
3510
+ this.needsInitialRemoteSearch = this.isRemoteMode();
3511
+ if (this.connected && this.isRemoteMode()) {
3512
+ const request = this.createSearchRequest();
3513
+ if (request)
3514
+ actions.push(Object.freeze({ type: 'request', request }));
3515
+ }
3516
+ return Object.freeze({ status: 'accepted', actions: immutableActions(actions) });
3517
+ }
3518
+ /** Request another page or explicitly retry the still-eligible position. */
3519
+ requestLoadMore(trigger = 'manual') {
3520
+ if (this.config.protocol !== 'acknowledged' || !this.connected || this.active) {
3521
+ return immutableActions([]);
3522
+ }
3523
+ if (trigger === 'sentinel' && this.sentinelBlocked)
3524
+ return immutableActions([]);
3525
+ if (!this.hasMore && !this.retryAvailable)
3526
+ return immutableActions([]);
3527
+ const position = this.retryAvailable && this.retryPosition
3528
+ ? this.retryPosition
3529
+ : this.nextEligiblePosition;
3530
+ if (this.config.paginationMode === 'cursor' &&
3531
+ position.mode === 'cursor' &&
3532
+ position.ordinal > this.config.maxCursorPages) {
3533
+ this.resourceLimit = Object.freeze({
3534
+ reason: 'cursor-depth',
3535
+ maxCursorPages: this.config.maxCursorPages,
3536
+ });
3537
+ this.status = 'resource-limited';
3538
+ this.sentinelBlocked = true;
3539
+ return immutableActions([]);
3540
+ }
3541
+ if (trigger === 'manual')
3542
+ this.sentinelBlocked = false;
3543
+ const retryKind = this.retryAvailable ? this.retryKind : undefined;
3544
+ this.retryAvailable = false;
3545
+ this.retryPosition = undefined;
3546
+ this.retryKind = undefined;
3547
+ const request = retryKind === 'search' && this.isRemoteMode()
3548
+ ? this.createSearchRequest(position)
3549
+ : this.createLoadMoreRequest(position);
3550
+ return request ? immutableActions([Object.freeze({ type: 'request', request })]) : immutableActions([]);
3551
+ }
3552
+ /** Feed observer state into the pure sentinel rearm state machine. */
3553
+ setSentinelIntersecting(intersecting) {
3554
+ if (!intersecting) {
3555
+ this.sentinelIntersecting = false;
3556
+ this.sentinelBlocked = false;
3557
+ return immutableActions([]);
3558
+ }
3559
+ if (this.sentinelIntersecting)
3560
+ return immutableActions([]);
3561
+ this.sentinelIntersecting = true;
3562
+ return this.requestLoadMore('sentinel');
3563
+ }
3564
+ /** Invalidate pending work before returning its best-effort host cancellation action. */
3565
+ disconnect() {
3566
+ if (!this.connected)
3567
+ return immutableActions([]);
3568
+ const activeRequest = this.active?.request;
3569
+ const actions = [];
3570
+ if (activeRequest) {
3571
+ if (activeRequest.kind === 'search' && !this.generationHasAcceptedResult) {
3572
+ this.needsInitialRemoteSearch = true;
3573
+ }
3574
+ const cancellation = this.invalidateActive('disconnected');
3575
+ if (cancellation)
3576
+ actions.push(cancellation);
3577
+ this.resourceLimit = null;
3578
+ this.status = 'cancelled';
3579
+ this.sentinelBlocked = true;
3580
+ // Encode invalidation in the generation, so late completions are stale
3581
+ // without retaining one request ID per cancellation.
3582
+ this.queryGeneration += 1;
3583
+ }
3584
+ this.sentinelIntersecting = false;
3585
+ this.connected = false;
3586
+ return immutableActions(actions);
3587
+ }
3588
+ completeDataRequest(completion) {
3589
+ if (!isRecord(completion) || !this.hasValidCompletionEnvelope(completion))
3590
+ return 'invalid';
3591
+ const requestId = completion.requestId;
3592
+ const generation = completion.queryGeneration;
3593
+ if (this.active?.request.requestId !== requestId) {
3594
+ return this.classifyInactiveRequest(requestId, generation);
3595
+ }
3596
+ if (generation !== this.active.request.queryGeneration || this.active.phase !== 'loading')
3597
+ return 'invalid';
3598
+ const validation = this.validateCompletionPayload(completion, this.active.request);
3599
+ if (!validation.valid) {
3600
+ if (validation.resourceLimit === 'cursor-token-size') {
3601
+ const cursor = completion.nextCursor;
3602
+ const actualCursorTokenBytes = cursorTokenByteLength(cursor);
3603
+ this.resourceLimit = Object.freeze({
3604
+ reason: 'cursor-token-size',
3605
+ maxCursorTokenBytes: this.config.maxCursorTokenBytes,
3606
+ actualCursorTokenBytes,
3607
+ requestId,
3608
+ });
3609
+ return 'resource-limit';
3610
+ }
3611
+ return 'invalid';
3612
+ }
3613
+ const request = this.active.request;
3614
+ const status = completion.status;
3615
+ const nextData = status === 'succeeded' || status === 'exhausted'
3616
+ ? asFrozenItems(completion.items)
3617
+ : this.items;
3618
+ let nextPosition = this.nextEligiblePosition;
3619
+ let nextLastCommittedPage = this.lastCommittedPage;
3620
+ let nextHasMore = this.hasMore;
3621
+ let nextRetryAvailable = false;
3622
+ let nextRetryPosition;
3623
+ let nextRetryKind;
3624
+ let nextError = null;
3625
+ let nextSentinelBlocked = false;
3626
+ let cursorToCommit;
3627
+ let nextResourceLimit = null;
3628
+ if (status === 'succeeded') {
3629
+ const advances = this.advanceFrom(request, completion);
3630
+ nextPosition = advances.position;
3631
+ nextLastCommittedPage = advances.lastCommittedPage;
3632
+ cursorToCommit = advances.cursorToCommit;
3633
+ nextHasMore = true;
3634
+ }
3635
+ else if (status === 'exhausted') {
3636
+ nextLastCommittedPage = request.position.mode === 'page'
3637
+ ? request.position.page
3638
+ : this.lastCommittedPage;
3639
+ nextHasMore = false;
3640
+ }
3641
+ else if (status === 'empty') {
3642
+ nextHasMore = true;
3643
+ nextSentinelBlocked = true;
3644
+ if (completion.advance === 'next') {
3645
+ const advances = this.advanceFrom(request, completion);
3646
+ nextPosition = advances.position;
3647
+ nextLastCommittedPage = advances.lastCommittedPage;
3648
+ cursorToCommit = advances.cursorToCommit;
3649
+ }
3650
+ else {
3651
+ nextRetryAvailable = true;
3652
+ nextRetryPosition = request.position;
3653
+ nextRetryKind = request.kind;
3654
+ }
3655
+ }
3656
+ else if (status === 'failed') {
3657
+ nextRetryAvailable = true;
3658
+ nextRetryPosition = request.position;
3659
+ nextRetryKind = request.kind;
3660
+ nextError = Object.freeze({ ...completion.error });
3661
+ nextSentinelBlocked = true;
3662
+ }
3663
+ else if (status === 'cancelled') {
3664
+ nextRetryAvailable = true;
3665
+ nextRetryPosition = request.position;
3666
+ nextRetryKind = request.kind;
3667
+ nextSentinelBlocked = true;
3668
+ }
3669
+ if (this.config.paginationMode === 'cursor' &&
3670
+ nextHasMore &&
3671
+ nextPosition.mode === 'cursor' &&
3672
+ nextPosition.ordinal > this.config.maxCursorPages) {
3673
+ nextResourceLimit = Object.freeze({
3674
+ reason: 'cursor-depth',
3675
+ maxCursorPages: this.config.maxCursorPages,
3676
+ requestId,
3677
+ });
3678
+ nextSentinelBlocked = true;
3679
+ }
3680
+ // Commit only after identity, generation, status, and every field validate.
3681
+ this.items = nextData;
3682
+ this.nextEligiblePosition = nextPosition;
3683
+ this.lastCommittedPage = nextLastCommittedPage;
3684
+ this.hasMore = nextHasMore;
3685
+ this.retryAvailable = nextRetryAvailable;
3686
+ this.retryPosition = nextRetryPosition;
3687
+ this.retryKind = nextRetryKind;
3688
+ this.error = nextError;
3689
+ this.resourceLimit = nextResourceLimit;
3690
+ this.sentinelBlocked = nextSentinelBlocked;
3691
+ if (cursorToCommit !== undefined)
3692
+ this.committedCursors.add(cursorToCommit);
3693
+ if (status === 'succeeded' || status === 'exhausted')
3694
+ this.generationHasAcceptedResult = true;
3695
+ this.active = null;
3696
+ this.status = nextResourceLimit ? 'resource-limited' : status;
3697
+ return 'accepted';
3698
+ }
3699
+ isRemoteMode() {
3700
+ return this.config.searchMode === 'remote' || this.config.searchMode === 'hybrid';
3701
+ }
3702
+ initialPosition() {
3703
+ if (this.config.paginationMode === 'cursor') {
3704
+ return Object.freeze({ mode: 'cursor', ordinal: 1 });
3705
+ }
3706
+ const page = this.isRemoteMode() ? this.config.firstPage : this.config.initialPage + 1;
3707
+ return Object.freeze({ mode: 'page', page });
3708
+ }
3709
+ resetPaginationForRemoteQuery(clearItems) {
3710
+ this.hasMore = false;
3711
+ this.lastCommittedPage = undefined;
3712
+ this.nextEligiblePosition = this.initialPosition();
3713
+ this.committedCursors.clear();
3714
+ this.retryAvailable = false;
3715
+ this.retryPosition = undefined;
3716
+ this.retryKind = undefined;
3717
+ this.resourceLimit = null;
3718
+ this.sentinelBlocked = false;
3719
+ this.error = null;
3720
+ if (clearItems)
3721
+ this.items = asFrozenItems([]);
3722
+ }
3723
+ /** Re-evaluate the local cursor cap without resetting accepted history. */
3724
+ refreshCursorDepthLimit() {
3725
+ if (this.config.protocol !== 'acknowledged' || this.config.paginationMode !== 'cursor')
3726
+ return;
3727
+ const position = this.retryAvailable && this.retryPosition
3728
+ ? this.retryPosition
3729
+ : this.nextEligiblePosition;
3730
+ const overLimit = (this.hasMore || this.retryAvailable) &&
3731
+ position.mode === 'cursor' && position.ordinal > this.config.maxCursorPages;
3732
+ if (overLimit) {
3733
+ this.resourceLimit = Object.freeze({
3734
+ reason: 'cursor-depth',
3735
+ maxCursorPages: this.config.maxCursorPages,
3736
+ });
3737
+ if (!this.active)
3738
+ this.status = 'resource-limited';
3739
+ this.sentinelBlocked = true;
3740
+ return;
3741
+ }
3742
+ if (this.resourceLimit?.reason === 'cursor-depth') {
3743
+ this.resourceLimit = null;
3744
+ if (!this.active && this.status === 'resource-limited')
3745
+ this.status = 'idle';
3746
+ }
3747
+ }
3748
+ createSearchRequest(position = this.nextEligiblePosition) {
3749
+ if (!this.connected || !this.isRemoteMode() || this.config.protocol !== 'acknowledged')
3750
+ return null;
3751
+ const request = this.createRequest({ kind: 'search', mode: this.config.searchMode }, position);
3752
+ if (request) {
3753
+ this.needsInitialRemoteSearch = false;
3754
+ this.status = 'requested';
3755
+ }
3756
+ return request;
3757
+ }
3758
+ createLoadMoreRequest(position) {
3759
+ if (!this.connected || this.config.protocol !== 'acknowledged')
3760
+ return null;
3761
+ const request = this.createRequest({ kind: 'loadMore' }, position);
3762
+ if (request)
3763
+ this.status = 'requested';
3764
+ return request;
3765
+ }
3766
+ createRequest(kind, position) {
3767
+ const fetchLimit = this.config.fetchLimit;
3768
+ if (fetchLimit === undefined || this.active)
3769
+ return null;
3770
+ this.requestSequence += 1;
3771
+ const check = requestIdCheck(this.requestIdSecret, this.instanceId, this.queryGeneration, this.requestSequence);
3772
+ const requestId = `data-${this.instanceId}-generation-${this.queryGeneration}-request-${this.requestSequence}-${check}`;
3773
+ const base = Object.freeze({
3774
+ requestId,
3775
+ queryGeneration: this.queryGeneration,
3776
+ query: this.query,
3777
+ normalizedQuery: this.query.trim(),
3778
+ fetchLimit,
3779
+ position: frozenPosition(position),
3780
+ });
3781
+ const request = kind.kind === 'search'
3782
+ ? Object.freeze({ ...base, kind: 'search', mode: kind.mode })
3783
+ : Object.freeze({ ...base, kind: 'loadMore' });
3784
+ this.active = { request, phase: 'requested' };
3785
+ this.status = 'requested';
3786
+ this.error = null;
3787
+ return request;
3788
+ }
3789
+ invalidateActive(reason) {
3790
+ if (!this.active)
3791
+ return null;
3792
+ const { request } = this.active;
3793
+ this.active = null;
3794
+ this.status = 'cancelled';
3795
+ const notification = Object.freeze({
3796
+ requestId: request.requestId,
3797
+ queryGeneration: request.queryGeneration,
3798
+ reason,
3799
+ });
3800
+ return Object.freeze({ type: 'cancel', notification });
3801
+ }
3802
+ classifyInactiveRequest(requestId, completionGeneration) {
3803
+ const parsed = parseRequestId(requestId);
3804
+ if (!parsed ||
3805
+ parsed.instanceId !== this.instanceId ||
3806
+ parsed.check !== requestIdCheck(this.requestIdSecret, parsed.instanceId, parsed.queryGeneration, parsed.sequence) ||
3807
+ parsed.sequence > this.requestSequence)
3808
+ return 'unknown-request';
3809
+ if (parsed.queryGeneration !== completionGeneration)
3810
+ return 'invalid';
3811
+ return parsed.queryGeneration < this.queryGeneration ? 'stale' : 'unknown-request';
3812
+ }
3813
+ hasValidCompletionEnvelope(completion) {
3814
+ return (typeof completion.requestId === 'string' &&
3815
+ completion.requestId.length > 0 &&
3816
+ isNonNegativeSafeInteger(completion.queryGeneration) &&
3817
+ typeof completion.status === 'string' &&
3818
+ ['succeeded', 'empty', 'exhausted', 'failed', 'cancelled'].includes(completion.status));
3819
+ }
3820
+ validateCompletionPayload(completion, request) {
3821
+ const common = ['requestId', 'queryGeneration', 'status'];
3822
+ switch (completion.status) {
3823
+ case 'succeeded': {
3824
+ const allowed = [...common, 'items', 'hasMore'];
3825
+ if (request.position.mode === 'cursor')
3826
+ allowed.push('nextCursor');
3827
+ if (!exactKeys(completion, allowed) || !Array.isArray(completion.items) || completion.hasMore !== true) {
3828
+ return { valid: false };
3829
+ }
3830
+ if (request.position.mode === 'cursor') {
3831
+ if (request.position.ordinal >= Number.MAX_SAFE_INTEGER || !isCursor(completion.nextCursor)) {
3832
+ return { valid: false };
3833
+ }
3834
+ if (cursorTokenByteLength(completion.nextCursor) > this.config.maxCursorTokenBytes) {
3835
+ return { valid: false, resourceLimit: 'cursor-token-size' };
3836
+ }
3837
+ if (this.hasCommittedCursor(completion.nextCursor))
3838
+ return { valid: false };
3839
+ }
3840
+ else if ('nextCursor' in completion) {
3841
+ return { valid: false };
3842
+ }
3843
+ else if (request.position.page >= Number.MAX_SAFE_INTEGER) {
3844
+ return { valid: false };
3845
+ }
3846
+ return { valid: true };
3847
+ }
3848
+ case 'empty': {
3849
+ const allowed = [...common, 'hasMore', 'advance'];
3850
+ if (request.position.mode === 'cursor' && completion.advance === 'next')
3851
+ allowed.push('nextCursor');
3852
+ if (!exactKeys(completion, allowed) || completion.hasMore !== true)
3853
+ return { valid: false };
3854
+ if (completion.advance !== 'next' && completion.advance !== 'retry')
3855
+ return { valid: false };
3856
+ if (request.position.mode === 'cursor') {
3857
+ if (completion.advance === 'next') {
3858
+ if (request.position.ordinal >= Number.MAX_SAFE_INTEGER || !isCursor(completion.nextCursor)) {
3859
+ return { valid: false };
3860
+ }
3861
+ if (cursorTokenByteLength(completion.nextCursor) > this.config.maxCursorTokenBytes) {
3862
+ return { valid: false, resourceLimit: 'cursor-token-size' };
3863
+ }
3864
+ if (this.hasCommittedCursor(completion.nextCursor))
3865
+ return { valid: false };
3866
+ }
3867
+ else if ('nextCursor' in completion) {
3868
+ return { valid: false };
3869
+ }
3870
+ }
3871
+ else if ('nextCursor' in completion) {
3872
+ return { valid: false };
3873
+ }
3874
+ else if (completion.advance === 'next' && request.position.page >= Number.MAX_SAFE_INTEGER) {
3875
+ return { valid: false };
3876
+ }
3877
+ return { valid: true };
3878
+ }
3879
+ case 'exhausted': {
3880
+ if (!exactKeys(completion, [...common, 'items', 'hasMore']) ||
3881
+ !Array.isArray(completion.items) ||
3882
+ completion.hasMore !== false) {
3883
+ return { valid: false };
3884
+ }
3885
+ return { valid: true };
3886
+ }
3887
+ case 'failed': {
3888
+ if (!exactKeys(completion, [...common, 'error']) || !isRecord(completion.error))
3889
+ return { valid: false };
3890
+ const error = completion.error;
3891
+ if (!exactKeys(error, ['message', 'code', 'retryable']) ||
3892
+ typeof error.message !== 'string' ||
3893
+ error.message.trim().length === 0 ||
3894
+ (error.code !== undefined && typeof error.code !== 'string') ||
3895
+ (error.retryable !== undefined && typeof error.retryable !== 'boolean')) {
3896
+ return { valid: false };
3897
+ }
3898
+ return { valid: true };
3899
+ }
3900
+ case 'cancelled': {
3901
+ const hasReason = 'reason' in completion;
3902
+ return (exactKeys(completion, hasReason ? [...common, 'reason'] : common) &&
3903
+ (!hasReason || completion.reason === undefined || completion.reason === 'host-cancelled'))
3904
+ ? { valid: true }
3905
+ : { valid: false };
3906
+ }
3907
+ default:
3908
+ return { valid: false };
3909
+ }
3910
+ }
3911
+ hasCommittedCursor(cursor) {
3912
+ return this.committedCursors.has(cursor) || (this.nextEligiblePosition.mode === 'cursor' && this.nextEligiblePosition.cursor === cursor);
3913
+ }
3914
+ advanceFrom(request, completion) {
3915
+ if (request.position.mode === 'page') {
3916
+ const page = request.position.page;
3917
+ return {
3918
+ position: Object.freeze({ mode: 'page', page: page + 1 }),
3919
+ lastCommittedPage: page,
3920
+ };
3921
+ }
3922
+ const nextCursor = completion.nextCursor;
3923
+ return {
3924
+ position: Object.freeze({
3925
+ mode: 'cursor',
3926
+ cursor: nextCursor,
3927
+ ordinal: request.position.ordinal + 1,
3928
+ }),
3929
+ lastCommittedPage: this.lastCommittedPage,
3930
+ cursorToCommit: nextCursor,
3931
+ };
3932
+ }
3933
+ }
3934
+
3053
3935
  /**
3054
3936
  * Enhanced Select Component
3055
3937
  * Implements all advanced features: infinite scroll, load more, busy state,
@@ -3057,9 +3939,72 @@ function arraysEqualByValue(a, b) {
3057
3939
  *
3058
3940
  * Redesigned with formal elegance, refined microinteractions, and polished UX
3059
3941
  */
3942
+ const LEGACY_DATA_LOADING_CONFIG = {
3943
+ protocol: 'legacy',
3944
+ searchMode: 'local',
3945
+ paginationMode: 'page',
3946
+ firstPage: 1,
3947
+ };
3948
+ const DATA_LOADING_CONFIG_FIELDS = ['protocol', 'searchMode', 'paginationMode', 'firstPage', 'fetchLimit'];
3949
+ const INVALID_OBJECT_VALUE = Object.freeze({ kind: 'object' });
3950
+ const INVALID_ARRAY_VALUE = Object.freeze({ kind: 'array' });
3951
+ const INVALID_FUNCTION_VALUE = Object.freeze({ kind: 'function' });
3952
+ function invalidConfigValueSignature(value) {
3953
+ if (value === null || (typeof value !== 'object' && typeof value !== 'function'))
3954
+ return value;
3955
+ if (typeof value === 'function')
3956
+ return INVALID_FUNCTION_VALUE;
3957
+ return Array.isArray(value) ? INVALID_ARRAY_VALUE : INVALID_OBJECT_VALUE;
3958
+ }
3959
+ function createInvalidDataLoadingCandidateSignature(candidate, issues) {
3960
+ const candidatePrototype = candidate !== null && typeof candidate === 'object'
3961
+ ? Object.getPrototypeOf(candidate)
3962
+ : undefined;
3963
+ const isRecord = candidate !== null
3964
+ && typeof candidate === 'object'
3965
+ && !Array.isArray(candidate)
3966
+ && (candidatePrototype === Object.prototype || candidatePrototype === null);
3967
+ const recordCandidate = isRecord ? candidate : undefined;
3968
+ const rootKind = isRecord
3969
+ ? 'record'
3970
+ : candidate === null
3971
+ ? 'null'
3972
+ : Array.isArray(candidate)
3973
+ ? 'array'
3974
+ : typeof candidate;
3975
+ return {
3976
+ rootKind,
3977
+ rootValue: candidate === null || typeof candidate !== 'object' ? candidate : undefined,
3978
+ // Compare at most five supported field values. Unknown fields are represented by their
3979
+ // validation issues below; their values are invalid regardless of shape. Signature work is
3980
+ // therefore independent of nested-value depth (and linear only in the already-built issue list).
3981
+ fieldValues: recordCandidate
3982
+ ? DATA_LOADING_CONFIG_FIELDS.map((field) => invalidConfigValueSignature(recordCandidate[field]))
3983
+ : [],
3984
+ issues: issues.map(({ path, code, message }) => [path, code, message]),
3985
+ };
3986
+ }
3987
+ function invalidDataLoadingSignaturesEqual(left, right) {
3988
+ if (left.rootKind !== right.rootKind || !Object.is(left.rootValue, right.rootValue))
3989
+ return false;
3990
+ if (left.fieldValues.length !== right.fieldValues.length || left.issues.length !== right.issues.length)
3991
+ return false;
3992
+ for (let index = 0; index < left.fieldValues.length; index += 1) {
3993
+ if (!Object.is(left.fieldValues[index], right.fieldValues[index]))
3994
+ return false;
3995
+ }
3996
+ for (let index = 0; index < left.issues.length; index += 1) {
3997
+ const leftIssue = left.issues[index];
3998
+ const rightIssue = right.issues[index];
3999
+ if (leftIssue[0] !== rightIssue[0] || leftIssue[1] !== rightIssue[1] || leftIssue[2] !== rightIssue[2]) {
4000
+ return false;
4001
+ }
4002
+ }
4003
+ return true;
4004
+ }
3060
4005
  class EnhancedSelect extends HTMLElement {
3061
4006
  static get observedAttributes() {
3062
- return ['aria-label', 'aria-description'];
4007
+ return ['aria-label', 'aria-description', 'aria-busy'];
3063
4008
  }
3064
4009
  get classMap() {
3065
4010
  return this._classMap;
@@ -3098,6 +4043,8 @@ class EnhancedSelect extends HTMLElement {
3098
4043
  }
3099
4044
  constructor() {
3100
4045
  super();
4046
+ this._dataLoadingConfig = { ...LEGACY_DATA_LOADING_CONFIG };
4047
+ this._hasLastInvalidDataLoadingCandidate = false;
3101
4048
  this._engine = new SelectEngineBridge();
3102
4049
  this._virtualizationScope = {
3103
4050
  dataKeys: [],
@@ -3141,6 +4088,29 @@ class EnhancedSelect extends HTMLElement {
3141
4088
  this._selectedRecordsByKey = new Map();
3142
4089
  this._registryItemsRef = [];
3143
4090
  this._pageCache = {};
4091
+ // One coordinator owns both acknowledged and legacy-adjacent lifecycle state;
4092
+ // the public protocol remains explicitly opt-in and legacy remains default.
4093
+ this._dataRequestCoordinator = null;
4094
+ this._acknowledgedSearchMode = null;
4095
+ this._acknowledgedReady = false;
4096
+ this._acknowledgedDeferredStart = false;
4097
+ this._hasEverConnected = false;
4098
+ this._acknowledgedStartTask = null;
4099
+ this._clearAcknowledgedCoordinatorAfterProjection = false;
4100
+ this._acknowledgedConfigUpdatePending = false;
4101
+ this._acknowledgedDeferredModeChange = false;
4102
+ this._acknowledgedProjectionPending = false;
4103
+ this._acknowledgedProjectionSettling = false;
4104
+ this._acknowledgedPendingSearchQuery = null;
4105
+ this._acknowledgedProjectionFailureStageForTest = null;
4106
+ this._acknowledgedProjectionRunning = false;
4107
+ this._acknowledgedProjectionTask = null;
4108
+ this._acknowledgedProjectionScrollTop = 0;
4109
+ this._acknowledgedLastRequest = null;
4110
+ this._acknowledgedProjectionCommitsPosition = false;
4111
+ this._acknowledgedProjectionRequest = null;
4112
+ this._acknowledgedProjectionAttempt = 0;
4113
+ this._acknowledgedProjectionDiagnostic = null;
3144
4114
  this._typeBuffer = '';
3145
4115
  this._hasError = false;
3146
4116
  this._errorMessage = '';
@@ -3163,6 +4133,9 @@ class EnhancedSelect extends HTMLElement {
3163
4133
  this._tracking = { events: [], styles: [], limitations: [] };
3164
4134
  this._suppressBlurClose = false;
3165
4135
  this._renderCycleId = 0;
4136
+ this._completedRenderCycleId = 0;
4137
+ this._renderCycleWaiters = new Map();
4138
+ this._renderCycleWaiterTimeouts = new Map();
3166
4139
  this._suppressNextOpenClick = false;
3167
4140
  this._resolvedDropdownPlacement = 'bottom';
3168
4141
  this._multiScrollDrag = {
@@ -3260,6 +4233,7 @@ class EnhancedSelect extends HTMLElement {
3260
4233
  this._syncListboxAccessibility();
3261
4234
  }
3262
4235
  connectedCallback() {
4236
+ this._hasEverConnected = true;
3263
4237
  // register instance
3264
4238
  EnhancedSelect._instances.add(this);
3265
4239
  this._runEngineEffects(this._engine.dispatch({ type: 'CONNECT' }));
@@ -3276,6 +4250,11 @@ class EnhancedSelect extends HTMLElement {
3276
4250
  // Sync direction attribute (must be in connectedCallback, not constructor)
3277
4251
  this._syncDirectionConfig();
3278
4252
  this._syncComboboxAccessibility();
4253
+ if (this._dataRequestCoordinator || this._dataLoadingConfig.protocol === 'acknowledged') {
4254
+ // Acknowledged dispatch remains behind the explicit readiness
4255
+ // gate; reconnect only restores observer ownership here.
4256
+ this._initializeObservers();
4257
+ }
3279
4258
  if (this._optionRenderer || this._classMap || this._groupHeaderRenderer) {
3280
4259
  this._setGlobalStylesMirroring(true);
3281
4260
  }
@@ -3293,15 +4272,33 @@ class EnhancedSelect extends HTMLElement {
3293
4272
  if (this._config.callbacks.onOpen) {
3294
4273
  this._config.callbacks.onOpen();
3295
4274
  }
4275
+ if (this._acknowledgedDeferredStart) {
4276
+ this._acknowledgedDeferredStart = false;
4277
+ this.startDataLoading();
4278
+ }
3296
4279
  }
3297
4280
  attributeChangedCallback(name, oldValue, newValue) {
3298
- if (oldValue === newValue || (name !== 'aria-label' && name !== 'aria-description'))
4281
+ if (oldValue === newValue)
4282
+ return;
4283
+ if (name === 'aria-busy') {
4284
+ this._syncListboxAccessibility();
4285
+ return;
4286
+ }
4287
+ if (name !== 'aria-label' && name !== 'aria-description')
3299
4288
  return;
3300
4289
  this._syncComboboxAccessibility();
3301
4290
  if (name === 'aria-label')
3302
4291
  this._syncListboxAccessibility();
3303
4292
  }
3304
4293
  disconnectedCallback() {
4294
+ if (this._dataRequestCoordinator) {
4295
+ const actions = this._dataRequestCoordinator.disconnect();
4296
+ this._acknowledgedReady = false;
4297
+ this._dispatchAcknowledgedActions(actions);
4298
+ this._state.isBusy = false;
4299
+ this._state.isSearching = false;
4300
+ this._state.preserveScrollPosition = false;
4301
+ }
3305
4302
  // unregister instance
3306
4303
  EnhancedSelect._instances.delete(this);
3307
4304
  if (this._state.isOpen) {
@@ -3336,6 +4333,7 @@ class EnhancedSelect extends HTMLElement {
3336
4333
  this._arrowContainer.removeEventListener('click', this._boundArrowClick);
3337
4334
  }
3338
4335
  this._renderCycleId += 1;
4336
+ this._resolvePendingRenderCycles(false);
3339
4337
  this._teardownGlobalStylesMirroring();
3340
4338
  }
3341
4339
  _setGlobalStylesMirroring(enabled) {
@@ -3866,9 +4864,9 @@ class EnhancedSelect extends HTMLElement {
3866
4864
  this._assertActiveProjection('selection config');
3867
4865
  }
3868
4866
  }
3869
- _rebuildItemRegistry(items = this._state.loadedItems) {
4867
+ _rebuildItemRegistry(items = this._state.loadedItems, stagedRegistry) {
3870
4868
  // Build first so duplicate-key rejection leaves the previous runtime intact.
3871
- const registry = createItemRegistry(items, this._itemAdapter, {
4869
+ const registry = stagedRegistry ?? createItemRegistry(items, this._itemAdapter, {
3872
4870
  duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
3873
4871
  });
3874
4872
  const activeKey = this._engine.state.activeKey;
@@ -6163,17 +7161,47 @@ class EnhancedSelect extends HTMLElement {
6163
7161
  this._intersectionObserver.disconnect();
6164
7162
  this._intersectionObserver = undefined;
6165
7163
  }
7164
+ if (this._dataLoadingConfig.protocol === 'acknowledged'
7165
+ && (!this._dataRequestCoordinator || !this._acknowledgedReady))
7166
+ return;
6166
7167
  // Intersection observer for infinite scroll
6167
7168
  if (this._config.infiniteScroll.enabled) {
6168
- this._intersectionObserver = new IntersectionObserver((entries) => {
6169
- entries.forEach((entry) => {
6170
- if (entry.isIntersecting) {
6171
- if (!this._state.isBusy) {
7169
+ const acknowledged = Boolean(this._dataRequestCoordinator && this._dataLoadingConfig.protocol === 'acknowledged');
7170
+ if (acknowledged && typeof IntersectionObserver === 'undefined')
7171
+ return;
7172
+ let observer;
7173
+ try {
7174
+ observer = new IntersectionObserver((entries) => {
7175
+ if (this._intersectionObserver !== observer)
7176
+ return;
7177
+ entries.forEach((entry) => {
7178
+ if (acknowledged) {
7179
+ if (!this._acknowledgedReady || !this.isConnected || entry.target !== this._loadMoreTrigger)
7180
+ return;
7181
+ if (!entry.isIntersecting) {
7182
+ this._dataRequestCoordinator?.setSentinelIntersecting(false);
7183
+ return;
7184
+ }
7185
+ if (this._acknowledgedProjectionPending || this._acknowledgedProjectionSettling)
7186
+ return;
7187
+ const actions = this._dataRequestCoordinator?.setSentinelIntersecting(true) ?? [];
7188
+ this._dispatchAcknowledgedActions(actions);
7189
+ return;
7190
+ }
7191
+ if (entry.isIntersecting && !this._state.isBusy) {
6172
7192
  this._loadMoreItems();
6173
7193
  }
6174
- }
6175
- });
6176
- }, { threshold: 0.1 });
7194
+ });
7195
+ }, acknowledged
7196
+ ? { root: this._optionsContainer, threshold: 0.1 }
7197
+ : { threshold: 0.1 });
7198
+ this._intersectionObserver = observer;
7199
+ }
7200
+ catch (error) {
7201
+ this._intersectionObserver = undefined;
7202
+ if (!acknowledged)
7203
+ throw error;
7204
+ }
6177
7205
  }
6178
7206
  }
6179
7207
  async _loadInitialSelectedItems() {
@@ -6255,7 +7283,10 @@ class EnhancedSelect extends HTMLElement {
6255
7283
  const accessibilityState = {
6256
7284
  ...derivedState,
6257
7285
  // The component's existing busy lifecycle is not yet mirrored to engine dataStatus.
6258
- busy: this._state.isBusy,
7286
+ // Host presentation busy is additive only for the accepted acknowledged
7287
+ // protocol; legacy host attributes remain inert for listbox semantics.
7288
+ busy: this._state.isBusy || (this._dataLoadingConfig.protocol === 'acknowledged'
7289
+ && this.getAttribute('aria-busy') === 'true'),
6259
7290
  };
6260
7291
  const effects = computeAccessibilityEffects(accessibilityState, {
6261
7292
  controlsId: this._dropdown.id || null,
@@ -6521,8 +7552,44 @@ class EnhancedSelect extends HTMLElement {
6521
7552
  return results;
6522
7553
  }
6523
7554
  _handleSearch(query) {
7555
+ if (this._dataRequestCoordinator
7556
+ && (this._acknowledgedProjectionPending || this._acknowledgedProjectionSettling)) {
7557
+ // Keep the committed query/generation stable until the accepted snapshot
7558
+ // has been projected. Coalesce input as a latest-wins intent and dispatch
7559
+ // exactly one new generation after recovery/projection succeeds.
7560
+ this._acknowledgedPendingSearchQuery = query;
7561
+ this._input.value = query;
7562
+ this._syncClearControlState();
7563
+ return;
7564
+ }
7565
+ if (this._dataLoadingConfig.protocol === 'acknowledged'
7566
+ && (this._dataLoadingConfig.searchMode === 'remote' || this._dataLoadingConfig.searchMode === 'hybrid')) {
7567
+ this._state.searchQuery = query;
7568
+ this._syncClearControlState();
7569
+ this._state.lastNotifiedQuery = query;
7570
+ this._state.lastNotifiedResultCount = 0;
7571
+ if (this._dataRequestCoordinator) {
7572
+ const actions = this._dataRequestCoordinator.setQuery(query);
7573
+ if (this._acknowledgedReady)
7574
+ this._dispatchAcknowledgedActions(actions);
7575
+ else
7576
+ this._renderOptions();
7577
+ }
7578
+ else if (!this._state.isOpen) {
7579
+ this._handleOpen();
7580
+ }
7581
+ else {
7582
+ this._renderOptions();
7583
+ }
7584
+ return;
7585
+ }
6524
7586
  this._state.searchQuery = query;
6525
7587
  this._syncClearControlState();
7588
+ if (this._dataLoadingConfig.protocol === 'acknowledged' && this._dataRequestCoordinator) {
7589
+ // Local acknowledged search has no remote request, but pagination still
7590
+ // belongs to the coordinator's current query generation.
7591
+ this._dispatchAcknowledgedActions(this._dataRequestCoordinator.setQuery(query));
7592
+ }
6526
7593
  if (query.length > 0) {
6527
7594
  this._perfMark('smilodon-search-input-last');
6528
7595
  this._pendingSearchRenderMark = true;
@@ -7074,8 +8141,19 @@ class EnhancedSelect extends HTMLElement {
7074
8141
  this._inputContent.insertBefore(badge, this._input);
7075
8142
  });
7076
8143
  }
8144
+ // A query typed during an accepted-snapshot projection is a pending user
8145
+ // intent, not part of the committed projection state. Keep it visible even
8146
+ // when selection/display synchronization runs during that transaction.
8147
+ if (this._acknowledgedPendingSearchQuery !== null) {
8148
+ this._input.value = this._acknowledgedPendingSearchQuery;
8149
+ }
7077
8150
  this._syncClearControlState();
7078
8151
  }
8152
+ _isActivelyEditingSearchInput() {
8153
+ return this._config.searchable === true
8154
+ && this._state.isOpen
8155
+ && this._shadow.activeElement === this._input;
8156
+ }
7079
8157
  _renderOptionsWithAnimation() {
7080
8158
  // Add fade-out animation
7081
8159
  this._optionsContainer.style.opacity = '0';
@@ -7141,7 +8219,24 @@ class EnhancedSelect extends HTMLElement {
7141
8219
  this._setActive(targetIndex, 'programmatic');
7142
8220
  }
7143
8221
  }
7144
- async _loadMoreItems() {
8222
+ async _loadMoreItems(trigger = 'manual') {
8223
+ if (this._dataLoadingConfig.protocol === 'acknowledged') {
8224
+ if (!this._dataRequestCoordinator
8225
+ || !this._acknowledgedReady
8226
+ || this._acknowledgedProjectionPending
8227
+ || this._acknowledgedProjectionSettling)
8228
+ return;
8229
+ const actions = this._dataRequestCoordinator.requestLoadMore(trigger);
8230
+ this._dispatchAcknowledgedActions(actions);
8231
+ return;
8232
+ }
8233
+ if (this._dataRequestCoordinator) {
8234
+ if (!this._acknowledgedReady || this._acknowledgedProjectionPending || this._acknowledgedProjectionSettling)
8235
+ return;
8236
+ const actions = this._dataRequestCoordinator.requestLoadMore(trigger);
8237
+ this._dispatchAcknowledgedActions(actions);
8238
+ return;
8239
+ }
7145
8240
  if (this._state.isBusy)
7146
8241
  return;
7147
8242
  this._setBusy(true);
@@ -7368,9 +8463,30 @@ class EnhancedSelect extends HTMLElement {
7368
8463
  const previousLength = this._state.loadedItems.length;
7369
8464
  this._rebuildItemRegistry(items);
7370
8465
  this._state.groupedItems = this._groupItemsByProperty(items);
7371
- if (!this._state.searchQuery)
8466
+ if (!this._state.searchQuery && !this._isActivelyEditingSearchInput())
7372
8467
  this._updateInputDisplay();
7373
8468
  const newLength = this._state.loadedItems.length;
8469
+ if (this._dataRequestCoordinator) {
8470
+ const acknowledgedBusy = this._dataRequestCoordinator.getSnapshot().busy
8471
+ || this._acknowledgedProjectionPending;
8472
+ this._state.isSearching = false;
8473
+ this._state.isBusy = acknowledgedBusy;
8474
+ if (this._state.preserveScrollPosition && this._dropdown) {
8475
+ const targetScrollTop = this._state.lastScrollPosition;
8476
+ this._renderOptions();
8477
+ this._optionsContainer.scrollTop = targetScrollTop;
8478
+ this._requestLifecycleFrame(() => {
8479
+ if (this._optionsContainer)
8480
+ this._optionsContainer.scrollTop = targetScrollTop;
8481
+ });
8482
+ if (!acknowledgedBusy)
8483
+ this._state.preserveScrollPosition = false;
8484
+ }
8485
+ else {
8486
+ this._renderOptions();
8487
+ }
8488
+ return;
8489
+ }
7374
8490
  // When infinite scroll is active (preserveScrollPosition = true),
7375
8491
  // we need to maintain scroll position during the update
7376
8492
  if (this._state.preserveScrollPosition && this._dropdown) {
@@ -7428,7 +8544,7 @@ class EnhancedSelect extends HTMLElement {
7428
8544
  this._rebuildItemRegistry(groupedItems.flatMap(group => group.options));
7429
8545
  this._state.groupedItems = groupedItems;
7430
8546
  this._renderOptions();
7431
- if (!this._state.searchQuery)
8547
+ if (!this._state.searchQuery && !this._isActivelyEditingSearchInput())
7432
8548
  this._updateInputDisplay();
7433
8549
  }
7434
8550
  /**
@@ -7546,9 +8662,55 @@ class EnhancedSelect extends HTMLElement {
7546
8662
  this._invalidateGuardedMeasurements();
7547
8663
  const previousMode = this._config.selection.mode;
7548
8664
  const previousEnabled = this._config.enabled;
7549
- this._config = this._mergeConfig(this._config, config);
8665
+ const previousDataLoadingConfig = this._dataLoadingConfig;
8666
+ const { dataLoading, callbacks, ...legacyConfig } = config;
8667
+ const legacyUpdate = { ...legacyConfig };
8668
+ let configErrorDetail;
8669
+ if (callbacks !== undefined && callbacks !== null) {
8670
+ const callbackInput = callbacks;
8671
+ if (Object.prototype.hasOwnProperty.call(callbackInput, 'onDataLoadingConfigError')) {
8672
+ this._dataLoadingConfigErrorCallback = callbackInput.onDataLoadingConfigError;
8673
+ }
8674
+ if (Object.prototype.hasOwnProperty.call(callbackInput, 'onDataRequestCancel')) {
8675
+ this._dataRequestCancelCallback = callbackInput.onDataRequestCancel;
8676
+ }
8677
+ if (Object.prototype.hasOwnProperty.call(callbackInput, 'onDataProjection')) {
8678
+ this._dataProjectionCallback = callbackInput.onDataProjection;
8679
+ }
8680
+ const legacyCallbacks = { ...callbackInput };
8681
+ delete legacyCallbacks.onDataLoadingConfigError;
8682
+ delete legacyCallbacks.onDataRequestCancel;
8683
+ delete legacyCallbacks.onDataProjection;
8684
+ legacyUpdate.callbacks = legacyCallbacks;
8685
+ }
8686
+ this._config = this._mergeConfig(this._config, legacyUpdate);
8687
+ if (dataLoading !== undefined) {
8688
+ const dataLoadingPrototype = dataLoading !== null && typeof dataLoading === 'object'
8689
+ ? Object.getPrototypeOf(dataLoading)
8690
+ : undefined;
8691
+ const candidate = dataLoadingPrototype === Object.prototype || dataLoadingPrototype === null
8692
+ ? { ...this._dataLoadingConfig, ...dataLoading }
8693
+ : dataLoading;
8694
+ const validation = validateDataLoadingConfig(candidate);
8695
+ if (validation.valid) {
8696
+ this._dataLoadingConfig = validation.value;
8697
+ this._hasLastInvalidDataLoadingCandidate = false;
8698
+ this._lastInvalidDataLoadingCandidate = undefined;
8699
+ }
8700
+ else {
8701
+ const candidateSignature = createInvalidDataLoadingCandidateSignature(candidate, validation.issues);
8702
+ if (!this._hasLastInvalidDataLoadingCandidate ||
8703
+ !this._lastInvalidDataLoadingCandidate ||
8704
+ !invalidDataLoadingSignaturesEqual(this._lastInvalidDataLoadingCandidate, candidateSignature)) {
8705
+ this._hasLastInvalidDataLoadingCandidate = true;
8706
+ this._lastInvalidDataLoadingCandidate = candidateSignature;
8707
+ configErrorDetail = { issues: validation.issues };
8708
+ }
8709
+ }
8710
+ }
7550
8711
  this._rebuildItemRegistry();
7551
8712
  if (previousEnabled !== this._config.enabled) {
8713
+ this._input.disabled = !this._config.enabled;
7552
8714
  if (!this._config.enabled && this._state.isOpen) {
7553
8715
  this._handleClose('disabled');
7554
8716
  }
@@ -7598,14 +8760,301 @@ class EnhancedSelect extends HTMLElement {
7598
8760
  // Re-initialize observers in case infinite scroll was enabled/disabled
7599
8761
  this._initializeObservers();
7600
8762
  this._syncClearControlState();
7601
- this._updateInputDisplay();
8763
+ if (!this._isActivelyEditingSearchInput())
8764
+ this._updateInputDisplay();
7602
8765
  this._renderOptions();
7603
8766
  }
7604
8767
  else {
7605
8768
  this._syncInputContainerMode();
7606
8769
  this._syncMultiSelectDisplayConfig();
7607
8770
  this._syncClearControlState();
7608
- this._updateInputDisplay();
8771
+ if (!this._isActivelyEditingSearchInput())
8772
+ this._updateInputDisplay();
8773
+ }
8774
+ this._acknowledgedSearchMode = this._dataLoadingConfig.searchMode;
8775
+ if (this._dataLoadingConfig.protocol === 'legacy')
8776
+ this._acknowledgedDeferredStart = false;
8777
+ const coordinator = this._dataRequestCoordinator;
8778
+ const switchesToLegacy = previousDataLoadingConfig.protocol === 'acknowledged'
8779
+ && this._dataLoadingConfig.protocol === 'legacy';
8780
+ const acknowledgedModeChanged = previousDataLoadingConfig.protocol !== this._dataLoadingConfig.protocol
8781
+ || previousDataLoadingConfig.searchMode !== this._dataLoadingConfig.searchMode
8782
+ || previousDataLoadingConfig.paginationMode !== this._dataLoadingConfig.paginationMode;
8783
+ if (coordinator && switchesToLegacy) {
8784
+ if (this._acknowledgedReady && !this._acknowledgedProjectionPending && !this._acknowledgedProjectionSettling) {
8785
+ const update = coordinator.updateConfig(this._createCoordinatorConfig());
8786
+ if (update.status === 'accepted')
8787
+ this._dispatchAcknowledgedActions(update.actions);
8788
+ }
8789
+ this._acknowledgedReady = false;
8790
+ this._dispatchAcknowledgedActions(coordinator.disconnect());
8791
+ if (this._acknowledgedProjectionPending || this._acknowledgedProjectionSettling) {
8792
+ this._clearAcknowledgedCoordinatorAfterProjection = true;
8793
+ }
8794
+ else {
8795
+ this._dataRequestCoordinator = null;
8796
+ this._acknowledgedSearchMode = null;
8797
+ this._state.isBusy = false;
8798
+ this._state.isSearching = false;
8799
+ this._syncListboxAccessibility();
8800
+ this._renderOptions();
8801
+ }
8802
+ }
8803
+ else if (coordinator && this._dataLoadingConfig.protocol === 'acknowledged') {
8804
+ this._clearAcknowledgedCoordinatorAfterProjection = false;
8805
+ if (this._acknowledgedProjectionPending || this._acknowledgedProjectionSettling) {
8806
+ this._acknowledgedConfigUpdatePending = true;
8807
+ this._acknowledgedDeferredModeChange || (this._acknowledgedDeferredModeChange = acknowledgedModeChanged);
8808
+ }
8809
+ else if (this._acknowledgedReady) {
8810
+ const update = coordinator.updateConfig(this._createCoordinatorConfig());
8811
+ if (update.status === 'accepted') {
8812
+ this._dispatchAcknowledgedActions(update.actions);
8813
+ const snapshot = coordinator.getSnapshot();
8814
+ this._state.isBusy = snapshot.busy;
8815
+ this._state.isSearching = snapshot.activeRequest?.kind === 'search';
8816
+ this._syncListboxAccessibility();
8817
+ if (update.actions.every((action) => action.type !== 'request'))
8818
+ this._renderOptions();
8819
+ }
8820
+ }
8821
+ }
8822
+ if (configErrorDetail) {
8823
+ this._emit('dataLoadingConfigError', configErrorDetail);
8824
+ try {
8825
+ this._dataLoadingConfigErrorCallback?.(configErrorDetail);
8826
+ }
8827
+ catch (error) {
8828
+ this._handleError(error);
8829
+ }
8830
+ }
8831
+ }
8832
+ /** Open the acknowledged request lifecycle after the host has installed listeners. */
8833
+ startDataLoading() {
8834
+ const projectionRecoveryOnly = Boolean(this._dataRequestCoordinator && this._acknowledgedProjectionPending);
8835
+ if (this._dataLoadingConfig.protocol !== 'acknowledged' && !projectionRecoveryOnly)
8836
+ return;
8837
+ if (this._dataLoadingConfig.protocol === 'acknowledged' && !this._ensureDataRequestCoordinator())
8838
+ return;
8839
+ if (!this.isConnected) {
8840
+ if (!this._hasEverConnected)
8841
+ this._acknowledgedDeferredStart = true;
8842
+ return;
8843
+ }
8844
+ if (this._acknowledgedReady)
8845
+ return;
8846
+ if (this._acknowledgedStartTask) {
8847
+ // A reconnect can arrive while the previous readiness task is still
8848
+ // unwinding an interrupted render. Preserve the restart request so the
8849
+ // accepted projection is recovered as soon as that task settles.
8850
+ this._acknowledgedDeferredStart = true;
8851
+ return;
8852
+ }
8853
+ const task = this._startAcknowledgedDataLoading();
8854
+ this._acknowledgedStartTask = task;
8855
+ void task.finally(() => {
8856
+ if (this._acknowledgedStartTask !== task)
8857
+ return;
8858
+ this._acknowledgedStartTask = null;
8859
+ if (this._acknowledgedDeferredStart && this.isConnected) {
8860
+ this._acknowledgedDeferredStart = false;
8861
+ this.startDataLoading();
8862
+ }
8863
+ }).catch((error) => this._handleError(error));
8864
+ }
8865
+ /** Return detached coordinator state without exposing its canonical item storage. */
8866
+ getDataLoadingState() {
8867
+ const coordinator = this._dataRequestCoordinator;
8868
+ if (!coordinator) {
8869
+ const isRemote = this._dataLoadingConfig.searchMode === 'remote'
8870
+ || this._dataLoadingConfig.searchMode === 'hybrid';
8871
+ const nextEligiblePosition = this._dataLoadingConfig.paginationMode === 'cursor'
8872
+ ? { mode: 'cursor', ordinal: 1 }
8873
+ : {
8874
+ mode: 'page',
8875
+ page: isRemote
8876
+ ? this._dataLoadingConfig.firstPage
8877
+ : (this._config.infiniteScroll.initialPage ?? 1) + 1,
8878
+ };
8879
+ return {
8880
+ status: 'idle',
8881
+ connected: this.isConnected,
8882
+ busy: false,
8883
+ projectionPending: false,
8884
+ queryGeneration: 0,
8885
+ activeRequest: null,
8886
+ hasMore: this._dataLoadingConfig.protocol === 'acknowledged'
8887
+ && !isRemote
8888
+ && (this._config.infiniteScroll.enabled || this._config.loadMore.enabled),
8889
+ nextEligiblePosition,
8890
+ error: null,
8891
+ resourceLimit: null,
8892
+ };
8893
+ }
8894
+ const snapshot = coordinator.getSnapshot();
8895
+ const activeRequest = snapshot.activeRequest
8896
+ ? {
8897
+ ...snapshot.activeRequest,
8898
+ position: { ...snapshot.activeRequest.position },
8899
+ }
8900
+ : null;
8901
+ return {
8902
+ status: snapshot.status,
8903
+ connected: snapshot.connected,
8904
+ busy: snapshot.busy || this._acknowledgedProjectionPending,
8905
+ projectionPending: this._acknowledgedProjectionPending,
8906
+ queryGeneration: snapshot.queryGeneration,
8907
+ activeRequest,
8908
+ hasMore: snapshot.hasMore,
8909
+ nextEligiblePosition: { ...snapshot.nextEligiblePosition },
8910
+ error: snapshot.error ? { ...snapshot.error } : null,
8911
+ resourceLimit: snapshot.resourceLimit ? { ...snapshot.resourceLimit } : null,
8912
+ };
8913
+ }
8914
+ /** Synchronously accept/classify a host completion; DOM projection proceeds asynchronously. */
8915
+ completeDataRequest(completion) {
8916
+ const coordinator = this._dataRequestCoordinator;
8917
+ if (!coordinator) {
8918
+ const candidate = completion;
8919
+ if (candidate === null
8920
+ || typeof candidate !== 'object'
8921
+ || !('requestId' in candidate)
8922
+ || typeof candidate.requestId !== 'string'
8923
+ || candidate.requestId.length === 0
8924
+ || !('queryGeneration' in candidate)
8925
+ || !Number.isSafeInteger(candidate.queryGeneration)
8926
+ || candidate.queryGeneration < 0
8927
+ || !('status' in candidate)
8928
+ || typeof candidate.status !== 'string'
8929
+ || !['succeeded', 'empty', 'exhausted', 'failed', 'cancelled'].includes(candidate.status))
8930
+ return 'invalid';
8931
+ return 'unknown-request';
8932
+ }
8933
+ const snapshotBefore = coordinator.getSnapshot();
8934
+ const completionRecord = completion && typeof completion === 'object'
8935
+ ? completion
8936
+ : null;
8937
+ const activeRequest = snapshotBefore.activeRequest;
8938
+ const request = activeRequest
8939
+ && completionRecord?.requestId === activeRequest.requestId
8940
+ && completionRecord?.queryGeneration === activeRequest.queryGeneration
8941
+ ? activeRequest
8942
+ : null;
8943
+ const status = completionRecord?.status;
8944
+ const advancesPosition = status === 'succeeded'
8945
+ || status === 'exhausted'
8946
+ || (status === 'empty' && completionRecord?.advance === 'next');
8947
+ const result = coordinator.completeDataRequest(completion);
8948
+ if (result === 'accepted' && request) {
8949
+ this._acknowledgedLastRequest = request;
8950
+ this._acknowledgedProjectionRequest = request;
8951
+ this._acknowledgedProjectionAttempt = 0;
8952
+ this._acknowledgedProjectionCommitsPosition = advancesPosition;
8953
+ void this._projectAcknowledgedSnapshot(coordinator.getSnapshot(), request, advancesPosition);
8954
+ }
8955
+ else if (result === 'resource-limit') {
8956
+ const resourceLimit = coordinator.getSnapshot().resourceLimit;
8957
+ this._emit('diagnostic', {
8958
+ timestamp: Date.now(),
8959
+ source: 'event',
8960
+ name: 'acknowledgedDataLoadingResourceLimit',
8961
+ detail: resourceLimit,
8962
+ });
8963
+ }
8964
+ return result;
8965
+ }
8966
+ _createCoordinatorConfig() {
8967
+ return {
8968
+ dataLoading: { ...this._dataLoadingConfig },
8969
+ infiniteScroll: {
8970
+ pageSize: this._config.infiniteScroll.pageSize,
8971
+ initialPage: this._config.infiniteScroll.initialPage,
8972
+ },
8973
+ };
8974
+ }
8975
+ _ensureDataRequestCoordinator() {
8976
+ if (!this._dataRequestCoordinator) {
8977
+ const isRemote = this._dataLoadingConfig.searchMode === 'remote'
8978
+ || this._dataLoadingConfig.searchMode === 'hybrid';
8979
+ try {
8980
+ this._dataRequestCoordinator = new DataRequestCoordinator({
8981
+ config: this._createCoordinatorConfig(),
8982
+ initialQuery: this._state.searchQuery,
8983
+ initialItems: this._state.loadedItems,
8984
+ hasMore: !isRemote && (this._config.infiniteScroll.enabled || this._config.loadMore.enabled),
8985
+ });
8986
+ }
8987
+ catch (error) {
8988
+ const detail = {
8989
+ issues: [{
8990
+ path: 'dataLoading',
8991
+ code: 'invalid-value',
8992
+ message: `Acknowledged data loading could not start: ${error instanceof Error ? error.message : String(error)}`,
8993
+ }],
8994
+ };
8995
+ this._emit('dataLoadingConfigError', detail);
8996
+ try {
8997
+ this._dataLoadingConfigErrorCallback?.(detail);
8998
+ }
8999
+ catch (callbackError) {
9000
+ this._handleError(callbackError);
9001
+ }
9002
+ return null;
9003
+ }
9004
+ }
9005
+ this._acknowledgedSearchMode = this._dataLoadingConfig.searchMode;
9006
+ return this._dataRequestCoordinator;
9007
+ }
9008
+ async _startAcknowledgedDataLoading() {
9009
+ const coordinator = this._dataRequestCoordinator;
9010
+ const projectionRecoveryOnly = Boolean(coordinator && this._acknowledgedProjectionPending);
9011
+ if (!coordinator
9012
+ || (this._dataLoadingConfig.protocol !== 'acknowledged' && !projectionRecoveryOnly)
9013
+ || !this.isConnected)
9014
+ return;
9015
+ if (this._acknowledgedReady)
9016
+ return;
9017
+ if (this._acknowledgedProjectionPending) {
9018
+ const interruptedProjection = this._acknowledgedProjectionTask;
9019
+ if (interruptedProjection)
9020
+ await interruptedProjection;
9021
+ if (!this.isConnected)
9022
+ return;
9023
+ if (this._acknowledgedProjectionPending) {
9024
+ await this._retryAcknowledgedProjection();
9025
+ }
9026
+ if (!this.isConnected || this._acknowledgedProjectionPending)
9027
+ return;
9028
+ }
9029
+ if (this._dataLoadingConfig.protocol !== 'acknowledged'
9030
+ || !this._dataRequestCoordinator)
9031
+ return;
9032
+ if (this._acknowledgedPendingSearchQuery !== null) {
9033
+ this._state.searchQuery = this._acknowledgedPendingSearchQuery;
9034
+ this._input.value = this._acknowledgedPendingSearchQuery;
9035
+ this._acknowledgedPendingSearchQuery = null;
9036
+ }
9037
+ const configUpdate = coordinator.updateConfig(this._createCoordinatorConfig());
9038
+ if (configUpdate.status !== 'accepted') {
9039
+ this._acknowledgedReady = false;
9040
+ return;
9041
+ }
9042
+ this._acknowledgedConfigUpdatePending = false;
9043
+ this._acknowledgedDeferredModeChange = false;
9044
+ this._clearAcknowledgedCoordinatorAfterProjection = false;
9045
+ this._acknowledgedReady = true;
9046
+ this._initializeObservers();
9047
+ const configActions = configUpdate.actions;
9048
+ this._dispatchAcknowledgedActions(configActions);
9049
+ const connectionActions = coordinator.connect(this._state.searchQuery);
9050
+ this._dispatchAcknowledgedActions(connectionActions);
9051
+ if (configActions.length === 0 && connectionActions.length === 0)
9052
+ this._renderOptions();
9053
+ const readyRenderCycleId = this._renderCycleId;
9054
+ const readyRenderCompleted = await this._waitForRenderCycle(readyRenderCycleId);
9055
+ if (!readyRenderCompleted) {
9056
+ this._acknowledgedReady = false;
9057
+ throw new Error('Acknowledged readiness render was superseded before completion');
7609
9058
  }
7610
9059
  }
7611
9060
  _mergeConfig(target, source) {
@@ -7659,7 +9108,8 @@ class EnhancedSelect extends HTMLElement {
7659
9108
  return;
7660
9109
  const enabled = this._config.clearControl.enabled === true;
7661
9110
  const hasSelection = this._state.selectedIndices.size > 0;
7662
- const hasSearch = this._state.searchQuery.length > 0;
9111
+ const visibleSearchQuery = this._acknowledgedPendingSearchQuery ?? this._state.searchQuery;
9112
+ const hasSearch = visibleSearchQuery.length > 0;
7663
9113
  const clearSelection = this._config.clearControl.clearSelection !== false;
7664
9114
  const clearSearch = this._config.clearControl.clearSearch !== false;
7665
9115
  const hasSomethingToClear = (clearSelection && hasSelection) || (clearSearch && hasSearch);
@@ -7930,6 +9380,357 @@ class EnhancedSelect extends HTMLElement {
7930
9380
  this._guardedVirtualOverscan = 0;
7931
9381
  return true;
7932
9382
  }
9383
+ /** Test-only activation seam; deliberately absent from public config/types. */
9384
+ _enableAcknowledgedDataLoadingForTest(config, options = {}) {
9385
+ if (this._dataRequestCoordinator) {
9386
+ throw new Error('Acknowledged data loading is already enabled for this test instance');
9387
+ }
9388
+ const dataLoading = config.dataLoading;
9389
+ this._dataLoadingConfig = {
9390
+ protocol: dataLoading?.protocol ?? 'acknowledged',
9391
+ searchMode: dataLoading?.searchMode ?? 'local',
9392
+ paginationMode: dataLoading?.paginationMode ?? 'page',
9393
+ firstPage: dataLoading?.firstPage ?? 1,
9394
+ ...(dataLoading?.fetchLimit === undefined ? {} : { fetchLimit: dataLoading.fetchLimit }),
9395
+ };
9396
+ this._acknowledgedSearchMode = config.dataLoading?.searchMode ?? 'local';
9397
+ this._dataRequestCoordinator = new DataRequestCoordinator({
9398
+ config,
9399
+ initialQuery: this._state.searchQuery,
9400
+ initialItems: this._state.loadedItems,
9401
+ hasMore: options.hasMore,
9402
+ });
9403
+ this._acknowledgedReady = false;
9404
+ if (this.isConnected)
9405
+ this._initializeObservers();
9406
+ }
9407
+ /** Listener installation must precede this private test-only readiness gate. */
9408
+ async _setAcknowledgedDataLoadingReadyForTest() {
9409
+ if (!this._dataRequestCoordinator)
9410
+ throw new Error('Enable acknowledged data loading before readiness');
9411
+ if (!this.isConnected)
9412
+ throw new Error('Acknowledged readiness requires a connected test element');
9413
+ if (this._acknowledgedReady)
9414
+ return;
9415
+ if (this._acknowledgedProjectionPending) {
9416
+ const interruptedProjection = this._acknowledgedProjectionTask;
9417
+ if (interruptedProjection)
9418
+ await interruptedProjection;
9419
+ if (this._acknowledgedProjectionPending) {
9420
+ await this._retryAcknowledgedProjectionForTest();
9421
+ }
9422
+ if (this._acknowledgedProjectionPending) {
9423
+ throw new Error('Acknowledged readiness cannot open while snapshot projection is pending');
9424
+ }
9425
+ }
9426
+ if (this._acknowledgedPendingSearchQuery !== null) {
9427
+ this._state.searchQuery = this._acknowledgedPendingSearchQuery;
9428
+ this._input.value = this._acknowledgedPendingSearchQuery;
9429
+ this._acknowledgedPendingSearchQuery = null;
9430
+ }
9431
+ this._acknowledgedReady = true;
9432
+ this._initializeObservers();
9433
+ const actions = this._dataRequestCoordinator.connect(this._state.searchQuery);
9434
+ this._dispatchAcknowledgedActions(actions);
9435
+ if (actions.length === 0)
9436
+ this._renderOptions();
9437
+ const readyRenderCycleId = this._renderCycleId;
9438
+ const readyRenderCompleted = await this._waitForRenderCycle(readyRenderCycleId);
9439
+ if (!readyRenderCompleted) {
9440
+ this._acknowledgedReady = false;
9441
+ throw new Error('Acknowledged readiness render was superseded before completion');
9442
+ }
9443
+ }
9444
+ _dispatchAcknowledgedActions(actions) {
9445
+ for (const action of actions) {
9446
+ if (action.type === 'cancel') {
9447
+ this._dispatchAcknowledgedEvent('dataRequestCancel', action.notification);
9448
+ try {
9449
+ this._dataRequestCancelCallback?.(action.notification);
9450
+ }
9451
+ catch (error) {
9452
+ this._handleError(error);
9453
+ }
9454
+ continue;
9455
+ }
9456
+ const request = action.request;
9457
+ const coordinator = this._dataRequestCoordinator;
9458
+ if (!coordinator || !this._acknowledgedReady)
9459
+ continue;
9460
+ if (request.kind === 'loadMore') {
9461
+ this._state.lastScrollPosition = this._optionsContainer.scrollTop;
9462
+ this._acknowledgedProjectionScrollTop = this._state.lastScrollPosition;
9463
+ this._state.preserveScrollPosition = true;
9464
+ this._state.isSearching = false;
9465
+ }
9466
+ else {
9467
+ this._acknowledgedProjectionScrollTop = 0;
9468
+ this._state.preserveScrollPosition = false;
9469
+ this._state.isSearching = true;
9470
+ }
9471
+ this._state.isBusy = true;
9472
+ this._acknowledgedLastRequest = request;
9473
+ this._syncListboxAccessibility();
9474
+ this._renderOptions();
9475
+ if (request.kind === 'loadMore') {
9476
+ this._optionsContainer.scrollTop = this._state.lastScrollPosition;
9477
+ }
9478
+ if (!coordinator.markNotificationsDispatched(request.requestId))
9479
+ continue;
9480
+ if (request.kind === 'search') {
9481
+ const detail = { query: request.query, results: [], count: 0, request };
9482
+ this._dispatchAcknowledgedEvent('search', detail);
9483
+ try {
9484
+ const callback = this._config.callbacks.onSearch;
9485
+ callback?.(request.query, request);
9486
+ }
9487
+ catch (error) {
9488
+ this._handleError(error);
9489
+ }
9490
+ }
9491
+ else {
9492
+ const page = request.position.mode === 'page'
9493
+ ? request.position.page
9494
+ : request.position.ordinal;
9495
+ const detail = { page, items: [], request };
9496
+ this._dispatchAcknowledgedEvent('loadMore', detail);
9497
+ try {
9498
+ const callback = this._config.callbacks.onLoadMore;
9499
+ callback?.(page, request);
9500
+ }
9501
+ catch (error) {
9502
+ this._handleError(error);
9503
+ }
9504
+ }
9505
+ }
9506
+ }
9507
+ _dispatchAcknowledgedEvent(name, detail) {
9508
+ this.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true }));
9509
+ this._track('event', name, detail);
9510
+ }
9511
+ /** Test-only completion seam; accepted snapshots are projected from coordinator state. */
9512
+ async _completeDataRequestForTest(completion) {
9513
+ const result = this.completeDataRequest(completion);
9514
+ if (result !== 'accepted')
9515
+ return result;
9516
+ await this._acknowledgedProjectionTask;
9517
+ return result;
9518
+ }
9519
+ _failNextAcknowledgedProjectionForTest(stage = 'before-publish') {
9520
+ this._acknowledgedProjectionFailureStageForTest = stage;
9521
+ }
9522
+ /** Retries only from the canonical accepted coordinator snapshot, never a host payload. */
9523
+ _retryAcknowledgedProjectionForTest() {
9524
+ return this._retryAcknowledgedProjection();
9525
+ }
9526
+ _retryAcknowledgedProjection() {
9527
+ if (!this._dataRequestCoordinator || !this._acknowledgedProjectionPending)
9528
+ return Promise.resolve();
9529
+ return this._projectAcknowledgedSnapshot(this._dataRequestCoordinator.getSnapshot(), this._acknowledgedProjectionRequest ?? this._acknowledgedLastRequest, this._acknowledgedProjectionCommitsPosition);
9530
+ }
9531
+ _projectAcknowledgedSnapshot(snapshot, request, commitPosition) {
9532
+ if (this._acknowledgedProjectionRunning) {
9533
+ return this._acknowledgedProjectionTask ?? Promise.resolve();
9534
+ }
9535
+ this._acknowledgedProjectionRequest = request ?? this._acknowledgedProjectionRequest;
9536
+ this._acknowledgedProjectionAttempt += 1;
9537
+ this._acknowledgedProjectionPending = true;
9538
+ const items = Array.from(snapshot.items);
9539
+ let stagedRegistry;
9540
+ let groupedItems;
9541
+ try {
9542
+ stagedRegistry = createItemRegistry(items, this._itemAdapter, {
9543
+ duplicateKeyPolicy: this._getDuplicateKeyPolicy(),
9544
+ });
9545
+ groupedItems = this._groupItemsByProperty(items);
9546
+ if (this._acknowledgedProjectionFailureStageForTest === 'before-publish') {
9547
+ this._acknowledgedProjectionFailureStageForTest = null;
9548
+ throw new Error('Injected acknowledged projection failure before publication');
9549
+ }
9550
+ }
9551
+ catch (error) {
9552
+ this._syncListboxAccessibility();
9553
+ this._recordAcknowledgedProjectionFailure(snapshot, request, error);
9554
+ return Promise.resolve();
9555
+ }
9556
+ this._acknowledgedProjectionRunning = true;
9557
+ const task = this._applyAcknowledgedSnapshot(snapshot, request, commitPosition, items, stagedRegistry, groupedItems);
9558
+ const trackedTask = task.finally(() => {
9559
+ if (this._acknowledgedProjectionTask === trackedTask) {
9560
+ this._acknowledgedProjectionRunning = false;
9561
+ this._acknowledgedProjectionTask = null;
9562
+ }
9563
+ });
9564
+ this._acknowledgedProjectionTask = trackedTask;
9565
+ return trackedTask;
9566
+ }
9567
+ async _applyAcknowledgedSnapshot(snapshot, request, commitPosition, items, stagedRegistry, groupedItems) {
9568
+ let published = false;
9569
+ try {
9570
+ this._rebuildItemRegistry(items, stagedRegistry);
9571
+ this._state.groupedItems = groupedItems;
9572
+ if (commitPosition && request) {
9573
+ this._state.currentPage = snapshot.lastCommittedPage
9574
+ ?? (request.position.mode === 'page' ? request.position.page : request.position.ordinal);
9575
+ }
9576
+ this._state.isSearching = false;
9577
+ this._state.isBusy = true;
9578
+ this._state.lastScrollPosition = this._acknowledgedProjectionScrollTop;
9579
+ this._state.preserveScrollPosition = request?.kind === 'loadMore';
9580
+ published = true;
9581
+ if (this._acknowledgedProjectionFailureStageForTest === 'after-publish') {
9582
+ this._acknowledgedProjectionFailureStageForTest = null;
9583
+ throw new Error('Injected acknowledged projection failure after publication');
9584
+ }
9585
+ if (!this._state.searchQuery
9586
+ && this._acknowledgedPendingSearchQuery === null
9587
+ && !this._isActivelyEditingSearchInput()) {
9588
+ this._updateInputDisplay();
9589
+ }
9590
+ this._syncListboxAccessibility();
9591
+ this._renderOptions();
9592
+ const renderCycleId = this._renderCycleId;
9593
+ const completed = await this._waitForRenderCycle(renderCycleId);
9594
+ if (!completed)
9595
+ throw new Error('Acknowledged snapshot render was superseded before completion');
9596
+ this._state.isBusy = snapshot.busy;
9597
+ if (!snapshot.busy) {
9598
+ this._optionsContainer.querySelector('.busy-bucket')?.remove();
9599
+ if (this._shouldRenderLoadMoreTrigger())
9600
+ this._addLoadMoreTrigger();
9601
+ }
9602
+ this._optionsContainer.scrollTop = this._acknowledgedProjectionScrollTop;
9603
+ this._syncListboxAccessibility();
9604
+ this._syncRenderedOptionAccessibility();
9605
+ this._syncLegacyActiveAria();
9606
+ this._state.preserveScrollPosition = false;
9607
+ this._acknowledgedProjectionPending = false;
9608
+ this._acknowledgedProjectionDiagnostic = null;
9609
+ this._acknowledgedProjectionSettling = true;
9610
+ try {
9611
+ this._dispatchDataProjectionNotification({
9612
+ requestId: this._acknowledgedProjectionRequest?.requestId ?? request?.requestId ?? 'unknown',
9613
+ queryGeneration: this._acknowledgedProjectionRequest?.queryGeneration ?? snapshot.queryGeneration,
9614
+ attempt: this._acknowledgedProjectionAttempt,
9615
+ status: 'complete',
9616
+ });
9617
+ }
9618
+ finally {
9619
+ this._acknowledgedProjectionSettling = false;
9620
+ }
9621
+ if (this._clearAcknowledgedCoordinatorAfterProjection) {
9622
+ this._dataRequestCoordinator = null;
9623
+ this._acknowledgedSearchMode = null;
9624
+ this._clearAcknowledgedCoordinatorAfterProjection = false;
9625
+ this._acknowledgedProjectionRequest = null;
9626
+ }
9627
+ else {
9628
+ this._acknowledgedProjectionRequest = null;
9629
+ }
9630
+ this._finishAcknowledgedProjectionSettlement();
9631
+ }
9632
+ catch (error) {
9633
+ if (published) {
9634
+ if (this.isConnected)
9635
+ this._state.isBusy = true;
9636
+ this._state.isSearching = false;
9637
+ this._syncListboxAccessibility();
9638
+ }
9639
+ this._acknowledgedProjectionPending = true;
9640
+ this._recordAcknowledgedProjectionFailure(snapshot, request, error);
9641
+ }
9642
+ }
9643
+ _recordAcknowledgedProjectionFailure(snapshot, request, error) {
9644
+ const message = error instanceof Error ? error.message : String(error);
9645
+ const diagnostic = {
9646
+ requestId: this._acknowledgedProjectionRequest?.requestId ?? request?.requestId ?? 'unknown',
9647
+ queryGeneration: this._acknowledgedProjectionRequest?.queryGeneration ?? snapshot.queryGeneration,
9648
+ message,
9649
+ };
9650
+ this._acknowledgedProjectionDiagnostic = diagnostic;
9651
+ this._emit('diagnostic', {
9652
+ timestamp: Date.now(),
9653
+ source: 'event',
9654
+ name: 'acknowledgedProjectionFailed',
9655
+ detail: diagnostic,
9656
+ });
9657
+ if (diagnostic.requestId !== 'unknown') {
9658
+ this._dispatchDataProjectionNotification({
9659
+ requestId: diagnostic.requestId,
9660
+ queryGeneration: diagnostic.queryGeneration,
9661
+ attempt: this._acknowledgedProjectionAttempt,
9662
+ status: 'failed',
9663
+ error: { message },
9664
+ });
9665
+ }
9666
+ }
9667
+ _dispatchDataProjectionNotification(detail) {
9668
+ this._dispatchAcknowledgedEvent('dataProjection', detail);
9669
+ try {
9670
+ this._dataProjectionCallback?.(detail);
9671
+ }
9672
+ catch (error) {
9673
+ this._handleError(error);
9674
+ }
9675
+ }
9676
+ _dispatchPendingAcknowledgedSearchIntent() {
9677
+ const query = this._acknowledgedPendingSearchQuery;
9678
+ if (query === null || !this._acknowledgedReady || !this.isConnected)
9679
+ return;
9680
+ this._acknowledgedPendingSearchQuery = null;
9681
+ this._handleSearch(query);
9682
+ }
9683
+ /** Apply config/query changes coalesced while an accepted snapshot projected. */
9684
+ _finishAcknowledgedProjectionSettlement() {
9685
+ const coordinator = this._dataRequestCoordinator;
9686
+ const query = this._acknowledgedPendingSearchQuery;
9687
+ if (this._dataLoadingConfig.protocol !== 'acknowledged' || !coordinator) {
9688
+ this._acknowledgedConfigUpdatePending = false;
9689
+ this._acknowledgedDeferredModeChange = false;
9690
+ if (this._dataLoadingConfig.protocol === 'legacy' && query !== null && this.isConnected) {
9691
+ this._acknowledgedPendingSearchQuery = null;
9692
+ this._handleSearch(query);
9693
+ }
9694
+ else {
9695
+ this._dispatchPendingAcknowledgedSearchIntent();
9696
+ }
9697
+ return;
9698
+ }
9699
+ if (!this.isConnected || !this._acknowledgedReady)
9700
+ return;
9701
+ if (this._acknowledgedConfigUpdatePending) {
9702
+ const requiresSingleLatestQueryRequest = this._acknowledgedDeferredModeChange && query !== null;
9703
+ if (requiresSingleLatestQueryRequest) {
9704
+ // Apply the mode transition while disconnected, set the latest query,
9705
+ // then reconnect once. This prevents an intermediate request for the
9706
+ // pre-projection query from escaping before the coalesced latest one.
9707
+ this._dispatchAcknowledgedActions(coordinator.disconnect());
9708
+ }
9709
+ const update = coordinator.updateConfig(this._createCoordinatorConfig());
9710
+ if (update.status !== 'accepted') {
9711
+ this._acknowledgedReady = false;
9712
+ return;
9713
+ }
9714
+ this._acknowledgedConfigUpdatePending = false;
9715
+ this._acknowledgedDeferredModeChange = false;
9716
+ if (requiresSingleLatestQueryRequest && query !== null) {
9717
+ this._acknowledgedPendingSearchQuery = null;
9718
+ this._state.searchQuery = query;
9719
+ this._input.value = query;
9720
+ this._dispatchAcknowledgedActions(coordinator.setQuery(query));
9721
+ this._dispatchAcknowledgedActions(coordinator.connect(query));
9722
+ this._syncListboxAccessibility();
9723
+ this._handleSearch(query);
9724
+ return;
9725
+ }
9726
+ this._dispatchAcknowledgedActions(update.actions);
9727
+ const state = coordinator.getSnapshot();
9728
+ this._state.isBusy = state.busy;
9729
+ this._state.isSearching = state.activeRequest?.kind === 'search';
9730
+ this._syncListboxAccessibility();
9731
+ }
9732
+ this._dispatchPendingAcknowledgedSearchIntent();
9733
+ }
7933
9734
  _updateGuardedVirtualWindow(scrollTop, viewportHeight) {
7934
9735
  this._guardedVirtualizationRequested = true;
7935
9736
  const virtualizer = this._ensureGuardedVirtualizer(this._renderPlan.filteredKeys);
@@ -8117,6 +9918,7 @@ class EnhancedSelect extends HTMLElement {
8117
9918
  const scrollTopBeforeRender = this._optionsContainer.scrollTop;
8118
9919
  this._renderCycleId += 1;
8119
9920
  const renderCycleId = this._renderCycleId;
9921
+ this._resolvePendingRenderCycles(false, renderCycleId);
8120
9922
  if (this._guardedVirtualizer) {
8121
9923
  this._guardedVirtualScrollTop = this._optionsContainer.scrollTop;
8122
9924
  }
@@ -8124,6 +9926,8 @@ class EnhancedSelect extends HTMLElement {
8124
9926
  if (this._loadMoreTrigger && this._intersectionObserver) {
8125
9927
  this._intersectionObserver.unobserve(this._loadMoreTrigger);
8126
9928
  }
9929
+ if (this._dataRequestCoordinator)
9930
+ this._loadMoreTrigger = undefined;
8127
9931
  this._unobserveGuardedOptionResizeTargets();
8128
9932
  // Clear options container
8129
9933
  this._optionsContainer.innerHTML = '';
@@ -8152,12 +9956,15 @@ class EnhancedSelect extends HTMLElement {
8152
9956
  searching.setAttribute('part', 'loading');
8153
9957
  searching.textContent = 'Searching...';
8154
9958
  this._optionsContainer.appendChild(searching);
9959
+ this._resolveRenderCycle(renderCycleId, true);
8155
9960
  return;
8156
9961
  }
8157
9962
  const getValue = this._config.serverSide.getValueFromItem || ((item) => item?.value ?? item);
8158
9963
  const getLabel = this._config.serverSide.getLabelFromItem || ((item) => item?.label ?? String(item));
8159
9964
  // Filter items by search query
8160
- const query = this._state.searchQuery.toLowerCase();
9965
+ const query = this._acknowledgedSearchMode === 'remote'
9966
+ ? ''
9967
+ : this._state.searchQuery.toLowerCase();
8161
9968
  if (this._guardedMeasurementQuery !== null && this._guardedMeasurementQuery !== query) {
8162
9969
  this._invalidateGuardedMeasurements();
8163
9970
  }
@@ -8282,8 +10089,10 @@ class EnhancedSelect extends HTMLElement {
8282
10089
  }
8283
10090
  }
8284
10091
  const renderChunk = () => {
8285
- if (renderCycleId !== this._renderCycleId)
10092
+ if (renderCycleId !== this._renderCycleId) {
10093
+ this._resolveRenderCycle(renderCycleId, false);
8286
10094
  return;
10095
+ }
8287
10096
  const fragment = document.createDocumentFragment();
8288
10097
  const chunkEnd = Math.min(Math.max(cursor + chunkSize, maxRenderTarget), filteredIndices.length);
8289
10098
  maxRenderTarget = 0; // Reset after fast-forwarding
@@ -8301,12 +10110,15 @@ class EnhancedSelect extends HTMLElement {
8301
10110
  this._requestLifecycleFrame(renderChunk);
8302
10111
  }
8303
10112
  else {
8304
- if (renderCycleId !== this._renderCycleId)
10113
+ if (renderCycleId !== this._renderCycleId) {
10114
+ this._resolveRenderCycle(renderCycleId, false);
8305
10115
  return;
8306
- if (!this._state.isBusy && (this._config.loadMore.enabled || this._config.infiniteScroll.enabled) && this._state.loadedItems.length > 0) {
10116
+ }
10117
+ if (!this._state.isBusy && this._shouldRenderLoadMoreTrigger()) {
8307
10118
  this._addLoadMoreTrigger();
8308
10119
  }
8309
10120
  this._finalizePerfMarks();
10121
+ this._resolveRenderCycle(renderCycleId, true);
8310
10122
  }
8311
10123
  };
8312
10124
  renderChunk();
@@ -8338,7 +10150,7 @@ class EnhancedSelect extends HTMLElement {
8338
10150
  this._optionsContainer.appendChild(busyBucket);
8339
10151
  }
8340
10152
  // Append Load More Trigger (Button or Sentinel) if enabled and not busy
8341
- else if ((this._config.loadMore.enabled || this._config.infiniteScroll.enabled) && this._state.loadedItems.length > 0) {
10153
+ else if ((!this._dataRequestCoordinator || !this._state.isBusy) && this._shouldRenderLoadMoreTrigger()) {
8342
10154
  this._addLoadMoreTrigger();
8343
10155
  }
8344
10156
  // Rebuilding the list temporarily removes its spacer geometry. Browsers
@@ -8351,6 +10163,43 @@ class EnhancedSelect extends HTMLElement {
8351
10163
  this._syncLegacyActiveAria();
8352
10164
  this._syncGuardedOptionResizeTargets();
8353
10165
  this._finalizePerfMarks();
10166
+ this._resolveRenderCycle(renderCycleId, true);
10167
+ }
10168
+ _waitForRenderCycle(renderCycleId) {
10169
+ if (renderCycleId < this._renderCycleId)
10170
+ return Promise.resolve(false);
10171
+ if (renderCycleId <= this._completedRenderCycleId)
10172
+ return Promise.resolve(true);
10173
+ return new Promise((resolve) => {
10174
+ this._renderCycleWaiters.set(renderCycleId, resolve);
10175
+ const timeout = window.setTimeout(() => this._resolveRenderCycle(renderCycleId, false), 120000);
10176
+ this._renderCycleWaiterTimeouts.set(renderCycleId, timeout);
10177
+ });
10178
+ }
10179
+ _resolveRenderCycle(renderCycleId, completed) {
10180
+ if (completed)
10181
+ this._completedRenderCycleId = Math.max(this._completedRenderCycleId, renderCycleId);
10182
+ const resolve = this._renderCycleWaiters.get(renderCycleId);
10183
+ const timeout = this._renderCycleWaiterTimeouts.get(renderCycleId);
10184
+ if (timeout !== undefined)
10185
+ window.clearTimeout(timeout);
10186
+ this._renderCycleWaiterTimeouts.delete(renderCycleId);
10187
+ if (!resolve)
10188
+ return;
10189
+ this._renderCycleWaiters.delete(renderCycleId);
10190
+ resolve(completed);
10191
+ }
10192
+ _resolvePendingRenderCycles(completed, beforeCycleId = Number.POSITIVE_INFINITY) {
10193
+ for (const [renderCycleId, resolve] of this._renderCycleWaiters) {
10194
+ if (renderCycleId >= beforeCycleId)
10195
+ continue;
10196
+ const timeout = this._renderCycleWaiterTimeouts.get(renderCycleId);
10197
+ if (timeout !== undefined)
10198
+ window.clearTimeout(timeout);
10199
+ this._renderCycleWaiterTimeouts.delete(renderCycleId);
10200
+ this._renderCycleWaiters.delete(renderCycleId);
10201
+ resolve(completed);
10202
+ }
8354
10203
  }
8355
10204
  _unobserveGuardedOptionResizeTargets() {
8356
10205
  for (const option of this._guardedObservedOptions) {
@@ -8563,6 +10412,46 @@ class EnhancedSelect extends HTMLElement {
8563
10412
  _addLoadMoreTrigger() {
8564
10413
  const container = document.createElement('div');
8565
10414
  container.className = 'load-more-container';
10415
+ if (this._dataRequestCoordinator) {
10416
+ const shouldObserve = this._config.infiniteScroll.enabled
10417
+ && Boolean(this._intersectionObserver)
10418
+ && this._acknowledgedReady;
10419
+ let sentinel;
10420
+ if (shouldObserve) {
10421
+ sentinel = this._acknowledgedSentinel ?? document.createElement('div');
10422
+ sentinel.className = 'infinite-scroll-sentinel';
10423
+ sentinel.style.height = '10px';
10424
+ sentinel.style.width = '100%';
10425
+ sentinel.style.opacity = '0';
10426
+ this._acknowledgedSentinel = sentinel;
10427
+ this._loadMoreTrigger = sentinel;
10428
+ container.appendChild(sentinel);
10429
+ }
10430
+ // Keep an explicit keyboard-accessible path even when automatic
10431
+ // observation is enabled, and use it as the fallback if IO is absent.
10432
+ if (this._config.loadMore.enabled || this._config.infiniteScroll.enabled) {
10433
+ const button = document.createElement('button');
10434
+ button.className = 'load-more-button';
10435
+ button.textContent = `Load ${this._config.loadMore.itemsPerLoad} more`;
10436
+ button.addEventListener('click', () => this._loadMoreItems('manual'));
10437
+ container.appendChild(button);
10438
+ if (!sentinel)
10439
+ this._loadMoreTrigger = button;
10440
+ }
10441
+ this._optionsContainer.appendChild(container);
10442
+ if (sentinel && this._intersectionObserver) {
10443
+ try {
10444
+ this._intersectionObserver.observe(sentinel);
10445
+ }
10446
+ catch (_error) {
10447
+ this._intersectionObserver.disconnect();
10448
+ this._intersectionObserver = undefined;
10449
+ sentinel.remove();
10450
+ this._loadMoreTrigger = container.querySelector('.load-more-button') ?? undefined;
10451
+ }
10452
+ }
10453
+ return;
10454
+ }
8566
10455
  if (this._config.infiniteScroll.enabled) {
8567
10456
  // Infinite Scroll: Render an invisible sentinel
8568
10457
  // It must have some height to be intersected
@@ -8589,6 +10478,23 @@ class EnhancedSelect extends HTMLElement {
8589
10478
  this._intersectionObserver.observe(this._loadMoreTrigger);
8590
10479
  }
8591
10480
  }
10481
+ _shouldRenderLoadMoreTrigger() {
10482
+ if (!this._config.loadMore.enabled && !this._config.infiniteScroll.enabled)
10483
+ return false;
10484
+ if (this._dataLoadingConfig.protocol === 'acknowledged'
10485
+ && (!this._dataRequestCoordinator || !this._acknowledgedReady))
10486
+ return false;
10487
+ if (!this._dataRequestCoordinator)
10488
+ return this._state.loadedItems.length > 0;
10489
+ const snapshot = this._dataRequestCoordinator.getSnapshot();
10490
+ if (snapshot.status === 'resource-limited')
10491
+ return false;
10492
+ return snapshot.hasMore
10493
+ || snapshot.error !== null
10494
+ || snapshot.status === 'empty'
10495
+ || snapshot.status === 'failed'
10496
+ || snapshot.status === 'cancelled';
10497
+ }
8592
10498
  }
8593
10499
  /** live set of all connected instances; used to auto-close siblings */
8594
10500
  EnhancedSelect._instances = new Set();
@@ -9685,6 +11591,7 @@ exports.setTextContent = setTextContent;
9685
11591
  exports.shadowDOMStyles = shadowDOMStyles;
9686
11592
  exports.toggleClass = toggleClass;
9687
11593
  exports.transition = transition;
11594
+ exports.validateDataLoadingConfig = validateDataLoadingConfig;
9688
11595
  exports.validateTemplate = validateTemplate;
9689
11596
  exports.valuesEqual = valuesEqual;
9690
11597
  exports.warnCSPViolation = warnCSPViolation;