import { $changes, $childType, $decoder, $deleteByIndex, $onEncodeEnd, $encoder, $filter, $getByIndex, $onDecodeEnd, $proxyTarget, $refId, $reset, $resyncPrune } from "../symbols.js"; import type { Schema } from "../../Schema.js"; import { type IRef, ChangeTree, installUntrackedChangeTree, IS_STREAM_COLLECTION, PENDING_SHIPPED_BY_FULL_SYNC, REATTACHED_CHILD } from "../../encoder/ChangeTree.js"; import { OPERATION } from "../../encoding/spec.js"; import { registerType } from "../registry.js"; import { Collection } from "../HelperTypes.js"; import { encodeArray } from "../../encoder/EncodeOperation.js"; import { CollectionKind, decodeArray } from "../../decoder/DecodeOperation.js"; import type { StateView } from "../../encoder/StateView.js"; import { assertInstanceType } from "../../encoding/assert.js"; const DEFAULT_SORT = (a: any, b: any) => { const A = a.toString(); const B = b.toString(); if (A < B) return -1; else if (A > B) return 1; else return 0 } /** * Whether a Proxy trap key addresses `items` rather than the instance. The * `get`, `set` and `has` traps all ask here, so they agree on every key. * * Only a canonical array index ("0", "17") does, as on a native Array. * Anything else ("length", "$changeAt", "-1", "1.5", "01", "1e0", "") is a * plain property of the instance: letting a number-like key through would * record a change at `Number(key)` while storing the value under the string * key, so clients would get a write the server never made. * * Names fail on their first char, so a named read never parses a number. */ function isIndexKey(key: string | symbol): key is string { if (typeof (key) === "symbol") { return false; } let c = key.charCodeAt(0); if (!(c >= 48 && c <= 57)) { return false; } // not a digit; NaN for "" if (c === 48) { return key.length === 1; } // "0", never "01" for (let i = 1, len = key.length; i < len; i++) { c = key.charCodeAt(i); if (c < 48 || c > 57) { return false; } } return true; } /** * Module-level Proxy handler shared by every `ArraySchema` instance. Hoisted * out of the ctor so per-instance Proxy setup stops allocating ~6 arrow * closures (the `__name` wrappers around those closures dominated one slice * of the decoder profile). The handlers reference the target via the trap's * `obj` arg — they don't need a captured `this`. Both `new ArraySchema()` * and `ArraySchema.initializeForDecoder()` plug into it. */ const ARRAY_PROXY_HANDLER: ProxyHandler = { get: (obj, prop) => { if (isIndexKey(prop)) { return obj.items[prop as unknown as number]; } return Reflect.get(obj, prop); }, set: (obj, key, setValue) => { if (isIndexKey(key)) { if (setValue === undefined || setValue === null) { // no null holes: remove, so both sides shift alike const index = Number(key); if (index < obj.items.length) { obj.splice(index, 1); } } else { // wire slot the write was recorded at; undefined = nothing // recorded (same value / skipped) — must NOT touch tmpItems // then, or a same-tick shifted layout gets clobbered. let wireIndex: number | undefined; if (setValue[$changes]) { assertInstanceType(setValue, obj[$childType] as typeof Schema, obj, key); const previousValue = obj.items[key as unknown as number]; if (!obj.isMovingItems) { wireIndex = obj.$changeAt(Number(key), setValue); } else { wireIndex = obj.$wireIndex(Number(key)); if (previousValue !== undefined) { if (setValue[$changes].isNew) { obj[$changes].indexedOperation(wireIndex, OPERATION.MOVE_AND_ADD); } else { if ((obj[$changes].getChange(wireIndex) & OPERATION.DELETE) === OPERATION.DELETE) { obj[$changes].indexedOperation(wireIndex, OPERATION.DELETE_AND_MOVE); } else { obj[$changes].indexedOperation(wireIndex, OPERATION.MOVE); } } } else if (setValue[$changes].isNew) { obj[$changes].indexedOperation(wireIndex, OPERATION.ADD); } setValue[$changes].setParent(obj, obj[$changes].root, wireIndex); } if (previousValue !== undefined) { // remove root reference from previous value previousValue[$changes].root?.remove(previousValue[$changes]); } } else { wireIndex = obj.$changeAt(Number(key), setValue); } obj.items[key as unknown as number] = setValue; if (wireIndex !== undefined) { obj.tmpItems[wireIndex] = setValue; } } return true; } return Reflect.set(obj, key, setValue); }, deleteProperty: (obj, prop) => { delete obj[prop as unknown as number]; return true; }, has: (obj, key) => { if (isIndexKey(key)) { return Reflect.has(obj.items, key); } return Reflect.has(obj, key); }, }; export class ArraySchema implements Array, Collection, IRef { [n: number]: V; [$changes]: ChangeTree; [$refId]?: number; [$proxyTarget]: this; protected [$childType]: string | typeof Schema; protected items: V[] = []; protected tmpItems: V[] = []; protected deletedIndexes: boolean[] = []; /** * Encoder-only, Schema children only. Aligned with `tmpItems`: the element * the client holds at each wire slot whose `tmpItems` value was overwritten * this tick (splice-replace, index write). A later delete of the slot must * name the client's element — `tmpItems` would name the replacement, which * the client never received (issue #246). Lazily allocated; dropped at * `$onEncodeEnd`. */ protected replacedItems: V[] | undefined = undefined; protected isMovingItems = false; /** Decode-side: `items` has holes (delete or gap-write) — `$onDecodeEnd` must compact. */ protected _needsCompaction = false; static [$encoder] = encodeArray; static [$decoder] = decodeArray; /** Integer tag read by `decodeKeyValueOperation` — see `CollectionKind`. */ static readonly COLLECTION_KIND = CollectionKind.Array; /** * Determine if a property must be filtered. * - If returns false, the property is NOT going to be encoded. * - If returns true, the property is going to be encoded. * * Encoding with "filters" happens in two steps: * - First, the encoder iterates over all "not owned" properties and encodes them. * - Then, the encoder iterates over all "owned" properties per instance and encodes them. */ static [$filter] (ref: ArraySchema, index: number, view: StateView) { if (!view) return true; // must stay first — encodeAll hits this per element const self = ref[$proxyTarget] ?? ref; // ref arrives proxied — skip traps below return ( typeof (self[$childType]) === "string" || view.isChangeTreeVisible(self['tmpItems'][index]?.[$changes]) ); } static is(type: any) { return ( // type format: ["string"] Array.isArray(type) || // type format: { array: "string" } (type['array'] !== undefined) ); } static from(iterable: Iterable | ArrayLike) { return new ArraySchema(...Array.from(iterable)); } constructor (...items: V[]) { this[$childType] = undefined as any; // Self-reference so methods called via the Proxy can recover the // underlying instance and access fields directly. See $proxyTarget. this[$proxyTarget] = this; const proxy = new Proxy(this, ARRAY_PROXY_HANDLER); Object.defineProperty(this, $changes, { value: new ChangeTree(proxy, this), enumerable: false, writable: true, }); if (items.length > 0) { this.push(...items); } return proxy; } /** * Decoder-side factory. Skips the `ChangeTree` allocation and * replicates the class-field initializers by hand (since `Object.create` * bypasses them). Must stay in sync with the class-field declarations * and the constructor body above. * * Pass the Proxy to `installUntrackedChangeTree` as the public identity * so children set their parent to the Proxy, not the raw target. */ static initializeForDecoder(): ArraySchema { const self: any = Object.create(ArraySchema.prototype); self.items = []; // `tmpItems` / `deletedIndexes` are encoder-only (consulted by the // staged-snapshot path in `$getByIndex`, `$onEncodeEnd`, etc.). The // decoder reads from `items` directly and never maintains them. self.isMovingItems = false; self._needsCompaction = false; self[$childType] = undefined; self[$proxyTarget] = self; const proxy = new Proxy(self, ARRAY_PROXY_HANDLER); installUntrackedChangeTree(self, proxy); return proxy; } set length (newLength: number) { if (newLength === 0) { this.clear(); } else if (newLength < this.items.length) { this.splice(newLength, this.length - newLength); } else { console.warn("ArraySchema: can't set .length to a higher value than its length."); } } get length() { return this.items.length; } // ────── Change tracking control (same API as Schema) ────── pauseTracking(): void { this[$changes].pause(); } resumeTracking(): void { this[$changes].resume(); } untracked(fn: () => T): T { return this[$changes].untracked(fn); } get isTrackingPaused(): boolean { return this[$changes].paused; } push(...values: V[]) { // `this` is the Proxy when called from user code. Grab the underlying // instance once so the body's field reads (items, tmpItems, $changes, // $childType) skip the Proxy.get trap on every iteration. const self = this[$proxyTarget]; const items = self.items; const tmpItems = self.tmpItems; const changeTree = self[$changes]; const childType = self[$childType]; let length = tmpItems.length; for (let i = 0, l = values.length; i < l; i++, length++) { const value = values[i]; if (value === undefined || value === null) { // skip null values return; } else if (typeof (value) === "object" && childType) { assertInstanceType(value as any, childType as typeof Schema, self, i); // TODO: move value[$changes]?.setParent() to this block. } changeTree.indexedOperation(length, OPERATION.ADD); items.push(value); tmpItems.push(value); // // set value's parent after the value is set // (to avoid encoding "refId" operations before parent's "ADD" operation) // Pass `this` (the Proxy) as parent — the Proxy is the public // identity of the array; ChangeTree.parentRef compares by identity. // if (value[$changes]?.setParent(this, changeTree.root, length)) { changeTree.flags |= REATTACHED_CHILD; } } return length; } /** * Removes the last element from an array and returns it. */ pop(): V | undefined { // Unwrap Proxy once — see push() for rationale. const self = this[$proxyTarget]; const tmpItems = self.tmpItems; const deletedIndexes = self.deletedIndexes; let index: number = -1; // find last non-undefined index for (let i = tmpItems.length - 1; i >= 0; i--) { if (deletedIndexes[i] !== true) { index = i; break; } } if (index < 0) { return undefined; } if (self.$settleReorder(index)) { return this.pop(); } const cancel = self.$isUnsentAdd(index); self[$changes].delete(index); if (cancel) { self.$cancelAdd(index); } else { deletedIndexes[index] = true; } return self.items.pop(); } at(index: number) { // Allow negative indexing from the end if (index < 0) index += this.length; return this.items[index]; } /** * items-index → wire (tmpItems) index. Identity while no deletions are * staged this tick; otherwise maps to the index-th live (non-deleted) * tmpItems slot — the same live-index walk `splice()` uses. Without the * translation, index writes recorded after a same-tick `shift()`/`splice()` * land on the wrong wire slots. */ protected $wireIndex(index: number): number { const deletedIndexes = this.deletedIndexes; if (deletedIndexes.length === 0) { return index; } const tmpItems = this.tmpItems; let live = 0; for (let i = 0; i < tmpItems.length; i++) { if (deletedIndexes[i] !== true) { if (live === index) { return i; } live++; } } // beyond the live range: appends land after the staged tmpItems tail return tmpItems.length + (index - live); } /** * True when `sort()` can re-state the order as one REPLACE per moved slot * on top of this tick's pending ops. A staged delete can't take it: its * slot would be re-pointed at whichever element sorted into it. Nor can a * Schema child's ADD or DELETE: REPLACE moves an instance without * touching its refCount, so a merged slot would ship a known instance as * new, or never create the new one. */ protected $canReorderInPlace(): boolean { if (this.deletedIndexes.length > 0) { return false; } if (typeof this[$childType] === "string") { return true; } for (const op of this[$changes].collDirty!.values()) { if ((op & (OPERATION.ADD | OPERATION.DELETE)) !== 0) { return false; } } return true; } /** * Schema children only. A pending REPLACE at wire slot `at` is `sort()` * moving an instance in, and the slot holds a single op: a delete or * write merged into it would name the instance the client holds there, * which `sort()` moved elsewhere. Re-state the array first so the op * lands on an unsent ADD instead. Never while paused: the re-state would * discard the tick's recorded ops without recording anything back. * * Returns true when it did — wire indexes computed before are stale. */ protected $settleReorder(at: number): boolean { if (typeof this[$childType] === "string") { return false; } // positional ops compose const changeTree = this[$changes]; if (changeTree.paused || changeTree.operationAt(at) !== OPERATION.REPLACE) { return false; } this.$restate(this.items.slice()); return true; } /** * Full re-state: CLEAR, then re-ADD `values` in order — for when this * tick's ops can't be carried across a reorder. Only ops every SDK * decoder already speaks; Schema children's refCounts re-balance through * `Root.add`'s refCount-0 restage. `clear()` also drops staged holes * (discard → `$onEncodeEnd`). */ protected $restate(values: V[]): void { const proxy = this[$changes].ref as ArraySchema; // parent identity for push() proxy.clear(); proxy.push(...values); } /** * True when wire slot `at` holds an ADD recorded this tick that no client * has seen, so the slot can be erased outright instead of shipping a * DELETE for something nobody has. For Schema children that DELETE goes * out as DELETE_BY_REFID, which the decoder resolves against every * reference to the instance — a phantom one decrements a refCount owned * by whichever other collection still holds it. For primitives it goes * out positionally, and unless the slot was a tail append the client * holds a different element there — `unshift(x); shift()` would delete * the client's first element (issue #246). * * Call BEFORE `ChangeTree.delete()`, which overwrites the ADD. One mask * test rules out both hazards (a same-tick full sync made the pending * indexes load-bearing; a stream journal owns the positions). */ protected $isUnsentAdd(at: number): boolean { const changeTree = this[$changes]; return ( (changeTree.flags & (PENDING_SHIPPED_BY_FULL_SYNC | IS_STREAM_COLLECTION)) === 0 && !changeTree.paused && changeTree.operationAt(at) === OPERATION.ADD ); } /** * Erase a wire slot whose ADD never reached a client. The staged layout * closes over it, so no emitter — shared pass, view drain, snapshot or * stream — can address it: the add never happened. * * Caller must have run `changeTree.delete(at)` FIRST: it resolves * `$getByIndex(at)` against the still-intact snapshot (splicing first * would resolve the next element) and releases the element's refCount. */ protected $cancelAdd(at: number, reindex: boolean = true): void { const changeTree = this[$changes]; const removed = this.tmpItems[at]; // before the splice this.tmpItems.splice(at, 1); if (this.deletedIndexes.length > 0) { this.deletedIndexes.splice(at, 1); } changeTree.removeAt(at, 1); this.replacedItems?.splice(at, 1); // `Root.remove` leaves a detached child's own parent edge in place on // purpose (encodeView resolves same-tick detached children through // it). Here the SLOT is gone too, so that edge would hand the view // drain the neighbour that inherited it. Drop it — unless the element // is still rooted elsewhere (shared), in which case its edges are live. const removedTree = removed?.[$changes]; if (removedTree !== undefined && removedTree.root === undefined) { removedTree.removeParent(this); } if (reindex) { this.$reindexChildren(at); } } /** * Remember the element the client holds at wire slot `at` before its * `tmpItems` entry is overwritten (see `replacedItems`). First write wins: * after one replacement `tmpItems` no longer holds the client's element. * Call only for a slot the client holds — not one with an unsent ADD. */ protected $stashReplaced(at: number): void { if (typeof this[$childType] === "string") { return; } // positional DELETE needs no identity const changeTree = this[$changes]; if (changeTree.paused || changeTree.isFullStateOnly) { return; } // nothing recorded — and no encode would drop it const replaced = (this.replacedItems ??= []); if (replaced[at] === undefined) { replaced[at] = this.tmpItems[at]; } } /** * Open wire slots at `at` for `values` — the inverse of `$cancelAdd`. * Records their ADDs, attaches them, and keeps every per-slot structure * aligned. `parent` is the Proxy: the array's public identity. */ protected $insertSlots(parent: ArraySchema, at: number, values: V[]): void { const changeTree = this[$changes]; const count = values.length; // single recorder op: shifts pending indexes up and records the new // ADDs lowest-first (the decoder splice-inserts in ascending order). changeTree.insertAt(at, count); // parent set AFTER recording, as in $changeAt for (let i = 0; i < count; i++) { if (values[i]?.[$changes]?.setParent(parent, changeTree.root, at + i)) { changeTree.flags |= REATTACHED_CHILD; } } if (at === 0) { this.tmpItems.unshift(...values); } // ~2× faster than splice(0, 0, …) in V8 else { this.tmpItems.splice(at, 0, ...values); } if (this.deletedIndexes.length > 0) { this.deletedIndexes.splice(at, 0, ...new Array(count).fill(false)); } this.replacedItems?.splice(at, 0, ...new Array(count)); this.$reindexChildren(at + count); // survivors only — the loop above placed the new items } /** * Re-point children at their wire slot. `ChangeTree._parentIndex` caches * the slot a child holds in `tmpItems`, and StateView addresses per-view * ADD/DELETE with it — so a reorder that leaves it behind aims those ops * at whichever element inherited the slot (issue #231). * * The filter check is a correctness boundary, not a tunable: StateView is * the only reader and reaches the index only through a filtered array * (`addParentOf` bails on `hasFilteredFields`, `remove` on the child's * `isFiltered`). Everything else stops at the flag read instead of walking * its children every tick. * * Callers name the lowest slot that moved as `from`. Compaction cannot, so * it hands over the pre-compaction layout as `staged` and the unchanged * prefix is skipped instead. Either way tail churn walks nothing. */ protected $reindexChildren(from: number, staged?: V[]) { if (!this[$changes].hasFilteredFields) { return; } // nothing will read the cache if (typeof this[$childType] === "string") { return; } // primitives have no child tree const tmpItems = this.tmpItems; const length = tmpItems.length; if (staged !== undefined) { while (from < length && tmpItems[from] === staged[from]) { from++; } } for (let i = from; i < length; i++) { tmpItems[i]?.[$changes]?.setParentIndex(this, i); } } // encoding only. Returns the wire index the change was recorded at // (undefined when nothing was recorded). protected $changeAt(index: number, value: V): number | undefined { if (value === undefined || value === null) { console.error("ArraySchema items cannot be null nor undefined; Use `splice(index, 1)` instead."); return undefined; } // skip if the value is the same as cached. if (this.items[index] === value) { return undefined; } const wireIndex = this.$wireIndex(index); if (this.$settleReorder(wireIndex)) { return this.$changeAt(index, value); } const changeTree = this[$changes]; const replacing = this.items[index] !== undefined; let operation = OPERATION.ADD; if (replacing && typeof (value) !== "object") { operation = OPERATION.REPLACE; // primitive } else if (replacing && changeTree.operationAt(wireIndex) !== OPERATION.ADD) { // schema child replacing one the client holds — over an unsent // ADD it stays ADD, or the decoder would overwrite, not insert this.$stashReplaced(wireIndex); operation = OPERATION.DELETE_AND_ADD; } changeTree.change(wireIndex, operation); // // set value's parent after the value is set // (to avoid encoding "refId" operations before parent's "ADD" operation) // if (value[$changes]?.setParent(this, changeTree.root, wireIndex)) { changeTree.flags |= REATTACHED_CHILD; } return wireIndex; } // decoding only protected $setAt(index: number, value: V, operation: OPERATION) { if ( operation === OPERATION.ADD && this.items[index] !== undefined ) { // ADD at an occupied index = insert (unshift / splice-insert): // shift existing items up instead of overwriting. this.items.splice(index, 0, value); } else if (operation === OPERATION.DELETE_AND_MOVE) { this.items.splice(index, 1); this.items[index] = value; } else { if (index > this.items.length) { this._needsCompaction = true; // gap-write (filtered/out-of-order ADD) leaves holes } this.items[index] = value; } } clear() { const self = this[$proxyTarget]; // skip if already clear if (self.items.length === 0) { return; } // discard previous operations. const changeTree = self[$changes]; // remove children references — and their edge here: every slot is // gone, so a refill must link fresh instead of looking re-attached changeTree.forEachChild((childChangeTree, _) => { changeTree.root?.remove(childChangeTree); childChangeTree.removeParent(self); }); changeTree.flags &= ~REATTACHED_CHILD; changeTree.discard(); changeTree.operation(OPERATION.CLEAR); self.items.length = 0; self.tmpItems.length = 0; self.replacedItems = undefined; } /** * Pool reset: empty this array and recycle its ChangeTree WITHOUT recording * any wire op (the parent field's ADD/DELETE owns the wire). Recurses into * ref-type children. Called by Schema.reset when a pooled entity has an * array field. The instance must already be detached from the encoder. */ [$reset]() { const self = this[$proxyTarget] ?? this; const changeTree = self[$changes]; if (changeTree.isStreamCollection) { throw new Error(`@colyseus/schema: cannot reset a streamed ArraySchema (pooling not supported).`); } const items = self.items; for (let i = 0; i < items.length; i++) (items[i] as any)?.[$reset]?.(); self.items.length = 0; self.tmpItems.length = 0; self.deletedIndexes.length = 0; self.replacedItems = undefined; changeTree.recycle(); self[$refId] = undefined; // assign (not delete) to avoid V8 dictionary-mode deopt } /** * Combines two or more arrays. * @param items Additional items to add to the end of array1. */ // @ts-ignore concat(...items: (V | ConcatArray)[]): ArraySchema { return new ArraySchema(...this.items.concat(...items)); } /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string { return this.items.join(separator); } /** * Reverses the elements in an Array. */ // @ts-ignore reverse(): ArraySchema { const self = this[$proxyTarget]; const changeTree = self[$changes]; if (changeTree.paused) { self.items.reverse(); // untracked: recorded ops keep reading the staged layout return this; } if (changeTree.has() || self.deletedIndexes.length > 0) { // // Ops recorded earlier this tick address the staged (pre-reverse) // layout, and the encoder only resolves their values at encode // time — a pure REVERSE would move that layout under them. // self.$restate(self.items.slice().reverse()); return this; } changeTree.operation(OPERATION.REVERSE); self.items.reverse(); self.tmpItems.reverse(); self.$reindexChildren(0); return this; } /** * Removes the first element from an array and returns it. */ shift(): V | undefined { const self = this[$proxyTarget]; const items = self.items; if (items.length === 0) { return undefined; } const changeTree = self[$changes]; // items[0] ≡ first live (non-deleted) tmpItems slot. Value-based // findIndex is unsafe here: same-tick index writes can duplicate a // value across tmp slots and resolve the wrong one. const deletedIndexes = self.deletedIndexes; let index = 0; while (deletedIndexes[index] === true) { index++; } if (self.$settleReorder(index)) { return this.shift(); } const cancel = self.$isUnsentAdd(index); changeTree.delete(index, OPERATION.DELETE); if (cancel) { self.$cancelAdd(index); } else { deletedIndexes[index] = true; } return items.shift(); } /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. */ slice(start?: number, end?: number): V[] { const sliced = new ArraySchema(); sliced.push(...this.items.slice(start, end)); return sliced as unknown as V[]; } /** * Sorts an array. * @param compareFn Function used to determine the order of the elements. It is expected to return * a negative value if first argument is less than second argument, zero if they're equal and a positive * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. * ```ts * [11,2,22,1].sort((a, b) => a - b) * ``` */ sort(compareFn: (a: V, b: V) => number = DEFAULT_SORT): this { const self = this[$proxyTarget]; const items = self.items; const changeTree = self[$changes]; if (changeTree.paused) { items.sort(compareFn); // untracked: recorded ops keep reading the staged layout return this; } if (!self.$canReorderInPlace()) { self.$restate(items.slice().sort(compareFn)); return this; } const tmpItems = self.tmpItems; // a pending primitive insert may hit the decoder's equal-value ADD skip — only re-stating every slot repairs it const everySlot = typeof self[$childType] === "string" && changeTree.has(); items.sort(compareFn); let firstMoved = -1; for (let i = 0, l = items.length; i < l; i++) { const moved = tmpItems[i] !== items[i]; if (!moved && !everySlot) { continue; } if (moved && firstMoved < 0) { firstMoved = i; } changeTree.change(i, OPERATION.REPLACE); tmpItems[i] = items[i]; // copy, not re-sort: a flaky comparator would diverge } if (firstMoved >= 0) { self.$reindexChildren(firstMoved); } return this; } /** * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. * @param start The zero-based location in the array from which to start removing elements. * @param deleteCount The number of elements to remove. * @param insertItems Elements to insert into the array in place of the deleted elements. */ splice( start: number, deleteCount?: number, ...insertItems: V[] ): V[] { const self = this[$proxyTarget]; const changeTree = self[$changes]; const items = self.items; const tmpItems = self.tmpItems; const deletedIndexes = self.deletedIndexes; const itemsLength = items.length; const tmpItemsLength = tmpItems.length; const insertCount = insertItems.length; // Array#splice semantics — indexes[] below is read with these as-is const relativeStart = Math.trunc(start) || 0; // NaN → 0 start = (relativeStart < 0) ? Math.max(itemsLength + relativeStart, 0) : Math.min(relativeStart, itemsLength); deleteCount = (arguments.length === 1) // omitted ≠ explicit undefined (→ 0) ? itemsLength - start : Math.min(Math.max(Math.trunc(deleteCount!) || 0, 0), itemsLength - start); // build up-to-date list of indexes, excluding removed values. const indexes: number[] = []; for (let i = 0; i < tmpItemsLength; i++) { if (deletedIndexes[i] !== true) { indexes.push(i); } } // Deleted wire slots whose ADD never reached a client, ascending. // Erased AFTER the loops below — doing it inline would invalidate // every later `indexes[]` entry and `base`. let unsent: number[] | undefined; const deleteEnd = start + deleteCount; for (let i = start; i < deleteEnd; i++) { if (self.$settleReorder(indexes[i])) { return this.splice(start, deleteCount, ...insertItems); } } for (let i = start; i < deleteEnd; i++) { const index = indexes[i]; const isUnsent = self.$isUnsentAdd(index); changeTree.delete(index, OPERATION.DELETE); if (isUnsent) { (unsent ??= []).push(index); } else { deletedIndexes[index] = true; } } // insert operations if (insertCount > 0) { // Appending (start past the last live slot) goes after the whole // staged layout — `itemsLength` would land in front of live slots // whenever a deletion is staged this tick (issue #246). const base = indexes[start] ?? tmpItemsLength; // the first `reuse` items take over the wire slots just deleted const reuse = Math.min(insertCount, deleteCount); for (let i = 0; i < reuse; i++) { const addIndex = base + i; // An unsent slot taken over by an insert needs no erasing, but // it must not carry the DELETE half: the decoder resolves that // positionally and would removeRef whatever the client holds // there — which is not the element being replaced. const u = (unsent !== undefined) ? unsent.indexOf(addIndex) : -1; if (u !== -1) { unsent!.splice(u, 1); } // never flagged deleted: stays ADD below let op = OPERATION.ADD; if (deletedIndexes[addIndex]) { self.$stashReplaced(addIndex); op = OPERATION.DELETE_AND_ADD; } changeTree.indexedOperation(addIndex, op); // the slot is live again — the staged snapshot must carry the // new value, or `$getByIndex` falls back to `items[addIndex]` // and resolves an unrelated element once tmp/items diverge. tmpItems[addIndex] = insertItems[i]; deletedIndexes[addIndex] = false; // set value's parent/root — use `this` (Proxy) as parent. if (insertItems[i][$changes]?.setParent(this, changeTree.root, addIndex)) { changeTree.flags |= REATTACHED_CHILD; } } // ...the rest have no slot to take: widen the wire layout if (insertCount > reuse) { self.$insertSlots(this, base + reuse, insertItems.slice(reuse)); } } // Unsent slots nothing took over. Inserting past `reuse` implies every // deleted slot was reused, so this never coexists with `$insertSlots` // above and `base` never needs recomputing. Descending: each erase // shifts the slots above it. One reindex from the lowest covers all. if (unsent !== undefined && unsent.length > 0) { for (let i = unsent.length - 1; i >= 0; i--) { self.$cancelAdd(unsent[i], false); } self.$reindexChildren(unsent[0]); } changeTree.root?.enqueueChangeTree(changeTree); return items.splice(start, deleteCount, ...insertItems); } /** * Inserts new elements at the start of an array. * @param items Elements to insert at the start of the Array. */ unshift(...items: V[]): number { const self = this[$proxyTarget]; // at the first live slot: DELETEs staged ahead of it keep their // indexes and ship before these ADDs (`unshift(shift())`, issue #246) self.$insertSlots(this, self.$wireIndex(0), items); return self.items.unshift(...items); } /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. */ indexOf(searchElement: V, fromIndex?: number): number { return this.items.indexOf(searchElement, fromIndex); } /** * Returns the index of the last occurrence of a specified value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. */ lastIndexOf(searchElement: V, fromIndex: number = this.length - 1): number { return this.items.lastIndexOf(searchElement, fromIndex); } /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in the array until the callbackfn returns a value * which is coercible to the Boolean value false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(predicate: (value: V, index: number, array: V[]) => value is S, thisArg?: any): this is S[]; every(callbackfn: (value: V, index: number, array: V[]) => unknown, thisArg?: any): boolean; every(callbackfn: (value: V, index: number, array: V[]) => unknown, thisArg?: any): boolean { return this.items.every(callbackfn, thisArg); } /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls * the callbackfn function for each element in the array until the callbackfn returns a value * which is coercible to the Boolean value true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: V, index: number, array: V[]) => unknown, thisArg?: any): boolean { return this.items.some(callbackfn, thisArg); } /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: V, index: number, array: V[]) => void, thisArg?: any): void { return this.items.forEach(callbackfn, thisArg); } /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: V, index: number, array: V[]) => U, thisArg?: any): U[] { return this.items.map(callbackfn, thisArg); } /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: V, index: number, array: V[]) => unknown, thisArg?: any): V[] filter(callbackfn: (value: V, index: number, array: V[]) => value is S, thisArg?: any): V[] { return this.items.filter(callbackfn, thisArg); } /** * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduce(callbackfn: (previousValue: U, currentValue: V, currentIndex: number, array: V[]) => U, initialValue?: U): U { // forward `arguments`: an omitted initialValue seeds from the array, an explicit undefined doesn't // @ts-ignore return this.items.reduce.apply(this.items, arguments); } /** * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. */ reduceRight(callbackfn: (previousValue: U, currentValue: V, currentIndex: number, array: V[]) => U, initialValue?: U): U { // @ts-ignore return this.items.reduceRight.apply(this.items, arguments); } /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: V, index: number, obj: V[]) => boolean, thisArg?: any): V | undefined { return this.items.find(predicate, thisArg); } /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: V, index: number, obj: V[]) => unknown, thisArg?: any): number { return this.items.findIndex(predicate, thisArg); } /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: V, start?: number, end?: number): this { throw new Error("ArraySchema#fill() not implemented"); } /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): this { throw new Error("ArraySchema#copyWithin() not implemented"); } /** * Returns a string representation of an array. */ toString(): string { return this.items.toString(); } /** * Returns a string representation of an array. The elements are converted to string using their toLocalString methods. */ toLocaleString(): string { return this.items.toLocaleString() }; /** Iterator */ [Symbol.iterator](): ArrayIterator { return this.items[Symbol.iterator](); } static get [Symbol.species]() { return ArraySchema; } // WORKAROUND for compatibility // - TypeScript 4 defines @@unscopables as a function // - TypeScript 5 defines @@unscopables as an object [Symbol.unscopables]: any; /** * Returns an iterable of key, value pairs for every entry in the array */ entries(): ArrayIterator<[number, V]> { return this.items.entries(); } /** * Returns an iterable of keys in the array */ keys(): ArrayIterator { return this.items.keys(); } /** * Returns an iterable of values in the array */ values(): ArrayIterator { return this.items.values(); } /** * Determines whether an array includes a certain element, returning true or false as appropriate. * @param searchElement The element to search for. * @param fromIndex The position in this array at which to begin searching for searchElement. */ includes(searchElement: V, fromIndex?: number): boolean { return this.items.includes(searchElement, fromIndex); } // // ES2022 // /** * Calls a defined callback function on each element of an array. Then, flattens the result into * a new array. * This is identical to a map followed by flat with depth 1. * * @param callback A function that accepts up to three arguments. The flatMap method calls the * callback function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callback function. If * thisArg is omitted, undefined is used as the this value. */ // @ts-ignore flatMap(callback: (this: This, value: V, index: number, array: V[]) => U | ReadonlyArray, thisArg?: This): U[] { // @ts-ignore throw new Error("ArraySchema#flatMap() is not supported."); } /** * Returns a new array with all sub-array elements concatenated into it recursively up to the * specified depth. * * @param depth The maximum recursion depth */ // @ts-ignore flat(this: A, depth?: D): any { throw new Error("ArraySchema#flat() is not supported."); } findLast() { // @ts-ignore return this.items.findLast.apply(this.items, arguments); } findLastIndex(...args: any[]) { // @ts-ignore return this.items.findLastIndex.apply(this.items, arguments); } // // ES2023 // with(index: number, value: V): ArraySchema { const copy = this.items.slice(); // Allow negative indexing from the end if (index < 0) index += this.length; copy[index] = value; return new ArraySchema(...copy); } toReversed(): V[] { return this.items.slice().reverse(); } toSorted(compareFn?: (a: V, b: V) => number): V[] { return this.items.slice().sort(compareFn); } toSpliced(start: number, deleteCount: number, ...items: V[]): V[]; toSpliced(start: number, deleteCount?: number): V[]; // @ts-ignore toSpliced(start: unknown, deleteCount?: unknown, ...items?: unknown[]): V[] { const copy = this.items.slice(); // forward `arguments` so an omitted deleteCount differs from an explicit undefined // @ts-ignore copy.splice.apply(copy, arguments); return copy; } shuffle() { return this.move((_) => { let currentIndex = this.items.length; while (currentIndex != 0) { let randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; [this[currentIndex], this[randomIndex]] = [this[randomIndex], this[currentIndex]]; } }); } /** * Allows to move items around in the array. * * Example: * state.cards.move((cards) => { * [cards[4], cards[3]] = [cards[3], cards[4]]; * [cards[3], cards[2]] = [cards[2], cards[3]]; * [cards[2], cards[0]] = [cards[0], cards[2]]; * [cards[1], cards[1]] = [cards[1], cards[1]]; * [cards[0], cards[0]] = [cards[0], cards[0]]; * }) * * @param cb * @returns */ move(cb: (arr: this) => void) { this.isMovingItems = true; cb(this); this.isMovingItems = false; return this; } /** * Encoder-only. Reads the staged-snapshot (`tmpItems`) so the encoder can * resolve a wire-index even after the user has mutated `items` mid-tick. * The decoder reads `items[index]` directly — see `decodeArray` and * `$deleteByIndex` below. */ [$getByIndex](index: number, isEncodeAll: boolean = false): any { const self = this[$proxyTarget] ?? this; // called via Proxy — one trap here beats one per field read return (isEncodeAll) ? self.items[index] : self.deletedIndexes[index] ? self.items[index] : self.tmpItems[index] || self.items[index]; } [$deleteByIndex](index: number): void { const self = this[$proxyTarget] ?? this; self.items[index] = undefined; self._needsCompaction = true; } protected [$onEncodeEnd]() { // No unwrap: ChangeTree's gated sites are the only callers and they // invoke on `refTarget` (the raw target) already. const staged = this.tmpItems; this.tmpItems = this.items.slice(); this.replacedItems = undefined; if (this.deletedIndexes.length > 0) { // compaction just closed the staged holes — everything above the // lowest one slid down a slot this.$reindexChildren(0, staged); this.deletedIndexes.length = 0; } } protected [$onDecodeEnd]() { const self = this[$proxyTarget] ?? this; if (self._needsCompaction) { self._needsCompaction = false; self.items = self.items.filter((item) => item !== undefined); } } [$resyncPrune]( visited: Set, prune: (value: V, identity: number | string) => void, keep: (value: V) => void, ): void { // `items` is hole-free here: the decode loop's $onDecodeEnd already // ran, and a full-sync emits dense ADDs (no DELETEs, no gap-writes) // so no compaction happened mid-decode. Visited indexes may still be // sparse (ADD_BY_REFID resolves to the current client-side index). const self = this[$proxyTarget] ?? this; const items = self.items; let removed = false; for (let i = 0; i < items.length; i++) { const value = items[i]; if (visited.has(i)) { keep(value); continue; } removed = true; prune(value, i); self[$deleteByIndex](i); } if (removed) { self[$onDecodeEnd](); } // compact the holes } toArray() { return this.items.slice(0); } toJSON(): (V extends { toJSON(...args: any[]): infer R } ? R : V)[] { return this.toArray().map((value: any) => { return (typeof (value['toJSON']) === "function") ? value['toJSON']() : value; }); } // // Decoding utilities // clone(isDecoding?: boolean): ArraySchema { let cloned: ArraySchema; if (isDecoding) { cloned = new ArraySchema(); cloned.push(...this.items); } else { cloned = new ArraySchema(...this.map(item => ( (item[$changes]) ? (item as any as Schema).clone() : item ))); } return cloned; }; } registerType("array", { constructor: ArraySchema });