@smilodon/core 1.10.0 → 1.10.1

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