Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

cordet

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cordet - npm Package Compare versions

Comparing version 0.0.1 to 0.0.2

dist/myers.d.ts

168

dist/index.d.ts

@@ -1,165 +0,3 @@

declare module "myers" {
export type GenericIndexable<T> = {
[key: number]: T;
readonly length: number;
};
type TypedArray = Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Float32Array | Float64Array;
export type Indexable<T> = string | T[] | TypedArray | GenericIndexable<T>;
export interface Sliceable<T> extends GenericIndexable<T> {
slice(start: number, end?: number): this;
}
type Vec4 = [number, number, number, number];
type Vec3 = [number, number, number];
export function diff_core(i: number, N: number, j: number, M: number, eq: (i: number, j: number) => boolean): IterableIterator<Vec4>;
export function diff<T extends Indexable<unknown>>(xs: T, ys: T): IterableIterator<Vec4>;
export function lcs<T extends Indexable<unknown>>(xs: T, ys: T): IterableIterator<Vec3>;
export function calcPatch<T, S extends Sliceable<T>>(xs: S, ys: S): Generator<[number, number, S]>;
export function applyPatch<T, S extends Sliceable<T>>(xs: S, patch: Iterable<[number, number, S]>): Generator<S>;
}
declare module "utils" {
export const isNull: (obj: any) => boolean;
export const isUndefined: (obj: any) => boolean;
export const isBoolean: (obj: any) => boolean;
export const isString: (obj: any) => boolean;
export const isNumber: (obj: any) => boolean;
export const isArray: (arg: any) => arg is any[];
export const isObject: (obj: any) => boolean;
export const isEmptyObject: (obj: any) => boolean;
export const isValue: (obj: any) => boolean;
export function isArrayEqual(a: any[], b: any[]): boolean;
export function getTime(): number;
export function getFixedTail(n: number, length: number): string;
export function getStringHash(str: string): number;
export function getHash(str: string): number;
export function sum(arr: number[]): number;
export function last<T>(arr: T[]): T;
export function shuffle<T>(arr: T[], copy?: boolean): T[];
export function randomString(n: number): string;
export function getMidPoint(start: number, end: number): number;
export function getInsertionIndex<T>(arr: T[], item: T, compareFn: (a: T, b: T) => number): number;
export function mapValues<T, V>(value: T[] | {
[i: string]: T;
}, f: (value: T, key: string | number) => V): V[] | {
[i: string]: V;
};
export const memoize: (...args: any[]) => any;
export function isArrayShallowEqual<T>(a: T[], b: T[]): boolean;
export function isArrayStartingWith<T>(base: T[], start: T[]): boolean;
export function walkTree<T>(node: any, f: (node: any) => void): any;
}
declare module "treeArray" {
type DiffValue = null | undefined | number | boolean | string;
type DiffResult = ["+" | "-" | "=", DiffValue, number][];
export function getArrayDiff(a: DiffValue[], b: DiffValue[]): DiffResult;
import { StoreObject, StoreObjectValue } from "store";
export function getArrayDiffMyers(a: any[], b: any[]): ["+" | "-" | "=", string, number][];
export function getArrayIndex(arrayIndex: StoreObject, arr: StoreObjectValue[], randomOffset?: number, DELETED?: undefined | string): StoreObject;
export function getArrayFromIndex(arrayIndex: {
[i: string]: any;
}, DELETED?: string | undefined): any[];
export function getOrderByNumberPath(a: string, b: string): number;
}
declare module "store" {
export const DELETED = "$$deleted$$";
export type StoreObject = {
[index: string]: StoreObjectValue;
};
export type StoreObjectValue = string | number | boolean | undefined | null;
type RowValue = StoreObjectValue | typeof DELETED;
type Row = {
client: string;
time: string;
id: string;
key: string;
value: RowValue;
};
export class Store {
rows: Row[];
indexByTime: {
[i: string]: Row;
};
indexByIdKey: {
[i: string]: {
[i: string]: Row[];
};
};
snapshot: Set<Row> | null;
client: string;
constructor(client: string);
addRow(row: Row): void;
addRows(rows: Row[]): void;
fork(client: string): Store;
merge(store: Store): void;
now(): number;
getTime(): string;
getObjectVersion(id: string): number;
getObjectVersionId(id: string): string;
getObjectKeys(id: string): string[];
getObjectValue(id: string, key: string): RowValue;
getObject(id: string): StoreObject;
getRows(from?: string): Row[];
getSnapshotRows(f: () => void): Row[];
private setObjectValue;
private deleteObjectValue;
setObject(id: string, values: StoreObject, updateOnly?: boolean): void;
}
}
declare module "structure" {
import type { StoreObject, StoreObjectValue } from "store";
export type StructuredValue = StructuredObjectValue | StructuredArrayValue | StoreObjectValue;
export type StructuredArrayValue = StructuredValue[];
export type StructuredObjectValue = {
[i: string]: StructuredValue;
};
export type FlattenedValue = StoreObjectValue | StoreObjectValue[] | StoreObject;
export type FlattenedObjects = {
[i: string]: FlattenedValue;
};
export function getReferenceId(value: any): string;
export function getFlattened(id: string, value: StructuredValue, createId: (value: StoreObjectValue, keyPath: (string | number)[]) => string): FlattenedObjects;
export function getFlattenedValue(value: StructuredValue, keyPath: (string | number)[], objects: FlattenedObjects, createId: (value: StoreObjectValue, keyPath: (string | number)[]) => string): FlattenedValue;
export function getStructured(value: FlattenedValue | undefined, get: (id: string, keyPath: (string | number)[]) => FlattenedValue | undefined, keyPath?: (string | number)[]): StructuredValue;
}
declare module "shelf" {
import { Store } from "store";
import { StructuredValue } from "structure";
export class Shelf {
store: Store;
keyPathIds: {
[i: string]: string;
};
constructor(store: Store);
getOffset: (client: any) => number;
private getKeyPathString;
private setObjectId;
private deleteObjectId;
private getObjectId;
getGeneratedObjectId(): string;
private setValue;
private setArray;
private setObject;
private setFlatObject;
private getTyped;
set(id: string, value: StructuredValue): void;
get(id: string): StructuredValue | undefined;
fork(client: string): Shelf;
merge(shelf: Shelf): void;
}
}
declare module "useSocket" {
export function useSocket(url: any): any;
}
declare module "useShelf" {
import { Shelf } from "shelf";
export function useShelf(client: string, url: string, name: string, isOnline?: boolean): [Shelf, () => void];
}
declare module "index" {
export { Store } from "store";
export { Shelf } from "shelf";
export { useShelf } from "useShelf";
}
declare module "shelf.test" { }
declare module "store.test" { }
declare module "structure.test" { }
declare module "treeArray.test" { }
declare module "utils.test" { }
export { Store } from "./store";
export { Shelf } from "./shelf";
export { useShelf } from "./useShelf";

@@ -1,1134 +0,3 @@

var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
Shelf: () => Shelf,
Store: () => Store,
useShelf: () => useShelf
});
module.exports = __toCommonJS(src_exports);
// node_modules/diff/lib/index.mjs
function Diff() {
}
Diff.prototype = {
diff: function diff(oldString, newString) {
var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
var callback = options.callback;
if (typeof options === "function") {
callback = options;
options = {};
}
this.options = options;
var self = this;
function done(value) {
if (callback) {
setTimeout(function() {
callback(void 0, value);
}, 0);
return true;
} else {
return value;
}
}
oldString = this.castInput(oldString);
newString = this.castInput(newString);
oldString = this.removeEmpty(this.tokenize(oldString));
newString = this.removeEmpty(this.tokenize(newString));
var newLen = newString.length, oldLen = oldString.length;
var editLength = 1;
var maxEditLength = newLen + oldLen;
if (options.maxEditLength) {
maxEditLength = Math.min(maxEditLength, options.maxEditLength);
}
var bestPath = [{
newPos: -1,
components: []
}];
var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
return done([{
value: this.join(newString),
count: newString.length
}]);
}
function execEditLength() {
for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
var basePath = void 0;
var addPath = bestPath[diagonalPath - 1], removePath = bestPath[diagonalPath + 1], _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
if (addPath) {
bestPath[diagonalPath - 1] = void 0;
}
var canAdd = addPath && addPath.newPos + 1 < newLen, canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
if (!canAdd && !canRemove) {
bestPath[diagonalPath] = void 0;
continue;
}
if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
basePath = clonePath(removePath);
self.pushComponent(basePath.components, void 0, true);
} else {
basePath = addPath;
basePath.newPos++;
self.pushComponent(basePath.components, true, void 0);
}
_oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath);
if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
} else {
bestPath[diagonalPath] = basePath;
}
}
editLength++;
}
if (callback) {
(function exec() {
setTimeout(function() {
if (editLength > maxEditLength) {
return callback();
}
if (!execEditLength()) {
exec();
}
}, 0);
})();
} else {
while (editLength <= maxEditLength) {
var ret = execEditLength();
if (ret) {
return ret;
}
}
}
},
pushComponent: function pushComponent(components, added, removed) {
var last2 = components[components.length - 1];
if (last2 && last2.added === added && last2.removed === removed) {
components[components.length - 1] = {
count: last2.count + 1,
added,
removed
};
} else {
components.push({
count: 1,
added,
removed
});
}
},
extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath, commonCount = 0;
while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
newPos++;
oldPos++;
commonCount++;
}
if (commonCount) {
basePath.components.push({
count: commonCount
});
}
basePath.newPos = newPos;
return oldPos;
},
equals: function equals(left, right) {
if (this.options.comparator) {
return this.options.comparator(left, right);
} else {
return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
}
},
removeEmpty: function removeEmpty(array) {
var ret = [];
for (var i = 0; i < array.length; i++) {
if (array[i]) {
ret.push(array[i]);
}
}
return ret;
},
castInput: function castInput(value) {
return value;
},
tokenize: function tokenize(value) {
return value.split("");
},
join: function join(chars) {
return chars.join("");
}
};
function buildValues(diff3, components, newString, oldString, useLongestToken) {
var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0;
for (; componentPos < componentLen; componentPos++) {
var component = components[componentPos];
if (!component.removed) {
if (!component.added && useLongestToken) {
var value = newString.slice(newPos, newPos + component.count);
value = value.map(function(value2, i) {
var oldValue = oldString[oldPos + i];
return oldValue.length > value2.length ? oldValue : value2;
});
component.value = diff3.join(value);
} else {
component.value = diff3.join(newString.slice(newPos, newPos + component.count));
}
newPos += component.count;
if (!component.added) {
oldPos += component.count;
}
} else {
component.value = diff3.join(oldString.slice(oldPos, oldPos + component.count));
oldPos += component.count;
if (componentPos && components[componentPos - 1].added) {
var tmp = components[componentPos - 1];
components[componentPos - 1] = components[componentPos];
components[componentPos] = tmp;
}
}
}
var lastComponent = components[componentLen - 1];
if (componentLen > 1 && typeof lastComponent.value === "string" && (lastComponent.added || lastComponent.removed) && diff3.equals("", lastComponent.value)) {
components[componentLen - 2].value += lastComponent.value;
components.pop();
}
return components;
}
function clonePath(path) {
return {
newPos: path.newPos,
components: path.components.slice(0)
};
}
var characterDiff = new Diff();
var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
var reWhitespace = /\S/;
var wordDiff = new Diff();
wordDiff.equals = function(left, right) {
if (this.options.ignoreCase) {
left = left.toLowerCase();
right = right.toLowerCase();
}
return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
};
wordDiff.tokenize = function(value) {
var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/);
for (var i = 0; i < tokens.length - 1; i++) {
if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
tokens[i] += tokens[i + 2];
tokens.splice(i + 1, 2);
i--;
}
}
return tokens;
};
var lineDiff = new Diff();
lineDiff.tokenize = function(value) {
var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
if (!linesAndNewlines[linesAndNewlines.length - 1]) {
linesAndNewlines.pop();
}
for (var i = 0; i < linesAndNewlines.length; i++) {
var line = linesAndNewlines[i];
if (i % 2 && !this.options.newlineIsToken) {
retLines[retLines.length - 1] += line;
} else {
if (this.options.ignoreWhitespace) {
line = line.trim();
}
retLines.push(line);
}
}
return retLines;
};
var sentenceDiff = new Diff();
sentenceDiff.tokenize = function(value) {
return value.split(/(\S.+?[.!?])(?=\s+|$)/);
};
var cssDiff = new Diff();
cssDiff.tokenize = function(value) {
return value.split(/([{}:;,]|\s+)/);
};
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function(obj2) {
return typeof obj2;
};
} else {
_typeof = function(obj2) {
return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
};
}
return _typeof(obj);
}
var objectPrototypeToString = Object.prototype.toString;
var jsonDiff = new Diff();
jsonDiff.useLongestToken = true;
jsonDiff.tokenize = lineDiff.tokenize;
jsonDiff.castInput = function(value) {
var _this$options = this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function(k, v) {
return typeof v === "undefined" ? undefinedReplacement : v;
} : _this$options$stringi;
return typeof value === "string" ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, " ");
};
jsonDiff.equals = function(left, right) {
return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, "$1"), right.replace(/,([\r\n])/g, "$1"));
};
function canonicalize(obj, stack, replacementStack, replacer, key) {
stack = stack || [];
replacementStack = replacementStack || [];
if (replacer) {
obj = replacer(key, obj);
}
var i;
for (i = 0; i < stack.length; i += 1) {
if (stack[i] === obj) {
return replacementStack[i];
}
}
var canonicalizedObj;
if ("[object Array]" === objectPrototypeToString.call(obj)) {
stack.push(obj);
canonicalizedObj = new Array(obj.length);
replacementStack.push(canonicalizedObj);
for (i = 0; i < obj.length; i += 1) {
canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
}
stack.pop();
replacementStack.pop();
return canonicalizedObj;
}
if (obj && obj.toJSON) {
obj = obj.toJSON();
}
if (_typeof(obj) === "object" && obj !== null) {
stack.push(obj);
canonicalizedObj = {};
replacementStack.push(canonicalizedObj);
var sortedKeys = [], _key;
for (_key in obj) {
if (obj.hasOwnProperty(_key)) {
sortedKeys.push(_key);
}
}
sortedKeys.sort();
for (i = 0; i < sortedKeys.length; i += 1) {
_key = sortedKeys[i];
canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
}
stack.pop();
replacementStack.pop();
} else {
canonicalizedObj = obj;
}
return canonicalizedObj;
}
var arrayDiff = new Diff();
arrayDiff.tokenize = function(value) {
return value.slice();
};
arrayDiff.join = arrayDiff.removeEmpty = function(value) {
return value;
};
function diffArrays(oldArr, newArr, callback) {
return arrayDiff.diff(oldArr, newArr, callback);
}
// src/myers.ts
function diff_internal(state, c) {
const { b, eq, stack_base } = state;
let { i, N, j, M, Z, stack_top } = state;
for (; ; ) {
switch (c) {
case 0: {
Z_block:
while (N > 0 && M > 0) {
b.fill(0, 0, 2 * Z);
const W = N - M;
const L = N + M;
const parity = L & 1;
const offsetx = i + N - 1;
const offsety = j + M - 1;
const hmax = (L + parity) / 2;
let z;
h_loop:
for (let h = 0; h <= hmax; h++) {
const kmin = 2 * Math.max(0, h - M) - h;
const kmax = h - 2 * Math.max(0, h - N);
for (let k = kmin; k <= kmax; k += 2) {
const gkm = b[k - 1 - Z * Math.floor((k - 1) / Z)];
const gkp = b[k + 1 - Z * Math.floor((k + 1) / Z)];
const u = k === -h || k !== h && gkm < gkp ? gkp : gkm + 1;
const v = u - k;
let x = u;
let y = v;
while (x < N && y < M && eq(i + x, j + y))
x++, y++;
b[k - Z * Math.floor(k / Z)] = x;
if (parity === 1 && (z = W - k) >= 1 - h && z < h && x + b[Z + z - Z * Math.floor(z / Z)] >= N) {
if (h > 1 || x !== u) {
stack_base[stack_top++] = i + x;
stack_base[stack_top++] = N - x;
stack_base[stack_top++] = j + y;
stack_base[stack_top++] = M - y;
N = u;
M = v;
Z = 2 * (Math.min(N, M) + 1);
continue Z_block;
} else
break h_loop;
}
}
for (let k = kmin; k <= kmax; k += 2) {
const pkm = b[Z + k - 1 - Z * Math.floor((k - 1) / Z)];
const pkp = b[Z + k + 1 - Z * Math.floor((k + 1) / Z)];
const u = k === -h || k !== h && pkm < pkp ? pkp : pkm + 1;
const v = u - k;
let x = u;
let y = v;
while (x < N && y < M && eq(offsetx - x, offsety - y))
x++, y++;
b[Z + k - Z * Math.floor(k / Z)] = x;
if (parity === 0 && (z = W - k) >= -h && z <= h && x + b[z - Z * Math.floor(z / Z)] >= N) {
if (h > 0 || x !== u) {
stack_base[stack_top++] = i + N - u;
stack_base[stack_top++] = u;
stack_base[stack_top++] = j + M - v;
stack_base[stack_top++] = v;
N = N - x;
M = M - y;
Z = 2 * (Math.min(N, M) + 1);
continue Z_block;
} else
break h_loop;
}
}
}
if (N === M)
continue;
if (M > N) {
i += N;
j += N;
M -= N;
N = 0;
} else {
i += M;
j += M;
N -= M;
M = 0;
}
break;
}
if (N + M !== 0) {
if (state.pxe === i || state.pye === j) {
state.pxe = i + N;
state.pye = j + M;
} else {
const sx = state.pxs;
state.oxs = state.pxs;
state.oxe = state.pxe;
state.oys = state.pys;
state.oye = state.pye;
state.pxs = i;
state.pxe = i + N;
state.pys = j;
state.pye = j + M;
if (sx >= 0) {
state.i = i;
state.N = N;
state.j = j;
state.M = M;
state.Z = Z;
state.stack_top = stack_top;
return 1;
}
}
}
}
case 1: {
if (stack_top === 0)
return 2;
M = stack_base[--stack_top];
j = stack_base[--stack_top];
N = stack_base[--stack_top];
i = stack_base[--stack_top];
Z = 2 * (Math.min(N, M) + 1);
c = 0;
}
}
}
}
var DiffGen = class {
constructor(state) {
this.state = state;
this.c = 0;
this.result = {
value: null,
done: false
};
}
[Symbol.iterator]() {
return this;
}
next() {
const { state, result } = this;
if (this.c > 1) {
result.done = true;
result.value = void 0;
return result;
}
const c = diff_internal(state, this.c);
this.c = c;
if (c === 1) {
result.value = [state.oxs, state.oxe, state.oys, state.oye];
return result;
}
if (state.pxs >= 0) {
result.value = [state.pxs, state.pxe, state.pys, state.pye];
return result;
}
result.done = true;
result.value = void 0;
return result;
}
};
var LCSGen = class {
constructor(diff3, N) {
this.diff = diff3;
this.N = N;
this.i = 0;
this.j = 0;
}
[Symbol.iterator]() {
return this;
}
next() {
const rec = this.diff.next();
if (rec.done) {
const { i: i2, j: j2, N } = this;
if (i2 < N) {
rec.done = false;
rec.value = [i2, j2, N - i2];
this.i = N;
}
return rec;
}
const v = rec.value;
const sx = v[0];
const ex = v[1];
const ey = v[3];
const { i, j } = this;
if (i !== sx) {
v.length--;
v[0] = i;
v[1] = j;
v[2] = sx - i;
}
this.i = ex;
this.j = ey;
return rec;
}
};
// src/utils.ts
var isNull = (obj) => obj === null;
var isUndefined = (obj) => typeof obj === "undefined";
var isBoolean = (obj) => typeof obj === "boolean";
var isString = (obj) => typeof obj === "string";
var isNumber = (obj) => typeof obj === "number";
var isArray = Array.isArray;
var isObject = (obj) => !isNull(obj) && !isArray(obj) && typeof obj === "object";
function getFixedTail(n, length) {
const tail = n.toString().substring(-length);
const head = length - tail.length > 0 ? "0".repeat(length - tail.length) : "";
return `${head}${tail}`;
}
function getStringHashReducer(prevHash, currVal) {
return (prevHash << 5) - prevHash + currVal.charCodeAt(0) | 0;
}
function getStringHash(str) {
return str.split("").reduce(getStringHashReducer, 0);
}
function sum(arr) {
return arr.reduce((a, b) => a + b, 0);
}
function last(arr) {
return arr[arr.length - 1];
}
function randomString(n) {
return Math.random().toString(36).slice(0 - n);
}
function getMidPoint(start, end) {
return Math.floor((end - start) / 2) + start;
}
function getInsertionIndex(arr, item, compareFn) {
const itemsCount = arr.length;
if (itemsCount === 0) {
return 0;
}
const lastItem = arr[itemsCount - 1];
if (compareFn(item, lastItem) >= 0) {
return itemsCount;
}
let start = 0;
let end = itemsCount - 1;
let index = getMidPoint(start, end);
while (start < end) {
const curItem = arr[index];
const comparison = compareFn(item, curItem);
if (comparison === 0) {
break;
} else if (comparison < 0) {
end = index;
} else {
start = index + 1;
}
index = getMidPoint(start, end);
}
return index;
}
function mapValues(value, f) {
if (isObject(value)) {
return Object.fromEntries(
Object.entries(value).map(([k, v]) => [k, f(v, k)])
);
}
if (isArray(value)) {
return value.map((v, i) => f(v, i));
}
throw Error(`mapValues: got something unexpected`);
}
var createCacheKeyFromArgs = (args) => args.length === 1 ? args[0] : JSON.stringify(args);
var memoize = function(fn) {
const cache = /* @__PURE__ */ new Map();
return function() {
const cacheKey = createCacheKeyFromArgs(Array.from(arguments));
if (cache.has(cacheKey)) {
return cache.get(cacheKey);
}
const asyncFn = fn.apply(this, arguments);
cache.set(cacheKey, asyncFn);
return asyncFn;
};
};
function isArrayShallowEqual(a, b) {
if (a.length !== b.length)
return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
function isArrayStartingWith(base, start) {
for (let i = 0; i < start.length; i++) {
if (base[i] !== start[i]) {
return false;
}
}
return true;
}
// src/treeArray.ts
function getArrayDiff(a, b) {
const result = [];
if (a.length === 0) {
return b.map((value, index2) => ["+", value, index2]);
}
if (b.length === 0) {
return a.map((value, index2) => ["-", value, index2]);
}
const diff3 = diffArrays(a, b);
let index = 0;
for (const d of diff3) {
for (const v of d.value) {
const operation = !d.added && !d.removed ? "=" : d.added ? "+" : "-";
result.push([operation, v, operation === "+" ? index - 1 : index]);
if (operation === "=" || operation === "-")
index++;
}
}
return result;
}
function getArrayIndex(arrayIndex, arr, randomOffset = 1, DELETED2 = void 0) {
if (randomOffset < 1) {
throw Error(`getArrayIndex: randomOffset has to be > 1`);
}
const a = getArrayFromIndex(arrayIndex);
const b = arr;
if (isArrayShallowEqual(a, b)) {
return arrayIndex;
}
const result = {};
const pairs = Object.entries(arrayIndex).filter(([k, v]) => v !== DELETED2).sort((a2, b2) => getOrderByNumberPath(a2[0], b2[0]));
if (isArrayStartingWith(b, a)) {
const maxIndex2 = pairs.length ? last(pairs)[0] : "0";
const offset = parseInt(maxIndex2.split(".")[0] || "0");
for (let i = a.length; i < b.length; i++) {
const indexKey = `${offset + randomOffset + i - a.length}`;
result[indexKey] = b[i];
}
return { ...arrayIndex, ...result };
}
const diff3 = getArrayDiff(a, b);
const maxIndex = pairs.length ? last(pairs)[0] : "0";
let lastEqualIndex = null;
let queue = [];
function flush() {
const prefix = lastEqualIndex === null ? "" : `${pairs[lastEqualIndex][0]}.`;
const offset = pairs.length === 0 ? randomOffset : lastEqualIndex === null ? parseInt(pairs[0][0].split(".").shift()) - queue.length - randomOffset + 1 : randomOffset;
for (let i = 0; i < queue.length; i++) {
const indexKey = `${prefix}${offset + i}`;
result[indexKey] = queue[i];
}
queue = [];
}
for (const [op, value, index] of diff3) {
if (op === "+") {
queue.push(value);
}
if (op === "=") {
flush();
result[pairs[index][0]] = value;
lastEqualIndex = index;
}
if (op === "-") {
result[pairs[index][0]] = DELETED2;
}
}
flush();
return result;
}
function getArrayFromIndex(arrayIndex, DELETED2 = void 0) {
return Object.entries(arrayIndex).sort((a, b) => getOrderByNumberPath(a[0], b[0])).map(([i, v]) => v).filter((v) => v !== DELETED2);
}
function getOrderByNumberPath(a, b) {
const aa = a.split(".");
const bb = b.split(".");
const l = Math.max(aa.length, bb.length);
for (let i = 0; i < l; i++) {
const av = parseInt(aa[i]);
const bv = parseInt(bb[i]);
if (bv > av || isNaN(av))
return -1;
if (av > bv || isNaN(bv))
return 1;
}
return 0;
}
// src/store.ts
var DELETED = "$$deleted$$";
function insertRowOrdered(rows, row) {
const insertIndex = getInsertionIndex(
rows,
row,
(a, b) => getOrderByNumberPath(a.time, b.time)
);
rows.splice(insertIndex, 0, row);
return row;
}
function isValidStoreValue(value) {
return isString(value) || isNumber(value) || isBoolean(value) || isNull(value) || isUndefined(value);
}
function isValidRowValue(value) {
return isValidStoreValue(value) || value === DELETED;
}
var Store = class {
constructor(client) {
this.rows = [];
this.indexByTime = {};
this.indexByIdKey = {};
this.snapshot = null;
this.client = client;
}
addRow(row) {
if (this.indexByTime[row.time])
return;
if (!isValidRowValue(row.value)) {
throw Error(
`store.addRow: row value type "${typeof row.value}" not supported`
);
}
this.indexByTime[row.time] = row;
if (!this.indexByIdKey[row.id]) {
this.indexByIdKey[row.id] = {};
}
if (!this.indexByIdKey[row.id][row.key]) {
this.indexByIdKey[row.id][row.key] = [];
}
insertRowOrdered(this.indexByIdKey[row.id][row.key], row);
insertRowOrdered(this.rows, row);
}
addRows(rows) {
for (const row of rows) {
this.addRow(row);
}
}
fork(client) {
const store = new Store(client);
store.addRows(this.rows);
return store;
}
merge(store) {
this.addRows(store.rows);
}
now() {
return Date.now();
}
getTime() {
return [
this.now(),
getFixedTail(this.rows.length, 4),
getFixedTail(Math.abs(getStringHash(this.client)), 4)
].join(".");
}
getObjectVersion(id) {
return sum(
this.getObjectKeys(id).map((key) => this.indexByIdKey[id][key].length)
);
}
getObjectVersionId(id) {
return `${id}/${this.getObjectVersion(id)}`;
}
getObjectKeys(id) {
return Object.keys(this.indexByIdKey[id] || {});
}
getObjectValue(id, key) {
if (!this.indexByIdKey[id] || !this.indexByIdKey[id][key])
return;
const row = last(this.indexByIdKey[id][key]);
if (this.snapshot)
this.snapshot.add(row);
return row.value;
}
getObject(id) {
return Object.fromEntries(
this.getObjectKeys(id).map((key) => [key, this.getObjectValue(id, key)]).filter(([k, v]) => v !== DELETED)
);
}
getRows(from) {
return from ? this.rows.filter((r) => r.time > from) : [...this.rows];
}
getSnapshotRows(f) {
this.snapshot = /* @__PURE__ */ new Set();
f();
const snapshot = Array.from(this.snapshot).filter(
(r) => r.value !== DELETED
);
this.snapshot = null;
return snapshot;
}
setObjectValue(id, key, value) {
if (this.getObjectValue(id, key) === value)
return;
const row = { time: this.getTime(), client: this.client, id, key, value };
this.addRow(row);
}
deleteObjectValue(id, key) {
const value = DELETED;
const row = { time: this.getTime(), client: this.client, id, key, value };
this.addRow(row);
}
setObject(id, values, updateOnly = false) {
const keys = Object.keys(values);
const currentKeys = this.getObjectKeys(id);
for (const key of keys) {
this.setObjectValue(id, key, values[key]);
}
if (updateOnly)
return;
for (const key of currentKeys) {
if (!keys.includes(key)) {
this.deleteObjectValue(id, key);
}
}
}
};
// src/structure.ts
function getReferenceString(id) {
return `$ref:${id}`;
}
function getReferenceId(value) {
if (typeof value === "string" && value.startsWith(`$ref:`)) {
return value.replace(`$ref:`, "");
}
}
function getFlattened(id, value, createId) {
const objects = {};
const result = getFlattenedValue(value, [], objects, createId);
if (objects[id])
throw Error(`getFlattened: ${id} already exists`);
objects[id] = result;
return objects;
}
function getFlattenedValue(value, keyPath = [], objects, createId) {
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null || value === void 0) {
return value;
}
if (isObject(value) || isArray(value)) {
const result = mapValues(
value,
(v, i) => getFlattenedValue(v, [...keyPath, i], objects, createId)
);
if (keyPath.length) {
const id = createId(value, keyPath);
if (objects[id]) {
console.warn(value, objects);
throw Error(`getFlattenedValue: ${id} already exists`);
}
objects[id] = result;
return getReferenceString(id);
} else {
return result;
}
}
console.error(value);
throw Error(`getFlattenedValue: ${typeof value} not supported`);
}
function getStructured(value, get, keyPath = []) {
if (value === void 0) {
return value;
}
const referenceId = getReferenceId(value);
if (referenceId) {
return getStructured(get(referenceId, keyPath), get, keyPath);
}
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null || value === void 0) {
return value;
}
if (isObject(value) || isArray(value)) {
return mapValues(value, (v, i) => getStructured(v, get, [...keyPath, i]));
}
}
// src/shelf.ts
var ValueKey = "value";
var Shelf = class {
constructor(store) {
this.keyPathIds = {};
this.getOffset = (client) => {
return parseInt(getFixedTail(getStringHash(client), 4)) + this.store.rows.length;
};
this.store = store;
}
getKeyPathString(keyPath) {
return keyPath.join(".");
}
setObjectId(keyPath, id) {
this.keyPathIds[this.getKeyPathString(keyPath)] = id;
}
deleteObjectId(keyPath) {
delete this.keyPathIds[this.getKeyPathString(keyPath)];
}
getObjectId(keyPath) {
const key = this.getKeyPathString(keyPath);
if (!this.keyPathIds[key]) {
this.setObjectId(keyPath, this.getGeneratedObjectId());
}
return this.keyPathIds[key];
}
getGeneratedObjectId() {
return randomString(8);
}
setValue(id, value) {
this.store.setObject(id, { [ValueKey]: value, _type: "value" });
}
setArray(id, value, keyPath) {
const arrayIndexesA = this.store.getObject(id) || {};
delete arrayIndexesA._type;
const arrayIndexesB = getArrayIndex(
arrayIndexesA,
value,
this.getOffset(this.store.client),
DELETED
);
const arrayB = getArrayFromIndex(arrayIndexesB);
for (let i = 0; i < arrayB.length; i++) {
if (arrayB[i] === DELETED) {
this.deleteObjectId([...keyPath, i]);
}
}
this.store.setObject(id, { ...arrayIndexesB, _type: "array" }, true);
}
setObject(id, value, updateOnly = false) {
this.store.setObject(id, { ...value, _type: "object" }, updateOnly);
}
setFlatObject(id, value, keyPath) {
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null || value === void 0) {
return this.setValue(id, value);
}
if (Array.isArray(value)) {
return this.setArray(id, value, keyPath);
}
if (isObject(value)) {
delete value._key;
return this.setObject(id, value);
}
throw Error(`shelf.setFlatObject: unkown value ${value} (${typeof value})`);
}
getTyped(id) {
const value = this.store.getObject(id);
const type = value._type;
if (type === void 0)
return;
delete value._type;
if (type === "array") {
return getArrayFromIndex(value, DELETED);
}
if (type === "value") {
return value[ValueKey];
}
return { _key: id, ...value };
}
set(id, value) {
if (isObject(value))
value["_key"] = id;
const keyPathsById = { [id]: [id] };
const flattenedObjects = getFlattened(id, value, (v, keyPath) => {
if (isObject(v)) {
if (!v["_key"]) {
v["_key"] = this.getGeneratedObjectId();
}
return v["_key"];
}
if (v && v["_key"]) {
return v["_key"];
}
const objectId = this.getObjectId([id, ...keyPath]);
keyPathsById[objectId] = [id, ...keyPath];
return objectId;
});
for (const [objectId, objectValue] of Object.entries(flattenedObjects)) {
this.setFlatObject(objectId, objectValue, keyPathsById[objectId]);
}
}
get(id) {
const value = this.getTyped(id);
if (value === void 0)
return;
return getStructured(value, (referenceId, keyPath) => {
this.setObjectId([id, ...keyPath], referenceId);
return this.getTyped(referenceId);
});
}
fork(client) {
return new Shelf(this.store.fork(client));
}
merge(shelf) {
this.store.merge(shelf.store);
}
};
// src/useShelf.ts
var import_react2 = require("react");
// src/useSocket.ts
var import_react = require("react");
function useSocket(url) {
const [socket, setStocket] = (0, import_react.useState)(null);
let timer = void 0;
let ws = null;
function onError(event) {
console.error(event);
}
function onOpen(event) {
setStocket(ws);
}
function onClose(event) {
cleanup();
}
function connect() {
ws = new WebSocket(url);
ws.addEventListener("error", onError);
ws.addEventListener("open", onOpen);
ws.addEventListener("close", onClose);
}
function cleanup() {
if (!ws)
return;
setStocket(null);
clearInterval(timer);
ws.removeEventListener("error", onError);
ws.removeEventListener("open", onOpen);
ws.removeEventListener("close", onClose);
ws.close();
ws = null;
}
(0, import_react.useEffect)(() => {
cleanup();
if (!url)
return;
timer = setInterval(() => {
if (!ws)
connect();
}, 1e3);
connect();
return cleanup;
}, [url]);
return socket;
}
// src/useShelf.ts
var getShelf = memoize(
(client, url, name) => new Shelf(new Store(client))
);
function useShelf(client, url, name, isOnline = true) {
const [update, setUpdate] = (0, import_react2.useState)(0);
const shelf = getShelf(client, url, name);
const socket = useSocket(isOnline ? url : void 0);
const onMessage = ({ data }) => {
const payload = JSON.parse(data);
const command = payload.command;
if (command === "rows" && Array.isArray(payload.rows)) {
shelf.store.addRows(payload.rows.filter((r) => r));
setUpdate(Date.now());
}
};
(0, import_react2.useEffect)(() => {
console.log("useShelf.useEffect", { url, isOnline, socket });
if (socket) {
socket.addEventListener("message", onMessage);
socket.send(JSON.stringify({ command: "join", channel: name }));
sendRows();
}
return () => {
if (socket)
socket.removeEventListener("message", onMessage);
};
}, [socket]);
function sendRows() {
if (!socket)
return;
socket.send(
JSON.stringify({ command: "rows", channel: name, rows: shelf.store.rows })
);
}
return [shelf, sendRows];
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Shelf,
Store,
useShelf
});
export { Store } from "./store";
export { Shelf } from "./shelf";
export { useShelf } from "./useShelf";
{
"name": "cordet",
"version": "0.0.1",
"version": "0.0.2",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"license": "MIT",

@@ -6,0 +7,0 @@ "devDependencies": {

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc