diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/dist/index.cjs b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/dist/index.cjs deleted file mode 100644 index e1c435d92..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/dist/index.cjs +++ /dev/null @@ -1,20650 +0,0 @@ -'use strict'; - -var zod = require('zod'); -var process$1 = require('process'); -var chalk = require('chalk'); -var lmsIsomorphic = require('@lmstudio/lms-isomorphic'); -var zodToJsonSchema = require('zod-to-json-schema'); - -function isSignalLike(value) { - return (typeof value === "object" && - value !== null && - typeof value.get === "function" && - typeof value.subscribe === "function"); -} -/** - * Base class for objects that can be subscribed to. Provides common utility methods. - */ -class Subscribable { - subscribeWithCleaner(cleaner, listener) { - const unsubscribe = this.subscribe(listener); - cleaner.register(unsubscribe); - } - subscribeOnce(listener) { - const unsubscribe = this.subscribe(data => { - unsubscribe(); - listener(data); - }); - return unsubscribe; - } - subscribeOnceWithCleaner(cleaner, listener) { - const unsubscribe = this.subscribeOnce(listener); - cleaner.register(unsubscribe); - } - derive(deriver, outputEqualsPredicate = (a, b) => a === b) { - if (isSignalLike(this)) { - return LazySignal.deriveFrom([this], deriver); - } - const thisWithGetter = this; - if (thisWithGetter.get !== undefined) { - const initialValue = thisWithGetter.get(); - if (initialValue === LazySignal.NOT_AVAILABLE) { - return LazySignal.createWithoutInitialValue(setDownstream => { - return thisWithGetter.subscribe(data => { - if (isAvailable(data)) { - setDownstream(deriver(data)); - } - }); - }); - } - const thisNarrowed = thisWithGetter; - return LazySignal.create(deriver(thisNarrowed.get()), setDownstream => { - return thisNarrowed.subscribe(data => { - setDownstream(deriver(data)); - }); - }, outputEqualsPredicate); - } - return LazySignal.createWithoutInitialValue(setDownstream => { - return this.subscribe(data => { - if (isAvailable(data)) { - setDownstream(deriver(data)); - } - }); - }, outputEqualsPredicate); - } -} - -/** - * Represents an event that can be subscribed to. Emitted events will trigger all subscribers in the - * next microtask. If multiple events are emitted, they will be triggered in the same microtask. - */ -class Event extends Subscribable { - /** - * Internal state that tracks whether the event has any subscribers. - */ - constructor() { - super(); - this.subscribers = new Set(); - /** - * Internal callback that is called when the number of subscribers goes from 0 to 1. - */ - this.onSubscribed = null; - /** - * Internal callback that is called when the number of subscribers goes from 1 to 0. - */ - this.onUnsubscribed = null; - } - emit(data) { - queueMicrotask(() => { - for (const subscriber of this.subscribers) { - subscriber(data); - } - }); - } - static create() { - const event = new Event(); - const emitter = data => { - event.emit(data); - }; - return [event, emitter]; - } - subscribe(listener) { - const previousSize = this.subscribers.size; - this.subscribers.add(listener); - if (previousSize === 0 && this.subscribers.size === 1) { - this.onSubscribed?.(); - } - return () => { - const previousSize = this.subscribers.size; - this.subscribers.delete(listener); - if (previousSize === 1 && this.subscribers.size === 0) { - this.onUnsubscribed?.(); - } - }; - } - batch({ minIdleTimeMs = 200, maxBatchTimeMs = 1000, }) { - const [batchedEvent, emitBatchedEvent] = Event.create(); - batchedEvent.onSubscribed = () => { - let batch = []; - let emitBatchTimeout = null; - let firstEventTime = 0; - const emitBatch = () => { - emitBatchTimeout = null; - emitBatchedEvent(batch); - batch = []; - }; - batchedEvent.onUnsubscribed = this.subscribe(data => { - batch.push(data); - if (emitBatchTimeout === null) { - // No scheduled batch - firstEventTime = Date.now(); - emitBatchTimeout = setTimeout(emitBatch, Math.min(minIdleTimeMs, maxBatchTimeMs)); - } - else { - // Reschedule emission - clearTimeout(emitBatchTimeout); - const timeSinceFirstEvent = Date.now() - firstEventTime; - emitBatchTimeout = setTimeout(emitBatch, Math.min(minIdleTimeMs, Math.max(0, maxBatchTimeMs - timeSinceFirstEvent))); - } - }); - }; - return batchedEvent; - } -} - -function makePromise() { - let resolve; - let reject; - const promise = new Promise((_resolve, _reject) => { - resolve = _resolve; - reject = _reject; - }); - return { promise, resolve: resolve, reject: reject }; -} - -// src/utils/env.ts -var NOTHING = Symbol.for("immer-nothing"); -var DRAFTABLE = Symbol.for("immer-draftable"); -var DRAFT_STATE = Symbol.for("immer-state"); - -// src/utils/errors.ts -var errors = process.env.NODE_ENV !== "production" ? [ - // All error codes, starting by 0: - function(plugin) { - return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`; - }, - function(thing) { - return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`; - }, - "This object has been frozen and should not be mutated", - function(data) { - return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data; - }, - "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.", - "Immer forbids circular references", - "The first or second argument to `produce` must be a function", - "The third argument to `produce` must be a function or undefined", - "First argument to `createDraft` must be a plain object, an array, or an immerable object", - "First argument to `finishDraft` must be a draft returned by `createDraft`", - function(thing) { - return `'current' expects a draft, got: ${thing}`; - }, - "Object.defineProperty() cannot be used on an Immer draft", - "Object.setPrototypeOf() cannot be used on an Immer draft", - "Immer only supports deleting array indices", - "Immer only supports setting array indices and the 'length' property", - function(thing) { - return `'original' expects a draft, got: ${thing}`; - } - // Note: if more errors are added, the errorOffset in Patches.ts should be increased - // See Patches.ts for additional errors -] : []; -function die(error, ...args) { - if (process.env.NODE_ENV !== "production") { - const e = errors[error]; - const msg = typeof e === "function" ? e.apply(null, args) : e; - throw new Error(`[Immer] ${msg}`); - } - throw new Error( - `[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf` - ); -} - -// src/utils/common.ts -var getPrototypeOf = Object.getPrototypeOf; -function isDraft(value) { - return !!value && !!value[DRAFT_STATE]; -} -function isDraftable(value) { - if (!value) - return false; - return isPlainObject$2(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor?.[DRAFTABLE] || isMap$1(value) || isSet$1(value); -} -var objectCtorString = Object.prototype.constructor.toString(); -function isPlainObject$2(value) { - if (!value || typeof value !== "object") - return false; - const proto = getPrototypeOf(value); - if (proto === null) { - return true; - } - const Ctor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor; - if (Ctor === Object) - return true; - return typeof Ctor == "function" && Function.toString.call(Ctor) === objectCtorString; -} -function each(obj, iter) { - if (getArchtype(obj) === 0 /* Object */) { - Reflect.ownKeys(obj).forEach((key) => { - iter(key, obj[key], obj); - }); - } else { - obj.forEach((entry, index) => iter(index, entry, obj)); - } -} -function getArchtype(thing) { - const state = thing[DRAFT_STATE]; - return state ? state.type_ : Array.isArray(thing) ? 1 /* Array */ : isMap$1(thing) ? 2 /* Map */ : isSet$1(thing) ? 3 /* Set */ : 0 /* Object */; -} -function has(thing, prop) { - return getArchtype(thing) === 2 /* Map */ ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop); -} -function get(thing, prop) { - return getArchtype(thing) === 2 /* Map */ ? thing.get(prop) : thing[prop]; -} -function set(thing, propOrOldValue, value) { - const t = getArchtype(thing); - if (t === 2 /* Map */) - thing.set(propOrOldValue, value); - else if (t === 3 /* Set */) { - thing.add(value); - } else - thing[propOrOldValue] = value; -} -function is(x, y) { - if (x === y) { - return x !== 0 || 1 / x === 1 / y; - } else { - return x !== x && y !== y; - } -} -function isMap$1(target) { - return target instanceof Map; -} -function isSet$1(target) { - return target instanceof Set; -} -function latest(state) { - return state.copy_ || state.base_; -} -function shallowCopy(base, strict) { - if (isMap$1(base)) { - return new Map(base); - } - if (isSet$1(base)) { - return new Set(base); - } - if (Array.isArray(base)) - return Array.prototype.slice.call(base); - const isPlain = isPlainObject$2(base); - if (strict === true || strict === "class_only" && !isPlain) { - const descriptors = Object.getOwnPropertyDescriptors(base); - delete descriptors[DRAFT_STATE]; - let keys = Reflect.ownKeys(descriptors); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - const desc = descriptors[key]; - if (desc.writable === false) { - desc.writable = true; - desc.configurable = true; - } - if (desc.get || desc.set) - descriptors[key] = { - configurable: true, - writable: true, - // could live with !!desc.set as well here... - enumerable: desc.enumerable, - value: base[key] - }; - } - return Object.create(getPrototypeOf(base), descriptors); - } else { - const proto = getPrototypeOf(base); - if (proto !== null && isPlain) { - return { ...base }; - } - const obj = Object.create(proto); - return Object.assign(obj, base); - } -} -function freeze(obj, deep = false) { - if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) - return obj; - if (getArchtype(obj) > 1) { - obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections; - } - Object.freeze(obj); - if (deep) - Object.values(obj).forEach((value) => freeze(value, true)); - return obj; -} -function dontMutateFrozenCollections() { - die(2); -} -function isFrozen(obj) { - return Object.isFrozen(obj); -} - -// src/utils/plugins.ts -var plugins = {}; -function getPlugin(pluginKey) { - const plugin = plugins[pluginKey]; - if (!plugin) { - die(0, pluginKey); - } - return plugin; -} -function loadPlugin(pluginKey, implementation) { - if (!plugins[pluginKey]) - plugins[pluginKey] = implementation; -} - -// src/core/scope.ts -var currentScope; -function getCurrentScope() { - return currentScope; -} -function createScope(parent_, immer_) { - return { - drafts_: [], - parent_, - immer_, - // Whenever the modified draft contains a draft from another scope, we - // need to prevent auto-freezing so the unowned draft can be finalized. - canAutoFreeze_: true, - unfinalizedDrafts_: 0 - }; -} -function usePatchesInScope(scope, patchListener) { - if (patchListener) { - getPlugin("Patches"); - scope.patches_ = []; - scope.inversePatches_ = []; - scope.patchListener_ = patchListener; - } -} -function revokeScope(scope) { - leaveScope(scope); - scope.drafts_.forEach(revokeDraft); - scope.drafts_ = null; -} -function leaveScope(scope) { - if (scope === currentScope) { - currentScope = scope.parent_; - } -} -function enterScope(immer2) { - return currentScope = createScope(currentScope, immer2); -} -function revokeDraft(draft) { - const state = draft[DRAFT_STATE]; - if (state.type_ === 0 /* Object */ || state.type_ === 1 /* Array */) - state.revoke_(); - else - state.revoked_ = true; -} - -// src/core/finalize.ts -function processResult(result, scope) { - scope.unfinalizedDrafts_ = scope.drafts_.length; - const baseDraft = scope.drafts_[0]; - const isReplaced = result !== void 0 && result !== baseDraft; - if (isReplaced) { - if (baseDraft[DRAFT_STATE].modified_) { - revokeScope(scope); - die(4); - } - if (isDraftable(result)) { - result = finalize(scope, result); - if (!scope.parent_) - maybeFreeze(scope, result); - } - if (scope.patches_) { - getPlugin("Patches").generateReplacementPatches_( - baseDraft[DRAFT_STATE].base_, - result, - scope.patches_, - scope.inversePatches_ - ); - } - } else { - result = finalize(scope, baseDraft, []); - } - revokeScope(scope); - if (scope.patches_) { - scope.patchListener_(scope.patches_, scope.inversePatches_); - } - return result !== NOTHING ? result : void 0; -} -function finalize(rootScope, value, path) { - if (isFrozen(value)) - return value; - const state = value[DRAFT_STATE]; - if (!state) { - each( - value, - (key, childValue) => finalizeProperty(rootScope, state, value, key, childValue, path) - ); - return value; - } - if (state.scope_ !== rootScope) - return value; - if (!state.modified_) { - maybeFreeze(rootScope, state.base_, true); - return state.base_; - } - if (!state.finalized_) { - state.finalized_ = true; - state.scope_.unfinalizedDrafts_--; - const result = state.copy_; - let resultEach = result; - let isSet2 = false; - if (state.type_ === 3 /* Set */) { - resultEach = new Set(result); - result.clear(); - isSet2 = true; - } - each( - resultEach, - (key, childValue) => finalizeProperty(rootScope, state, result, key, childValue, path, isSet2) - ); - maybeFreeze(rootScope, result, false); - if (path && rootScope.patches_) { - getPlugin("Patches").generatePatches_( - state, - path, - rootScope.patches_, - rootScope.inversePatches_ - ); - } - } - return state.copy_; -} -function finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath, targetIsSet) { - if (process.env.NODE_ENV !== "production" && childValue === targetObject) - die(5); - if (isDraft(childValue)) { - const path = rootPath && parentState && parentState.type_ !== 3 /* Set */ && // Set objects are atomic since they have no keys. - !has(parentState.assigned_, prop) ? rootPath.concat(prop) : void 0; - const res = finalize(rootScope, childValue, path); - set(targetObject, prop, res); - if (isDraft(res)) { - rootScope.canAutoFreeze_ = false; - } else - return; - } else if (targetIsSet) { - targetObject.add(childValue); - } - if (isDraftable(childValue) && !isFrozen(childValue)) { - if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) { - return; - } - finalize(rootScope, childValue); - if ((!parentState || !parentState.scope_.parent_) && typeof prop !== "symbol" && Object.prototype.propertyIsEnumerable.call(targetObject, prop)) - maybeFreeze(rootScope, childValue); - } -} -function maybeFreeze(scope, value, deep = false) { - if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) { - freeze(value, deep); - } -} - -// src/core/proxy.ts -function createProxyProxy(base, parent) { - const isArray = Array.isArray(base); - const state = { - type_: isArray ? 1 /* Array */ : 0 /* Object */, - // Track which produce call this is associated with. - scope_: parent ? parent.scope_ : getCurrentScope(), - // True for both shallow and deep changes. - modified_: false, - // Used during finalization. - finalized_: false, - // Track which properties have been assigned (true) or deleted (false). - assigned_: {}, - // The parent draft state. - parent_: parent, - // The base state. - base_: base, - // The base proxy. - draft_: null, - // set below - // The base copy with any updated values. - copy_: null, - // Called by the `produce` function. - revoke_: null, - isManual_: false - }; - let target = state; - let traps = objectTraps; - if (isArray) { - target = [state]; - traps = arrayTraps; - } - const { revoke, proxy } = Proxy.revocable(target, traps); - state.draft_ = proxy; - state.revoke_ = revoke; - return proxy; -} -var objectTraps = { - get(state, prop) { - if (prop === DRAFT_STATE) - return state; - const source = latest(state); - if (!has(source, prop)) { - return readPropFromProto(state, source, prop); - } - const value = source[prop]; - if (state.finalized_ || !isDraftable(value)) { - return value; - } - if (value === peek(state.base_, prop)) { - prepareCopy(state); - return state.copy_[prop] = createProxy(value, state); - } - return value; - }, - has(state, prop) { - return prop in latest(state); - }, - ownKeys(state) { - return Reflect.ownKeys(latest(state)); - }, - set(state, prop, value) { - const desc = getDescriptorFromProto(latest(state), prop); - if (desc?.set) { - desc.set.call(state.draft_, value); - return true; - } - if (!state.modified_) { - const current2 = peek(latest(state), prop); - const currentState = current2?.[DRAFT_STATE]; - if (currentState && currentState.base_ === value) { - state.copy_[prop] = value; - state.assigned_[prop] = false; - return true; - } - if (is(value, current2) && (value !== void 0 || has(state.base_, prop))) - return true; - prepareCopy(state); - markChanged(state); - } - if (state.copy_[prop] === value && // special case: handle new props with value 'undefined' - (value !== void 0 || prop in state.copy_) || // special case: NaN - Number.isNaN(value) && Number.isNaN(state.copy_[prop])) - return true; - state.copy_[prop] = value; - state.assigned_[prop] = true; - return true; - }, - deleteProperty(state, prop) { - if (peek(state.base_, prop) !== void 0 || prop in state.base_) { - state.assigned_[prop] = false; - prepareCopy(state); - markChanged(state); - } else { - delete state.assigned_[prop]; - } - if (state.copy_) { - delete state.copy_[prop]; - } - return true; - }, - // Note: We never coerce `desc.value` into an Immer draft, because we can't make - // the same guarantee in ES5 mode. - getOwnPropertyDescriptor(state, prop) { - const owner = latest(state); - const desc = Reflect.getOwnPropertyDescriptor(owner, prop); - if (!desc) - return desc; - return { - writable: true, - configurable: state.type_ !== 1 /* Array */ || prop !== "length", - enumerable: desc.enumerable, - value: owner[prop] - }; - }, - defineProperty() { - die(11); - }, - getPrototypeOf(state) { - return getPrototypeOf(state.base_); - }, - setPrototypeOf() { - die(12); - } -}; -var arrayTraps = {}; -each(objectTraps, (key, fn) => { - arrayTraps[key] = function() { - arguments[0] = arguments[0][0]; - return fn.apply(this, arguments); - }; -}); -arrayTraps.deleteProperty = function(state, prop) { - if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop))) - die(13); - return arrayTraps.set.call(this, state, prop, void 0); -}; -arrayTraps.set = function(state, prop, value) { - if (process.env.NODE_ENV !== "production" && prop !== "length" && isNaN(parseInt(prop))) - die(14); - return objectTraps.set.call(this, state[0], prop, value, state[0]); -}; -function peek(draft, prop) { - const state = draft[DRAFT_STATE]; - const source = state ? latest(state) : draft; - return source[prop]; -} -function readPropFromProto(state, source, prop) { - const desc = getDescriptorFromProto(source, prop); - return desc ? `value` in desc ? desc.value : ( - // This is a very special case, if the prop is a getter defined by the - // prototype, we should invoke it with the draft as context! - desc.get?.call(state.draft_) - ) : void 0; -} -function getDescriptorFromProto(source, prop) { - if (!(prop in source)) - return void 0; - let proto = getPrototypeOf(source); - while (proto) { - const desc = Object.getOwnPropertyDescriptor(proto, prop); - if (desc) - return desc; - proto = getPrototypeOf(proto); - } - return void 0; -} -function markChanged(state) { - if (!state.modified_) { - state.modified_ = true; - if (state.parent_) { - markChanged(state.parent_); - } - } -} -function prepareCopy(state) { - if (!state.copy_) { - state.copy_ = shallowCopy( - state.base_, - state.scope_.immer_.useStrictShallowCopy_ - ); - } -} - -// src/core/immerClass.ts -var Immer2 = class { - constructor(config) { - this.autoFreeze_ = true; - this.useStrictShallowCopy_ = false; - /** - * The `produce` function takes a value and a "recipe function" (whose - * return value often depends on the base state). The recipe function is - * free to mutate its first argument however it wants. All mutations are - * only ever applied to a __copy__ of the base state. - * - * Pass only a function to create a "curried producer" which relieves you - * from passing the recipe function every time. - * - * Only plain objects and arrays are made mutable. All other objects are - * considered uncopyable. - * - * Note: This function is __bound__ to its `Immer` instance. - * - * @param {any} base - the initial state - * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified - * @param {Function} patchListener - optional function that will be called with all the patches produced here - * @returns {any} a new state, or the initial state if nothing was modified - */ - this.produce = (base, recipe, patchListener) => { - if (typeof base === "function" && typeof recipe !== "function") { - const defaultBase = recipe; - recipe = base; - const self = this; - return function curriedProduce(base2 = defaultBase, ...args) { - return self.produce(base2, (draft) => recipe.call(this, draft, ...args)); - }; - } - if (typeof recipe !== "function") - die(6); - if (patchListener !== void 0 && typeof patchListener !== "function") - die(7); - let result; - if (isDraftable(base)) { - const scope = enterScope(this); - const proxy = createProxy(base, void 0); - let hasError = true; - try { - result = recipe(proxy); - hasError = false; - } finally { - if (hasError) - revokeScope(scope); - else - leaveScope(scope); - } - usePatchesInScope(scope, patchListener); - return processResult(result, scope); - } else if (!base || typeof base !== "object") { - result = recipe(base); - if (result === void 0) - result = base; - if (result === NOTHING) - result = void 0; - if (this.autoFreeze_) - freeze(result, true); - if (patchListener) { - const p = []; - const ip = []; - getPlugin("Patches").generateReplacementPatches_(base, result, p, ip); - patchListener(p, ip); - } - return result; - } else - die(1, base); - }; - this.produceWithPatches = (base, recipe) => { - if (typeof base === "function") { - return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args)); - } - let patches, inversePatches; - const result = this.produce(base, recipe, (p, ip) => { - patches = p; - inversePatches = ip; - }); - return [result, patches, inversePatches]; - }; - if (typeof config?.autoFreeze === "boolean") - this.setAutoFreeze(config.autoFreeze); - if (typeof config?.useStrictShallowCopy === "boolean") - this.setUseStrictShallowCopy(config.useStrictShallowCopy); - } - createDraft(base) { - if (!isDraftable(base)) - die(8); - if (isDraft(base)) - base = current(base); - const scope = enterScope(this); - const proxy = createProxy(base, void 0); - proxy[DRAFT_STATE].isManual_ = true; - leaveScope(scope); - return proxy; - } - finishDraft(draft, patchListener) { - const state = draft && draft[DRAFT_STATE]; - if (!state || !state.isManual_) - die(9); - const { scope_: scope } = state; - usePatchesInScope(scope, patchListener); - return processResult(void 0, scope); - } - /** - * Pass true to automatically freeze all copies created by Immer. - * - * By default, auto-freezing is enabled. - */ - setAutoFreeze(value) { - this.autoFreeze_ = value; - } - /** - * Pass true to enable strict shallow copy. - * - * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties. - */ - setUseStrictShallowCopy(value) { - this.useStrictShallowCopy_ = value; - } - applyPatches(base, patches) { - let i; - for (i = patches.length - 1; i >= 0; i--) { - const patch = patches[i]; - if (patch.path.length === 0 && patch.op === "replace") { - base = patch.value; - break; - } - } - if (i > -1) { - patches = patches.slice(i + 1); - } - const applyPatchesImpl = getPlugin("Patches").applyPatches_; - if (isDraft(base)) { - return applyPatchesImpl(base, patches); - } - return this.produce( - base, - (draft) => applyPatchesImpl(draft, patches) - ); - } -}; -function createProxy(value, parent) { - const draft = isMap$1(value) ? getPlugin("MapSet").proxyMap_(value, parent) : isSet$1(value) ? getPlugin("MapSet").proxySet_(value, parent) : createProxyProxy(value, parent); - const scope = parent ? parent.scope_ : getCurrentScope(); - scope.drafts_.push(draft); - return draft; -} - -// src/core/current.ts -function current(value) { - if (!isDraft(value)) - die(10, value); - return currentImpl(value); -} -function currentImpl(value) { - if (!isDraftable(value) || isFrozen(value)) - return value; - const state = value[DRAFT_STATE]; - let copy; - if (state) { - if (!state.modified_) - return state.base_; - state.finalized_ = true; - copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_); - } else { - copy = shallowCopy(value, true); - } - each(copy, (key, childValue) => { - set(copy, key, currentImpl(childValue)); - }); - if (state) { - state.finalized_ = false; - } - return copy; -} - -// src/plugins/mapset.ts -function enableMapSet() { - class DraftMap extends Map { - constructor(target, parent) { - super(); - this[DRAFT_STATE] = { - type_: 2 /* Map */, - parent_: parent, - scope_: parent ? parent.scope_ : getCurrentScope(), - modified_: false, - finalized_: false, - copy_: void 0, - assigned_: void 0, - base_: target, - draft_: this, - isManual_: false, - revoked_: false - }; - } - get size() { - return latest(this[DRAFT_STATE]).size; - } - has(key) { - return latest(this[DRAFT_STATE]).has(key); - } - set(key, value) { - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - if (!latest(state).has(key) || latest(state).get(key) !== value) { - prepareMapCopy(state); - markChanged(state); - state.assigned_.set(key, true); - state.copy_.set(key, value); - state.assigned_.set(key, true); - } - return this; - } - delete(key) { - if (!this.has(key)) { - return false; - } - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - prepareMapCopy(state); - markChanged(state); - if (state.base_.has(key)) { - state.assigned_.set(key, false); - } else { - state.assigned_.delete(key); - } - state.copy_.delete(key); - return true; - } - clear() { - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - if (latest(state).size) { - prepareMapCopy(state); - markChanged(state); - state.assigned_ = /* @__PURE__ */ new Map(); - each(state.base_, (key) => { - state.assigned_.set(key, false); - }); - state.copy_.clear(); - } - } - forEach(cb, thisArg) { - const state = this[DRAFT_STATE]; - latest(state).forEach((_value, key, _map) => { - cb.call(thisArg, this.get(key), key, this); - }); - } - get(key) { - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - const value = latest(state).get(key); - if (state.finalized_ || !isDraftable(value)) { - return value; - } - if (value !== state.base_.get(key)) { - return value; - } - const draft = createProxy(value, state); - prepareMapCopy(state); - state.copy_.set(key, draft); - return draft; - } - keys() { - return latest(this[DRAFT_STATE]).keys(); - } - values() { - const iterator = this.keys(); - return { - [Symbol.iterator]: () => this.values(), - next: () => { - const r = iterator.next(); - if (r.done) - return r; - const value = this.get(r.value); - return { - done: false, - value - }; - } - }; - } - entries() { - const iterator = this.keys(); - return { - [Symbol.iterator]: () => this.entries(), - next: () => { - const r = iterator.next(); - if (r.done) - return r; - const value = this.get(r.value); - return { - done: false, - value: [r.value, value] - }; - } - }; - } - [(Symbol.iterator)]() { - return this.entries(); - } - } - function proxyMap_(target, parent) { - return new DraftMap(target, parent); - } - function prepareMapCopy(state) { - if (!state.copy_) { - state.assigned_ = /* @__PURE__ */ new Map(); - state.copy_ = new Map(state.base_); - } - } - class DraftSet extends Set { - constructor(target, parent) { - super(); - this[DRAFT_STATE] = { - type_: 3 /* Set */, - parent_: parent, - scope_: parent ? parent.scope_ : getCurrentScope(), - modified_: false, - finalized_: false, - copy_: void 0, - base_: target, - draft_: this, - drafts_: /* @__PURE__ */ new Map(), - revoked_: false, - isManual_: false - }; - } - get size() { - return latest(this[DRAFT_STATE]).size; - } - has(value) { - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - if (!state.copy_) { - return state.base_.has(value); - } - if (state.copy_.has(value)) - return true; - if (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value))) - return true; - return false; - } - add(value) { - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - if (!this.has(value)) { - prepareSetCopy(state); - markChanged(state); - state.copy_.add(value); - } - return this; - } - delete(value) { - if (!this.has(value)) { - return false; - } - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - prepareSetCopy(state); - markChanged(state); - return state.copy_.delete(value) || (state.drafts_.has(value) ? state.copy_.delete(state.drafts_.get(value)) : ( - /* istanbul ignore next */ - false - )); - } - clear() { - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - if (latest(state).size) { - prepareSetCopy(state); - markChanged(state); - state.copy_.clear(); - } - } - values() { - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - prepareSetCopy(state); - return state.copy_.values(); - } - entries() { - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - prepareSetCopy(state); - return state.copy_.entries(); - } - keys() { - return this.values(); - } - [(Symbol.iterator)]() { - return this.values(); - } - forEach(cb, thisArg) { - const iterator = this.values(); - let result = iterator.next(); - while (!result.done) { - cb.call(thisArg, result.value, result.value, this); - result = iterator.next(); - } - } - } - function proxySet_(target, parent) { - return new DraftSet(target, parent); - } - function prepareSetCopy(state) { - if (!state.copy_) { - state.copy_ = /* @__PURE__ */ new Set(); - state.base_.forEach((value) => { - if (isDraftable(value)) { - const draft = createProxy(value, state); - state.drafts_.set(value, draft); - state.copy_.add(draft); - } else { - state.copy_.add(value); - } - }); - } - } - function assertUnrevoked(state) { - if (state.revoked_) - die(3, JSON.stringify(latest(state))); - } - loadPlugin("MapSet", { proxyMap_, proxySet_ }); -} - -// src/plugins/patches.ts -function enablePatches() { - const errorOffset = 16; - if (process.env.NODE_ENV !== "production") { - errors.push( - 'Sets cannot have "replace" patches.', - function(op) { - return "Unsupported patch operation: " + op; - }, - function(path) { - return "Cannot apply patch, path doesn't resolve: " + path; - }, - "Patching reserved attributes like __proto__, prototype and constructor is not allowed" - ); - } - const REPLACE = "replace"; - const ADD = "add"; - const REMOVE = "remove"; - function generatePatches_(state, basePath, patches, inversePatches) { - switch (state.type_) { - case 0 /* Object */: - case 2 /* Map */: - return generatePatchesFromAssigned( - state, - basePath, - patches, - inversePatches - ); - case 1 /* Array */: - return generateArrayPatches(state, basePath, patches, inversePatches); - case 3 /* Set */: - return generateSetPatches( - state, - basePath, - patches, - inversePatches - ); - } - } - function generateArrayPatches(state, basePath, patches, inversePatches) { - let { base_, assigned_ } = state; - let copy_ = state.copy_; - if (copy_.length < base_.length) { - [base_, copy_] = [copy_, base_]; - [patches, inversePatches] = [inversePatches, patches]; - } - for (let i = 0; i < base_.length; i++) { - if (assigned_[i] && copy_[i] !== base_[i]) { - const path = basePath.concat([i]); - patches.push({ - op: REPLACE, - path, - // Need to maybe clone it, as it can in fact be the original value - // due to the base/copy inversion at the start of this function - value: clonePatchValueIfNeeded(copy_[i]) - }); - inversePatches.push({ - op: REPLACE, - path, - value: clonePatchValueIfNeeded(base_[i]) - }); - } - } - for (let i = base_.length; i < copy_.length; i++) { - const path = basePath.concat([i]); - patches.push({ - op: ADD, - path, - // Need to maybe clone it, as it can in fact be the original value - // due to the base/copy inversion at the start of this function - value: clonePatchValueIfNeeded(copy_[i]) - }); - } - for (let i = copy_.length - 1; base_.length <= i; --i) { - const path = basePath.concat([i]); - inversePatches.push({ - op: REMOVE, - path - }); - } - } - function generatePatchesFromAssigned(state, basePath, patches, inversePatches) { - const { base_, copy_ } = state; - each(state.assigned_, (key, assignedValue) => { - const origValue = get(base_, key); - const value = get(copy_, key); - const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD; - if (origValue === value && op === REPLACE) - return; - const path = basePath.concat(key); - patches.push(op === REMOVE ? { op, path } : { op, path, value }); - inversePatches.push( - op === ADD ? { op: REMOVE, path } : op === REMOVE ? { op: ADD, path, value: clonePatchValueIfNeeded(origValue) } : { op: REPLACE, path, value: clonePatchValueIfNeeded(origValue) } - ); - }); - } - function generateSetPatches(state, basePath, patches, inversePatches) { - let { base_, copy_ } = state; - let i = 0; - base_.forEach((value) => { - if (!copy_.has(value)) { - const path = basePath.concat([i]); - patches.push({ - op: REMOVE, - path, - value - }); - inversePatches.unshift({ - op: ADD, - path, - value - }); - } - i++; - }); - i = 0; - copy_.forEach((value) => { - if (!base_.has(value)) { - const path = basePath.concat([i]); - patches.push({ - op: ADD, - path, - value - }); - inversePatches.unshift({ - op: REMOVE, - path, - value - }); - } - i++; - }); - } - function generateReplacementPatches_(baseValue, replacement, patches, inversePatches) { - patches.push({ - op: REPLACE, - path: [], - value: replacement === NOTHING ? void 0 : replacement - }); - inversePatches.push({ - op: REPLACE, - path: [], - value: baseValue - }); - } - function applyPatches_(draft, patches) { - patches.forEach((patch) => { - const { path, op } = patch; - let base = draft; - for (let i = 0; i < path.length - 1; i++) { - const parentType = getArchtype(base); - let p = path[i]; - if (typeof p !== "string" && typeof p !== "number") { - p = "" + p; - } - if ((parentType === 0 /* Object */ || parentType === 1 /* Array */) && (p === "__proto__" || p === "constructor")) - die(errorOffset + 3); - if (typeof base === "function" && p === "prototype") - die(errorOffset + 3); - base = get(base, p); - if (typeof base !== "object") - die(errorOffset + 2, path.join("/")); - } - const type = getArchtype(base); - const value = deepClonePatchValue(patch.value); - const key = path[path.length - 1]; - switch (op) { - case REPLACE: - switch (type) { - case 2 /* Map */: - return base.set(key, value); - case 3 /* Set */: - die(errorOffset); - default: - return base[key] = value; - } - case ADD: - switch (type) { - case 1 /* Array */: - return key === "-" ? base.push(value) : base.splice(key, 0, value); - case 2 /* Map */: - return base.set(key, value); - case 3 /* Set */: - return base.add(value); - default: - return base[key] = value; - } - case REMOVE: - switch (type) { - case 1 /* Array */: - return base.splice(key, 1); - case 2 /* Map */: - return base.delete(key); - case 3 /* Set */: - return base.delete(patch.value); - default: - return delete base[key]; - } - default: - die(errorOffset + 1, op); - } - }); - return draft; - } - function deepClonePatchValue(obj) { - if (!isDraftable(obj)) - return obj; - if (Array.isArray(obj)) - return obj.map(deepClonePatchValue); - if (isMap$1(obj)) - return new Map( - Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)]) - ); - if (isSet$1(obj)) - return new Set(Array.from(obj).map(deepClonePatchValue)); - const cloned = Object.create(getPrototypeOf(obj)); - for (const key in obj) - cloned[key] = deepClonePatchValue(obj[key]); - if (has(obj, DRAFTABLE)) - cloned[DRAFTABLE] = obj[DRAFTABLE]; - return cloned; - } - function clonePatchValueIfNeeded(obj) { - if (isDraft(obj)) { - return deepClonePatchValue(obj); - } else - return obj; - } - loadPlugin("Patches", { - applyPatches_, - generatePatches_, - generateReplacementPatches_ - }); -} - -// src/immer.ts -var immer = new Immer2(); -immer.produce; -var produceWithPatches = immer.produceWithPatches.bind( - immer -); -immer.setAutoFreeze.bind(immer); -immer.setUseStrictShallowCopy.bind(immer); -var applyPatches = immer.applyPatches.bind(immer); -immer.createDraft.bind(immer); -immer.finishDraft.bind(immer); -enableMapSet(); -enablePatches(); - -/** - * Concatenate Writable Tags - */ -function cwt(...allTags) { - return allTags - .filter(tags => tags !== undefined) - .reduce((acc, tags) => acc.concat(tags), []); -} -function makeRootReplacingPatches(value) { - return [ - { - op: "replace", - path: [], - value, - }, - ]; -} -/** - * Creates a setter function that can be used to update a value. This setter will also return the - * patches that were applied to the value. - */ -function makeSetterWithPatches(update, prependTagsFn) { - const setter = (value, tags) => { - update(() => [value, makeRootReplacingPatches(value)], cwt(prependTagsFn?.(), tags)); - }; - setter.withProducer = (producer, tags) => { - update(oldData => { - const [newData, patches] = produceWithPatches(oldData, producer); - if (isAvailable(newData)) { - return [newData, patches]; - } - throw new Error("Cannot update value to NOT_AVAILABLE"); - }, cwt(prependTagsFn?.(), tags)); - }; - setter.withUpdater = (updater, tags) => { - update(oldData => { - const newData = updater(oldData); - return [newData, makeRootReplacingPatches(newData)]; - }, cwt(prependTagsFn?.(), tags)); - }; - setter.withPatchUpdater = (updater, tags) => { - update(updater, cwt(prependTagsFn?.(), tags)); - }; - setter.withPatches = (patches, tags) => { - update(oldData => { - return [applyPatches(oldData, patches), patches]; - }, cwt(prependTagsFn?.(), tags)); - }; - setter.withValueAndPatches = (newValue, patches, tags) => { - update(() => [newValue, patches], cwt(prependTagsFn?.(), tags)); - }; - return setter; -} - -const equals = (a, b) => a === b; -/** - * A signal is a wrapper for a value. It can be used to notify subscribers when the value changes. - * For it to work properly, the value should be immutable. - * - * To create a signal, please use the `Signal.create` static method. It will return a signal - * along with a function to update its value. - */ -class Signal extends Subscribable { - /** - * Creates a signal. - * - * @param value - The initial value of the signal. - * @param equalsPredicate - A function to compare two values. The subscribers will only be called - * if the value changes according to the `equalsPredicate`. By default, it uses the `===` - * operator. - * @returns This method returns a tuple with two elements: - * - The signal - * - A function to update the value - **/ - static create(value, equalsPredicate = equals) { - const signal = new Signal(value, equalsPredicate); - const update = (updater, tags) => { - signal.update(updater, tags); - }; - const setter = makeSetterWithPatches(update); - return [signal, setter]; - } - static createReadonly(value) { - return Signal.create(value)[0]; - } - constructor(value, equalsPredicate) { - super(); - this.value = value; - this.equalsPredicate = equalsPredicate; - this.subscribers = new Set(); - this.queuedUpdaters = []; - this.isEmitting = false; - } - /** - * Returns the current value of the signal. - */ - get() { - return this.value; - } - pull() { - return this.value; - } - notifyFull(value, patches, tags) { - for (const { type, callback } of this.subscribers) { - if (type === "full") { - callback(value, patches, tags); - } - } - } - notifyAll(value, patches, tags) { - for (const { type, callback } of this.subscribers) { - if (type === "regular") { - callback(value); - } - else { - callback(value, patches, tags); - } - } - } - notifyAndUpdateIfChanged(value, patches, tags) { - // If the value has changed, or if there are any tags that need to be flushed, notify - if (!this.equalsPredicate(this.value, value)) { - this.value = value; - // If the values have changed, notify everyone - this.notifyAll(value, patches, tags); - } - else if (tags.length > 0) { - // If values not changed, but there is a tag to be flushed, notify only full subscribers - this.notifyFull(value, patches, tags); - } - } - isReplaceRoot(patch) { - return patch.path.length === 0 && patch.op === "replace"; - } - update(updater, tags) { - this.queuedUpdaters.push([updater, tags]); - // Only one concurrent update may emit - if (this.isEmitting) { - return; - } - this.isEmitting = true; - try { - // Outer while is for handling new updates caused by the notify - while (this.queuedUpdaters.length > 0) { - let value = this.value; - let patches = []; - const tags = []; - // Inner while is for handling multiple updates - while (this.queuedUpdaters.length > 0) { - const [updater, newTags] = this.queuedUpdaters.shift(); - const [newValue, newPatches] = updater(value); - value = newValue; - // Extremely rudimentary patch merging - const rootReplacerIndex = newPatches.findIndex(this.isReplaceRoot); - if (rootReplacerIndex !== -1) { - patches = newPatches.slice(rootReplacerIndex); - } - else { - patches.push(...newPatches); - } - if (newTags !== undefined) { - tags.push(...newTags); - } - } - this.notifyAndUpdateIfChanged(value, patches, tags); - } - } - finally { - this.isEmitting = false; - } - } - /** - * Subscribes to the signal. The callback will be called whenever the value changes. All callbacks - * are called synchronously upon updating. It will NOT be immediately called with the current - * value. (Use `get()` to get the current value.) Returns a function to unsubscribe. - * - * Edge cases involving manipulating the signal in the callback: - * - * - If the callback adds new subscribers, they will also be called within the same update. - * - If the callback causes removal of subscribers that have not been called yet, they will no - * longer be called. - * - If the callback causes an update of the value, the update will be queued. If multiple updates - * are queued, only the last one will be executed. - * - * Edge cases involving adding the same callback multiple times. - * - * - Callbacks are tracked with a set. Adding the same subscriber will not cause it to be called - * multiple times. - */ - subscribe(callback) { - const subscriber = { - type: "regular", - callback, - }; - this.subscribers.add(subscriber); - return () => { - this.subscribers.delete(subscriber); - }; - } - /** - * Subscribes to the signal with the callback and trigger the callback immediately with the - * current value. - */ - subscribeAndNow(callback) { - const unsubscribe = this.subscribe(callback); - callback(this.value); - return unsubscribe; - } - subscribeFull(callback) { - const subscriber = { - type: "full", - callback, - }; - this.subscribers.add(subscriber); - return () => { - this.subscribers.delete(subscriber); - }; - } - /** - * Wait until the signal satisfies a predicate. If the predicate is already satisfied, it will - * return immediately. Otherwise, it will wait until the signal satisfies the predicate. - */ - async until(predicate) { - const current = this.get(); - if (predicate(current)) { - return current; - } - const { promise, resolve } = makePromise(); - const unsubscribe = this.subscribe(data => { - if (predicate(data)) { - resolve(data); - unsubscribe(); - } - }); - return await promise; - } -} - -function isAvailable(data) { - return data !== LazySignal.NOT_AVAILABLE; -} -/** - * A lazy signal is a signal that will only subscribe to the upstream when at least one subscriber - * is attached. It will unsubscribe from the upstream when the last subscriber is removed. - * - * A lazy signal can possess a special value "NOT_AVAILABLE", accessible from the static property - * {@link LazySignal.NOT_AVAILABLE}. This value is used to indicate that the value is not available - * yet. This can happen when the signal is created without an initial value and the upstream has not - * emitted a value yet. - */ -class LazySignal extends Subscribable { - static { this.NOT_AVAILABLE = Symbol("notAvailable"); } - static create(initialValue, subscribeUpstream, equalsPredicate = (a, b) => a === b) { - return new LazySignal(initialValue, subscribeUpstream, equalsPredicate); - } - static createWithoutInitialValue(subscribeUpstream, equalsPredicate = (a, b) => a === b) { - const fullEqualsPredicate = (a, b) => { - if (a === LazySignal.NOT_AVAILABLE || b === LazySignal.NOT_AVAILABLE) { - return a === b; - } - return equalsPredicate(a, b); - }; - return new LazySignal(LazySignal.NOT_AVAILABLE, subscribeUpstream, fullEqualsPredicate); - } - static deriveFrom(sourceSignals, deriver, outputEqualsPredicate) { - let fullEqualsPredicate = undefined; - if (outputEqualsPredicate !== undefined) { - fullEqualsPredicate = (a, b) => { - if (a === LazySignal.NOT_AVAILABLE || b === LazySignal.NOT_AVAILABLE) { - return a === b; - } - return outputEqualsPredicate(a, b); - }; - } - const derive = () => { - const sourceValues = sourceSignals.map(signal => signal.get()); - if (sourceValues.some(value => value === LazySignal.NOT_AVAILABLE)) { - return LazySignal.NOT_AVAILABLE; - } - return deriver(...sourceValues); - }; - return new LazySignal(derive(), setDownstream => { - const unsubscriber = sourceSignals.map(signal => signal.subscribe(() => { - const value = derive(); - if (isAvailable(value)) { - setDownstream(value); - } - })); - const newValue = derive(); - if (isAvailable(newValue)) { - setDownstream(newValue); - } - return () => { - unsubscriber.forEach(unsub => unsub()); - }; - }, fullEqualsPredicate); - } - static asyncDeriveFrom(strategy, sourceSignals, deriver, outputEqualsPredicate) { - let fullEqualsPredicate = undefined; - if (outputEqualsPredicate !== undefined) { - fullEqualsPredicate = (a, b) => { - if (a === LazySignal.NOT_AVAILABLE || b === LazySignal.NOT_AVAILABLE) { - return a === b; - } - return outputEqualsPredicate(a, b); - }; - } - let lastAppliedUpdateId = -1; - let lastIssuedUpdateId = -1; - return new LazySignal(LazySignal.NOT_AVAILABLE, setDownstream => { - const deriveAndUpdate = () => { - lastIssuedUpdateId++; - const updateId = lastIssuedUpdateId; - const sourceValues = sourceSignals.map(signal => signal.get()); - if (sourceValues.some(value => value === LazySignal.NOT_AVAILABLE)) { - return; - } - deriver(...sourceValues).then(result => { - if (!isAvailable(result)) { - return; - } - switch (strategy) { - case "eager": { - if (updateId > lastAppliedUpdateId) { - lastAppliedUpdateId = updateId; - setDownstream(result); - } - break; - } - default: { - const exhaustiveCheck = strategy; - throw new Error(`Unknown strategy: ${exhaustiveCheck}`); - } - } - }); - }; - const unsubscriber = sourceSignals.map(signal => signal.subscribe(() => { - deriveAndUpdate(); - })); - deriveAndUpdate(); - return () => { - unsubscriber.forEach(unsub => unsub()); - }; - }, fullEqualsPredicate); - } - constructor(initialValue, subscribeUpstream, equalsPredicate = (a, b) => a === b) { - super(); - this.subscribeUpstream = subscribeUpstream; - this.dataIsStale = true; - this.upstreamUnsubscribe = null; - this.subscribersCount = 0; - this.isSubscribedToUpstream = false; - this.updateReceivedSynchronousCallbacks = new Set(); - [this.signal, this.setValue] = Signal.create(initialValue, equalsPredicate); - [this.updateReceivedEvent, this.emitUpdateReceivedEvent] = Event.create(); - } - /** - * Returns whether the value is currently stale. - * - * A value is stale whenever the upstream subscription is not active. This can happen in three - * cases: - * - * 1. When no subscriber is attached to this signal, the signal will not subscribe to the - * upstream. In this case, the value is always stale. - * 2. When a subscriber is attached, but the upstream has not yet emitted a single value, the - * value is also stale. - * 3. When the upstream has emitted an error. In this case, the subscription to the upstream is - * terminated and the value is stale. - * - * If you wish to get the current value and ensure that it is not stale, use the method - * {@link LazySignal#pull}. - */ - isStale() { - return this.dataIsStale; - } - subscribeToUpstream() { - this.isSubscribedToUpstream = true; - let subscribed = true; - let becameStale = false; - const unsubscribeFromUpstream = this.subscribeUpstream(makeSetterWithPatches((updater, tags) => { - if (!subscribed) { - return; - } - this.setValue.withPatchUpdater(updater, tags); - this.dataIsStale = becameStale; - this.emitUpdateReceivedEvent(); - for (const callback of this.updateReceivedSynchronousCallbacks) { - callback(); - } - }), error => { - if (!subscribed) { - return; - } - Promise.reject(error); // Prints a global error for now - this.dataIsStale = true; - this.isSubscribedToUpstream = false; - this.upstreamUnsubscribe = null; - subscribed = false; - }); - this.upstreamUnsubscribe = () => { - if (subscribed) { - subscribed = false; - becameStale = true; - unsubscribeFromUpstream(); - } - }; - } - unsubscribeFromUpstream() { - this.isSubscribedToUpstream = false; - if (this.upstreamUnsubscribe !== null) { - this.upstreamUnsubscribe(); - this.upstreamUnsubscribe = null; - this.dataIsStale = true; - } - } - /** - * Gets the current value of the signal. If the value is not available, it will return - * {@link LazySignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is created - * without an initial value and the upstream has not emitted a value yet.) - * - * In addition, the value returned by this method may be stale. Use {@link LazySignal#isStale} to - * check if the value is stale. - * - * If you wish to get the current value and ensure that it is not stale, use the method - * {@link LazySignal#pull}. - */ - get() { - return this.signal.get(); - } - /** - * Pulls the current value of the signal. If the value is stale, it will subscribe and wait for - * the next value from the upstream and return it. - */ - async pull() { - const { promise, resolve } = makePromise(); - if (!this.isStale()) { - // If not stale, definitely not "NOT_AVAILABLE" - resolve(this.get()); - } - else { - const unsubscribe = this.subscribe(() => { }); - this.updateReceivedEvent.subscribeOnce(() => { - resolve(this.get()); - }); - promise.then(unsubscribe); - } - return promise; - } - /** - * If the data is not stale, the callback will be called synchronously with the current value. - * - * If the data is stale, it will pull the current value and call the callback with the value. - */ - runOnNextFreshData(callback) { - if (!this.isStale()) { - callback(this.get()); - } - else { - let unsubscribe = null; - const updateCallback = () => { - this.updateReceivedSynchronousCallbacks.delete(updateCallback); - callback(this.get()); - unsubscribe?.(); - }; - this.updateReceivedSynchronousCallbacks.add(updateCallback); - unsubscribe = this.subscribe(() => { }); - } - } - async ensureAvailable() { - await this.pull(); - return this; - } - subscribe(subscriber) { - if (!this.isSubscribedToUpstream) { - this.subscribeToUpstream(); - } - this.subscribersCount++; - const unsubscribe = this.signal.subscribe(subscriber); - let unsubscribeCalled = false; - return () => { - if (unsubscribeCalled) { - return; - } - unsubscribe(); - unsubscribeCalled = true; - this.subscribersCount--; - if (this.subscribersCount === 0 && this.isSubscribedToUpstream) { - this.unsubscribeFromUpstream(); - } - }; - } - subscribeFull(subscriber) { - if (!this.isSubscribedToUpstream) { - this.subscribeToUpstream(); - } - this.subscribersCount++; - const unsubscribe = this.signal.subscribeFull(subscriber); - let unsubscribeCalled = false; - return () => { - if (unsubscribeCalled) { - return; - } - unsubscribe(); - unsubscribeCalled = true; - this.subscribersCount--; - if (this.subscribersCount === 0 && this.isSubscribedToUpstream) { - this.unsubscribeFromUpstream(); - } - }; - } - /** - * Subscribes to the signal. Will not cause the signal to subscribe to the upstream. - */ - passiveSubscribe(subscriber) { - return this.signal.subscribe(subscriber); - } - passiveSubscribeFull(subscriber) { - return this.signal.subscribeFull(subscriber); - } - async until(predicate) { - const current = this.get(); - if (isAvailable(current) && predicate(current)) { - return current; - } - const { promise, resolve } = makePromise(); - const unsubscribe = this.subscribe(data => { - if (isAvailable(data) && predicate(data)) { - resolve(data); - unsubscribe(); - } - }); - return await promise; - } -} - -const apiServerPorts = [41343, 52993, 16141, 39414, 22931]; - -const waitForNextMicroTask = Symbol(); -/** - * A buffered event will buffer events in a queue if no subscribers are present. When a subscriber - * is added, all buffered events will trigger sequentially in the next microtask. - * - * Similar to Event, events are always emitted during the next microtask. - * - * Attempting to add more than one subscriber will resulting in an error. - */ -class BufferedEvent extends Subscribable { - static create() { - const event = new BufferedEvent(); - const emitter = data => { - event.emit(data); - }; - return [event, emitter]; - } - constructor() { - super(); - this.subscriber = null; - this.queued = []; - this.isNotifying = false; - } - emit(data) { - if (this.queued.length === 0 && this.queued.at(-1) !== waitForNextMicroTask) { - this.queued.push(waitForNextMicroTask); - } - this.queued.push(data); - if (!this.isNotifying) { - this.notifier(); - } - } - async notifier() { - this.isNotifying = true; - while (this.subscriber !== null && this.queued.length > 0) { - const data = this.queued.shift(); - if (data === waitForNextMicroTask) { - await Promise.resolve(); - } - else { - this.subscriber(data); - } - } - this.isNotifying = false; - } - subscribe(listener) { - if (this.subscriber !== null) { - throw new Error("Cannot have more than one subscriber"); - } - this.subscriber = listener; - if (!this.isNotifying && this.queued.length > 0) { - this.queued = [ - waitForNextMicroTask, - ...this.queued.filter(data => data !== waitForNextMicroTask), - ]; - this.notifier(); - } - return () => { - this.subscriber = null; - }; - } - /** - * Convert this buffered event to an event by stop buffering and triggering events on the new - * returned event. - */ - flow() { - const [event, emit] = Event.create(); - this.subscribe(emit); - return event; - } -} - -class CancelEvent extends Subscribable { - constructor() { - super(...arguments); - this.canceled = false; - this.listeners = new Set(); - } - subscribe(listener) { - if (this.canceled) { - let callbackCanceled = false; - Promise.resolve().then(() => { - if (!callbackCanceled) { - listener(); - } - }); - return () => { - callbackCanceled = true; - }; - } - this.listeners.add(listener); - return () => { - this.listeners.delete(listener); - }; - } - cancel() { - if (this.canceled) { - throw new Error("Already canceled"); - } - this.canceled = true; - for (const listener of this.listeners) { - listener(); - } - } - isCanceled() { - return this.canceled; - } -} - -class Cleaner { - constructor() { - this.eagerCleaned = false; - this.disposed = false; - this.cleanups = []; - } - register(fn) { - if (this.eagerCleaned) { - throw new Error("Cannot register a cleanup after eagerClean() was called."); - } - if (this.disposed) { - throw new Error("Cannot register a cleanup after the Cleaner was disposed."); - } - this.cleanups.push(fn); - } - runCleanersInternal() { - for (const cleanup of this.cleanups) { - cleanup(); - } - // Just to free some memory because why not - this.cleanups.length = 0; - } - [Symbol.dispose]() { - if (this.eagerCleaned) { - // Already eagerly cleaned. Nothing to do. - return; - } - if (this.disposed) { - throw new Error("Cannot dispose a Cleaner that was already disposed."); - } - this.runCleanersInternal(); - } - eagerClean() { - if (this.eagerCleaned) { - throw new Error("Cannot call eagerClean() twice."); - } - if (this.disposed) { - throw new Error("Cannot call eagerClean() after the Cleaner was disposed."); - } - this.eagerCleaned = true; - this.runCleanersInternal(); - } -} - -// Error stack manipulation related functions -function getCurrentStack(goAbove = 0) { - const stack = new Error().stack; - if (!stack) { - return ""; - } - const lines = stack.split("\n"); - return lines.slice(2 + goAbove).join("\n"); -} -function changeErrorStackInPlace(error, newStack) { - if (process$1.env.LMS_KEEP_INTERNAL_STACK) { - return; - } - const stackContent = error.stack ?? ""; - error.stack = (stackContent.substring(0, stackContent.indexOf("\n at ")).trimEnd() + - "\n" + - newStack).trimEnd(); -} - -class IdGiver { - constructor(firstId = 0) { - this.nextId = firstId; - } - next() { - const id = this.nextId; - this.nextId++; - return id; - } -} - -function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; -} - -var boxen$1 = {exports: {}}; - -var stringWidth = {exports: {}}; - -var ansiRegex; -var hasRequiredAnsiRegex; - -function requireAnsiRegex () { - if (hasRequiredAnsiRegex) return ansiRegex; - hasRequiredAnsiRegex = 1; - - ansiRegex = ({onlyFirst = false} = {}) => { - const pattern = [ - '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', - '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' - ].join('|'); - - return new RegExp(pattern, onlyFirst ? undefined : 'g'); - }; - return ansiRegex; -} - -var stripAnsi; -var hasRequiredStripAnsi; - -function requireStripAnsi () { - if (hasRequiredStripAnsi) return stripAnsi; - hasRequiredStripAnsi = 1; - const ansiRegex = requireAnsiRegex(); - - stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; - return stripAnsi; -} - -var isFullwidthCodePoint = {exports: {}}; - -/* eslint-disable yoda */ - -var hasRequiredIsFullwidthCodePoint; - -function requireIsFullwidthCodePoint () { - if (hasRequiredIsFullwidthCodePoint) return isFullwidthCodePoint.exports; - hasRequiredIsFullwidthCodePoint = 1; - - const isFullwidthCodePoint$1 = codePoint => { - if (Number.isNaN(codePoint)) { - return false; - } - - // Code points are derived from: - // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt - if ( - codePoint >= 0x1100 && ( - codePoint <= 0x115F || // Hangul Jamo - codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET - codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET - // CJK Radicals Supplement .. Enclosed CJK Letters and Months - (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || - // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A - (0x3250 <= codePoint && codePoint <= 0x4DBF) || - // CJK Unified Ideographs .. Yi Radicals - (0x4E00 <= codePoint && codePoint <= 0xA4C6) || - // Hangul Jamo Extended-A - (0xA960 <= codePoint && codePoint <= 0xA97C) || - // Hangul Syllables - (0xAC00 <= codePoint && codePoint <= 0xD7A3) || - // CJK Compatibility Ideographs - (0xF900 <= codePoint && codePoint <= 0xFAFF) || - // Vertical Forms - (0xFE10 <= codePoint && codePoint <= 0xFE19) || - // CJK Compatibility Forms .. Small Form Variants - (0xFE30 <= codePoint && codePoint <= 0xFE6B) || - // Halfwidth and Fullwidth Forms - (0xFF01 <= codePoint && codePoint <= 0xFF60) || - (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || - // Kana Supplement - (0x1B000 <= codePoint && codePoint <= 0x1B001) || - // Enclosed Ideographic Supplement - (0x1F200 <= codePoint && codePoint <= 0x1F251) || - // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane - (0x20000 <= codePoint && codePoint <= 0x3FFFD) - ) - ) { - return true; - } - - return false; - }; - - isFullwidthCodePoint.exports = isFullwidthCodePoint$1; - isFullwidthCodePoint.exports.default = isFullwidthCodePoint$1; - return isFullwidthCodePoint.exports; -} - -var emojiRegex; -var hasRequiredEmojiRegex; - -function requireEmojiRegex () { - if (hasRequiredEmojiRegex) return emojiRegex; - hasRequiredEmojiRegex = 1; - - emojiRegex = function () { - // https://mths.be/emoji - return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDF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DDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; - }; - return emojiRegex; -} - -var hasRequiredStringWidth; - -function requireStringWidth () { - if (hasRequiredStringWidth) return stringWidth.exports; - hasRequiredStringWidth = 1; - const stripAnsi = requireStripAnsi(); - const isFullwidthCodePoint = requireIsFullwidthCodePoint(); - const emojiRegex = requireEmojiRegex(); - - const stringWidth$1 = string => { - if (typeof string !== 'string' || string.length === 0) { - return 0; - } - - string = stripAnsi(string); - - if (string.length === 0) { - return 0; - } - - string = string.replace(emojiRegex(), ' '); - - let width = 0; - - for (let i = 0; i < string.length; i++) { - const code = string.codePointAt(i); - - // Ignore control characters - if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { - continue; - } - - // Ignore combining characters - if (code >= 0x300 && code <= 0x36F) { - continue; - } - - // Surrogates - if (code > 0xFFFF) { - i++; - } - - width += isFullwidthCodePoint(code) ? 2 : 1; - } - - return width; - }; - - stringWidth.exports = stringWidth$1; - // TODO: remove this in the next major version - stringWidth.exports.default = stringWidth$1; - return stringWidth.exports; -} - -var widestLine = {exports: {}}; - -var hasRequiredWidestLine; - -function requireWidestLine () { - if (hasRequiredWidestLine) return widestLine.exports; - hasRequiredWidestLine = 1; - const stringWidth = requireStringWidth(); - - const widestLine$1 = input => { - let max = 0; - - for (const line of input.split('\n')) { - max = Math.max(max, stringWidth(line)); - } - - return max; - }; - - widestLine.exports = widestLine$1; - // TODO: remove this in the next major version - widestLine.exports.default = widestLine$1; - return widestLine.exports; -} - -var cliBoxes = {exports: {}}; - -var single = { - topLeft: "┌", - topRight: "┐", - bottomRight: "┘", - bottomLeft: "└", - vertical: "│", - horizontal: "─" -}; -var double = { - topLeft: "╔", - topRight: "╗", - bottomRight: "╝", - bottomLeft: "╚", - vertical: "║", - horizontal: "═" -}; -var round = { - topLeft: "╭", - topRight: "╮", - bottomRight: "╯", - bottomLeft: "╰", - vertical: "│", - horizontal: "─" -}; -var bold = { - topLeft: "┏", - topRight: "┓", - bottomRight: "┛", - bottomLeft: "┗", - vertical: "┃", - horizontal: "━" -}; -var singleDouble = { - topLeft: "╓", - topRight: "╖", - bottomRight: "╜", - bottomLeft: "╙", - vertical: "║", - horizontal: "─" -}; -var doubleSingle = { - topLeft: "╒", - topRight: "╕", - bottomRight: "╛", - bottomLeft: "╘", - vertical: "│", - horizontal: "═" -}; -var classic = { - topLeft: "+", - topRight: "+", - bottomRight: "+", - bottomLeft: "+", - vertical: "|", - horizontal: "-" -}; -var require$$0 = { - single: single, - double: double, - round: round, - bold: bold, - singleDouble: singleDouble, - doubleSingle: doubleSingle, - classic: classic -}; - -var hasRequiredCliBoxes; - -function requireCliBoxes () { - if (hasRequiredCliBoxes) return cliBoxes.exports; - hasRequiredCliBoxes = 1; - const cliBoxes$1 = require$$0; - - cliBoxes.exports = cliBoxes$1; - // TODO: Remove this for the next major release - cliBoxes.exports.default = cliBoxes$1; - return cliBoxes.exports; -} - -var camelcase = {exports: {}}; - -var hasRequiredCamelcase; - -function requireCamelcase () { - if (hasRequiredCamelcase) return camelcase.exports; - hasRequiredCamelcase = 1; - - const UPPERCASE = /[\p{Lu}]/u; - const LOWERCASE = /[\p{Ll}]/u; - const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu; - const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u; - const SEPARATORS = /[_.\- ]+/; - - const LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source); - const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu'); - const NUMBERS_AND_IDENTIFIER = new RegExp('\\d+' + IDENTIFIER.source, 'gu'); - - const preserveCamelCase = (string, toLowerCase, toUpperCase) => { - let isLastCharLower = false; - let isLastCharUpper = false; - let isLastLastCharUpper = false; - - for (let i = 0; i < string.length; i++) { - const character = string[i]; - - if (isLastCharLower && UPPERCASE.test(character)) { - string = string.slice(0, i) + '-' + string.slice(i); - isLastCharLower = false; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = true; - i++; - } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) { - string = string.slice(0, i - 1) + '-' + string.slice(i - 1); - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = false; - isLastCharLower = true; - } else { - isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character; - } - } - - return string; - }; - - const preserveConsecutiveUppercase = (input, toLowerCase) => { - LEADING_CAPITAL.lastIndex = 0; - - return input.replace(LEADING_CAPITAL, m1 => toLowerCase(m1)); - }; - - const postProcess = (input, toUpperCase) => { - SEPARATORS_AND_IDENTIFIER.lastIndex = 0; - NUMBERS_AND_IDENTIFIER.lastIndex = 0; - - return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier)) - .replace(NUMBERS_AND_IDENTIFIER, m => toUpperCase(m)); - }; - - const camelCase = (input, options) => { - if (!(typeof input === 'string' || Array.isArray(input))) { - throw new TypeError('Expected the input to be `string | string[]`'); - } - - options = { - pascalCase: false, - preserveConsecutiveUppercase: false, - ...options - }; - - if (Array.isArray(input)) { - input = input.map(x => x.trim()) - .filter(x => x.length) - .join('-'); - } else { - input = input.trim(); - } - - if (input.length === 0) { - return ''; - } - - const toLowerCase = options.locale === false ? - string => string.toLowerCase() : - string => string.toLocaleLowerCase(options.locale); - const toUpperCase = options.locale === false ? - string => string.toUpperCase() : - string => string.toLocaleUpperCase(options.locale); - - if (input.length === 1) { - return options.pascalCase ? toUpperCase(input) : toLowerCase(input); - } - - const hasUpperCase = input !== toLowerCase(input); - - if (hasUpperCase) { - input = preserveCamelCase(input, toLowerCase, toUpperCase); - } - - input = input.replace(LEADING_SEPARATORS, ''); - - if (options.preserveConsecutiveUppercase) { - input = preserveConsecutiveUppercase(input, toLowerCase); - } else { - input = toLowerCase(input); - } - - if (options.pascalCase) { - input = toUpperCase(input.charAt(0)) + input.slice(1); - } - - return postProcess(input, toUpperCase); - }; - - camelcase.exports = camelCase; - // TODO: Remove this for the next major release - camelcase.exports.default = camelCase; - return camelcase.exports; -} - -var ansiAlign_1; -var hasRequiredAnsiAlign; - -function requireAnsiAlign () { - if (hasRequiredAnsiAlign) return ansiAlign_1; - hasRequiredAnsiAlign = 1; - - const stringWidth = requireStringWidth(); - - function ansiAlign (text, opts) { - if (!text) return text - - opts = opts || {}; - const align = opts.align || 'center'; - - // short-circuit `align: 'left'` as no-op - if (align === 'left') return text - - const split = opts.split || '\n'; - const pad = opts.pad || ' '; - const widthDiffFn = align !== 'right' ? halfDiff : fullDiff; - - let returnString = false; - if (!Array.isArray(text)) { - returnString = true; - text = String(text).split(split); - } - - let width; - let maxWidth = 0; - text = text.map(function (str) { - str = String(str); - width = stringWidth(str); - maxWidth = Math.max(width, maxWidth); - return { - str, - width - } - }).map(function (obj) { - return new Array(widthDiffFn(maxWidth, obj.width) + 1).join(pad) + obj.str - }); - - return returnString ? text.join(split) : text - } - - ansiAlign.left = function left (text) { - return ansiAlign(text, { align: 'left' }) - }; - - ansiAlign.center = function center (text) { - return ansiAlign(text, { align: 'center' }) - }; - - ansiAlign.right = function right (text) { - return ansiAlign(text, { align: 'right' }) - }; - - ansiAlign_1 = ansiAlign; - - function halfDiff (maxWidth, curWidth) { - return Math.floor((maxWidth - curWidth) / 2) - } - - function fullDiff (maxWidth, curWidth) { - return maxWidth - curWidth - } - return ansiAlign_1; -} - -var ansiStyles = {exports: {}}; - -var colorName; -var hasRequiredColorName; - -function requireColorName () { - if (hasRequiredColorName) return colorName; - hasRequiredColorName = 1; - - colorName = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aqua": [0, 255, 255], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 219], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [219, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "rebeccapurple": [102, 51, 153], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] - }; - return colorName; -} - -/* MIT license */ - -var conversions; -var hasRequiredConversions; - -function requireConversions () { - if (hasRequiredConversions) return conversions; - hasRequiredConversions = 1; - /* eslint-disable no-mixed-operators */ - const cssKeywords = requireColorName(); - - // NOTE: conversions should only return primitive values (i.e. arrays, or - // values that give correct `typeof` results). - // do not use box values types (i.e. Number(), String(), etc.) - - const reverseKeywords = {}; - for (const key of Object.keys(cssKeywords)) { - reverseKeywords[cssKeywords[key]] = key; - } - - const convert = { - rgb: {channels: 3, labels: 'rgb'}, - hsl: {channels: 3, labels: 'hsl'}, - hsv: {channels: 3, labels: 'hsv'}, - hwb: {channels: 3, labels: 'hwb'}, - cmyk: {channels: 4, labels: 'cmyk'}, - xyz: {channels: 3, labels: 'xyz'}, - lab: {channels: 3, labels: 'lab'}, - lch: {channels: 3, labels: 'lch'}, - hex: {channels: 1, labels: ['hex']}, - keyword: {channels: 1, labels: ['keyword']}, - ansi16: {channels: 1, labels: ['ansi16']}, - ansi256: {channels: 1, labels: ['ansi256']}, - hcg: {channels: 3, labels: ['h', 'c', 'g']}, - apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, - gray: {channels: 1, labels: ['gray']} - }; - - conversions = convert; - - // Hide .channels and .labels properties - for (const model of Object.keys(convert)) { - if (!('channels' in convert[model])) { - throw new Error('missing channels property: ' + model); - } - - if (!('labels' in convert[model])) { - throw new Error('missing channel labels property: ' + model); - } - - if (convert[model].labels.length !== convert[model].channels) { - throw new Error('channel and label counts mismatch: ' + model); - } - - const {channels, labels} = convert[model]; - delete convert[model].channels; - delete convert[model].labels; - Object.defineProperty(convert[model], 'channels', {value: channels}); - Object.defineProperty(convert[model], 'labels', {value: labels}); - } - - convert.rgb.hsl = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const min = Math.min(r, g, b); - const max = Math.max(r, g, b); - const delta = max - min; - let h; - let s; - - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta; - } else if (g === max) { - h = 2 + (b - r) / delta; - } else if (b === max) { - h = 4 + (r - g) / delta; - } - - h = Math.min(h * 60, 360); - - if (h < 0) { - h += 360; - } - - const l = (min + max) / 2; - - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta / (max + min); - } else { - s = delta / (2 - max - min); - } - - return [h, s * 100, l * 100]; - }; - - convert.rgb.hsv = function (rgb) { - let rdif; - let gdif; - let bdif; - let h; - let s; - - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const v = Math.max(r, g, b); - const diff = v - Math.min(r, g, b); - const diffc = function (c) { - return (v - c) / 6 / diff + 1 / 2; - }; - - if (diff === 0) { - h = 0; - s = 0; - } else { - s = diff / v; - rdif = diffc(r); - gdif = diffc(g); - bdif = diffc(b); - - if (r === v) { - h = bdif - gdif; - } else if (g === v) { - h = (1 / 3) + rdif - bdif; - } else if (b === v) { - h = (2 / 3) + gdif - rdif; - } - - if (h < 0) { - h += 1; - } else if (h > 1) { - h -= 1; - } - } - - return [ - h * 360, - s * 100, - v * 100 - ]; - }; - - convert.rgb.hwb = function (rgb) { - const r = rgb[0]; - const g = rgb[1]; - let b = rgb[2]; - const h = convert.rgb.hsl(rgb)[0]; - const w = 1 / 255 * Math.min(r, Math.min(g, b)); - - b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); - - return [h, w * 100, b * 100]; - }; - - convert.rgb.cmyk = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - - const k = Math.min(1 - r, 1 - g, 1 - b); - const c = (1 - r - k) / (1 - k) || 0; - const m = (1 - g - k) / (1 - k) || 0; - const y = (1 - b - k) / (1 - k) || 0; - - return [c * 100, m * 100, y * 100, k * 100]; - }; - - function comparativeDistance(x, y) { - /* - See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance - */ - return ( - ((x[0] - y[0]) ** 2) + - ((x[1] - y[1]) ** 2) + - ((x[2] - y[2]) ** 2) - ); - } - - convert.rgb.keyword = function (rgb) { - const reversed = reverseKeywords[rgb]; - if (reversed) { - return reversed; - } - - let currentClosestDistance = Infinity; - let currentClosestKeyword; - - for (const keyword of Object.keys(cssKeywords)) { - const value = cssKeywords[keyword]; - - // Compute comparative distance - const distance = comparativeDistance(rgb, value); - - // Check if its less, if so set as closest - if (distance < currentClosestDistance) { - currentClosestDistance = distance; - currentClosestKeyword = keyword; - } - } - - return currentClosestKeyword; - }; - - convert.keyword.rgb = function (keyword) { - return cssKeywords[keyword]; - }; - - convert.rgb.xyz = function (rgb) { - let r = rgb[0] / 255; - let g = rgb[1] / 255; - let b = rgb[2] / 255; - - // Assume sRGB - r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); - g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); - b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); - - const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); - const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); - const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); - - return [x * 100, y * 100, z * 100]; - }; - - convert.rgb.lab = function (rgb) { - const xyz = convert.rgb.xyz(rgb); - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; - - x /= 95.047; - y /= 100; - z /= 108.883; - - x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); - - const l = (116 * y) - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); - - return [l, a, b]; - }; - - convert.hsl.rgb = function (hsl) { - const h = hsl[0] / 360; - const s = hsl[1] / 100; - const l = hsl[2] / 100; - let t2; - let t3; - let val; - - if (s === 0) { - val = l * 255; - return [val, val, val]; - } - - if (l < 0.5) { - t2 = l * (1 + s); - } else { - t2 = l + s - l * s; - } - - const t1 = 2 * l - t2; - - const rgb = [0, 0, 0]; - for (let i = 0; i < 3; i++) { - t3 = h + 1 / 3 * -(i - 1); - if (t3 < 0) { - t3++; - } - - if (t3 > 1) { - t3--; - } - - if (6 * t3 < 1) { - val = t1 + (t2 - t1) * 6 * t3; - } else if (2 * t3 < 1) { - val = t2; - } else if (3 * t3 < 2) { - val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; - } else { - val = t1; - } - - rgb[i] = val * 255; - } - - return rgb; - }; - - convert.hsl.hsv = function (hsl) { - const h = hsl[0]; - let s = hsl[1] / 100; - let l = hsl[2] / 100; - let smin = s; - const lmin = Math.max(l, 0.01); - - l *= 2; - s *= (l <= 1) ? l : 2 - l; - smin *= lmin <= 1 ? lmin : 2 - lmin; - const v = (l + s) / 2; - const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); - - return [h, sv * 100, v * 100]; - }; - - convert.hsv.rgb = function (hsv) { - const h = hsv[0] / 60; - const s = hsv[1] / 100; - let v = hsv[2] / 100; - const hi = Math.floor(h) % 6; - - const f = h - Math.floor(h); - const p = 255 * v * (1 - s); - const q = 255 * v * (1 - (s * f)); - const t = 255 * v * (1 - (s * (1 - f))); - v *= 255; - - switch (hi) { - case 0: - return [v, t, p]; - case 1: - return [q, v, p]; - case 2: - return [p, v, t]; - case 3: - return [p, q, v]; - case 4: - return [t, p, v]; - case 5: - return [v, p, q]; - } - }; - - convert.hsv.hsl = function (hsv) { - const h = hsv[0]; - const s = hsv[1] / 100; - const v = hsv[2] / 100; - const vmin = Math.max(v, 0.01); - let sl; - let l; - - l = (2 - s) * v; - const lmin = (2 - s) * vmin; - sl = s * vmin; - sl /= (lmin <= 1) ? lmin : 2 - lmin; - sl = sl || 0; - l /= 2; - - return [h, sl * 100, l * 100]; - }; - - // http://dev.w3.org/csswg/css-color/#hwb-to-rgb - convert.hwb.rgb = function (hwb) { - const h = hwb[0] / 360; - let wh = hwb[1] / 100; - let bl = hwb[2] / 100; - const ratio = wh + bl; - let f; - - // Wh + bl cant be > 1 - if (ratio > 1) { - wh /= ratio; - bl /= ratio; - } - - const i = Math.floor(6 * h); - const v = 1 - bl; - f = 6 * h - i; - - if ((i & 0x01) !== 0) { - f = 1 - f; - } - - const n = wh + f * (v - wh); // Linear interpolation - - let r; - let g; - let b; - /* eslint-disable max-statements-per-line,no-multi-spaces */ - switch (i) { - default: - case 6: - case 0: r = v; g = n; b = wh; break; - case 1: r = n; g = v; b = wh; break; - case 2: r = wh; g = v; b = n; break; - case 3: r = wh; g = n; b = v; break; - case 4: r = n; g = wh; b = v; break; - case 5: r = v; g = wh; b = n; break; - } - /* eslint-enable max-statements-per-line,no-multi-spaces */ - - return [r * 255, g * 255, b * 255]; - }; - - convert.cmyk.rgb = function (cmyk) { - const c = cmyk[0] / 100; - const m = cmyk[1] / 100; - const y = cmyk[2] / 100; - const k = cmyk[3] / 100; - - const r = 1 - Math.min(1, c * (1 - k) + k); - const g = 1 - Math.min(1, m * (1 - k) + k); - const b = 1 - Math.min(1, y * (1 - k) + k); - - return [r * 255, g * 255, b * 255]; - }; - - convert.xyz.rgb = function (xyz) { - const x = xyz[0] / 100; - const y = xyz[1] / 100; - const z = xyz[2] / 100; - let r; - let g; - let b; - - r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); - g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); - b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); - - // Assume sRGB - r = r > 0.0031308 - ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) - : r * 12.92; - - g = g > 0.0031308 - ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) - : g * 12.92; - - b = b > 0.0031308 - ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) - : b * 12.92; - - r = Math.min(Math.max(0, r), 1); - g = Math.min(Math.max(0, g), 1); - b = Math.min(Math.max(0, b), 1); - - return [r * 255, g * 255, b * 255]; - }; - - convert.xyz.lab = function (xyz) { - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; - - x /= 95.047; - y /= 100; - z /= 108.883; - - x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); - - const l = (116 * y) - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); - - return [l, a, b]; - }; - - convert.lab.xyz = function (lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let x; - let y; - let z; - - y = (l + 16) / 116; - x = a / 500 + y; - z = y - b / 200; - - const y2 = y ** 3; - const x2 = x ** 3; - const z2 = z ** 3; - y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; - x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; - z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; - - x *= 95.047; - y *= 100; - z *= 108.883; - - return [x, y, z]; - }; - - convert.lab.lch = function (lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let h; - - const hr = Math.atan2(b, a); - h = hr * 360 / 2 / Math.PI; - - if (h < 0) { - h += 360; - } - - const c = Math.sqrt(a * a + b * b); - - return [l, c, h]; - }; - - convert.lch.lab = function (lch) { - const l = lch[0]; - const c = lch[1]; - const h = lch[2]; - - const hr = h / 360 * 2 * Math.PI; - const a = c * Math.cos(hr); - const b = c * Math.sin(hr); - - return [l, a, b]; - }; - - convert.rgb.ansi16 = function (args, saturation = null) { - const [r, g, b] = args; - let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization - - value = Math.round(value / 50); - - if (value === 0) { - return 30; - } - - let ansi = 30 - + ((Math.round(b / 255) << 2) - | (Math.round(g / 255) << 1) - | Math.round(r / 255)); - - if (value === 2) { - ansi += 60; - } - - return ansi; - }; - - convert.hsv.ansi16 = function (args) { - // Optimization here; we already know the value and don't need to get - // it converted for us. - return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); - }; - - convert.rgb.ansi256 = function (args) { - const r = args[0]; - const g = args[1]; - const b = args[2]; - - // We use the extended greyscale palette here, with the exception of - // black and white. normal palette only has 4 greyscale shades. - if (r === g && g === b) { - if (r < 8) { - return 16; - } - - if (r > 248) { - return 231; - } - - return Math.round(((r - 8) / 247) * 24) + 232; - } - - const ansi = 16 - + (36 * Math.round(r / 255 * 5)) - + (6 * Math.round(g / 255 * 5)) - + Math.round(b / 255 * 5); - - return ansi; - }; - - convert.ansi16.rgb = function (args) { - let color = args % 10; - - // Handle greyscale - if (color === 0 || color === 7) { - if (args > 50) { - color += 3.5; - } - - color = color / 10.5 * 255; - - return [color, color, color]; - } - - const mult = (~~(args > 50) + 1) * 0.5; - const r = ((color & 1) * mult) * 255; - const g = (((color >> 1) & 1) * mult) * 255; - const b = (((color >> 2) & 1) * mult) * 255; - - return [r, g, b]; - }; - - convert.ansi256.rgb = function (args) { - // Handle greyscale - if (args >= 232) { - const c = (args - 232) * 10 + 8; - return [c, c, c]; - } - - args -= 16; - - let rem; - const r = Math.floor(args / 36) / 5 * 255; - const g = Math.floor((rem = args % 36) / 6) / 5 * 255; - const b = (rem % 6) / 5 * 255; - - return [r, g, b]; - }; - - convert.rgb.hex = function (args) { - const integer = ((Math.round(args[0]) & 0xFF) << 16) - + ((Math.round(args[1]) & 0xFF) << 8) - + (Math.round(args[2]) & 0xFF); - - const string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; - }; - - convert.hex.rgb = function (args) { - const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); - if (!match) { - return [0, 0, 0]; - } - - let colorString = match[0]; - - if (match[0].length === 3) { - colorString = colorString.split('').map(char => { - return char + char; - }).join(''); - } - - const integer = parseInt(colorString, 16); - const r = (integer >> 16) & 0xFF; - const g = (integer >> 8) & 0xFF; - const b = integer & 0xFF; - - return [r, g, b]; - }; - - convert.rgb.hcg = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const max = Math.max(Math.max(r, g), b); - const min = Math.min(Math.min(r, g), b); - const chroma = (max - min); - let grayscale; - let hue; - - if (chroma < 1) { - grayscale = min / (1 - chroma); - } else { - grayscale = 0; - } - - if (chroma <= 0) { - hue = 0; - } else - if (max === r) { - hue = ((g - b) / chroma) % 6; - } else - if (max === g) { - hue = 2 + (b - r) / chroma; - } else { - hue = 4 + (r - g) / chroma; - } - - hue /= 6; - hue %= 1; - - return [hue * 360, chroma * 100, grayscale * 100]; - }; - - convert.hsl.hcg = function (hsl) { - const s = hsl[1] / 100; - const l = hsl[2] / 100; - - const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); - - let f = 0; - if (c < 1.0) { - f = (l - 0.5 * c) / (1.0 - c); - } - - return [hsl[0], c * 100, f * 100]; - }; - - convert.hsv.hcg = function (hsv) { - const s = hsv[1] / 100; - const v = hsv[2] / 100; - - const c = s * v; - let f = 0; - - if (c < 1.0) { - f = (v - c) / (1 - c); - } - - return [hsv[0], c * 100, f * 100]; - }; - - convert.hcg.rgb = function (hcg) { - const h = hcg[0] / 360; - const c = hcg[1] / 100; - const g = hcg[2] / 100; - - if (c === 0.0) { - return [g * 255, g * 255, g * 255]; - } - - const pure = [0, 0, 0]; - const hi = (h % 1) * 6; - const v = hi % 1; - const w = 1 - v; - let mg = 0; - - /* eslint-disable max-statements-per-line */ - switch (Math.floor(hi)) { - case 0: - pure[0] = 1; pure[1] = v; pure[2] = 0; break; - case 1: - pure[0] = w; pure[1] = 1; pure[2] = 0; break; - case 2: - pure[0] = 0; pure[1] = 1; pure[2] = v; break; - case 3: - pure[0] = 0; pure[1] = w; pure[2] = 1; break; - case 4: - pure[0] = v; pure[1] = 0; pure[2] = 1; break; - default: - pure[0] = 1; pure[1] = 0; pure[2] = w; - } - /* eslint-enable max-statements-per-line */ - - mg = (1.0 - c) * g; - - return [ - (c * pure[0] + mg) * 255, - (c * pure[1] + mg) * 255, - (c * pure[2] + mg) * 255 - ]; - }; - - convert.hcg.hsv = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - - const v = c + g * (1.0 - c); - let f = 0; - - if (v > 0.0) { - f = c / v; - } - - return [hcg[0], f * 100, v * 100]; - }; - - convert.hcg.hsl = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - - const l = g * (1.0 - c) + 0.5 * c; - let s = 0; - - if (l > 0.0 && l < 0.5) { - s = c / (2 * l); - } else - if (l >= 0.5 && l < 1.0) { - s = c / (2 * (1 - l)); - } - - return [hcg[0], s * 100, l * 100]; - }; - - convert.hcg.hwb = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - const v = c + g * (1.0 - c); - return [hcg[0], (v - c) * 100, (1 - v) * 100]; - }; - - convert.hwb.hcg = function (hwb) { - const w = hwb[1] / 100; - const b = hwb[2] / 100; - const v = 1 - b; - const c = v - w; - let g = 0; - - if (c < 1) { - g = (v - c) / (1 - c); - } - - return [hwb[0], c * 100, g * 100]; - }; - - convert.apple.rgb = function (apple) { - return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; - }; - - convert.rgb.apple = function (rgb) { - return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; - }; - - convert.gray.rgb = function (args) { - return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; - }; - - convert.gray.hsl = function (args) { - return [0, 0, args[0]]; - }; - - convert.gray.hsv = convert.gray.hsl; - - convert.gray.hwb = function (gray) { - return [0, 100, gray[0]]; - }; - - convert.gray.cmyk = function (gray) { - return [0, 0, 0, gray[0]]; - }; - - convert.gray.lab = function (gray) { - return [gray[0], 0, 0]; - }; - - convert.gray.hex = function (gray) { - const val = Math.round(gray[0] / 100 * 255) & 0xFF; - const integer = (val << 16) + (val << 8) + val; - - const string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; - }; - - convert.rgb.gray = function (rgb) { - const val = (rgb[0] + rgb[1] + rgb[2]) / 3; - return [val / 255 * 100]; - }; - return conversions; -} - -var route; -var hasRequiredRoute; - -function requireRoute () { - if (hasRequiredRoute) return route; - hasRequiredRoute = 1; - const conversions = requireConversions(); - - /* - This function routes a model to all other models. - - all functions that are routed have a property `.conversion` attached - to the returned synthetic function. This property is an array - of strings, each with the steps in between the 'from' and 'to' - color models (inclusive). - - conversions that are not possible simply are not included. - */ - - function buildGraph() { - const graph = {}; - // https://jsperf.com/object-keys-vs-for-in-with-closure/3 - const models = Object.keys(conversions); - - for (let len = models.length, i = 0; i < len; i++) { - graph[models[i]] = { - // http://jsperf.com/1-vs-infinity - // micro-opt, but this is simple. - distance: -1, - parent: null - }; - } - - return graph; - } - - // https://en.wikipedia.org/wiki/Breadth-first_search - function deriveBFS(fromModel) { - const graph = buildGraph(); - const queue = [fromModel]; // Unshift -> queue -> pop - - graph[fromModel].distance = 0; - - while (queue.length) { - const current = queue.pop(); - const adjacents = Object.keys(conversions[current]); - - for (let len = adjacents.length, i = 0; i < len; i++) { - const adjacent = adjacents[i]; - const node = graph[adjacent]; - - if (node.distance === -1) { - node.distance = graph[current].distance + 1; - node.parent = current; - queue.unshift(adjacent); - } - } - } - - return graph; - } - - function link(from, to) { - return function (args) { - return to(from(args)); - }; - } - - function wrapConversion(toModel, graph) { - const path = [graph[toModel].parent, toModel]; - let fn = conversions[graph[toModel].parent][toModel]; - - let cur = graph[toModel].parent; - while (graph[cur].parent) { - path.unshift(graph[cur].parent); - fn = link(conversions[graph[cur].parent][cur], fn); - cur = graph[cur].parent; - } - - fn.conversion = path; - return fn; - } - - route = function (fromModel) { - const graph = deriveBFS(fromModel); - const conversion = {}; - - const models = Object.keys(graph); - for (let len = models.length, i = 0; i < len; i++) { - const toModel = models[i]; - const node = graph[toModel]; - - if (node.parent === null) { - // No possible conversion, or this node is the source model. - continue; - } - - conversion[toModel] = wrapConversion(toModel, graph); - } - - return conversion; - }; - return route; -} - -var colorConvert; -var hasRequiredColorConvert; - -function requireColorConvert () { - if (hasRequiredColorConvert) return colorConvert; - hasRequiredColorConvert = 1; - const conversions = requireConversions(); - const route = requireRoute(); - - const convert = {}; - - const models = Object.keys(conversions); - - function wrapRaw(fn) { - const wrappedFn = function (...args) { - const arg0 = args[0]; - if (arg0 === undefined || arg0 === null) { - return arg0; - } - - if (arg0.length > 1) { - args = arg0; - } - - return fn(args); - }; - - // Preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; - } - - function wrapRounded(fn) { - const wrappedFn = function (...args) { - const arg0 = args[0]; - - if (arg0 === undefined || arg0 === null) { - return arg0; - } - - if (arg0.length > 1) { - args = arg0; - } - - const result = fn(args); - - // We're assuming the result is an array here. - // see notice in conversions.js; don't use box types - // in conversion functions. - if (typeof result === 'object') { - for (let len = result.length, i = 0; i < len; i++) { - result[i] = Math.round(result[i]); - } - } - - return result; - }; - - // Preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; - } - - models.forEach(fromModel => { - convert[fromModel] = {}; - - Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); - Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); - - const routes = route(fromModel); - const routeModels = Object.keys(routes); - - routeModels.forEach(toModel => { - const fn = routes[toModel]; - - convert[fromModel][toModel] = wrapRounded(fn); - convert[fromModel][toModel].raw = wrapRaw(fn); - }); - }); - - colorConvert = convert; - return colorConvert; -} - -ansiStyles.exports; - -var hasRequiredAnsiStyles; - -function requireAnsiStyles () { - if (hasRequiredAnsiStyles) return ansiStyles.exports; - hasRequiredAnsiStyles = 1; - (function (module) { - - const wrapAnsi16 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${code + offset}m`; - }; - - const wrapAnsi256 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${38 + offset};5;${code}m`; - }; - - const wrapAnsi16m = (fn, offset) => (...args) => { - const rgb = fn(...args); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; - }; - - const ansi2ansi = n => n; - const rgb2rgb = (r, g, b) => [r, g, b]; - - const setLazyProperty = (object, property, get) => { - Object.defineProperty(object, property, { - get: () => { - const value = get(); - - Object.defineProperty(object, property, { - value, - enumerable: true, - configurable: true - }); - - return value; - }, - enumerable: true, - configurable: true - }); - }; - - /** @type {typeof import('color-convert')} */ - let colorConvert; - const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { - if (colorConvert === undefined) { - colorConvert = requireColorConvert(); - } - - const offset = isBackground ? 10 : 0; - const styles = {}; - - for (const [sourceSpace, suite] of Object.entries(colorConvert)) { - const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; - if (sourceSpace === targetSpace) { - styles[name] = wrap(identity, offset); - } else if (typeof suite === 'object') { - styles[name] = wrap(suite[targetSpace], offset); - } - } - - return styles; - }; - - function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - - // Bright color - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - - // Alias bright black as gray (and grey) - styles.color.gray = styles.color.blackBright; - styles.bgColor.bgGray = styles.bgColor.bgBlackBright; - styles.color.grey = styles.color.blackBright; - styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; - - for (const [groupName, group] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group)) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; - - group[styleName] = styles[styleName]; - - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - } - - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; - - setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); - setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); - - return styles; - } - - // Make the export immutable - Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles - }); - } (ansiStyles)); - return ansiStyles.exports; -} - -var wrapAnsi_1; -var hasRequiredWrapAnsi; - -function requireWrapAnsi () { - if (hasRequiredWrapAnsi) return wrapAnsi_1; - hasRequiredWrapAnsi = 1; - const stringWidth = requireStringWidth(); - const stripAnsi = requireStripAnsi(); - const ansiStyles = requireAnsiStyles(); - - const ESCAPES = new Set([ - '\u001B', - '\u009B' - ]); - - const END_CODE = 39; - - const ANSI_ESCAPE_BELL = '\u0007'; - const ANSI_CSI = '['; - const ANSI_OSC = ']'; - const ANSI_SGR_TERMINATOR = 'm'; - const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`; - - const wrapAnsi = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`; - const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`; - - // Calculate the length of words split on ' ', ignoring - // the extra characters added by ansi escape codes - const wordLengths = string => string.split(' ').map(character => stringWidth(character)); - - // Wrap a long word across multiple rows - // Ansi escape codes do not count towards length - const wrapWord = (rows, word, columns) => { - const characters = [...word]; - - let isInsideEscape = false; - let isInsideLinkEscape = false; - let visible = stringWidth(stripAnsi(rows[rows.length - 1])); - - for (const [index, character] of characters.entries()) { - const characterLength = stringWidth(character); - - if (visible + characterLength <= columns) { - rows[rows.length - 1] += character; - } else { - rows.push(character); - visible = 0; - } - - if (ESCAPES.has(character)) { - isInsideEscape = true; - isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK); - } - - if (isInsideEscape) { - if (isInsideLinkEscape) { - if (character === ANSI_ESCAPE_BELL) { - isInsideEscape = false; - isInsideLinkEscape = false; - } - } else if (character === ANSI_SGR_TERMINATOR) { - isInsideEscape = false; - } - - continue; - } - - visible += characterLength; - - if (visible === columns && index < characters.length - 1) { - rows.push(''); - visible = 0; - } - } - - // It's possible that the last row we copy over is only - // ansi escape characters, handle this edge-case - if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { - rows[rows.length - 2] += rows.pop(); - } - }; - - // Trims spaces from a string ignoring invisible sequences - const stringVisibleTrimSpacesRight = string => { - const words = string.split(' '); - let last = words.length; - - while (last > 0) { - if (stringWidth(words[last - 1]) > 0) { - break; - } - - last--; - } - - if (last === words.length) { - return string; - } - - return words.slice(0, last).join(' ') + words.slice(last).join(''); - }; - - // The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode - // - // 'hard' will never allow a string to take up more than columns characters - // - // 'soft' allows long words to expand past the column length - const exec = (string, columns, options = {}) => { - if (options.trim !== false && string.trim() === '') { - return ''; - } - - let returnValue = ''; - let escapeCode; - let escapeUrl; - - const lengths = wordLengths(string); - let rows = ['']; - - for (const [index, word] of string.split(' ').entries()) { - if (options.trim !== false) { - rows[rows.length - 1] = rows[rows.length - 1].trimStart(); - } - - let rowLength = stringWidth(rows[rows.length - 1]); - - if (index !== 0) { - if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { - // If we start with a new word but the current row length equals the length of the columns, add a new row - rows.push(''); - rowLength = 0; - } - - if (rowLength > 0 || options.trim === false) { - rows[rows.length - 1] += ' '; - rowLength++; - } - } - - // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' - if (options.hard && lengths[index] > columns) { - const remainingColumns = (columns - rowLength); - const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); - const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); - if (breaksStartingNextLine < breaksStartingThisLine) { - rows.push(''); - } - - wrapWord(rows, word, columns); - continue; - } - - if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { - if (options.wordWrap === false && rowLength < columns) { - wrapWord(rows, word, columns); - continue; - } - - rows.push(''); - } - - if (rowLength + lengths[index] > columns && options.wordWrap === false) { - wrapWord(rows, word, columns); - continue; - } - - rows[rows.length - 1] += word; - } - - if (options.trim !== false) { - rows = rows.map(stringVisibleTrimSpacesRight); - } - - const pre = [...rows.join('\n')]; - - for (const [index, character] of pre.entries()) { - returnValue += character; - - if (ESCAPES.has(character)) { - const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}}; - if (groups.code !== undefined) { - const code = Number.parseFloat(groups.code); - escapeCode = code === END_CODE ? undefined : code; - } else if (groups.uri !== undefined) { - escapeUrl = groups.uri.length === 0 ? undefined : groups.uri; - } - } - - const code = ansiStyles.codes.get(Number(escapeCode)); - - if (pre[index + 1] === '\n') { - if (escapeUrl) { - returnValue += wrapAnsiHyperlink(''); - } - - if (escapeCode && code) { - returnValue += wrapAnsi(code); - } - } else if (character === '\n') { - if (escapeCode && code) { - returnValue += wrapAnsi(escapeCode); - } - - if (escapeUrl) { - returnValue += wrapAnsiHyperlink(escapeUrl); - } - } - } - - return returnValue; - }; - - // For each newline, invoke the method separately - wrapAnsi_1 = (string, columns, options) => { - return String(string) - .normalize() - .replace(/\r\n/g, '\n') - .split('\n') - .map(line => exec(line, columns, options)) - .join('\n'); - }; - return wrapAnsi_1; -} - -var hasRequiredBoxen; - -function requireBoxen () { - if (hasRequiredBoxen) return boxen$1.exports; - hasRequiredBoxen = 1; - const stringWidth = requireStringWidth(); - const chalk$1 = chalk; - const widestLine = requireWidestLine(); - const cliBoxes = requireCliBoxes(); - const camelCase = requireCamelcase(); - const ansiAlign = requireAnsiAlign(); - const wrapAnsi = requireWrapAnsi(); - - const NL = '\n'; - const PAD = ' '; - - const terminalColumns = () => { - const {env, stdout, stderr} = process; - - if (stdout && stdout.columns) { - return stdout.columns; - } - - if (stderr && stderr.columns) { - return stderr.columns; - } - - if (env.COLUMNS) { - return Number.parseInt(env.COLUMNS, 10); - } - - return 80; - }; - - const getObject = detail => { - return typeof detail === 'number' ? { - top: detail, - right: detail * 3, - bottom: detail, - left: detail * 3 - } : { - top: 0, - right: 0, - bottom: 0, - left: 0, - ...detail - }; - }; - - const getBorderChars = borderStyle => { - const sides = [ - 'topLeft', - 'topRight', - 'bottomRight', - 'bottomLeft', - 'vertical', - 'horizontal' - ]; - - let chararacters; - - if (typeof borderStyle === 'string') { - chararacters = cliBoxes[borderStyle]; - - if (!chararacters) { - throw new TypeError(`Invalid border style: ${borderStyle}`); - } - } else { - for (const side of sides) { - if (!borderStyle[side] || typeof borderStyle[side] !== 'string') { - throw new TypeError(`Invalid border style: ${side}`); - } - } - - chararacters = borderStyle; - } - - return chararacters; - }; - - const makeTitle = (text, horizontal, alignement) => { - let title = ''; - - const textWidth = stringWidth(text); - - switch (alignement) { - case 'left': - title = text + horizontal.slice(textWidth); - break; - case 'right': - title = horizontal.slice(textWidth) + text; - break; - default: - horizontal = horizontal.slice(textWidth); - - if (horizontal.length % 2 === 1) { // This is needed in case the length is odd - horizontal = horizontal.slice(Math.floor(horizontal.length / 2)); - title = horizontal.slice(1) + text + horizontal; // We reduce the left part of one character to avoid the bar to go beyond its limit - } else { - horizontal = horizontal.slice(horizontal.length / 2); - title = horizontal + text + horizontal; - } - - break; - } - - return title; - }; - - const makeContentText = (text, padding, columns, align) => { - text = ansiAlign(text, {align}); - let lines = text.split(NL); - const textWidth = widestLine(text); - - const max = columns - padding.left - padding.right; - - if (textWidth > max) { - const newLines = []; - for (const line of lines) { - const createdLines = wrapAnsi(line, max, {hard: true}); - const alignedLines = ansiAlign(createdLines, {align}); - const alignedLinesArray = alignedLines.split('\n'); - const longestLength = Math.max(...alignedLinesArray.map(s => stringWidth(s))); - - for (const alignedLine of alignedLinesArray) { - let paddedLine; - switch (align) { - case 'center': - paddedLine = PAD.repeat((max - longestLength) / 2) + alignedLine; - break; - case 'right': - paddedLine = PAD.repeat(max - longestLength) + alignedLine; - break; - default: - paddedLine = alignedLine; - break; - } - - newLines.push(paddedLine); - } - } - - lines = newLines; - } - - if (align === 'center' && textWidth < max) { - lines = lines.map(line => PAD.repeat((max - textWidth) / 2) + line); - } else if (align === 'right' && textWidth < max) { - lines = lines.map(line => PAD.repeat(max - textWidth) + line); - } - - const paddingLeft = PAD.repeat(padding.left); - const paddingRight = PAD.repeat(padding.right); - - lines = lines.map(line => paddingLeft + line + paddingRight); - - lines = lines.map(line => { - if (columns - stringWidth(line) > 0) { - switch (align) { - case 'center': - return line + PAD.repeat(columns - stringWidth(line)); - case 'right': - return line + PAD.repeat(columns - stringWidth(line)); - default: - return line + PAD.repeat(columns - stringWidth(line)); - } - } - - return line; - }); - - if (padding.top > 0) { - lines = new Array(padding.top).fill(PAD.repeat(columns)).concat(lines); - } - - if (padding.bottom > 0) { - lines = lines.concat(new Array(padding.bottom).fill(PAD.repeat(columns))); - } - - return lines.join(NL); - }; - - const isHex = color => color.match(/^#(?:[0-f]{3}){1,2}$/i); - const isColorValid = color => typeof color === 'string' && ((chalk$1[color]) || isHex(color)); - const getColorFn = color => isHex(color) ? chalk$1.hex(color) : chalk$1[color]; - const getBGColorFn = color => isHex(color) ? chalk$1.bgHex(color) : chalk$1[camelCase(['bg', color])]; - - boxen$1.exports = (text, options) => { - options = { - padding: 0, - borderStyle: 'single', - dimBorder: false, - textAlignment: 'left', - float: 'left', - titleAlignment: 'left', - ...options - }; - - // This option is deprecated - if (options.align) { - options.textAlignment = options.align; - } - - const BORDERS_WIDTH = 2; - - if (options.borderColor && !isColorValid(options.borderColor)) { - throw new Error(`${options.borderColor} is not a valid borderColor`); - } - - if (options.backgroundColor && !isColorValid(options.backgroundColor)) { - throw new Error(`${options.backgroundColor} is not a valid backgroundColor`); - } - - const chars = getBorderChars(options.borderStyle); - const padding = getObject(options.padding); - const margin = getObject(options.margin); - - const colorizeBorder = border => { - const newBorder = options.borderColor ? getColorFn(options.borderColor)(border) : border; - return options.dimBorder ? chalk$1.dim(newBorder) : newBorder; - }; - - const colorizeContent = content => options.backgroundColor ? getBGColorFn(options.backgroundColor)(content) : content; - - const columns = terminalColumns() - 1; - - let contentWidth = widestLine(wrapAnsi(text, columns - BORDERS_WIDTH, {hard: true, trim: false})) + padding.left + padding.right; - - // This prevents the title bar to exceed the console's width - let title = options.title && options.title.slice(0, columns - 4 - margin.left - margin.right); - - if (title) { - title = ` ${title} `; - // Make the box larger to fit a larger title - if (stringWidth(title) > contentWidth) { - contentWidth = stringWidth(title); - } - } - - if ((margin.left && margin.right) && contentWidth + BORDERS_WIDTH + margin.left + margin.right > columns) { - // Let's assume we have margins: left = 3, right = 5, in total = 8 - const spaceForMargins = columns - contentWidth - BORDERS_WIDTH; - // Let's assume we have space = 4 - const multiplier = spaceForMargins / (margin.left + margin.right); - // Here: multiplier = 4/8 = 0.5 - margin.left = Math.max(0, Math.floor(margin.left * multiplier)); - margin.right = Math.max(0, Math.floor(margin.right * multiplier)); - // Left: 3 * 0.5 = 1.5 -> 1 - // Right: 6 * 0.5 = 3 - } - - // Prevent content from exceeding the console's width - contentWidth = Math.min(contentWidth, columns - BORDERS_WIDTH - margin.left - margin.right); - - text = makeContentText(text, padding, contentWidth, options.textAlignment); - - let marginLeft = PAD.repeat(margin.left); - - if (options.float === 'center') { - const marginWidth = Math.max((columns - contentWidth - BORDERS_WIDTH) / 2, 0); - marginLeft = PAD.repeat(marginWidth); - } else if (options.float === 'right') { - const marginWidth = Math.max(columns - contentWidth - margin.right - BORDERS_WIDTH, 0); - marginLeft = PAD.repeat(marginWidth); - } - - const horizontal = chars.horizontal.repeat(contentWidth); - const top = colorizeBorder(NL.repeat(margin.top) + marginLeft + chars.topLeft + (title ? makeTitle(title, horizontal, options.titleAlignment) : horizontal) + chars.topRight); - const bottom = colorizeBorder(marginLeft + chars.bottomLeft + horizontal + chars.bottomRight + NL.repeat(margin.bottom)); - const side = colorizeBorder(chars.vertical); - - const LINE_SEPARATOR = NL; - - const lines = text.split(NL); - - const middle = lines.map(line => { - return marginLeft + side + colorizeContent(line) + side; - }).join(LINE_SEPARATOR); - - return top + LINE_SEPARATOR + middle + LINE_SEPARATOR + bottom; - }; - - boxen$1.exports._borderStyles = cliBoxes; - return boxen$1.exports; -} - -var boxenExports = requireBoxen(); -var boxen = /*@__PURE__*/getDefaultExportFromCjs(boxenExports); - -function makeTitledPrettyError(title, content, stack) { - return makePrettyError(chalk.redBright(title) + "\n\n" + content, stack); -} -function makePrettyError(content, stack) { - if (process$1.browser || process$1.env.LMS_NO_FANCY_ERRORS || lmsIsomorphic.terminalSize().columns < 80) { - const error = new Error(content); - if (stack === undefined) { - changeErrorStackInPlace(error, ""); - } - else { - changeErrorStackInPlace(error, stack); - } - return error; - } - else { - if (stack !== undefined) { - content += - "\n\n\n " + chalk.bgWhite.black(" STACK TRACE ") + "\n\n" + chalk.gray(stack); - } - const error = new Error("\n" + boxen(content, { padding: 1, margin: 1, borderColor: "redBright", title: "Error" })); - Object.defineProperty(error, "lmstudioRawError", { value: content, enumerable: false }); - changeErrorStackInPlace(error, ""); - return error; - } -} - -/** - * A cache for avoiding recompiling the same template strings. - * - * The cached value is a string with 2N + 1 elements, where N is the number of variables in the - * template. - */ -const compiledTemplatesCache = new WeakMap(); -/** - * A string literal tag function that does the following: - * - * - Removes leading new lines - * - Removes trailing new lines and whitespace - * - Removes common indentation from the start of each line (Empty lines are ignored) - * - Single newlines are replaced with a space + extra whitespace is removed - * - * Note: Only spaces are considered. - * - * @remarks - * - * The exact implementation of this function is not guaranteed to be the same, as we may add - * additional edge case handling in the future. However, the general behavior should remain the - * same. - * - * @public - */ -function text(strings, ...values) { - if (values.length + 1 !== strings.length) { - throw new Error("text called with the wrong number of arguments."); - } - let compiled = compiledTemplatesCache.get(strings); - if (compiled === undefined) { - compiled = compile(strings); - compiledTemplatesCache.set(strings, compiled); - } - // We can modify the array in place because JavaScript is single-threaded and the array is not - // being accessed by any other code. - for (let i = 0; i < values.length; i++) { - if (typeof values[i] === "object") { - if (typeof values[i].stack === "string") { - compiled[i * 2 + 1] = values[i].stack; - } - else { - try { - compiled[i * 2 + 1] = JSON.stringify(values[i]); - } - catch (error) { - compiled[i * 2 + 1] = "[Object failed to stringify]"; - } - } - } - else { - compiled[i * 2 + 1] = String(values[i]); - } - } - return compiled.join(""); -} -function removeLeadingNewlines(input) { - return input.replace(/^\n+/, ""); -} -function removeTrailingNewlinesAndWhitespace(input) { - return input.replace(/[\n ]+$/, ""); -} -function removeLeadingWhitespace(input) { - return input.replace(/^ +/, ""); -} -function removeTrailingWhitespace(input) { - return input.replace(/ +$/, ""); -} -function breakIntoLines(strings) { - const lines = []; - let currentLine = []; - for (const string of strings) { - let prevNewlineIndex = -1; - let nextNewlineIndex; - while ((nextNewlineIndex = string.indexOf("\n", prevNewlineIndex + 1)) !== -1) { - currentLine.push(string.substring(prevNewlineIndex + 1, nextNewlineIndex)); - lines.push(currentLine); - currentLine = []; - prevNewlineIndex = nextNewlineIndex; - } - currentLine.push(string.substring(prevNewlineIndex + 1)); - } - lines.push(currentLine); - return lines; -} -/** - * Returns the number of spaces at the start of the string. If the string only contains spaces, - * returns infinity. - */ -function countStringIndentations(string) { - let count = 0; - for (const char of string) { - if (char === " ") { - count++; - } - else { - return count; - } - } - return Infinity; -} -function countLineIndentations(line) { - const firstPart = line[0]; - const firstPartIndentation = countStringIndentations(firstPart); - if (firstPartIndentation === Infinity) { - if (line.length === 1) { - return Infinity; - } - else { - // If there is a variable after it, the length of indentation is the same as the length of the - // first part. - return firstPart.length; - } - } - return firstPartIndentation; -} -function findMaxCommonIndentation(lines) { - let minIndentation = Infinity; - for (const line of lines) { - minIndentation = Math.min(minIndentation, countLineIndentations(line)); - } - return minIndentation; -} -function removeIndentation(line, indentation) { - if (line.length < indentation) { - return ""; - } - return line.slice(indentation); -} -function removeAllIndentation(lines, indentation) { - for (const line of lines) { - line[0] = removeIndentation(line[0], indentation); - } -} -function isEmptyLine(line) { - if (line.length !== 1) { - return false; - } - for (const char of line[0]) { - if (char !== " ") { - return false; - } - } - return true; -} -function mergeLines(lines) { - const linesAreEmpty = lines.map(isEmptyLine); - const paragraphs = []; - let currentParagraph = []; - for (let i = 0; i < lines.length; i++) { - if (linesAreEmpty[i]) { - if (currentParagraph.length !== 0) { - paragraphs.push(currentParagraph); - currentParagraph = []; - } - continue; - } - if (currentParagraph.length !== 0) { - const last = removeTrailingWhitespace(currentParagraph[currentParagraph.length - 1]); - const next = removeLeadingWhitespace(lines[i][0]); - currentParagraph[currentParagraph.length - 1] = last + " " + next; - currentParagraph.push(...lines[i].slice(1)); - } - else { - currentParagraph.push(...lines[i]); - } - } - if (currentParagraph.length !== 0) { - paragraphs.push(currentParagraph); - } - return paragraphs; -} -function mergeParagraphs(paragraphs) { - const result = []; - if (paragraphs.length === 0) { - return [""]; - } - result.push(...paragraphs[0]); - for (let i = 1; i < paragraphs.length; i++) { - result[result.length - 1] += "\n\n" + paragraphs[i][0]; - result.push(...paragraphs[i].slice(1)); - } - return result; -} -function addHolesForVariables(strings) { - const result = []; - for (let i = 0; i < strings.length; i++) { - result.push(strings[i]); - if (i < strings.length - 1) { - result.push(""); - } - } - return result; -} -function compile(readonlyStrings) { - const strings = [...readonlyStrings]; - strings[0] = removeLeadingNewlines(strings[0]); - strings[strings.length - 1] = removeTrailingNewlinesAndWhitespace(strings[strings.length - 1]); - const lines = breakIntoLines(strings); - const commonIndentation = findMaxCommonIndentation(lines); - removeAllIndentation(lines, commonIndentation); - const paragraphs = mergeLines(lines); - return addHolesForVariables(mergeParagraphs(paragraphs)); -} - -/** - * Represents some underlying data that may or may not be mutable. - * - * @public - */ -class MaybeMutable { - constructor(data, mutable) { - this.data = data; - this.mutable = mutable; - } - /** - * Gets the underlying data without any access control. Only used internally. - * - * @internal - */ - _internalGetData() { - return this.data; - } - /** - * If this instance is mutable, return as is. - * - * If this instance is immutable, return a mutable copy. - * - * Very easy to misuse, thus internal only for now. - * - * @internal - */ - _internalToMutable() { - if (this.mutable) { - return this; - } - return this.asMutableCopy(); - } - asMutableCopy() { - return this.create(this.cloneData(this.data), true); - } - asImmutableCopy() { - if (this.mutable) { - return this.create(this.cloneData(this.data), false); - } - return this; - } - guardMutable() { - if (!this.mutable) { - throw new Error(text ` - Cannot modify immutable ${this.getClassName()} instance. Use asMutableCopy() to get a - mutable copy. - `); - } - } -} -function accessMaybeMutableInternals(maybeMutable) { - return maybeMutable; -} - -/** - * OWLSignal - Optimistic Writable Lazy Signal - * - * - Signal: It is a signal, i.e. an observable that remembers its current value - * - Lazy: It is lazy, i.e. it does not subscribe to the upstream until a subscriber is attached - * - Writable: It is writable, i.e. it has a setter to update its value - * - Optimistic: It is optimistic, i.e. it updates its value optimistically and then waits for the - * upstream to confirm the update - * - Once the setter is called, the value is updated optimistically and all subscribers are - * notified synchronously - * - * Guarantees: - * - * - The OWLSignal is designed for single-writer multiple-reader scenarios, as the coordination of - * writes are tracked inside the OWLSignal. If there are multiple writers for the same data (i.e. - * multiple OWLSignal backed by the same upstream), there are no strong guarantees. For example, - * two updaters may read the same value, update it, and write it back to the upstream, causing one - * of the updates to be lost. The following guarantees are provided for single-writer scenarios: - * - The updates are applied in the order they are received, and each updater is guaranteed to see - * all updates that were applied before it. - * - If there are updaters [u_0, u_1, ..., u_n], for any read-only reader, there exists a time t - * where the reader will see the updates [u_0, u_1, ..., u_t] in the order they were applied. This - * also applies to the writer itself. - */ -class OWLSignal extends Subscribable { - static { this.NOT_AVAILABLE = LazySignal.NOT_AVAILABLE; } - applyOptimisticUpdates(data) { - for (const update of this.queuedUpdates) { - [data] = update.updater(data); - } - return data; - } - updateOptimisticValue(tags) { - const innerValue = this.innerSignal.get(); - if (!isAvailable(innerValue)) { - return; - } - this.setOuterSignal(this.applyOptimisticUpdates(innerValue), tags); - } - constructor(initialValue, subscribeUpstream, writeUpstream, equalsPredicate) { - super(); - this.writeUpstream = writeUpstream; - this.isWriteLoopRunning = false; - /** - * We have a passive subscription to the inner signal to update the optimistic value whenever the - * inner signal changes. - * - * However, if the content changes are caused by a write, we want to update the inner value, - * remove the optimistic update, and apply the remaining optimistic updates all at once. - * - * Therefore, when a write is ongoing, we set this flag to true to prevent the passive - * subscription from updating the optimistic value. We will handle the updates within the write - * loop. - */ - this.isSubscriptionHandledByWriteLoop = false; - /** - * A queue of updates to apply optimistically. - */ - this.queuedUpdates = []; - this.currentEnsureAvailablePromise = null; - [this.writeErrorEvent, this.emitWriteErrorEvent] = Event.create(); - [this.outerSignal, this.setOuterSignal] = Signal.create(initialValue, equalsPredicate); - this.innerSignal = LazySignal.create(initialValue, subscribeUpstream, equalsPredicate); - this.innerSignal.passiveSubscribeFull((_data, _patches, tags) => { - if (this.isSubscriptionHandledByWriteLoop) { - return; - } - this.updateOptimisticValue(tags); - }); - } - static create(initialValue, subscribeUpstream, - /** - * Returns true if the update is sent to the upstream (thus should wait for the upstream to - * confirm. Returns false if the update is not sent and the update should be dropped. - */ - writeUpstream, equalsPredicate = (a, b) => a === b) { - const signal = new OWLSignal(initialValue, subscribeUpstream, writeUpstream, equalsPredicate); - const setSignal = makeSetterWithPatches(signal.update.bind(signal)); - const emitError = (tags, error) => signal.emitWriteErrorEvent({ tags, error }); - return [signal, setSignal, emitError]; - } - static createWithoutInitialValue(subscribeUpstream, writeUpstream, equalsPredicate = (a, b) => a === b) { - const fullEqualsPredicate = (a, b) => { - if (a === OWLSignal.NOT_AVAILABLE || b === OWLSignal.NOT_AVAILABLE) { - return a === b; - } - return equalsPredicate(a, b); - }; - return OWLSignal.create(OWLSignal.NOT_AVAILABLE, subscribeUpstream, writeUpstream, fullEqualsPredicate); - } - async update(updater, tags) { - const { promise, reject, resolve } = makePromise(); - this.queuedUpdates.push({ - updater, - tags: tags ?? [], - resolve, - reject, - }); - this.updateOptimisticValue(); - this.ensureWriteLoop(); - return promise; - } - /** - * Starts the write loop if it is not already running. - */ - ensureWriteLoop() { - if (!this.isWriteLoopRunning) { - this.writeLoop(); // This is not expected to error, if it does, just default behavior - } - } - /** - * The main write loop, it will keep running until there are no more updates to process. - */ - async writeLoop() { - const unsubscribe = this.innerSignal.subscribe(() => { }); - this.isWriteLoopRunning = true; - if (this.isStale()) { - await this.innerSignal.pull(); - } - while (this.queuedUpdates.length > 0) { - const numQueuedUpdatesToHandle = this.queuedUpdates.length; - const updater = (data) => { - const patches = []; - for (let i = 0; i < numQueuedUpdatesToHandle; i++) { - const [newData, newPatches] = this.queuedUpdates[i].updater(data); - data = newData; - patches.push(...newPatches); - } - return [data, patches]; - }; - const resolve = () => { - for (let i = 0; i < numQueuedUpdatesToHandle; i++) { - this.queuedUpdates[i].resolve(); - } - }; - const reject = (error) => { - for (let i = 0; i < numQueuedUpdatesToHandle; i++) { - this.queuedUpdates[i].reject(error); - } - }; - const queuedUpdateTags = this.queuedUpdates.flatMap(update => update.tags); - const tag = Date.now() + "-" + Math.random(); - await new Promise(nextStep => { - this.isSubscriptionHandledByWriteLoop = true; - const unsubscribeArray = []; - const settle = () => { - this.isSubscriptionHandledByWriteLoop = false; - unsubscribeArray.forEach(unsubscribe => unsubscribe()); - nextStep(); - }; - unsubscribeArray.push(this.innerSignal.subscribeFull((_data, _patches, tags) => { - if (!this.isSubscriptionHandledByWriteLoop) { - return; - } - if (tags?.includes(tag)) { - settle(); - resolve(); - // If this update is caused by the write, we need to remove the optimistic update - // and apply the remaining optimistic updates - this.queuedUpdates.splice(0, numQueuedUpdatesToHandle); - this.updateOptimisticValue(tags.filter(t => t !== tag)); - } - else { - // This update is not caused by the write, simply update the optimistic value - // as normal - this.updateOptimisticValue(tags); - } - })); - unsubscribeArray.push(this.writeErrorEvent.subscribe(({ tags, error }) => { - if (!this.isSubscriptionHandledByWriteLoop) { - return; - } - if (tags.includes(tag)) { - settle(); - reject(error); - this.queuedUpdates.splice(0, numQueuedUpdatesToHandle); - } - })); - // At this point, we know the data is available, because upon entering the write loop, we - // ensure that the data is available by pulling. Hence, we can safely cast the data to - // StripNotAvailable. - const sent = this.writeUpstream(...updater(this.innerSignal.get()), [tag, ...queuedUpdateTags]); - if (!sent) { - settle(); - resolve(); - this.queuedUpdates.splice(0, numQueuedUpdatesToHandle); - this.updateOptimisticValue(queuedUpdateTags.filter(t => t !== tag)); - } - }); - } - this.isWriteLoopRunning = false; - unsubscribe(); - } - /** - * Returns whether the value is currently stale. - * - * A value is stale whenever the upstream subscription is not active. This can happen in three - * cases: - * - * 1. When no subscriber is attached to this signal, the signal will not subscribe to the - * upstream. In this case, the value is always stale. - * 2. When a subscriber is attached, but the upstream has not yet emitted a single value, the - * value is also stale. - * 3. When the upstream has emitted an error. In this case, the subscription to the upstream is - * terminated and the value is stale. - * - * If you wish to get the current value and ensure that it is not stale, use the method - * {@link OWLSignal#pull}. - */ - isStale() { - return this.innerSignal.isStale(); - } - /** - * Gets the current value of the signal. If the value is not available, it will return - * {@link OWLSignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is created - * without an initial value and the upstream has not emitted a value yet.) - * - * In addition, the value returned by this method may be stale. Use {@link OWLSignal#isStale} to - * check if the value is stale. - * - * If you wish to get the current value and ensure that it is not stale, use the method - * {@link OWLSignal#pull}. - */ - get() { - return this.outerSignal.get(); - } - /** - * Gets the current value of the signal pessimistically. If the value is not available, it will - * return {@link OWLSignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is - * created without an initial value and the upstream has not emitted a value yet.) - */ - getPessimistic() { - return this.innerSignal.get(); - } - /** - * Pulls the current value of the signal. If the value is stale, it will subscribe and wait for - * the next value from the upstream and return it. - * - * You must also provide an `optimistic` flag. If `optimistic` is true, the pending optimistic - * updates will be applied to the value before returning it. - */ - async pull({ optimistic = true } = {}) { - if (optimistic) { - return this.applyOptimisticUpdates(await this.innerSignal.pull()); - } - else { - return this.innerSignal.pull(); - } - } - async ensureAvailable() { - if (this.currentEnsureAvailablePromise === null) { - this.currentEnsureAvailablePromise = (async () => { - await this.innerSignal.pull(); - return this; - })(); - } - return this.currentEnsureAvailablePromise; - } - subscribe(subscriber) { - const unsubscribeOuter = this.outerSignal.subscribe(subscriber); - const unsubscribeInner = this.innerSignal.subscribe(() => { }); - return () => { - unsubscribeOuter(); - unsubscribeInner(); - }; - } - subscribeFull(subscriber) { - const unsubscribeOuter = this.outerSignal.subscribeFull(subscriber); - const unsubscribeInner = this.innerSignal.subscribeFull(() => { }); - return () => { - unsubscribeOuter(); - unsubscribeInner(); - }; - } -} - -function parseFileIdentifier(fileIdentifier) { - if (!fileIdentifier.includes(":")) { - fileIdentifier = `local:${fileIdentifier}`; - } - const colonIndex = fileIdentifier.indexOf(":"); - const namespace = fileIdentifier.slice(0, colonIndex); - const content = fileIdentifier.slice(colonIndex + 1); - switch (namespace) { - case "local": { - if (content.includes("/") || content.includes("\\") || content.length === 0) { - throw new Error(`Invalid local file name: ${content}.`); - } - return { - type: "local", - fileName: content, - }; - } - case "base64": { - return { - type: "base64", - base64Data: content, - }; - } - default: { - throw new Error(`Unknown file identifier namespace: ${namespace}.`); - } - } -} - -function promisifyAbortSignal(abortSignal) { - return new Promise((_resolve, reject) => { - if (abortSignal.aborted) { - reject(abortSignal.reason); - return; - } - abortSignal.addEventListener("abort", () => { - reject(abortSignal.reason); - }, { once: true }); - }); -} -function raceWithAbortSignal(promise, abortSignal) { - return Promise.race([promise, promisifyAbortSignal(abortSignal)]); -} - -const allowableEnvVarKeys = ["HSA_OVERRIDE_GFX_VERSION"]; -const allowableEnvVarKeysSchema = zod.z.enum(allowableEnvVarKeys); -const allowableEnvVarsSchema = zod.z.record(allowableEnvVarKeysSchema, zod.z.string()); - -const kebabCaseRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; -const kebabCaseSchema = zod.z.string().regex(kebabCaseRegex); -const kebabCaseWithDotsRegex = /^[a-z0-9]+(?:[-.][a-z0-9]+)*$/; -const kebabCaseWithDotsSchema = zod.z.string().regex(kebabCaseWithDotsRegex); - -/** - * Matches valid file names - */ -const fileNameRegex = /^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(? { - try { - // Needs a more performant way to do this. - return JSON.parse(JSON.stringify(val)); - } - catch (e) { - ctx.addIssue({ - code: zod.z.ZodIssueCode.custom, - message: "Not JSON serializable: " + e.message, - }); - return val; - } -}); - -const chatMessagePartTextDataSchema = zod.z.object({ - type: zod.z.literal("text"), - text: zod.z.string(), -}); -const chatMessagePartFileDataSchema = zod.z.object({ - type: zod.z.literal("file"), - name: zod.z.string(), - identifier: zod.z.string(), - sizeBytes: zod.z.number().int(), - fileType: fileTypeSchema, -}); -const functionToolCallRequestSchema = zod.z.object({ - id: zod.z.string().optional(), - type: zod.z.literal("function"), - arguments: zod.z.record(jsonSerializableSchema).optional(), - name: zod.z.string(), -}); -const toolCallRequestSchema = zod.z.discriminatedUnion("type", [ - functionToolCallRequestSchema, -]); -const chatMessagePartToolCallRequestDataSchema = zod.z.object({ - type: zod.z.literal("toolCallRequest"), - toolCallRequest: toolCallRequestSchema, -}); -zod.z.object({ - content: zod.z.string(), - toolCallId: zod.z.string().optional(), -}); -const chatMessagePartToolCallResultDataSchema = zod.z.object({ - type: zod.z.literal("toolCallResult"), - content: zod.z.string(), - toolCallId: zod.z.string().optional(), -}); -zod.z.discriminatedUnion("type", [ - chatMessagePartTextDataSchema, - chatMessagePartFileDataSchema, - chatMessagePartToolCallRequestDataSchema, - chatMessagePartToolCallResultDataSchema, -]); -zod.z.enum(["assistant", "user", "system", "tool"]); -const chatMessageDataSchema = zod.z.discriminatedUnion("role", [ - zod.z.object({ - role: zod.z.literal("assistant"), - content: zod.z.array(zod.z.discriminatedUnion("type", [ - chatMessagePartTextDataSchema, - chatMessagePartFileDataSchema, - chatMessagePartToolCallRequestDataSchema, - ])), - }), - zod.z.object({ - role: zod.z.literal("user"), - content: zod.z.array(zod.z.discriminatedUnion("type", [chatMessagePartTextDataSchema, chatMessagePartFileDataSchema])), - }), - zod.z.object({ - role: zod.z.literal("system"), - content: zod.z.array(zod.z.discriminatedUnion("type", [chatMessagePartTextDataSchema, chatMessagePartFileDataSchema])), - }), - zod.z.object({ - role: zod.z.literal("tool"), - content: zod.z.array(chatMessagePartToolCallResultDataSchema), - }), -]); -const chatHistoryDataSchema = zod.z.object({ - messages: zod.z.array(chatMessageDataSchema), -}); - -const citationSourceSchema = zod.z.object({ - fileName: zod.z.string(), - absoluteFilePath: zod.z.string().optional(), - pageNumber: zod.z.union([zod.z.number().int(), zod.z.tuple([zod.z.number().int(), zod.z.number().int()])]).optional(), - lineNumber: zod.z.union([zod.z.number().int(), zod.z.tuple([zod.z.number().int(), zod.z.number().int()])]).optional(), -}); - -/** - * @deprecated Use colorPaletteSchema instead. - */ -const colorPalette = zod.z.enum([ - "red", - "green", - "blue", - "yellow", - "orange", - "purple", - "default", -]); -const colorPaletteSchema = colorPalette; - -const diagnosticsLogEventDataSchema = zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("llm.prediction.input"), - modelPath: zod.z.string(), - modelIdentifier: zod.z.string(), - input: zod.z.string(), - }), -]); -const diagnosticsLogEventSchema = zod.z.object({ - timestamp: zod.z.number(), - data: diagnosticsLogEventDataSchema, -}); - -const llmLlamaAccelerationOffloadRatioSchema = zod.z.union([ - zod.z.number().min(0).max(1), - zod.z.literal("max"), - zod.z.literal("off"), -]); -const llmSplitStrategySchema = zod.z.enum(["evenly", "favorMainGpu"]); -const gpuSettingSchema = zod.z.object({ - ratio: llmLlamaAccelerationOffloadRatioSchema.optional(), - mainGpu: zod.z.number().int().optional(), - splitStrategy: llmSplitStrategySchema.optional(), - disabledGpus: zod.z.array(zod.z.number().int()).optional(), -}); -const llmLlamaCacheQuantizationTypes = [ - "f32", - "f16", - "q8_0", - "q4_0", - "q4_1", - "iq4_nl", - "q5_0", - "q5_1", -]; -const llmLlamaCacheQuantizationTypeSchema = zod.z.enum(llmLlamaCacheQuantizationTypes); -const llmMlxKvCacheBitsTypeSchema = zod.z.union([ - zod.z.literal(8), - zod.z.literal(6), - zod.z.literal(4), - zod.z.literal(3), - zod.z.literal(2), -]); -const llmMlxKvCacheGroupSizeTypesSchema = zod.z.union([ - zod.z.literal(32), - zod.z.literal(64), - zod.z.literal(128), -]); -const llmMlxKvCacheQuantizationSchema = zod.z.object({ - enabled: zod.z.boolean(), - bits: llmMlxKvCacheBitsTypeSchema, - groupSize: llmMlxKvCacheGroupSizeTypesSchema, - quantizedStart: zod.z.number().int().nonnegative(), -}); -const llmLoadModelConfigSchema = zod.z.object({ - gpu: gpuSettingSchema.optional(), - gpuStrictVramCap: zod.z.boolean().optional(), - offloadKVCacheToGpu: zod.z.boolean().optional(), - contextLength: zod.z.number().int().min(1).optional(), - ropeFrequencyBase: zod.z.number().optional(), - ropeFrequencyScale: zod.z.number().optional(), - evalBatchSize: zod.z.number().int().min(1).optional(), - flashAttention: zod.z.boolean().optional(), - keepModelInMemory: zod.z.boolean().optional(), - seed: zod.z.number().int().optional(), - useFp16ForKVCache: zod.z.boolean().optional(), - tryMmap: zod.z.boolean().optional(), - numExperts: zod.z.number().int().optional(), - llamaKCacheQuantizationType: zod.z - .enum(llmLlamaCacheQuantizationTypes) - .or(zod.z.literal(false)) - .optional(), - llamaVCacheQuantizationType: zod.z - .enum(llmLlamaCacheQuantizationTypes) - .or(zod.z.literal(false)) - .optional(), -}); - -const embeddingLoadModelConfigSchema = zod.z.object({ - gpu: gpuSettingSchema.optional(), - contextLength: zod.z.number().int().min(1).optional(), - ropeFrequencyBase: zod.z.number().optional(), - ropeFrequencyScale: zod.z.number().optional(), - keepModelInMemory: zod.z.boolean().optional(), - tryMmap: zod.z.boolean().optional(), -}); - -const modelCompatibilityTypeSchema = zod.z.enum([ - "gguf", - "safetensors", - "onnx", - "ggml", - "mlx_placeholder", - "torch_safetensors", -]); - -const quantizationSchema = zod.z.object({ - name: zod.z.string(), - bits: zod.z.number().int(), -}); - -const modelInfoBaseSchema = zod.z.object({ - modelKey: zod.z.string(), - format: modelCompatibilityTypeSchema, - displayName: zod.z.string(), - path: zod.z.string(), - sizeBytes: zod.z.number().int(), - paramsString: zod.z.string().optional(), - architecture: zod.z.string().optional(), - quantization: quantizationSchema.optional(), -}); -const modelInstanceInfoBaseSchema = modelInfoBaseSchema.extend({ - identifier: zod.z.string(), - instanceReference: zod.z.string(), -}); - -const embeddingModelAdditionalInfoSchema = zod.z.object({ - maxContextLength: zod.z.number().int(), -}); -const embeddingModelInstanceAdditionalInfoSchema = zod.z.object({ - contextLength: zod.z.number().int(), -}); -const embeddingModelInfoSchema = zod.z - .object({ - type: zod.z.literal("embedding"), -}) - .extend(modelInfoBaseSchema.shape) - .extend(embeddingModelAdditionalInfoSchema.shape); -const embeddingModelInstanceInfoSchema = zod.z - .object({ type: zod.z.literal("embedding") }) - .extend(modelInstanceInfoBaseSchema.shape) - .extend(embeddingModelAdditionalInfoSchema.shape) - .extend(embeddingModelInstanceAdditionalInfoSchema.shape); - -const modelDomainTypeSchema = zod.z.enum([ - "llm", - "embedding", - "imageGen", - "transcription", - "tts", -]); - -/** - * A string that is reasonable to use as a key. For example, as preset name, model path, or model - * identifier. - */ -const reasonableKeyStringSchema = zod.z - .string() - .min(1) - .max(1024) - .refine(value => value !== "__proto__", { - message: 'For security reasons, "__proto__" is not allowed', -}) - .refine(value => /\p{C}/u.test(value) === false, { - message: "Control characters are not allowed", -}); - -const modelQuerySchema = zod.z.object({ - domain: modelDomainTypeSchema.optional(), - identifier: reasonableKeyStringSchema.optional(), - path: reasonableKeyStringSchema.optional(), - vision: zod.z.boolean().optional(), -}); -const modelSpecifierSchema = zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("query"), - query: modelQuerySchema, - }), - zod.z.object({ - type: zod.z.literal("instanceReference"), - instanceReference: zod.z.string(), - }), -]); - -const genericErrorDisplayDataSchema = [ - zod.z.object({ - code: zod.z.literal("generic.specificModelUnloaded"), - }), - zod.z.object({ - code: zod.z.literal("generic.noModelMatchingQuery"), - query: modelQuerySchema, - loadedModelsSample: zod.z.array(zod.z.string()), - totalLoadedModels: zod.z.number().int(), - }), - zod.z.object({ - code: zod.z.literal("generic.pathNotFound"), - path: zod.z.string(), - availablePathsSample: zod.z.array(zod.z.string()), - totalModels: zod.z.number().int(), - }), - zod.z.object({ - code: zod.z.literal("generic.identifierNotFound"), - identifier: zod.z.string(), - loadedModelsSample: zod.z.array(zod.z.string()), - totalLoadedModels: zod.z.number().int(), - }), - zod.z.object({ - code: zod.z.literal("generic.domainMismatch"), - path: zod.z.string(), - actualDomain: modelDomainTypeSchema, - expectedDomain: modelDomainTypeSchema, - }), - zod.z.object({ - code: zod.z.literal("generic.engineDoesNotSupportFeature"), - feature: zod.z.string(), - engineName: zod.z.string(), - engineType: zod.z.string(), - installedVersion: zod.z.string(), - supportedVersion: zod.z.string().nullable(), - }), - zod.z.object({ - code: zod.z.literal("generic.presetNotFound"), - specifiedFuzzyPresetIdentifier: zod.z.string(), - availablePresetsSample: zod.z.array(zod.z.object({ - identifier: zod.z.string(), - name: zod.z.string(), - })), - totalAvailablePresets: zod.z.number().int(), - }), -]; - -const llmErrorDisplayDataSchema = []; - -const errorDisplayDataSchema = zod.z.discriminatedUnion("code", [ - ...llmErrorDisplayDataSchema, - ...genericErrorDisplayDataSchema, -]); -/** - * Makes a Zod schema that turns a failed parse into an `undefined`. - */ -function failOk(schema) { - return zod.z.any().transform(val => (schema.safeParse(val).success ? val : undefined)); -} -const serializedLMSExtendedErrorSchema = zod.z.object({ - title: failOk(zod.z.string()).default("Unknown error"), - cause: failOk(zod.z.string()).optional(), - suggestion: failOk(zod.z.string()).optional(), - errorData: failOk(zod.z.record(zod.z.string(), zod.z.unknown())).optional(), - displayData: failOk(errorDisplayDataSchema).optional(), - stack: failOk(zod.z.string()).optional(), - rootTitle: failOk(zod.z.string()).optional(), -}); -function serializeError(error) { - if (typeof error === "object") { - const title = error.title ?? error.lmstudioRawError ?? error.message ?? "Unknown error"; - return serializedLMSExtendedErrorSchema.parse({ - title, - cause: error.cause, - suggestion: error.suggestion, - errorData: error.errorData, - displayData: error.displayData, - stack: error.stack, - rootTitle: title, - }); - } - else { - const title = String(error); - return { - title, - rootTitle: title, - }; - } -} -/** - * Attaches the additional error data from a serialized error to an error object. - */ -function attachSerializedErrorData(error, serialized) { - const untypedError = error; - untypedError.title = serialized.title; - if (serialized.cause !== undefined) { - untypedError.cause = serialized.cause; - } - if (serialized.suggestion !== undefined) { - untypedError.suggestion = serialized.suggestion; - } - if (serialized.errorData !== undefined) { - untypedError.errorData = serialized.errorData; - } -} -function fromSerializedError(error, message = "Rehydrated error", replacementStack) { - const result = new Error(error.rootTitle); - attachSerializedErrorData(result, error); - if (error.displayData !== undefined) { - result.displayData = error.displayData; - } - if (replacementStack !== undefined) { - if (error.stack !== undefined) { - result.stack = `Error: ${message}\n${replacementStack}\n- Caused By: ${error.stack}`; - } - else { - result.stack = `Error: ${message}\n${replacementStack}`; - } - } - else { - if (error.stack !== undefined) { - result.stack = - `Error: ${message}\n${result.stack.substring(error.stack.indexOf("\n") + 1)}\n- Caused By: ` + - error.stack; - } - else { - result.message += ` - caused by error without stack (${error.title})`; - } - } - return result; -} - -const documentParsingLibraryIdentifierSchema = zod.z.object({ - library: zod.z.string(), - version: zod.z.string(), -}); -const documentParsingOptsSchema = zod.z.object({ - parserId: documentParsingLibraryIdentifierSchema.optional(), -}); - -zod.z.enum(["local", "base64"]); -zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("local"), - fileName: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("base64"), - base64Data: zod.z.string(), - }), -]); - -const gpuSplitStrategies = ["evenly", "priorityOrder", "custom"]; -const gpuSplitStrategySchema = zod.z.enum(gpuSplitStrategies); -const defaultGPUSplitConfig = { - strategy: "evenly", - disabledGpus: [], - priority: [], - customRatio: [], -}; -const gpuSplitConfigSchema = zod.z.object({ - strategy: gpuSplitStrategySchema, - disabledGpus: zod.z.array(zod.z.number().int().min(0)), - priority: zod.z.array(zod.z.number().int().min(0)), - customRatio: zod.z.array(zod.z.number().min(0)), -}); -function convertGPUSettingToGPUSplitConfig(gpuSetting) { - return { - strategy: gpuSetting?.splitStrategy == "favorMainGpu" - ? "priorityOrder" - : gpuSetting?.splitStrategy ?? "evenly", - disabledGpus: gpuSetting?.disabledGpus ?? [], - priority: gpuSetting?.mainGpu ? [gpuSetting.mainGpu] : [], - customRatio: [], - }; -} - -const kvConfigFieldSchema = zod.z.object({ - key: zod.z.string(), - value: zod.z.any(), -}); -const kvConfigSchema = zod.z.object({ - fields: zod.z.array(kvConfigFieldSchema), -}); -const kvConfigLayerNameSchema = zod.z.enum([ - "currentlyEditing", - "currentlyLoaded", - "apiOverride", - "conversationSpecific", - "conversationGlobal", - "preset", - "serverSession", - "httpServerRequestOverride", - "completeModeFormatting", - "instance", - "userModelDefault", - "virtualModel", - "modelDefault", - "hardware", -]); -const kvConfigStackLayerSchema = zod.z.object({ - layerName: kvConfigLayerNameSchema, - config: kvConfigSchema, -}); -const kvConfigStackSchema = zod.z.object({ - layers: zod.z.array(kvConfigStackLayerSchema), -}); -const kvConfigFieldDependencySchema = zod.z.object({ - key: zod.z.string(), - condition: zod.z.discriminatedUnion("type", [ - zod.z.object({ type: zod.z.literal("equals"), value: zod.z.any() }), - zod.z.object({ type: zod.z.literal("notEquals"), value: zod.z.any() }), - ]), -}); - -const contentBlockStyleSchema = zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("default"), - }), - zod.z.object({ - type: zod.z.literal("customLabel"), - label: zod.z.string(), - color: zod.z.optional(colorPaletteSchema), - }), - zod.z.object({ - type: zod.z.literal("thinking"), - ended: zod.z.boolean().optional(), - title: zod.z.string().optional(), - }), -]); - -const llmToolParametersSchema = zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("object"), - properties: zod.z.record(jsonSerializableSchema), - required: zod.z.array(zod.z.string()).optional(), - additionalProperties: zod.z.boolean().optional(), - $defs: zod.z.record(jsonSerializableSchema).optional(), - }), - // add more parameter types here - // ... -]); -const llmToolSchema = zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("function"), - function: zod.z.object({ - name: zod.z.string(), - description: zod.z.string().optional(), - parameters: llmToolParametersSchema.optional(), - }), - }), - // add more tool types here - // ... -]); -/** - * For convenience - */ -zod.z.array(llmToolSchema); -const llmToolUseSettingSchema = zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("none"), - }), - zod.z.object({ - type: zod.z.literal("toolArray"), - tools: zod.z.array(llmToolSchema).optional(), - force: zod.z.boolean().optional(), - }), -]); - -const llmApplyPromptTemplateOptsSchema = zod.z.object({ - omitBosToken: zod.z.boolean().optional(), - omitEosToken: zod.z.boolean().optional(), - toolDefinitions: zod.z.array(llmToolSchema).optional(), -}); - -const llmContextReferenceSchema = zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("jsonFile"), - absPath: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("yamlFile"), - absPath: zod.z.string(), - }), -]); -zod.z.array(zod.z.object({ - role: zod.z.enum(["user", "assistant", "system"]), - content: zod.z.string(), -})); -zod.z.array(zod.z.union([ - zod.z.object({ - system: zod.z.string(), - }), - zod.z.object({ - user: zod.z.string(), - }), - zod.z.object({ - assistant: zod.z.string(), - }), -])); - -const llmAdditionalInfoSchema = zod.z.object({ - vision: zod.z.boolean(), - trainedForToolUse: zod.z.boolean(), - maxContextLength: zod.z.number().int(), -}); -const llmInstanceAdditionalInfoSchema = zod.z.object({ - contextLength: zod.z.number().int(), -}); -const llmInfoSchema = zod.z - .object({ - type: zod.z.literal("llm"), -}) - .extend(modelInfoBaseSchema.shape) - .extend(llmAdditionalInfoSchema.shape); -const llmInstanceInfoSchema = zod.z - .object({ - type: zod.z.literal("llm"), -}) - .extend(modelInstanceInfoBaseSchema.shape) - .extend(llmAdditionalInfoSchema.shape) - .extend(llmInstanceAdditionalInfoSchema.shape); - -const toolNamingSchema = zod.z.enum(["passThrough", "removeSpecial", "snakeCase", "camelCase"]); - -/** - * Check if has a parse method. If not, output error message asking for it to be a zod schema. - */ -const zodSchemaSchema = zod.z.custom(value => { - if (typeof value?.parse !== "function") { - return false; - } - return true; -}, "Expected a zod schema"); - -const llmManualPromptTemplateSchema = zod.z.object({ - beforeSystem: zod.z.string(), - afterSystem: zod.z.string(), - beforeUser: zod.z.string(), - afterUser: zod.z.string(), - beforeAssistant: zod.z.string(), - afterAssistant: zod.z.string(), -}); -const llmJinjaPromptTemplateSchema = zod.z.object({ - template: zod.z.string(), -}); -const llmPromptTemplateTypeSchema = zod.z.enum(["manual", "jinja"]); -const llmPromptTemplateSchema = zod.z.object({ - type: llmPromptTemplateTypeSchema, - manualPromptTemplate: llmManualPromptTemplateSchema.optional(), - jinjaPromptTemplate: llmJinjaPromptTemplateSchema.optional(), - stopStrings: zod.z.array(zod.z.string()), -}); - -const llmStructuredPredictionTypeSchema = zod.z.enum(["none", "json", "gbnf"]); -const llmStructuredPredictionSettingSchema = zod.z.object({ - type: llmStructuredPredictionTypeSchema, - jsonSchema: jsonSerializableSchema.optional(), - gbnfGrammar: zod.z.string().optional(), -}); - -const llmContextOverflowPolicySchema = zod.z.enum([ - "stopAtLimit", - "truncateMiddle", - "rollingWindow", -]); -const llmReasoningParsingSchema = zod.z.object({ - enabled: zod.z.boolean(), - startString: zod.z.string(), - endString: zod.z.string(), -}); -const llmPredictionConfigInputSchema = zod.z.object({ - maxTokens: zod.z.number().int().min(-1).optional().or(zod.z.literal(false)), - temperature: zod.z.number().min(0).optional(), - stopStrings: zod.z.array(zod.z.string()).optional(), - toolCallStopStrings: zod.z.array(zod.z.string()).optional(), - contextOverflowPolicy: llmContextOverflowPolicySchema.optional(), - structured: zod.z.union([zodSchemaSchema, llmStructuredPredictionSettingSchema]).optional(), - rawTools: llmToolUseSettingSchema.optional(), - toolNaming: toolNamingSchema.optional(), - topKSampling: zod.z.number().optional(), - repeatPenalty: zod.z.number().optional().or(zod.z.literal(false)), - minPSampling: zod.z.number().optional().or(zod.z.literal(false)), - topPSampling: zod.z.number().optional().or(zod.z.literal(false)), - cpuThreads: zod.z.number().int().optional(), - promptTemplate: llmPromptTemplateSchema.optional(), - draftModel: zod.z.string().optional(), - speculativeDecodingNumDraftTokensExact: zod.z.number().int().min(1).optional(), - speculativeDecodingMinDraftLengthToConsider: zod.z.number().int().min(0).optional(), - speculativeDecodingMinContinueDraftingProbability: zod.z.number().optional(), - reasoningParsing: llmReasoningParsingSchema.optional(), - raw: kvConfigSchema.optional(), -}); -zod.z.object({ - ...llmPredictionConfigInputSchema.shape, - structured: llmStructuredPredictionSettingSchema.optional(), -}); -const llmLlamaMirostatSamplingConfigSchema = zod.z.object({ - version: zod.z.union([zod.z.literal(0), zod.z.literal(1), zod.z.literal(2)]), - learningRate: zod.z.number(), - targetEntropy: zod.z.number(), -}); -const llmLlamaSingleLogitBiasModificationSchema = zod.z.union([zod.z.number(), zod.z.literal("-inf")]); -const llmLlamaLogitBiasConfigSchema = zod.z.array(zod.z.tuple([zod.z.number(), llmLlamaSingleLogitBiasModificationSchema])); - -const llmPredictionFragmentReasoningTypeSchema = zod.z.enum([ - "none", - "reasoning", - "reasoningStartTag", - "reasoningEndTag", -]); -const llmPredictionFragmentSchema = zod.z.object({ - content: zod.z.string(), - tokensCount: zod.z.number().int(), - containsDrafted: zod.z.boolean(), - reasoningType: llmPredictionFragmentReasoningTypeSchema, - isStructural: zod.z.boolean(), -}); -const llmPredictionFragmentInputOptsSchema = zod.z.object({ - tokenCount: zod.z.number().int().optional(), - containsDrafted: zod.z.boolean().optional(), - reasoningType: llmPredictionFragmentReasoningTypeSchema.optional(), - isStructural: zod.z.boolean().optional(), -}); - -const llmPredictionStopReasonSchema = zod.z.enum([ - "userStopped", - "modelUnloaded", - "failed", - "eosFound", - "stopStringFound", - "toolCalls", - "maxPredictedTokensReached", - "contextLengthReached", -]); -const llmPredictionStatsSchema = zod.z.object({ - stopReason: llmPredictionStopReasonSchema, - tokensPerSecond: zod.z.number().optional(), - numGpuLayers: zod.z.number().optional(), - timeToFirstTokenSec: zod.z.number().optional(), - totalTimeSec: zod.z.number().optional(), - promptTokensCount: zod.z.number().int().optional(), - predictedTokensCount: zod.z.number().int().optional(), - totalTokensCount: zod.z.number().int().optional(), - usedDraftModelKey: zod.z.string().optional(), - totalDraftTokensCount: zod.z.number().int().optional(), - acceptedDraftTokensCount: zod.z.number().int().optional(), - rejectedDraftTokensCount: zod.z.number().int().optional(), - ignoredDraftTokensCount: zod.z.number().int().optional(), -}); -const llmGenInfoSchema = zod.z.object({ - indexedModelIdentifier: zod.z.string(), - identifier: zod.z.string(), - loadModelConfig: kvConfigSchema, - predictionConfig: kvConfigSchema, - stats: llmPredictionStatsSchema, -}); - -const blockLocationSchema = zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("beforeId"), - id: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("afterId"), - id: zod.z.string(), - }), -]); -const statusStepStatusSchema = zod.z.enum([ - "waiting", - "loading", - "done", - "error", - "canceled", -]); -const statusStepStateSchema = zod.z.object({ - status: statusStepStatusSchema, - text: zod.z.string(), -}); -const processingUpdateStatusCreateSchema = zod.z.object({ - type: zod.z.literal("status.create"), - id: zod.z.string(), - state: statusStepStateSchema, - location: blockLocationSchema.optional(), - indentation: zod.z.number().int().optional(), -}); -const processingUpdateStatusUpdateSchema = zod.z.object({ - type: zod.z.literal("status.update"), - id: zod.z.string(), - state: statusStepStateSchema, -}); -const processingUpdateStatusRemoveSchema = zod.z.object({ - type: zod.z.literal("status.remove"), - id: zod.z.string(), -}); -const processingUpdateCitationBlockCreateSchema = zod.z.object({ - type: zod.z.literal("citationBlock.create"), - id: zod.z.string(), - citedText: zod.z.string(), - fileName: zod.z.string(), - fileIdentifier: zod.z.string(), - pageNumber: zod.z.union([zod.z.number().int(), zod.z.tuple([zod.z.number().int(), zod.z.number().int()])]).optional(), - lineNumber: zod.z.union([zod.z.number().int(), zod.z.tuple([zod.z.number().int(), zod.z.number().int()])]).optional(), -}); -const processingUpdateDebugInfoBlockCreateSchema = zod.z.object({ - type: zod.z.literal("debugInfoBlock.create"), - id: zod.z.string(), - debugInfo: zod.z.string(), -}); -const processingUpdateContentBlockCreateSchema = zod.z.object({ - type: zod.z.literal("contentBlock.create"), - id: zod.z.string(), - includeInContext: zod.z.boolean(), - roleOverride: zod.z.enum(["user", "assistant", "system", "tool"]).optional(), - style: contentBlockStyleSchema.optional(), - prefix: zod.z.string().optional(), - suffix: zod.z.string().optional(), -}); -const processingUpdateContentBlockAppendTextSchema = zod.z.object({ - type: zod.z.literal("contentBlock.appendText"), - id: zod.z.string(), - text: zod.z.string(), - tokensCount: zod.z.number().int().optional(), - fromDraftModel: zod.z.boolean().optional(), - isStructural: zod.z.boolean().optional(), -}); -const processingUpdateContentBlockAppendToolResultSchema = zod.z.object({ - type: zod.z.literal("contentBlock.appendToolResult"), - id: zod.z.string(), - callId: zod.z.number().int(), - toolCallRequestId: zod.z.string().optional(), - content: zod.z.string(), -}); -const processingUpdateContentBlockAppendToolRequestSchema = zod.z.object({ - type: zod.z.literal("contentBlock.appendToolRequest"), - id: zod.z.string(), - callId: zod.z.number().int(), - toolCallRequestId: zod.z.string().optional(), - name: zod.z.string(), - parameters: zod.z.record(zod.z.unknown()), - pluginIdentifier: zod.z.string().optional(), -}); -const processingUpdateContentBlockReplaceToolRequestSchema = zod.z.object({ - type: zod.z.literal("contentBlock.replaceToolRequest"), - id: zod.z.string(), - callId: zod.z.number().int(), - toolCallRequestId: zod.z.string().optional(), - name: zod.z.string(), - parameters: zod.z.record(zod.z.unknown()), - pluginIdentifier: zod.z.string().optional(), -}); -const processingUpdateContentBlockReplaceTextSchema = zod.z.object({ - type: zod.z.literal("contentBlock.replaceText"), - id: zod.z.string(), - text: zod.z.string(), -}); -const processingUpdateContentBlockSetPrefixSchema = zod.z.object({ - type: zod.z.literal("contentBlock.setPrefix"), - id: zod.z.string(), - prefix: zod.z.string(), -}); -const processingUpdateContentBlockSetSuffixSchema = zod.z.object({ - type: zod.z.literal("contentBlock.setSuffix"), - id: zod.z.string(), - suffix: zod.z.string(), -}); -const processingUpdateContentBlockAttachGenInfoSchema = zod.z.object({ - type: zod.z.literal("contentBlock.attachGenInfo"), - id: zod.z.string(), - genInfo: llmGenInfoSchema, -}); -const processingUpdateContentBlockSetStyleSchema = zod.z.object({ - type: zod.z.literal("contentBlock.setStyle"), - id: zod.z.string(), - style: contentBlockStyleSchema, -}); -const toolStatusStepStateStatusSchema = zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("generatingToolCall"), - name: zod.z.string().optional(), - pluginIdentifier: zod.z.string().optional(), - argumentsString: zod.z.string().optional(), - }), - zod.z.object({ - type: zod.z.literal("toolCallGenerationFailed"), - error: zod.z.string(), - rawContent: zod.z.string().optional(), - }), - zod.z.object({ - type: zod.z.literal("toolCallQueued"), - }), - zod.z.object({ - type: zod.z.literal("confirmingToolCall"), - }), - zod.z.object({ - type: zod.z.literal("toolCallDenied"), - denyReason: zod.z.string().optional(), - }), - zod.z.object({ - type: zod.z.literal("callingTool"), - }), - zod.z.object({ - type: zod.z.literal("toolCallFailed"), - error: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("toolCallSucceeded"), - timeMs: zod.z.number().int(), - }), -]); -const toolStatusStepStateSchema = zod.z.object({ - status: toolStatusStepStateStatusSchema, - customStatus: zod.z.string(), - customWarnings: zod.z.array(zod.z.string()), -}); -const processingUpdateToolStatusCreateSchema = zod.z.object({ - type: zod.z.literal("toolStatus.create"), - id: zod.z.string(), - callId: zod.z.number().int(), - state: toolStatusStepStateSchema, -}); -const processingUpdateToolStatusUpdateSchema = zod.z.object({ - type: zod.z.literal("toolStatus.update"), - id: zod.z.string(), - state: toolStatusStepStateSchema, -}); -const processingUpdateToolStatusArgumentFragmentSchema = zod.z.object({ - type: zod.z.literal("toolStatus.argumentFragment"), - id: zod.z.string(), - content: zod.z.string(), -}); -const processingUpdateSetSenderNameSchema = zod.z.object({ - type: zod.z.literal("setSenderName"), - name: zod.z.string(), -}); -const processingUpdateSchema = zod.z.discriminatedUnion("type", [ - processingUpdateStatusCreateSchema, - processingUpdateStatusUpdateSchema, - processingUpdateStatusRemoveSchema, - processingUpdateCitationBlockCreateSchema, - processingUpdateDebugInfoBlockCreateSchema, - processingUpdateContentBlockCreateSchema, - processingUpdateContentBlockAppendTextSchema, - processingUpdateContentBlockAppendToolRequestSchema, - processingUpdateContentBlockReplaceToolRequestSchema, - processingUpdateContentBlockAppendToolResultSchema, - processingUpdateContentBlockReplaceTextSchema, - processingUpdateContentBlockSetPrefixSchema, - processingUpdateContentBlockSetSuffixSchema, - processingUpdateContentBlockAttachGenInfoSchema, - processingUpdateContentBlockSetStyleSchema, - processingUpdateToolStatusCreateSchema, - processingUpdateToolStatusUpdateSchema, - processingUpdateToolStatusArgumentFragmentSchema, - processingUpdateSetSenderNameSchema, -]); - -zod.z.discriminatedUnion("type", [ - processingUpdateStatusCreateSchema, - processingUpdateStatusUpdateSchema, - processingUpdateStatusRemoveSchema, - processingUpdateCitationBlockCreateSchema, - processingUpdateDebugInfoBlockCreateSchema, - processingUpdateContentBlockCreateSchema, - processingUpdateContentBlockAppendTextSchema, - processingUpdateContentBlockReplaceTextSchema, - processingUpdateContentBlockAppendToolRequestSchema, - processingUpdateContentBlockReplaceToolRequestSchema, - processingUpdateContentBlockAppendToolResultSchema, - processingUpdateContentBlockAttachGenInfoSchema, - processingUpdateContentBlockSetStyleSchema, - processingUpdateToolStatusCreateSchema, - processingUpdateToolStatusUpdateSchema, - processingUpdateToolStatusArgumentFragmentSchema, - processingUpdateSetSenderNameSchema, -]); - -const processingRequestConfirmToolCallSchema = zod.z.object({ - type: zod.z.literal("confirmToolCall"), - callId: zod.z.number().int(), - pluginIdentifier: zod.z.string().optional(), - name: zod.z.string(), - parameters: zod.z.record(zod.z.any()), -}); -const processingRequestTextInputSchema = zod.z.object({ - type: zod.z.literal("textInput"), - prompt: zod.z.string(), -}); -const processingRequestSchema = zod.z.discriminatedUnion("type", [ - processingRequestConfirmToolCallSchema, - processingRequestTextInputSchema, -]); -const processingRequestResponseConfirmToolCallSchema = zod.z.object({ - type: zod.z.literal("confirmToolCall"), - result: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("allow"), - toolArgsOverride: zod.z.record(zod.z.any()).optional(), - }), - zod.z.object({ - type: zod.z.literal("deny"), - denyReason: zod.z.string().optional(), - }), - ]), -}); -const processingRequestResponseTextInputSchema = zod.z.object({ - type: zod.z.literal("textInput"), - result: zod.z.string(), -}); -const processingRequestResponseSchema = zod.z.discriminatedUnion("type", [ - processingRequestResponseConfirmToolCallSchema, - processingRequestResponseTextInputSchema, -]); - -zod.z.object({ - modelTag: zod.z.string().optional(), - ignoreUserConfig: zod.z.boolean().optional(), -}); - -zod.z.discriminatedUnion("type", [ - processingUpdateStatusCreateSchema, - processingUpdateStatusUpdateSchema, - processingUpdateStatusRemoveSchema, - processingUpdateCitationBlockCreateSchema, - processingUpdateDebugInfoBlockCreateSchema, -]); - -const tokenSourceIdentifierSchema = zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("model"), - identifier: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("generator"), - pluginIdentifier: zod.z.string(), - }), -]); - -const modelInfoSchema = zod.z.discriminatedUnion("type", [ - llmInfoSchema, - embeddingModelInfoSchema, -]); -const modelInstanceInfoSchema = zod.z.discriminatedUnion("type", [ - llmInstanceInfoSchema, - embeddingModelInstanceInfoSchema, -]); - -const pluginConfigSpecifierSchema = zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("direct"), - config: kvConfigSchema, - workingDirectoryPath: zod.z.string().optional(), - }), - zod.z.object({ - type: zod.z.literal("predictionProcess"), - pci: zod.z.string(), - token: zod.z.string(), - }), -]); - -const remotePluginInfoSchema = zod.z.object({ - identifier: zod.z.string(), - isDev: zod.z.boolean(), - isTrusted: zod.z.boolean(), - hasPromptPreprocessor: zod.z.boolean(), - hasPredictionLoopHandler: zod.z.boolean(), - hasToolsProvider: zod.z.boolean(), - hasGenerator: zod.z.boolean(), -}); - -const artifactDownloadPlanModelInfoSchema = zod.z.object({ - displayName: zod.z.string(), - sizeBytes: zod.z.number(), - quantName: zod.z.string().optional(), - compatibilityType: modelCompatibilityTypeSchema, -}); -const artifactDownloadPlanNodeStateSchema = zod.z.enum(["pending", "fetching", "satisfied", "completed"]); -const artifactDownloadPlanNodeSchema = zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("artifact"), - owner: kebabCaseSchema, - name: kebabCaseWithDotsSchema, - state: artifactDownloadPlanNodeStateSchema, - artifactType: artifactTypeSchema.optional(), - sizeBytes: zod.z.number().int().optional(), - dependencyNodes: zod.z.array(zod.z.number().int()), - }), - zod.z.object({ - type: zod.z.literal("model"), - state: artifactDownloadPlanNodeStateSchema, - resolvedSources: zod.z.number().int().optional(), - totalSources: zod.z.number().int().optional(), - alreadyOwned: artifactDownloadPlanModelInfoSchema.optional(), - selected: artifactDownloadPlanModelInfoSchema.optional(), - }), -]); -const artifactDownloadPlanSchema = zod.z.object({ - nodes: zod.z.array(artifactDownloadPlanNodeSchema), - downloadSizeBytes: zod.z.number().int(), -}); - -const localArtifactFileEntrySchema = zod.z.object({ - relativePath: zod.z.string(), - sizeBytes: zod.z.number().int(), -}); -const localArtifactFileListSchema = zod.z.object({ - files: zod.z.array(localArtifactFileEntrySchema), - usedIgnoreFile: zod.z.string().nullable(), -}); - -const downloadProgressUpdateSchema = zod.z.object({ - downloadedBytes: zod.z.number().int(), - totalBytes: zod.z.number().int(), - speedBytesPerSecond: zod.z.number(), -}); - -const modelSearchResultDownloadOptionFitEstimationSchema = zod.z.enum([ - "fullGPUOffload", - "partialGPUOffload", - "fitWithoutGPU", - "willNotFit", -]); -const modelSearchResultDownloadOptionDataSchema = zod.z.object({ - quantization: zod.z.string().optional(), - name: zod.z.string(), - sizeBytes: zod.z.number().int(), - fitEstimation: modelSearchResultDownloadOptionFitEstimationSchema, - recommended: zod.z.boolean().optional(), - downloadIdentifier: zod.z.string(), - indexedModelIdentifier: zod.z.string(), -}); -const modelSearchResultIdentifierSchema = zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("catalog"), - identifier: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("hf"), - identifier: zod.z.string(), - }), -]); -const modelSearchResultEntryDataSchema = zod.z.object({ - name: zod.z.string(), - identifier: modelSearchResultIdentifierSchema, - exact: zod.z.boolean().optional(), - staffPick: zod.z.boolean().optional(), -}); -const modelSearchOptsSchema = zod.z.object({ - searchTerm: zod.z.string().optional(), - limit: zod.z.number().int().positive().max(25).optional(), - compatibilityTypes: zod.z.array(modelCompatibilityTypeSchema).optional(), -}); - -const internalRetrievalResultEntrySchema = zod.z.object({ - content: zod.z.string(), - score: zod.z.number(), - sourceIndex: zod.z.number().int(), - pageNumber: zod.z.union([zod.z.number().int(), zod.z.tuple([zod.z.number().int(), zod.z.number().int()])]).optional(), - lineNumber: zod.z.union([zod.z.number().int(), zod.z.tuple([zod.z.number().int(), zod.z.number().int()])]).optional(), -}); -const internalRetrievalResultSchema = zod.z.object({ - entries: zod.z.array(internalRetrievalResultEntrySchema), -}); - -zod.z.object({ - content: zod.z.string(), - score: zod.z.number(), - citation: citationSourceSchema, -}); - -const retrievalChunkingMethodSchema = zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("recursive-v1"), - chunkSize: zod.z.number().int(), - chunkOverlap: zod.z.number().int(), - }), -]); - -const retrievalFileProcessingStepSchema = zod.z.enum(["loading", "chunking", "embedding"]); - -const acceleratorTypeSchema = zod.z.enum(["unknown", "integratedGpu", "dedicatedGpu"]); -const acceleratorSchema = zod.z.object({ - name: zod.z.string(), - deviceId: zod.z.number().int(), - totalMemoryBytes: zod.z.number().int(), - type: acceleratorTypeSchema, -}); -zod.z.object({ - key: zod.z.string(), - name: zod.z.string(), - accelerators: zod.z.array(acceleratorSchema), -}); - -const serializedKVConfigSchematicsFieldSchema = zod.z.object({ - shortKey: zod.z.string(), - fullKey: zod.z.string(), - typeKey: zod.z.string(), - typeParams: jsonSerializableSchema, - defaultValue: jsonSerializableSchema, -}); -const serializedKVConfigSchematicsSchema = zod.z.object({ - fields: zod.z.array(serializedKVConfigSchematicsFieldSchema), - extensionPrefixes: zod.z.array(zod.z.string()).optional(), -}); -zod.z.object({ - fullKey: zod.z.string(), - error: jsonSerializableSchema, -}); - -const booleanOrMixedSchema = zod.z.union([ - zod.z.literal(true), - zod.z.literal(false), - zod.z.literal("mixed"), -]); -const virtualModelDefinitionMetadataOverridesSchema = zod.z.object({ - domain: modelDomainTypeSchema.optional(), - architectures: zod.z.array(zod.z.string()).optional(), - compatibilityTypes: zod.z.array(modelCompatibilityTypeSchema).optional(), - paramsStrings: zod.z.array(zod.z.string()).optional(), - minMemoryUsageBytes: zod.z.number().optional(), - contextLengths: zod.z.array(zod.z.number()).optional(), - trainedForToolUse: booleanOrMixedSchema.optional(), - vision: booleanOrMixedSchema.optional(), - reasoning: booleanOrMixedSchema.optional(), - fim: booleanOrMixedSchema.optional(), -}); -const virtualModelDefinitionConcreteModelBaseSchema = zod.z.object({ - key: zod.z.string(), - sources: zod.z.array(modelDownloadSourceSchema), -}); -const virtualModelCustomFieldSetJinjaVariableEffectSchema = zod.z.object({ - type: zod.z.literal("setJinjaVariable"), - variable: zod.z.string(), -}); -const virtualModelCustomFieldPrependSystemPromptEffectSchema = zod.z.object({ - type: zod.z.literal("prependSystemPrompt"), - content: zod.z.string(), -}); -const virtualModelCustomFieldAppendSystemPromptEffectSchema = zod.z.object({ - type: zod.z.literal("appendSystemPrompt"), - content: zod.z.string(), -}); -const virtualModelCustomFieldDefinitionBaseSchema = zod.z.object({ - key: zod.z.string(), - displayName: zod.z.string(), - description: zod.z.string(), -}); -const virtualModelBooleanCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({ - type: zod.z.literal("boolean"), - defaultValue: zod.z.boolean(), - effects: zod.z.array(zod.z.discriminatedUnion("type", [ - virtualModelCustomFieldSetJinjaVariableEffectSchema, - virtualModelCustomFieldPrependSystemPromptEffectSchema, - virtualModelCustomFieldAppendSystemPromptEffectSchema, - ])), -}); -const virtualModelStringCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({ - type: zod.z.literal("string"), - defaultValue: zod.z.string(), - effects: zod.z.array(zod.z.discriminatedUnion("type", [virtualModelCustomFieldSetJinjaVariableEffectSchema])), -}); -const virtualModelSelectCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({ - type: zod.z.literal("select"), - options: zod.z.array(zod.z.object({ - label: zod.z.string(), - value: zod.z.string(), - })), - defaultValue: zod.z.string(), - effects: zod.z.array(zod.z.discriminatedUnion("type", [virtualModelCustomFieldSetJinjaVariableEffectSchema])), -}); -const virtualModelCustomFieldDefinitionSchema = zod.z.discriminatedUnion("type", [ - virtualModelBooleanCustomFieldDefinitionSchema, - virtualModelStringCustomFieldDefinitionSchema, - virtualModelSelectCustomFieldDefinitionSchema, -]); -const virtualModelConditionEqualsSchema = zod.z.object({ - type: zod.z.literal("equals"), - key: zod.z.string(), - value: jsonSerializableSchema, -}); -const virtualModelConditionSchema = zod.z.discriminatedUnion("type", [ - virtualModelConditionEqualsSchema, -]); -const virtualModelSuggestionSchema = zod.z.object({ - message: zod.z.string(), - conditions: zod.z.array(virtualModelConditionSchema), - fields: zod.z.array(kvConfigFieldSchema).optional(), -}); -zod.z.object({ - model: zod.z.string().regex(/^[^/]+\/[^/]+$/), - base: zod.z.union([zod.z.string(), zod.z.array(virtualModelDefinitionConcreteModelBaseSchema)]), - tags: zod.z.array(zod.z.string().max(100)).optional(), - config: zod.z - .object({ - load: kvConfigSchema.optional(), - operation: kvConfigSchema.optional(), - }) - .optional(), - metadataOverrides: virtualModelDefinitionMetadataOverridesSchema.optional(), - customFields: zod.z.array(virtualModelCustomFieldDefinitionSchema).optional(), - suggestions: zod.z.array(virtualModelSuggestionSchema).optional(), -}); - -const logLevelSchema = zod.z.enum(["debug", "info", "warn", "error"]); - -/** - * Call a user provided callback and log any errors that occur. This prevents the error from - * crashing the application. - */ -function safeCallCallback(logger, name, callback, args) { - if (callback === undefined) { - return; - } - try { - const maybePromise = callback(...args); - if (typeof maybePromise === "object" && typeof maybePromise.catch === "function") { - maybePromise.catch((error) => { - logger.error(`Error in the ${name} callback (triggered asynchronously):`, error); - }); - } - } - catch (error) { - logger.error(`Error in the ${name} callback:`, error); - } -} - -function isSimpleLogger(logger) { - return logger?.isSimpleLogger === true; -} -const defaultInfoPrefix = chalk.greenBright("I"); -const defaultWarnPrefix = chalk.yellowBright("W"); -const defaultErrorPrefix = chalk.redBright("E"); -const defaultDebugPrefix = chalk.blueBright("D"); -class SimpleLogger { - constructor(prefixText = "", parentLogger = console, { useLogLevelPrefixes, infoPrefix, warnPrefix, errorPrefix, debugPrefix, } = {}) { - this.isSimpleLogger = true; - this.infoPrefix = []; - this.warnPrefix = []; - this.errorPrefix = []; - this.debugPrefix = []; - if (isSimpleLogger(parentLogger)) { - useLogLevelPrefixes = useLogLevelPrefixes ?? parentLogger.opts.useLogLevelPrefixes; - infoPrefix = infoPrefix === undefined ? parentLogger.opts.infoPrefix : infoPrefix; - warnPrefix = warnPrefix === undefined ? parentLogger.opts.warnPrefix : warnPrefix; - errorPrefix = errorPrefix === undefined ? parentLogger.opts.errorPrefix : errorPrefix; - debugPrefix = debugPrefix === undefined ? parentLogger.opts.debugPrefix : debugPrefix; - if (prefixText === "") { - this.innerPrefix = parentLogger.innerPrefix; - this.fullPrefix = parentLogger.fullPrefix; - } - else { - if (parentLogger.fullPrefix === "") { - this.innerPrefix = prefixText; - } - else { - this.innerPrefix = `${parentLogger.innerPrefix}][${prefixText}`; - } - this.fullPrefix = chalk.whiteBright(`[${this.innerPrefix}]`); - } - this.parentLogger = parentLogger.parentLogger; - } - else { - useLogLevelPrefixes = useLogLevelPrefixes ?? false; - infoPrefix = infoPrefix === undefined ? defaultInfoPrefix : infoPrefix; - warnPrefix = warnPrefix === undefined ? defaultWarnPrefix : warnPrefix; - errorPrefix = errorPrefix === undefined ? defaultErrorPrefix : errorPrefix; - debugPrefix = debugPrefix === undefined ? defaultDebugPrefix : debugPrefix; - if (prefixText === "") { - this.innerPrefix = ""; - this.fullPrefix = ""; - } - else { - this.innerPrefix = prefixText; - this.fullPrefix = chalk.whiteBright(`[${this.innerPrefix}]`); - } - this.parentLogger = parentLogger; - } - if (useLogLevelPrefixes) { - if (infoPrefix !== null) { - this.infoPrefix.push(infoPrefix); - } - if (warnPrefix !== null) { - this.warnPrefix.push(warnPrefix); - } - if (errorPrefix !== null) { - this.errorPrefix.push(errorPrefix); - } - if (debugPrefix !== null) { - this.debugPrefix.push(debugPrefix); - } - } - if (this.fullPrefix !== "") { - this.infoPrefix.push(this.fullPrefix); - this.warnPrefix.push(this.fullPrefix); - this.errorPrefix.push(this.fullPrefix); - this.debugPrefix.push(this.fullPrefix); - } - this.opts = { - useLogLevelPrefixes, - infoPrefix, - warnPrefix, - errorPrefix, - debugPrefix, - }; - } - subclass(prefixText) { - return new SimpleLogger(`${this.innerPrefix}:${prefixText}`, this.parentLogger); - } - info(...messages) { - this.parentLogger.info(...this.infoPrefix, ...messages); - } - infoText(strings, ...values) { - this.info(text(strings, ...values)); - } - infoWithoutPrefix(...messages) { - this.parentLogger.info(...messages); - } - error(...messages) { - this.parentLogger.error(...this.errorPrefix, ...messages); - } - errorText(strings, ...values) { - this.error(text(strings, ...values)); - } - errorWithoutPrefix(...messages) { - this.parentLogger.error(...messages); - } - warn(...messages) { - this.parentLogger.warn(...this.warnPrefix, ...messages); - } - warnText(strings, ...values) { - this.warn(text(strings, ...values)); - } - warnWithoutPrefix(...messages) { - this.parentLogger.warn(...messages); - } - debug(...messages) { - this.parentLogger.debug(...this.debugPrefix, ...messages); - } - debugText(strings, ...values) { - this.debug(text(strings, ...values)); - } - debugWithoutPrefix(...messages) { - this.parentLogger.debug(...messages); - } - throw(message) { - throw new Error(`${this.fullPrefix} ${message}`); - } - logAtLevel(level, ...messages) { - switch (level) { - case "debug": - this.debug(...messages); - break; - case "info": - this.info(...messages); - break; - case "warn": - this.warn(...messages); - break; - case "error": - this.error(...messages); - break; - } - } - static fromMultiple(loggers, opts) { - return new SimpleLogger("", { - debug: (...messages) => { - for (const logger of loggers) { - logger.debug(...messages); - } - }, - info: (...messages) => { - for (const logger of loggers) { - logger.info(...messages); - } - }, - warn: (...messages) => { - for (const logger of loggers) { - logger.warn(...messages); - } - }, - error: (...messages) => { - for (const logger of loggers) { - logger.error(...messages); - } - }, - }, { - ...opts, - useLogLevelPrefixes: false, - }); - } -} - -var _a; -const finished = Symbol("finished"); -/** - * A StreamablePromise is a promise-like that is also async iterable. This means you can use it as a - * promise (awaiting it, using `.then`, `.catch`, etc.), and you can also use it as an async - * iterable (using `for await`). - * - * Notably, as much as it implements the async iterable interface, it is not a traditional iterable, - * as it internally maintains a buffer and new values are pushed into the buffer by the producer, as - * oppose to being pulled by the consumer. - * - * The async iterable interface is used instead of the Node.js object stream because streams are too - * clunky to use, and the `for await` syntax is much more ergonomic for most people. - * - * If any iterator is created for this instance, an empty rejection handler will be attached to the - * promise to prevent unhandled rejection warnings. - * - * This class is provided as an abstract class and is meant to be extended. Crucially, the `collect` - * method must be implemented, which will be called to convert an array of values into the final - * resolved value of the promise. - * - * In addition, the constructor of the subclass should be marked as private, and a static method - * that exposes the constructor, the `finished` method, and the `push` method should be provided. - * - * @typeParam TFragment - The type of the individual fragments that are pushed into the buffer. - * @typeParam TFinal - The type of the final resolved value of the promise. - * @public - */ -class StreamablePromise { - /** - * Called by the producer when it has finished producing values. If an error is provided, the - * promise will be rejected with that error. If no error is provided, the promise will be resolved - * with the final value. - * - * This method should be exposed in the static constructor of the subclass. - * - * @param error - The error to reject the promise with, if any. - */ - finished(error) { - if (this.status !== "pending") { - throw new Error("`finished` called while not pending"); - } - if (error === undefined) { - this.status = "resolved"; - this.nextFragmentPromiseBundle?.resolve(finished); - this.resolveFinal(this.collect(this.buffer)); - } - else { - this.status = "rejected"; - this.nextFragmentPromiseBundle?.reject(error); - this.rejectFinal(error); - } - } - /** - * Called by the producer to push a new fragment into the buffer. This method should be exposed in - * the static constructor of the subclass. - * - * This method should be exposed in the static constructor of the subclass. - * - * @param fragment - The fragment to push into the buffer. - */ - push(fragment) { - if (this.status !== "pending") { - throw new Error("`push` called while not pending"); - } - this.buffer.push(fragment); - this.nextFragmentPromiseBundle?.resolve(fragment); - this.nextFragmentPromiseBundle = null; - } - constructor() { - this.status = "pending"; - this.buffer = []; - this.nextFragmentPromiseBundle = null; - /** - * If there has ever been any iterators created for this instance. Once any iterator is created, - * a reject handler will be attached to the promise to prevent unhandled rejection warnings, as - * the errors will be handled by the iterator. - * - * The purpose of this variable is to prevent registering the reject handler more than once. - */ - this.hasIterator = false; - this[_a] = "StreamablePromise"; - const { promise, resolve, reject } = makePromise(); - this.promiseFinal = promise; - this.resolveFinal = resolve; - this.rejectFinal = reject; - } - then(onfulfilled, onrejected) { - return this.promiseFinal.then(onfulfilled, onrejected); - } - catch(onrejected) { - return this.promiseFinal.catch(onrejected); - } - finally(onfinally) { - return this.promiseFinal.finally(onfinally); - } - /** - * If nextFragmentPromiseBundle exists, it is returned. Otherwise, a new one is created and - * returned. - */ - obtainNextFragmentPromiseBundle() { - if (this.nextFragmentPromiseBundle === null) { - this.nextFragmentPromiseBundle = makePromise(); - } - return this.nextFragmentPromiseBundle; - } - async *[(_a = Symbol.toStringTag, Symbol.asyncIterator)]() { - if (!this.hasIterator) { - this.promiseFinal.catch(() => { }); // Prevent unhandled rejection warning - this.hasIterator = true; - } - let i = 0; - while (i < this.buffer.length || this.status === "pending") { - if (i < this.buffer.length) { - yield this.buffer[i]; - i++; - } - else { - const nextFragmentPromiseBundle = this.obtainNextFragmentPromiseBundle(); - const nextFragment = await nextFragmentPromiseBundle.promise; - if (nextFragment === finished) { - // Make sure the promise is resolved before breaking the loop. - break; - } - yield nextFragment; - i++; - } - } - await this.promiseFinal; - // Wait for one more microtask to ensure that the promise is resolved before terminating the - // loop. This ensures that the by the time async loop is terminated, the onMessage handler is - // already triggered. - await Promise.resolve(); - } -} - -class Validator { - constructor({ attachStack } = {}) { - this.attachStack = attachStack ?? true; - } - /** - * Pretty-prints a Zod error. - * - * @param rootObjectName - The name of the object being validated (used for error messages) - * @param error - The Zod error to pretty-print - * - * @returns The pretty-printed error in a string - */ - static prettyPrintZod(rootObjectName, error) { - return error.errors - .map(e => { - if (e.path.length === 0) { - return `- ${chalk.redBright(rootObjectName)}: ${e.message}`; - } - const path = chalk.red(`.${e.path.join(".")}`); - return `- ${chalk.redBright(rootObjectName)}${path}: ${e.message}`; - }) - .join("\n"); - } - /** - * Validates a value against a schema and throws an error if it's invalid. - * - * @param lead - The start of the error message (used for error messages) - * @param rootObjectName - The name of the object being validated (used for error messages) - * @param schema - The schema to validate against - * @param value - The value to validate - * - * @returns The validated value - * @throws An error if the value is invalid - */ - validateOrThrow(lead, rootObjectName, schema, value, stack) { - const result = schema.safeParse(value); - if (result.success) { - return result.data; - } - else { - throw makePrettyError(`${lead}\n\n${Validator.prettyPrintZod(rootObjectName, result.error)}`, this.attachStack ? stack : undefined); - } - } - /** - * Validates multiple values against multiple schemas and throws an error if any of them are - * invalid. All values are validated before any errors are thrown. This is useful when you want to - * validate multiple values at once and want to see all the errors at once. - * - * @param leadProducer - The function to produce the start of the error message (used for error). - * It is called with a set of indices of the invalid values. - * @param rootObjectNames - The names of the objects being validated (used for error messages) - * @param schemas - The schemas to validate against - * @param values - The values to validate - * - * @returns The validated values - * @throws An error if any of the values are invalid - */ - validateMultipleOrThrow(leadProducer, rootObjectNames, schemas, values, stack) { - const results = schemas.map((schema, index) => schema.safeParse(values[index])); - const errors = results - .map((result, index) => ({ result, index, rootObjectName: rootObjectNames[index] })) - .filter(({ result }) => !result.success) - .map(({ result, rootObjectName, index }) => ({ - error: result.error, - rootObjectName, - index, - })); - if (errors.length === 0) { - return results.map(result => result.data); - } - else { - const erroredValues = new Set(errors.map(({ index }) => index)); - const lead = leadProducer(erroredValues); - throw makePrettyError(`${lead}\n\n${errors - .map(({ error, rootObjectName }) => Validator.prettyPrintZod(rootObjectName, error)) - .join("\n")}`, this.attachStack ? stack : undefined); - } - } - /** - * Validates a value against a schema and throws an error if it's invalid. This is a convenience - * function for validating one single method parameter. - * - * @param className - The name of the class containing the method (used for error messages) - * @param methodName - The name of the method (used for error messages) - * @param paramName - The name of the parameter being validated (used for error messages) - * @param schema - The schema to validate against - * @param value - The value to validate - * - * @returns The validated value - * @throws An error if the value is invalid - */ - validateMethodParamOrThrow(className, methodName, paramName, schema, value, stack) { - const functionCall = chalk.yellowBright(text ` - ${className}.${methodName}(${chalk.redBright(paramName)}) - `); - return this.validateOrThrow(`Invalid parameter(s) for ${functionCall}:`, paramName, schema, value, stack); - } - /** - * Validates multiple values against multiple schemas and throws an error if any of them are - * invalid. This is a convenience function for validating multiple method parameters. - * - * @param className - The name of the class containing the method (used for error messages) - * @param methodName - The name of the method (used for error messages) - * @param paramNames - The names of the parameters being validated (used for error messages) - * @param schemas - The schemas to validate against - * @param values - The values to validate - * - * @returns The validated values - * @throws An error if any of the values are invalid - */ - validateMethodParamsOrThrow(className, methodName, paramNames, schemas, values, stack) { - return this.validateMultipleOrThrow(erroredValues => { - const coloredParamNames = paramNames.map((name, index) => erroredValues.has(index) ? chalk.redBright(name) : name); - const functionCall = chalk.yellowBright(text ` - ${className}.${methodName}(${coloredParamNames.join(", ")}) - `); - return `Invalid parameter(s) for ${functionCall}:`; - }, paramNames, schemas, values, stack); - } - /** - * Validates a value against a schema and throws an error if it's invalid. This is a convenience - * function for validating one single constructor parameter. - * - * @param className - The name of the class (used for error messages) - * @param paramName - The name of the parameter being validated (used for error messages) - * @param schema - The schema to validate against - * @param value - The value to validate - * - * @returns The validated value - * @throws An error if the value is invalid - */ - validateConstructorParamOrThrow(className, paramName, schema, value, stack) { - const functionCall = chalk.yellowBright(text ` - ${className}(${chalk.redBright(paramName)}) - `); - return this.validateOrThrow(`Invalid parameter(s) when constructing ${functionCall}`, paramName, schema, value, stack); - } - /** - * Validates multiple values against multiple schemas and throws an error if any of them are - * invalid. This is a convenience function for validating multiple constructor parameters. - * - * @param className - The name of the class (used for error messages) - * @param paramNames - The names of the parameters being validated (used for error messages) - * - * @param schemas - The schemas to validate against - * @param values - The values to validate - */ - validateConstructorParamsOrThrow(className, paramNames, schemas, values, stack) { - return this.validateMultipleOrThrow(erroredValues => { - const coloredParamNames = paramNames.map((name, index) => erroredValues.has(index) ? chalk.redBright(name) : name); - const functionCall = chalk.yellowBright(text ` - ${className}(${coloredParamNames.join(", ")}) - `); - return `Invalid parameter(s) when constructing ${functionCall}:`; - }, paramNames, schemas, values, stack); - } -} -const sharedValidator = new Validator(); - -/** - * Represents a file. Currently, the file can be either in the local file system or base64 encoded. - * - * @public - */ -class FileHandle { - /** - * @deprecated Direct construction is not recommended. Please use the `prepareFile` API instead - */ - constructor(filesNamespace, identifier, type, sizeBytes, - /** - * Original file name - */ - name) { - this.filesNamespace = filesNamespace; - this.identifier = identifier; - this.type = type; - this.sizeBytes = sizeBytes; - this.name = name; - this.parsedIdentifier = parseFileIdentifier(identifier); - } - /** - * Gets the absolute file path of this file. - */ - async getFilePath() { - switch (this.parsedIdentifier.type) { - case "local": { - return (await this.filesNamespace.getLocalFileAbsolutePath(this.parsedIdentifier.fileName)) - .path; - } - case "base64": { - throw new Error("Not implemented. Please open an issue on GitHub if you encountered this error."); - } - default: { - const _exhaustiveCheck = this.parsedIdentifier; - throw new Error(`Unexpected file identifier type: ${JSON.stringify(_exhaustiveCheck)}`); - } - } - } - isImage() { - return this.type === "image"; - } -} - -const chatMessageInputSchema = zod.z.object({ - role: zod.z.enum(["user", "assistant", "system"]).optional(), - content: zod.z.string().optional(), - images: zod.z.array(zod.z.instanceof(FileHandle)).optional(), -}); -const chatHistoryInputSchema = zod.z.array(chatMessageInputSchema); -/** - * Given a `ChatMessageInput` or `ChatMessageData`, returns true if the input is a - * `ChatMessageInput`. - */ -function isChatMessageInputAsOpposeToChatMessageData(chatMessageInput) { - return !Array.isArray(chatMessageInput.content); -} -function isChatMessageInputAsOpposeToChatHistoryData(chatMessageInput) { - return !("messages" in chatMessageInput); -} -function chatMessageInputToChatMessageData(chatMessageInput) { - const { role, content, images } = chatMessageInput; - const parts = []; - if (images === undefined || images.length === 0) { - if (content === undefined) { - // If both content and file are undefined, let's just create an empty part. - parts.push({ - type: "text", - text: "", - }); - } - } - else { - for (const file of images) { - parts.push({ - type: "file", - identifier: file.identifier, - name: file.name, - fileType: file.type, - sizeBytes: file.sizeBytes, - }); - } - } - if (content !== undefined) { - parts.push({ - type: "text", - text: content, - }); - } - return { - role: role ?? "user", - content: parts, - }; -} - -/** - * Represents a chat history. - * - * @public - */ -class Chat extends MaybeMutable { - getClassName() { - return "Chat"; - } - create(data, mutable) { - return new Chat(data, mutable); - } - cloneData(data) { - return chatHistoryDataSchema.parse(data); // Using zod to clone the data - } - /** - * Don't use this constructor directly. - * - * - To create an empty chat history, use `Chat.empty()`. - * - To create a chat history with existing data, use `Chat.from()`. - */ - constructor(data, mutable) { - super(data, mutable); - } - /** - * Creates an empty mutable chat history. - */ - static empty() { - return new Chat({ messages: [] }, true); - } - /** - * Quickly create a mutable chat history with something that can be converted to a chat history. - * - * The created chat history will be a mutable copy of the input. - * - * @example - * ```ts - * const history = Chat.from([ - * { role: "user", content: "Hello" }, - * { role: "assistant", content: "Hi!" }, - * { role: "user", content: "What is your name?" }, - * ]); - * ``` - */ - static from(initializer) { - const stack = getCurrentStack(1); - sharedValidator.validateMethodParamOrThrow("Chat", "from", "initializer", chatHistoryLikeSchema, initializer, stack); - if (initializer instanceof Chat) { - // Chat - return initializer.asMutableCopy(); - } - if (typeof initializer === "string") { - const chatHistory = Chat.empty(); - chatHistory.append("user", initializer); - return chatHistory; - } - if (Array.isArray(initializer)) { - // ChatInput - return new Chat({ messages: initializer.map(chatMessageInputToChatMessageData) }, true); - } - if (isChatMessageInputAsOpposeToChatHistoryData(initializer)) { - // ChatMessageInput - return new Chat({ messages: [chatMessageInputToChatMessageData(initializer)] }, true); - } - else { - // ChatHistoryData - return new Chat(initializer, false).asMutableCopy(); - } - } - /** - * Creates a chat history with raw data. This method is intended for internal use only. - * - * If mutable is set to false, you MUST ensure that the data is not mutated. - * - * @internal - */ - static createRaw(data, mutable) { - return new Chat(data, mutable); - } - /** - * Gets the raw data of this message. This method is intended for internal use only. - * - * If mutable is set to false, you MUST ensure that the data is not mutated. - * - * @internal - */ - getRaw() { - return this.data; - } - append(...args) { - this.guardMutable(); - if (args.length === 1) { - const [chatMessageLike] = args; - const chatMessage = ChatMessage.from(chatMessageLike); - const messageMutable = accessMaybeMutableInternals(chatMessage)._internalToMutable(); - this.data.messages.push(accessMaybeMutableInternals(messageMutable)._internalGetData()); - } - else { - const [role, content, opts = {}] = args; - if (role === "user" || role === "system" || role === "assistant") { - const parts = [ - { type: "text", text: content }, - ]; - if (opts.images !== undefined) { - for (const image of opts.images) { - parts.push({ - type: "file", - name: image.name, - identifier: image.identifier, - sizeBytes: image.sizeBytes, - fileType: image.type, - }); - } - } - this.data.messages.push({ role, content: parts }); - } - else { - throw new Error(text ` - Unsupported role for append() API with [role, content] parameters: ${role}. - Supported roles are 'user', 'system', and 'assistant'. - `); - } - } - } - withAppended(...args) { - const copy = this.asMutableCopy(); - copy.append(...args); - return copy; - } - /** - * Get the number of messages in the history. - */ - getLength() { - return this.data.messages.length; - } - /** - * Get the number of messages in the history. - */ - get length() { - return this.getLength(); - } - /** - * Remove the last message from the history. If the history is empty, this method will throw. - */ - pop() { - this.guardMutable(); - if (this.data.messages.length === 0) { - throw new Error("Tried to pop from an empty history."); - } - const popped = this.data.messages.pop(); - return ChatMessage.createRaw(popped, true); - } - /** - * Gets all files contained in this history. - * - * @param client - LMStudio client - */ - getAllFiles(client) { - return this.data.messages - .flatMap(message => message.content.filter(part => part.type === "file")) - .map(part => new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name)); - } - /** - * Allows iterating over the files in the history. - */ - *files(client) { - for (const message of this.data.messages) { - for (const part of message.content) { - if (part.type === "file") { - yield new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name); - } - } - } - } - /** - * Returns true if this history contains any files. - */ - hasFiles() { - return this.data.messages.some(message => message.content.some(part => part.type === "file")); - } - /** - * Gets the message at the given index. If the index is negative, it will be counted from the end. - * - * If the index is out of bounds, this method will throw as oppose to returning undefined. This is - * to help catch bugs early. - */ - at(index) { - let actualIndex = index; - if (index < 0) { - actualIndex = this.data.messages.length + index; - } - if (actualIndex < 0 || actualIndex >= this.data.messages.length) { - throw new Error(text ` - Tried to access the message at index ${index}, but the history only has - ${this.data.messages.length} messages. - `); - } - return ChatMessage.createRaw(this.data.messages[actualIndex], this.mutable); - } - /** - * Get all the messages in the history as an array of ChatMessage objects. - */ - getMessagesArray() { - return this.data.messages.map(message => ChatMessage.createRaw(message, this.mutable)); - } - /** - * Maps over the messages in the history and returns an array of the results. - */ - map(mapper) { - return this.getMessagesArray().map(mapper); - } - /** - * Maps over the messages in the history and returns a flattened array of the results. - * - * This is similar to `Array.prototype.flatMap`, but it works with ChatMessage objects. - */ - flatMap(mapper) { - return this.getMessagesArray().flatMap(mapper); - } - /** - * Allows iterating over the messages in the history. - */ - *[Symbol.iterator]() { - for (const message of this.data.messages) { - yield ChatMessage.createRaw(message, this.mutable); - } - } - /** - * Given a predicate, the predicate is called for each file in the history. - * - * - If the predicate returns true, the file is removed from the history and is collected into the - * returned array. - * - If the predicate returns false, the file is kept in the history. - * - * This method is useful if you are implementing a promptPreprocessor that needs to convert certain - * types of files. - * - * If the predicate needs to be async, use the {@link Chat#consumeFilesAsync} method. - * - * @param client - LMStudio client - * @param predicate - The predicate to call for each file. - * @returns The files that were consumed. - */ - consumeFiles(client, predicate) { - this.guardMutable(); - const consumedFiles = []; - for (const message of this.data.messages) { - consumedFiles.push(...ChatMessage.createRaw(message, true).consumeFiles(client, predicate)); - } - return consumedFiles; - } - /** - * Given an async predicate, the predicate is called for each file in the history. - * - * - If the predicate returns true, the file is removed from the history and is collected into the - * returned array. - * - If the predicate returns false, the file is kept in the history. - * - * This method is useful if you are implementing a promptPreprocessor that needs to convert certain - * types of files. - * - * If you need a synchronous version, use the {@link Chat#consumeFiles} method. - * - * @param client - LMStudio client - * @param predicate - The predicate to call for each file. - * @returns The files that were consumed. - */ - async consumeFilesAsync(client, predicate) { - this.guardMutable(); - const consumedFiles = []; - for (const message of this.data.messages) { - consumedFiles.push(...(await ChatMessage.createRaw(message, true).consumeFilesAsync(client, predicate))); - } - return consumedFiles; - } - getSystemPrompt() { - return this.data.messages - .filter(message => message.role === "system") - .map(message => message.content - .filter(part => part.type === "text") - .map(part => part.text) - .join(" ")) - .join("\n\n"); - } - replaceSystemPrompt(content) { - this.guardMutable(); - this.data.messages = this.data.messages.filter(message => message.role !== "system"); - this.data.messages.unshift({ role: "system", content: [{ type: "text", text: content }] }); - } - filterInPlace(predicate) { - this.guardMutable(); - this.data.messages = this.data.messages.filter(message => predicate(ChatMessage.createRaw(message, true))); - } - toString() { - return ("Chat {\n" + - this.data.messages - .map(message => { - const messageString = ChatMessage.createRaw(message, false).toString(); - return messageString - .split("\n") - .map(line => " " + line) - .join("\n"); - }) - .join("\n") + - "\n}"); - } -} -const chatHistoryLikeSchema = zod.z.union([ - zod.z.instanceof(Chat), - chatHistoryDataSchema, - zod.z.string(), - chatHistoryInputSchema, - chatMessageInputSchema, -]); -/** - * Represents a single message in the history. - * - * @public - */ -class ChatMessage extends MaybeMutable { - getClassName() { - return "ChatMessage"; - } - create(data, mutable) { - return new ChatMessage(data, mutable); - } - cloneData(data) { - return chatMessageDataSchema.parse(data); // Using zod to clone the data - } - constructor(data, mutable) { - super(data, mutable); - } - /** - * Create a mutable text only message. - */ - static create(role, content) { - return new ChatMessage(chatMessageDataSchema.parse({ - role, - content: [{ type: "text", text: content }], - }), true); - } - /** - * Quickly create a mutable message with something that can be converted to a message. - */ - static from(initializer) { - const stack = getCurrentStack(1); - sharedValidator.validateMethodParamOrThrow("ChatMessage", "from", "initializer", chatMessageLikeSchema, initializer, stack); - if (initializer instanceof ChatMessage) { - // ChatMessage - return initializer.asMutableCopy(); - } - if (typeof initializer === "string") { - return new ChatMessage(chatMessageDataSchema.parse({ - role: "user", - content: [{ type: "text", text: initializer }], - }), true); - } - if (isChatMessageInputAsOpposeToChatMessageData(initializer)) { - // ChatMessageData - return new ChatMessage(chatMessageInputToChatMessageData(initializer), true); - } - else { - // ChatMessageInput - return new ChatMessage(initializer, true); - } - } - /** - * Creates a chat history with raw data. This method is intended for internal use only. - * - * If mutable is set to false, you MUST ensure that the data is not mutated. - * - * @internal - */ - static createRaw(data, mutable) { - return new ChatMessage(data, mutable); - } - /** - * Gets the raw data of this message. This method is intended for internal use only. - * - * If mutable is set to false, you MUST ensure that the data is not mutated. - * - * @internal - */ - getRaw() { - return this.data; - } - getRole() { - return this.data.role; - } - setRole(role) { - this.guardMutable(); - this.data.role = role; - } - getFileParts() { - return this.data.content.filter(part => part.type === "file"); - } - /** - * Gets all text contained in this message. - */ - getText() { - return this.data.content - .filter(part => part.type === "text") - .map(part => part.text) - .join(" "); - } - /** - * Get all tool call results within this message. - */ - getToolCallResults() { - return this.data.content - .filter(part => part.type === "toolCallResult") - .map(part => ({ - content: part.content, - toolCallId: part.toolCallId, - })); - } - /** - * Gets all file parts contained in this message. - */ - getToolCallRequests() { - return this.data.content - .filter(part => part.type === "toolCallRequest") - .map(part => part.toolCallRequest); - } - /** - * Gets all files contained in this message. - * - * @param client - LMStudio client - */ - getFiles(client) { - return this.getFileParts().map(part => new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name)); - } - /** - * Allows iterating over the files in the message. - */ - *files(client) { - for (const part of this.getFileParts()) { - yield new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name); - } - } - /** - * Given a predicate, the predicate is called for each file in the message. - * - * - If the predicate returns true, the file is removed from the message and is collected into the - * returned array. - * - If the predicate returns false, the file is kept in the message. - * - * This method is useful if you are implementing a promptPreprocessor that needs to convert certain - * types of files. - * - * If the predicate needs to be async, use the {@link ChatMessage#consumeFilesAsync} method. - * - * @param client - LMStudio client - * @param predicate - The predicate to call for each file. - * @returns The files that were consumed. - */ - consumeFiles(client, predicate) { - this.guardMutable(); - const consumedFiles = []; - const partIndexesToRemove = new Set(); - for (const [index, part] of this.data.content.entries()) { - if (part.type !== "file") { - continue; - } - const file = new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name); - if (predicate(file)) { - consumedFiles.push(file); - partIndexesToRemove.add(index); - } - } - this.data.content = this.data.content.filter((_, index) => !partIndexesToRemove.has(index)); - return consumedFiles; - } - /** - * Given an async predicate, the predicate is called for each file in the message. - * - * - If the predicate returns true, the file is removed from the message and is collected into the - * returned array. - * - If the predicate returns false, the file is kept in the message. - * - * This method is useful if you are implementing a promptPreprocessor that needs to convert certain - * types of files. - * - * If you need a synchronous version, use the {@link ChatMessage#consumeFiles} method. - * - * @param client - LMStudio client - * @param predicate - The predicate to call for each file. - * @returns The files that were consumed. - */ - async consumeFilesAsync(client, predicate) { - this.guardMutable(); - const consumedFiles = []; - const partIndexesToRemove = new Set(); - for (const [index, part] of this.data.content.entries()) { - if (part.type !== "file") { - continue; - } - const file = new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name); - if (await predicate(file)) { - consumedFiles.push(file); - partIndexesToRemove.add(index); - } - } - this.data.content = this.data.content.filter((_, index) => !partIndexesToRemove.has(index)); - return consumedFiles; - } - /** - * Returns true if this message contains any files. - */ - hasFiles() { - return this.data.content.some(part => part.type === "file"); - } - /** - * Append text to the message. - */ - appendText(text) { - this.guardMutable(); - switch (this.data.role) { - case "assistant": - case "user": - case "system": - this.data.content.push({ - type: "text", - text, - }); - break; - case "tool": - throw new Error(`Cannot append text to a message with role "${this.data.role}"`); - default: { - const exhaustiveCheck = this.data; - throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`); - } - } - } - /** - * Append a file to the message. Takes in a FileHandle. You can obtain a FileHandle from - * `client.files.prepareImage`. - */ - appendFile(file) { - this.guardMutable(); - switch (this.data.role) { - case "assistant": - case "user": - case "system": - this.data.content.push({ - type: "file", - name: file.name, - identifier: file.identifier, - sizeBytes: file.sizeBytes, - fileType: file.type, - }); - break; - case "tool": - throw new Error(`Cannot append text to a message with role "${this.data.role}"`); - default: { - const exhaustiveCheck = this.data; - throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`); - } - } - } - /** - * Replaces all text in the messages. - * - * If the message contains other components (such as files), they will kept. The replaced text - * will be inserted to the beginning of the message. - */ - replaceText(text) { - this.guardMutable(); - switch (this.data.role) { - case "assistant": - case "user": - case "system": - this.data.content = [ - { type: "text", text }, - ...this.data.content.filter(part => part.type !== "text"), - ]; - break; - case "tool": - throw new Error(`Cannot replace text in a message with role "${this.data.role}"`); - default: { - const exhaustiveCheck = this.data; - throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`); - } - } - } - isSystemPrompt() { - return this.data.role === "system"; - } - isUserMessage() { - return this.data.role === "user"; - } - isAssistantMessage() { - return this.data.role === "assistant"; - } - toString() { - const text = this.data.content - .map(part => { - switch (part.type) { - case "text": - return part.text; - case "file": - return ``; - case "toolCallRequest": - return (part.toolCallRequest.name + `(${JSON.stringify(part.toolCallRequest.arguments)})`); - case "toolCallResult": - return part.content; - default: { - const exhaustiveCheck = part; - throw new Error(`Unknown part type: ${exhaustiveCheck.type}`); - } - } - }) - .join(" "); - if (text.includes("\n")) { - return (this.data.role + - ":\n" + - text - .split("\n") - .map(line => " " + line) - .join("\n")); - } - else { - return this.data.role + ": " + text; - } - } -} -const chatMessageLikeSchema = zod.z.union([ - zod.z.instanceof(ChatMessage), - chatMessageInputSchema, - zod.z.string(), - chatMessageDataSchema, -]); - -/** - * A builder for building a KVFieldValueTypeLibrary. - * - * The reason why a builder is used is to enable much better type inference when defining the value - * types. - */ -class KVFieldValueTypesLibraryBuilder { - constructor(baseSchema) { - this.baseSchema = baseSchema; - this.valueTypes = new Map(); - } - /** - * Define a new field value type. - */ - valueType(key, param) { - if (this.valueTypes.has(key)) { - throw new Error(`ValueType with key ${key} already exists`); - } - this.valueTypes.set(key, { - paramType: zod.z.object({ - ...this.baseSchema, - ...param.paramType, - }), - schemaMaker: param.schemaMaker, - effectiveEquals: param.effectiveEquals, - stringify: param.stringify, - }); - return this; - } - build() { - return new KVFieldValueTypeLibrary(new Map(this.valueTypes)); - } -} -/** - * Represents a library of field value types. - * - * @public - */ -class KVFieldValueTypeLibrary { - constructor(valueTypes) { - this.valueTypes = valueTypes; - } - /** - * Gets the schema for a specific field value type with the given key and parameters. - */ - getSchema(key, param) { - const valueType = this.valueTypes.get(key); - if (valueType === undefined) { - throw new Error(`Cannot find value type ${key}`); - } - return valueType.schemaMaker(valueType.paramType.parse(param)); - } - parseParamTypes(key, param) { - return this.valueTypes.get(key).paramType.parse(param); - } - effectiveEquals(key, typeParam, a, b) { - return this.valueTypes.get(key).effectiveEquals(a, b, typeParam); - } - stringify(key, typeParam, opts, value) { - return this.valueTypes.get(key).stringify(value, typeParam, opts); - } -} -class KVConfigSchematicsBuilder { - constructor(valueTypeLibrary) { - this.valueTypeLibrary = valueTypeLibrary; - this.fields = new Map(); - /** - * Prefixes for extensions. Does not affect parsing (i.e. extension fields will still not be - * visible). However, if a key starts with a prefix that is specified here, it will not be removed - * when going through the lenient zod schema. - */ - this.extensionPrefixes = []; - } - /** - * Adds a field - */ - field(key, valueTypeKey, valueTypeParams, defaultValue) { - const schema = this.valueTypeLibrary.getSchema(valueTypeKey, valueTypeParams); - const defaultValueParseResult = schema.safeParse(defaultValue); - if (!defaultValueParseResult.success) { - throw new Error(`Invalid default value for field ${key}: ${defaultValueParseResult.error.message}`); - } - defaultValue = defaultValueParseResult.data; - if (this.fields.has(key)) { - throw new Error(`Cannot add field with key ${key}. Key already exists in the schematics.`); - } - this.fields.set(key, { - valueTypeKey, - valueTypeParams, - schema: this.valueTypeLibrary.getSchema(valueTypeKey, valueTypeParams), - fullKey: key, - defaultValue, - }); - return this; - } - /** - * Adds an extension point. For example, if called with .extension("hello.world"), then any keys - * that match "hello.world.*" will be allowed when going through lenient zod schema. However, - * any extension fields will still not be accessible via this schematics. - */ - extension(prefix) { - this.extensionPrefixes.push(`${prefix}.`); - return this; - } - /** - * Convenience method for grouping a set of fields under a shared namespace. - * - * For example, if we want to create two fields: `some:namespace:a` and `some:namespace:b`. - * Instead of doing: - * - * ```ts - * builder - * .field("some:namespace:a", ...) - * .field("some:namespace:b", ...) - * ``` - * - * We can do: - * - * ```ts - * builder.scope("some:namespace", builder => - * builder - * .field("a", ...) - * .field("b", ...) - * ) - * ``` - * - * This method does support nesting. Whether to nest or not is up to the user. - */ - scope(scopeKey, fn) { - const innerBuilder = fn(new KVConfigSchematicsBuilder(this.valueTypeLibrary)); - for (const [key, { valueTypeKey, valueTypeParams, schema, defaultValue },] of innerBuilder.fields.entries()) { - const fullKey = `${scopeKey}.${key}`; - if (this.fields.has(fullKey)) { - throw new Error(`Cannot add field with key ${fullKey}. Key already exists in the schematics.`); - } - this.fields.set(fullKey, { - valueTypeKey, - valueTypeParams, - schema, - fullKey, - defaultValue, - }); - } - this.extensionPrefixes.push(...innerBuilder.extensionPrefixes.map(prefix => `${scopeKey}.${prefix}`)); - return this; - } - build() { - return new KVConfigSchematics(this.valueTypeLibrary, this.fields, this.extensionPrefixes); - } -} -const createParsedKVConfig = Symbol("createParsedKVConfig"); -class KVConfigSchematics { - constructor(valueTypeLibrary, fields, extensionPrefixes) { - this.valueTypeLibrary = valueTypeLibrary; - this.fields = fields; - this.extensionPrefixes = extensionPrefixes; - /** - * Cached full key map - */ - this.fullKepMap = undefined; - /** - * Cached lenient zod schema - */ - this.lenientZodSchema = undefined; - } - getFieldsMap() { - return new Map([...this.fields.values()].map(field => [field.fullKey, field])); - } - obtainField(key) { - const field = this.fields.get(key); - if (field === undefined) { - const fieldKeys = [...this.fields.keys()]; - let availableList = fieldKeys - .slice(0, 10) - .map(key => `- ${key}`) - .join("\n"); - if (fieldKeys.length > 10) { - availableList += `\n... and ${fieldKeys.length - 10} more`; - } - throw new Error(`Cannot access key ${key}. Key does not exist in the schematics. Available keys:\n\n` + - availableList); - } - return field; - } - obtainFieldByFullKey(fullKey) { - const field = this.getFullKeyMap().get(fullKey); - if (field === undefined) { - const fieldKeys = [...this.getFullKeyMap().keys()]; - let availableList = fieldKeys - .slice(0, 10) - .map(key => `- ${key}`) - .join("\n"); - if (fieldKeys.length > 10) { - availableList += `\n... and ${fieldKeys.length - 10} more`; - } - throw new Error(`Cannot access full key ${fullKey}. Full key does not exist in the schematics. Available` + - `keys:\n\n` + - availableList); - } - return field; - } - getSchemaForKey(key) { - const field = this.obtainField(key); - return field.schema; - } - parseField(fieldSchema, value) { - if (value === undefined) { - if (fieldSchema.defaultValue === undefined) { - throw new Error(`Field with key ${fieldSchema.fullKey} is missing and has no default value`); - } - return fieldSchema.defaultValue; - } - const parseResult = fieldSchema.schema.safeParse(value); - if (!parseResult.success) { - throw new Error(`Field with key ${fieldSchema.fullKey} does not satisfy the schema:` + - parseResult.error.message); - } - return parseResult.data; - } - parseFieldWithoutDefault(field, value) { - if (value === undefined) { - return undefined; - } - const parseResult = field.schema.safeParse(value); - if (!parseResult.success) { - throw new Error(`Field with key ${field.fullKey} does not satisfy the schema:` + parseResult.error.message); - } - return parseResult.data; - } - /** - * Parse and access a field in the config. - */ - access(config, key) { - const field = this.obtainField(key); - return this.parseField(field, config.fields.find(f => f.key === field.fullKey)?.value); - } - accessByFullKey(config, fullKey) { - const field = this.obtainFieldByFullKey(fullKey); - return this.parseField(field, config.fields.find(f => f.key === field.fullKey)?.value); - } - /** - * Parse and access a field in the config. Returns undefined if the field is missing. - */ - accessPartial(config, key) { - const field = this.obtainField(key); - return this.parseFieldWithoutDefault(field, config.fields.find(f => f.key === field.fullKey)?.value); - } - /** - * Gets a slice of the config schema with the given key patterns. Support syntax: - * - * - `some.namespace.key`: Matches exactly `some.namespace.key` - * - `some.namespace.*`: Matches anything that starts with `some.namespace.` - */ - sliced(...patterns) { - const parsedPatterns = patterns.map(p => { - if (p.endsWith("*")) { - return { type: "prefix", value: p.substring(0, p.length - 1) }; - } - return { type: "exact", value: p }; - }); - const newFields = new Map(); - for (const [key, field] of this.fields.entries()) { - for (const pattern of parsedPatterns) { - if ((pattern.type === "exact" && key === pattern.value) || - (pattern.type === "prefix" && key.startsWith(pattern.value))) { - newFields.set(key, field); - } - } - } - return new KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes); - } - /** - * Get a subset of the config schema with a specific scope. - */ - scoped(scopeKey) { - const newFields = new Map(); - for (const [key, field] of this.fields.entries()) { - if (key.startsWith(`${scopeKey}.`)) { - newFields.set(key.substring(scopeKey.length + 1), field); - } - } - return new KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes); - } - union(other) { - const newFields = new Map(); - for (const [key, field] of this.fields.entries()) { - newFields.set(key, field); - } - for (const [key, field] of other.fields.entries()) { - if (newFields.has(key)) { - throw new Error("Cannot union two KVConfigSchematics. The following key is duplicated: " + key); - } - newFields.set(key, field); - } - return new KVConfigSchematics(this.valueTypeLibrary, newFields, [ - ...this.extensionPrefixes, - ...other.extensionPrefixes, - ]); - } - /** - * Combine baseKey into the fields. Effectively removes the baseKey. - */ - flattenBaseKey() { - const newFields = new Map(); - for (const field of this.fields.values()) { - newFields.set(field.fullKey, field); - } - return new KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes); - } - parseToMap(config) { - const rawConfigMap = kvConfigToMap(config); - const parsedConfigMap = new Map(); - for (const [key, field] of this.fields.entries()) { - const value = rawConfigMap.get(field.fullKey); - const parsedValue = this.parseField(field, value); - parsedConfigMap.set(key, parsedValue); - } - return parsedConfigMap; - } - parseToMapWithFullKey(config) { - const rawConfigMap = kvConfigToMap(config); - const parsedConfigMap = new Map(); - for (const field of this.fields.values()) { - const value = rawConfigMap.get(field.fullKey); - const parsedValue = this.parseField(field, value); - parsedConfigMap.set(field.fullKey, parsedValue); - } - return parsedConfigMap; - } - parseToMapPartial(config) { - const rawConfigMap = kvConfigToMap(config); - const parsedConfigMap = new Map(); - for (const [key, field] of this.fields.entries()) { - const value = rawConfigMap.get(field.fullKey); - const parsedValue = this.parseFieldWithoutDefault(field, value); - if (parsedValue !== undefined) { - parsedConfigMap.set(key, parsedValue); - } - } - return parsedConfigMap; - } - /** - * Parse the given config to a ParsedKVConfig. **Will throw** if the config does not satisfy the - * schema. - */ - parse(config) { - return ParsedKVConfig[createParsedKVConfig](this.parseToMap(config)); - } - parsePartial(config) { - return PartialParsedKVConfig[createParsedKVConfig](this.parseToMapPartial(config)); - } - /** - * Builds a full KV config from the given values record. **Will throw** if any of the values are - * missing or do not satisfy the schema. - */ - buildFullConfig(valuesRecord) { - return { - fields: Array.from(this.fields.entries()).map(([key, field]) => { - const value = this.parseField(field, valuesRecord[key]); - return { key: field.fullKey, value }; - }), - }; - } - /** - * Builds a partial KV config from the given values record. Will leave holes in the config if the - * values are missing. **Will throw** if any of the values do not satisfy the schema. - */ - buildPartialConfig(valuesRecord) { - return { - fields: Object.entries(valuesRecord) - .filter(([_key, value]) => value !== undefined) - .map(([key, value]) => { - const field = this.obtainField(key); - return { key: field.fullKey, value: this.parseField(field, value) }; - }), - }; - } - createBuildPartialConfigInput() { - return {}; - } - configBuilder() { - return new KVConfigBuilder(this.fields); - } - clone() { - return new KVConfigSchematics(this.valueTypeLibrary, new Map(this.fields), this.extensionPrefixes); - } - withTypeParamOverride(key, paramMapper) { - const field = this.obtainField(key); - const clone = this.clone(); - clone.fields.set(key, { - ...field, - valueTypeParams: paramMapper(field.valueTypeParams), - schema: this.valueTypeLibrary.getSchema(field.valueTypeKey, paramMapper(field.valueTypeParams)), - }); - return clone; - } - getFullKeyMap() { - if (this.fullKepMap !== undefined) { - return this.fullKepMap; - } - this.fullKepMap = new Map([...this.fields.values()].map(field => [field.fullKey, field])); - return this.fullKepMap; - } - makeLenientZodSchema() { - const fullKeyMap = this.getFullKeyMap(); - return kvConfigSchema.transform(value => { - const seenKeys = new Set(); - return { - fields: value.fields.filter(field => { - if (this.extensionPrefixes.some(prefix => field.key.startsWith(prefix))) { - // If we matched an extension prefix, we don't care about the key or value type. Just - // allow it. - return true; - } - if (seenKeys.has(field.key)) { - return false; - } - const fieldDef = fullKeyMap.get(field.key); - if (fieldDef === undefined) { - return false; - } - const parsed = fieldDef.schema.safeParse(field.value); - if (!parsed.success) { - return false; - } - seenKeys.add(field.key); - return true; - }), - }; - }); - } - /** - * Makes a zod schema that parses a KVConfig which only allows fields with correct keys and types - * through. - * - * Will filter out any fields that are not in the schema. - */ - getLenientZodSchema() { - if (this.lenientZodSchema !== undefined) { - return this.lenientZodSchema; - } - this.lenientZodSchema = this.makeLenientZodSchema(); - return this.lenientZodSchema; - } - getValueType(key) { - const field = this.fields.get(key); - if (field === undefined) { - return null; - } - return field.valueTypeKey; - } - getValueTypeParam(key) { - const field = this.fields.get(key); - if (field === undefined) { - return null; - } - return field.valueTypeParams; - } - getValueTypeParamByFullKey(key) { - const field = this.getFullKeyMap().get(key); - if (field === undefined) { - throw new Error(`Field with key ${key} does not exist in the schematics`); - } - return field.valueTypeParams; - } - hasFullKey(key) { - const field = this.getFullKeyMap().get(key); - return field !== undefined; - } - /** - * Given a KVConfig, filter it to only include fields that are in the schematics. - */ - filterConfig(config, additionalFilter) { - const fullKeyMap = this.getFullKeyMap(); - return { - fields: config.fields.filter(configField => { - const field = fullKeyMap.get(configField.key); - if (field === undefined) { - return false; - } - if (additionalFilter !== undefined) { - return additionalFilter(field.fullKey, { - type: field.valueTypeKey, - param: field.valueTypeParams, - }); - } - return true; - }), - }; - } - /** - * Given a KVConfigStack, filter it to only include fields that are in the schematics. - */ - filterStack(stack) { - return { - layers: stack.layers.map(layer => ({ - layerName: layer.layerName, - config: this.filterConfig(layer.config), - })), - }; - } - twoWayFilterConfig(config, additionalFilter) { - const includedFields = []; - const excludedFields = []; - const fullKeyMap = this.getFullKeyMap(); - for (const configField of config.fields) { - const field = fullKeyMap.get(configField.key); - let include = field !== undefined; - if (field !== undefined && additionalFilter !== undefined) { - include = additionalFilter(field.fullKey, { - type: field.valueTypeKey, - param: field.valueTypeParams, - }); - } - if (include) { - includedFields.push(configField); - } - else { - excludedFields.push(configField); - } - } - return [{ fields: includedFields }, { fields: excludedFields }]; - } - /** - * Given a list of keys, filter it to only include keys that are in the schematics. - */ - filterFullKeys(keys) { - const fullKeyMap = this.getFullKeyMap(); - return keys.filter(key => fullKeyMap.has(key)); - } - /** - * Compares two KV config. Compare with "effective equals". Only compare fields in the schematics. - * Does not apply defaults. - */ - configEffectiveEquals(a, b) { - const aMap = kvConfigToMap(a); - const bMap = kvConfigToMap(b); - for (const field of this.fields.values()) { - const aValue = aMap.get(field.fullKey); - const bValue = bMap.get(field.fullKey); - if (aValue === undefined) { - if (bValue === undefined) { - // Both are missing, continue - continue; - } - else { - return false; - } - } - this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, aValue, bValue); - } - return true; - } - /** - * Compares two KV config field. Compare with "effective equals". Can only compare fields in the - * schematics. - */ - fieldEffectiveEquals(key, a, b) { - const field = this.obtainField(key); - return this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, field.schema.parse(a), field.schema.parse(b)); - } - fieldEffectiveEqualsWithFullKey(fullKey, a, b) { - const fullKeyMap = this.getFullKeyMap(); - const field = fullKeyMap.get(fullKey); - if (field === undefined) { - throw new Error(`Field with key ${fullKey} does not exist in the schematics`); - } - return this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, field.schema.parse(a), field.schema.parse(b)); - } - makeInternalFieldStringifyOpts(opts) { - return { - t: opts.t ?? ((_key, fallback) => fallback), - desiredLength: opts.desiredLength, - }; - } - stringifyField(key, value, opts = {}) { - const field = this.obtainField(key); - return this.valueTypeLibrary.stringify(field.valueTypeKey, field.valueTypeParams, this.makeInternalFieldStringifyOpts(opts), value); - } - tryStringifyFieldWithFullKey(key, value, opts) { - const fullKeyMap = this.getFullKeyMap(); - const field = fullKeyMap.get(key); - if (field === undefined) { - return null; - } - return this.valueTypeLibrary.stringify(field.valueTypeKey, field.valueTypeParams, this.makeInternalFieldStringifyOpts(opts), value); - } - /** - * Apply config in patch to target. Only apply fields that are in the schematics. - */ - apply(target, patch) { - const filteredPatch = this.filterConfig(patch); - return collapseKVStackRaw([target, filteredPatch]); - } - /** - * Tries to un-apply the patch from the target. Will only un-apply fields that are in the - * schematics. - * - * If the value in the target is not effective equal to the value in the patch, it will not be - * removed. - */ - unApply(target, patch) { - const filteredPatch = this.filterConfig(patch); - const patchMap = kvConfigToMap(filteredPatch); - const newMap = new Map(kvConfigToMap(target)); - const fullKeyMap = this.getFullKeyMap(); - for (const [key, value] of patchMap.entries()) { - const field = fullKeyMap.get(key); - if (field === undefined) { - continue; - } - const targetValue = newMap.get(key); - if (targetValue !== undefined) { - if (!this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, value, targetValue)) { - continue; - } - newMap.delete(key); - } - } - return mapToKVConfig(newMap); - } - /** - * Given a KVConfig, iterate through all the fields that are in the schematics. Keys will be full - * keys. - */ - *iterateFieldsOfConfig(config) { - const fullKeyMap = this.getFullKeyMap(); - for (const { key, value } of config.fields) { - const field = fullKeyMap.get(key); - if (field !== undefined) { - yield [key, value]; - } - } - } - /** - * Given a KVConfig, iterate through all the fields that are in the schematics. - */ - *fullKeys() { - const fullKeyMap = this.getFullKeyMap(); - for (const key of fullKeyMap.keys()) { - yield key; - } - } - /** - * Effectively compare two KV config, and return full keys of fields that are different. - */ - effectiveCompareConfig(a, b, opts = {}) { - const { fieldFilter } = opts; - const aMap = kvConfigToMap(a); - const bMap = kvConfigToMap(b); - const onlyInA = []; - const onlyInB = []; - const inBothButDifferent = []; - for (const field of this.fields.values()) { - if (fieldFilter !== undefined) { - if (!fieldFilter(field.fullKey, { - type: field.valueTypeKey, - param: field.valueTypeParams, - })) { - continue; - } - } - const aValue = aMap.get(field.fullKey); - const bValue = bMap.get(field.fullKey); - if (aValue === undefined) { - if (bValue === undefined) { - continue; - } - else { - onlyInB.push(field.fullKey); - } - } - else { - if (bValue === undefined) { - onlyInA.push(field.fullKey); - } - else { - if (!this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, aValue, bValue)) { - inBothButDifferent.push(field.fullKey); - } - } - } - } - return { onlyInA, onlyInB, inBothButDifferent }; - } - serialize() { - return { - fields: [...this.fields.entries()].map(([key, field]) => ({ - shortKey: key, - fullKey: field.fullKey, - typeKey: field.valueTypeKey, - typeParams: field.valueTypeParams, - defaultValue: field.defaultValue, - })), - extensionPrefixes: this.extensionPrefixes, - }; - } - /** - * Check if any of the fields in the schematics has a full key that starts with the given prefix. - */ - hasFieldsWithPrefix(prefix) { - for (const field of this.fields.values()) { - if (field.fullKey.startsWith(prefix)) { - return true; - } - } - return false; - } - static deserialize(valueTypeLibrary, serialized) { - const fields = new Map(serialized.fields.map(field => { - const typeParams = valueTypeLibrary.parseParamTypes(field.typeKey, field.typeParams); - const valueSchema = valueTypeLibrary.getSchema(field.typeKey, typeParams); - return [ - field.shortKey, - { - valueTypeKey: field.typeKey, - valueTypeParams: typeParams, - schema: valueSchema, - fullKey: field.fullKey, - defaultValue: valueSchema.parse(field.defaultValue), - }, - ]; - })); - return new KVConfigSchematics(valueTypeLibrary, fields, serialized.extensionPrefixes ?? []); - } - static tryDeserialize(valueTypeLibrary, serialized) { - const fields = new Map(); - const errors = []; - for (const field of serialized.fields) { - try { - const typeParams = valueTypeLibrary.parseParamTypes(field.typeKey, field.typeParams); - const valueSchema = valueTypeLibrary.getSchema(field.typeKey, typeParams); - fields.set(field.shortKey, { - valueTypeKey: field.typeKey, - valueTypeParams: typeParams, - schema: valueSchema, - fullKey: field.fullKey, - defaultValue: valueSchema.parse(field.defaultValue), - }); - } - catch (error) { - errors.push({ - fullKey: field.fullKey, - error: serializeError(error), - }); - } - } - return { - schematics: new KVConfigSchematics(valueTypeLibrary, fields, serialized.extensionPrefixes ?? []), - errors, - }; - } -} -class KVConfigBuilder { - constructor(fieldDefs) { - this.fieldDefs = fieldDefs; - this.fields = new Map(); - } - with(key, value) { - const field = this.fieldDefs.get(key); - if (field === undefined) { - throw new Error(`Field with key ${key} does not exist in the schematics.`); - } - this.fields.set(field.fullKey, value); - return this; - } - build() { - return mapToKVConfig(this.fields); - } -} -/** - * This class can be only constructed via the `parse` method on `KVConfigSchema`. It is guaranteed - * to satisfy the schema. - * - * All fields that exist on the schematics is guaranteed to exist here. - */ -class ParsedKVConfig { - constructor( - /** - * Guaranteed to satisfy the schema. - */ - configMap) { - this.configMap = configMap; - } - /** - * @internal - */ - static [createParsedKVConfig](configMap) { - return new ParsedKVConfig(configMap); - } - get(key) { - return this.configMap.get(key); - } -} -/** - * This class can be constructed via the `parsePartial` method on `KVConfigSchema`. All existing - * fields are guaranteed to satisfy the schema. However, there may be missing fields. - */ -class PartialParsedKVConfig { - constructor( - /** - * Guaranteed to satisfy the schema. - */ - configMap) { - this.configMap = configMap; - } - static [createParsedKVConfig](configMap) { - return new PartialParsedKVConfig(configMap); - } - get(key) { - return this.configMap.get(key); - } - has(key) { - return this.configMap.has(key); - } -} -function kvConfigToMap(config) { - return new Map(config.fields.map(f => [f.key, f.value])); -} -function mapToKVConfig(map) { - return { - fields: Array.from(map.entries()).map(([key, value]) => ({ key, value })), - }; -} -function collapseKVStackRaw(configs) { - const map = new Map(); - for (const config of configs) { - for (const { key, value } of config.fields) { - map.set(key, value); - } - } - return mapToKVConfig(map); -} -const emptyKVConfig = { - fields: [], -}; -function singleLayerKVConfigStackOf(name, config) { - return { - layers: [ - { - layerName: name, - config, - }, - ], - }; -} -/** - * Given a KVConfigStack, add a new layer to the top of the stack. Does not mutate the original - * stack. - */ -function addKVConfigToStack(stack, newLayerName, newLayerConfig) { - return { - layers: [ - ...stack.layers, - { - layerName: newLayerName, - config: newLayerConfig, - }, - ], - }; -} -function deepEquals(a, b) { - if (a === b) { - return true; - } - if (typeof a !== "object" || typeof b !== "object") { - return false; - } - if (a === null || b === null) { - return false; - } - if (Array.isArray(a) !== Array.isArray(b)) { - return false; - } - if (Array.isArray(a)) { - if (a.length !== b?.length) { - return false; - } - for (let i = 0; i < a.length; i++) { - if (!deepEquals(a[i], b[i])) { - return false; - } - } - return true; - } - const aKeys = new Set(Object.keys(a)); - const bKeys = new Set(Object.keys(b)); - if (aKeys.size !== bKeys.size) { - return false; - } - for (const key of aKeys) { - if (!bKeys.has(key)) { - return false; - } - if (!deepEquals(a[key], b[key])) { - return false; - } - } - return true; -} - -/** - * Quote a string. - */ -function quoteString(str, empty) { - if (str === undefined || str === "") { - return empty ?? '""'; - } - return JSON.stringify(str); -} -/** - * Quote a string that may include manual escape. (i.e. newlines represented with "\\n") - */ -function quoteStringWithManualEscape(str, empty) { - return quoteString(str?.replace(/\\n/g, "\n"), empty); -} -/** - * Builder for all the basic KV types. - * - * @public - */ -const baseKVValueTypesLibraryBuilder = new KVFieldValueTypesLibraryBuilder({ - /** - * Display name of the field. - */ - displayName: zod.z.string().optional(), - /** - * Hint about the field. Shown when hovering over the field. - */ - hint: zod.z.string().optional(), - /** - * A field can be marked as model centric when it loses its meaning when there is no model to - * reference. - * - * An example would be prompt template. There is no point to configure prompt template when there - * isn't a specific model. - * - * @experimental This field is experimental and may change in the future. - */ - modelCentric: zod.z.boolean().optional(), - /** - * A field can be marked as non-configurable when it is only used as a means to carry information. - * As a result, it will not be shown in the UI. - * - * An example would be context length for MLX, as you cannot change it. - * - * @experimental This field is experimental and may change in the future. - */ - nonConfigurable: zod.z.boolean().optional(), - /** - * A field can be marked as engineDoesNotSupport when when the engine running the model does not - * support the field. - * - * @experimental This field is experimental and may change in the future. - */ - engineDoesNotSupport: zod.z.boolean().optional(), - /** - * A field can be marked as machine dependent when its value is highly dependent on the machine - * that is being used. When exporting the config, one may decide to not include machine dependent - * fields by default. - * - * An example would be GPU offload settings. - * - * @experimental This field is experimental and may change in the future. - */ - machineDependent: zod.z.boolean().optional(), - warning: zod.z.string().optional(), - subtitle: zod.z.string().optional(), - isExperimental: zod.z.boolean().optional(), - dependencies: zod.z.array(kvConfigFieldDependencySchema).optional(), -}) - .valueType("numeric", { - paramType: { - min: zod.z.number().optional(), - max: zod.z.number().optional(), - step: zod.z.number().optional(), - int: zod.z.boolean().optional(), - precision: zod.z.number().int().nonnegative().optional(), - slider: zod.z - .object({ - min: zod.z.number(), - max: zod.z.number(), - step: zod.z.number(), - }) - .optional(), - shortHand: zod.z.string().optional(), - }, - schemaMaker: ({ min, max, int, precision }) => { - let schema = zod.z.number(); - if (min !== undefined) { - schema = schema.min(min); - } - if (max !== undefined) { - schema = schema.max(max); - } - if (int) { - if (precision !== undefined) { - throw new Error("Cannot specify both int and precision."); - } - schema = schema.int(); - } - return schema; - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: (value, { int, precision }) => { - if (int) { - return String(Math.round(value)); - } - return value.toFixed(precision ?? 2); - }, -}) - .valueType("string", { - paramType: { - minLength: zod.z.number().optional(), - maxLength: zod.z.number().optional(), - isParagraph: zod.z.boolean().optional(), - isProtected: zod.z.boolean().optional(), - /** - * If true, the string should match to a single token. - */ - isToken: zod.z.boolean().optional(), - placeholder: zod.z.string().optional(), - }, - schemaMaker: ({ minLength, maxLength }) => { - let schema = zod.z.string(); - if (minLength !== undefined) { - schema = schema.min(minLength); - } - if (maxLength !== undefined) { - schema = schema.max(maxLength); - } - return schema; - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: (value, { isParagraph, isProtected }, { t, desiredLength }) => { - if (isProtected) { - return "********"; - } - if (isParagraph) { - if (value === "") { - return t("config:customInputs.string.emptyParagraph", ""); - } - else { - if (desiredLength === undefined || value.length <= desiredLength) { - return value; - } - else { - return (value.slice(0, Math.floor(desiredLength / 2)) + - " ... " + - value.slice(-Math.ceil(desiredLength / 2))); - } - } - } - else { - const quoted = quoteString(value); - if (desiredLength === undefined || quoted.length <= desiredLength) { - return quoted; - } - else { - return (quoted.slice(0, Math.floor(desiredLength / 2)) + - "..." + - quoted.slice(-Math.ceil(desiredLength / 2))); - } - } - }, -}) - .valueType("select", { - paramType: { - options: zod.z - .array(zod.z.object({ value: zod.z.string().nonempty(), displayName: zod.z.string() }).or(zod.z.string())) - .refine(options => { - // See if there are any duplicate values. - const values = new Set(); - for (const option of options) { - const value = typeof option === "string" ? option : option.value; - if (values.has(value)) { - return false; - } - values.add(value); - } - return true; - }, { - message: "Duplicate values in options.", - }), - }, - schemaMaker: ({ options }) => { - const allowedValues = new Set(options.map(option => (typeof option === "string" ? option : option.value))); - return zod.z.string().refine(value => allowedValues.has(value)); - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: value => { - return value; - }, -}) - .valueType("boolean", { - paramType: {}, - schemaMaker: () => { - return zod.z.boolean(); - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: value => { - return value ? "ON" : "OFF"; - }, -}) - .valueType("stringArray", { - paramType: { - maxNumItems: zod.z.number().optional(), - /** - * Whether to allow empty strings in the array. Default is false. - */ - allowEmptyStrings: zod.z.boolean().optional(), - }, - schemaMaker: ({ maxNumItems, allowEmptyStrings }) => { - let stringSchema = zod.z.string(); - if (!allowEmptyStrings) { - stringSchema = stringSchema.min(1); - } - let schema = zod.z.array(stringSchema); - if (maxNumItems !== undefined) { - schema = schema.max(maxNumItems); - } - return schema; - }, - effectiveEquals: (a, b) => { - return a.length === b.length && a.every((v, i) => v === b[i]); - }, - stringify: (value, _typeParam, { t, desiredLength }) => { - const quoted = value.map(v => quoteString(v)); - if (quoted.length === 0) { - return t("config:customInputs.stringArray.empty", ""); - } - if (quoted.length <= 2 || desiredLength === undefined) { - return quoted.join(", "); - } - // Desired length does not need to be followed strictly. It is just a hint. - let currentLength = quoted[0].length + quoted[1].length + 6; - for (let i = 1; i < quoted.length - 1; i++) { - currentLength += quoted[i].length + 2; - if (currentLength >= desiredLength) { - return quoted.slice(0, i).join(", ") + ", ..." + quoted[quoted.length - 1]; - } - } - return quoted.join(", "); - }, -}); -/** - * Basic key-value field value types library. These are the types that are exposed to plugins. - * - * @public - */ -baseKVValueTypesLibraryBuilder.build(); -/** - * The global key-value field value types library. This includes all the basic types and additional - * types that are used in the LM Studio application. - * - * @public - */ -const kvValueTypesLibrary = baseKVValueTypesLibraryBuilder - .valueType("checkboxNumeric", { - paramType: { - min: zod.z.number().optional(), - max: zod.z.number().optional(), - step: zod.z.number().optional(), - int: zod.z.boolean().optional(), - uncheckedHint: zod.z.string().optional(), - precision: zod.z.number().int().nonnegative().optional(), - slider: zod.z - .object({ - min: zod.z.number(), - max: zod.z.number(), - step: zod.z.number(), - }) - .optional(), - }, - schemaMaker: ({ min, max, int, precision }) => { - let numberSchema = zod.z.number(); - if (min !== undefined) { - numberSchema = numberSchema.min(min); - } - if (max !== undefined) { - numberSchema = numberSchema.max(max); - } - if (int) { - if (precision !== undefined) { - throw new Error("Cannot specify both int and precision."); - } - numberSchema = numberSchema.int(); - } - return zod.z.object({ - checked: zod.z.boolean(), - value: numberSchema, - }); - }, - effectiveEquals: (a, b) => { - if (a.checked !== b.checked) { - return false; - } - if (!a.checked) { - return true; - } - return a.value === b.value; - }, - stringify: (value, { int, precision }, { t }) => { - if (!value.checked) { - return t("config:customInputs.checkboxNumeric.off", "OFF"); - } - if (int) { - return String(Math.round(value.value)); - } - return value.value.toFixed(precision ?? 2); - }, -}) - .valueType("numericArray", { - paramType: { - min: zod.z.number().optional(), - max: zod.z.number().optional(), - int: zod.z.boolean().optional(), - }, - schemaMaker: ({ min, max, int }) => { - let numberSchema = zod.z.number(); - if (min !== undefined) { - numberSchema = numberSchema.min(min); - } - if (max !== undefined) { - numberSchema = numberSchema.max(max); - } - if (int) { - numberSchema = numberSchema.int(); - } - return zod.z.array(numberSchema); - }, - effectiveEquals: (a, b) => { - return a.length === b.length && a.every((v, i) => v === b[i]); - }, - stringify: (value, { int }) => { - return value.map(v => (int ? String(Math.round(v)) : String(v))).join(", "); - }, -}) - .valueType("contextOverflowPolicy", { - paramType: {}, - schemaMaker: () => { - return llmContextOverflowPolicySchema; - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: (value, _typeParam, { t }) => { - switch (value) { - case "stopAtLimit": - return t("config:customInputs.contextOverflowPolicy.stopAtLimit", "Stop At Limit"); - case "truncateMiddle": - return t("config:customInputs.contextOverflowPolicy.truncateMiddle", "Truncate Middle"); - case "rollingWindow": - return t("config:customInputs.contextOverflowPolicy.rollingWindow", "Rolling Window"); - } - }, -}) - .valueType("context", { - paramType: {}, - schemaMaker: () => { - return zod.z.array(llmContextReferenceSchema); - }, - effectiveEquals: (a, b) => { - return deepEquals(a, b); - }, - stringify: value => { - return JSON.stringify(value, null, 2); // TODO: pretty print - }, -}) - .valueType("contextLength", { - paramType: { - max: zod.z.number().optional(), - }, - schemaMaker: () => { - return zod.z.number().int().positive(); - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: (value, { max }) => { - if (max === undefined) { - return String(value); - } - return `${value}/${max}`; - }, -}) - .valueType("modelIdentifier", { - paramType: { - domain: zod.z.array(modelDomainTypeSchema).optional(), - }, - schemaMaker: () => { - return zod.z.string(); - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: value => { - return value; - }, -}) - .valueType("llmPromptTemplate", { - paramType: {}, - schemaMaker: () => { - return llmPromptTemplateSchema; - }, - effectiveEquals: (a, b) => { - if (a.type !== b.type) { - return false; - } - if (a.stopStrings.length !== b.stopStrings.length) { - return false; - } - if (!a.stopStrings.every((v, i) => v === b.stopStrings[i])) { - return false; - } - switch (a.type) { - case "jinja": - return a.jinjaPromptTemplate?.template === b.jinjaPromptTemplate?.template; - case "manual": - return (a.manualPromptTemplate?.beforeSystem === b.manualPromptTemplate?.beforeSystem && - a.manualPromptTemplate?.afterSystem === b.manualPromptTemplate?.afterSystem && - a.manualPromptTemplate?.beforeUser === b.manualPromptTemplate?.beforeUser && - a.manualPromptTemplate?.afterUser === b.manualPromptTemplate?.afterUser && - a.manualPromptTemplate?.beforeAssistant === b.manualPromptTemplate?.beforeAssistant && - a.manualPromptTemplate?.afterAssistant === b.manualPromptTemplate?.afterAssistant); - default: { - const exhaustiveCheck = a.type; - throw new Error("Unknown template type: " + exhaustiveCheck); - } - } - }, - stringify: (value, _typeParam, { t, desiredLength }) => { - switch (value.type) { - case "jinja": { - const lead = `${t("config:customInputs.llmPromptTemplate.type", "Type")}: ` + - `${t("config:customInputs.llmPromptTemplate.types.jinja/label", "Jinja")}\n` + - `${t("config:customInputs.llmPromptTemplate.jinja.template/label", "Template")}: `; - if (desiredLength === undefined) { - return lead + value.jinjaPromptTemplate?.template; - } - const currentLength = lead.length; - const remainingLength = Math.min(100, desiredLength - currentLength); - const template = value.jinjaPromptTemplate?.template ?? ""; - if (template.length <= remainingLength) { - return lead + template; - } - return (lead + - template.slice(0, Math.floor(remainingLength / 2)) + - "..." + - template.slice(-Math.ceil(remainingLength / 2))); - } - case "manual": { - return (`${t("config:customInputs.llmPromptTemplate.type", "Type")}: ` + - `${t("config:customInputs.llmPromptTemplate.types.manual/label", "Manual")}\n` + - `${t("config:customInputs.llmPromptTemplate.manual.subfield.beforeSystem/label", "Before System")}: ` + - `${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeSystem)}\n` + - `${t("config:customInputs.llmPromptTemplate.manual.subfield.afterSystem/label", "After System")}: ` + - `${quoteStringWithManualEscape(value.manualPromptTemplate?.afterSystem)}\n` + - `${t("config:customInputs.llmPromptTemplate.manual.subfield.beforeUser/label", "Before User")}: ` + - `${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeUser)}\n` + - `${t("config:customInputs.llmPromptTemplate.manual.subfield.afterUser/label", "After User")}: ` + - `${quoteStringWithManualEscape(value.manualPromptTemplate?.afterUser)}\n` + - `${t("config:customInputs.llmPromptTemplate.manual.subfield.beforeAssistant/label", "Before Assistant")}: ` + - `${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeAssistant)}\n` + - `${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label", "After Assistant")}: ` + - `${quoteStringWithManualEscape(value.manualPromptTemplate?.afterAssistant)}`); - } - default: { - const exhaustiveCheck = value.type; - throw new Error("Unknown template type: " + exhaustiveCheck); - } - } - }, -}) - .valueType("llmReasoningParsing", { - paramType: {}, - schemaMaker: () => { - return llmReasoningParsingSchema; - }, - effectiveEquals: (a, b) => { - return a.startString === b.startString && a.endString === b.endString; - }, - stringify: value => { - return JSON.stringify(value, null, 2); // TODO: pretty print - }, -}) - .valueType("llamaStructuredOutput", { - paramType: {}, - schemaMaker: () => { - return llmStructuredPredictionSettingSchema; - }, - effectiveEquals: (a, b) => { - if (a.type === "json" && b.type === "json") { - return deepEquals(a, b); - } - else if (a.type === "none" && b.type === "none") { - return true; - } - else { - return false; - } - }, - stringify: value => { - return JSON.stringify(value, null, 2); // TODO: pretty print - }, -}) - .valueType("speculativeDecodingDraftModel", { - paramType: {}, - schemaMaker: () => { - // Empty string means no speculative decoding. - return zod.z.string(); - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: (value, _typeParam, { t }) => { - if (value === "") { - return t("config:customInputs.speculativeDecodingDraftModel.off", "OFF"); - } - return value; - }, -}) - .valueType("toolUse", { - paramType: {}, - schemaMaker: () => { - return llmToolUseSettingSchema; - }, - effectiveEquals: (a, b) => { - return deepEquals(a, b); // TODO: more performant comparison - }, - stringify: value => { - return JSON.stringify(value, null, 2); // TODO: pretty print - }, -}) - .valueType("toolNaming", { - paramType: {}, - schemaMaker: () => { - return toolNamingSchema; - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: value => { - return value; - }, -}) - .valueType("llamaAccelerationOffloadRatio", { - paramType: { - numLayers: zod.z.number().optional(), - }, - schemaMaker: () => { - return llmLlamaAccelerationOffloadRatioSchema; - }, - effectiveEquals: (a, b) => { - const ratioA = a === "max" ? 1 : a === "off" ? 0 : a; - const ratioB = b === "max" ? 1 : b === "off" ? 0 : b; - return ratioA === ratioB; - }, - stringify: (value, { numLayers }, { t }) => { - if (value === "max" || value === 1) { - const label = t("config:customInputs.llamaAccelerationOffloadRatio.max", "MAX"); - if (numLayers !== 0) { - return `${label} (${numLayers})`; - } - return label; - } - if (value === "off" || value === 0) { - return t("config:customInputs.llamaAccelerationOffloadRatio.off", "OFF"); - } - if (numLayers !== undefined) { - return String(Math.round(numLayers * value)); - } - return (value * 100).toFixed(0) + "%"; - }, -}) - .valueType("llamaMirostatSampling", { - paramType: {}, - schemaMaker: () => { - return llmLlamaMirostatSamplingConfigSchema; - }, - effectiveEquals: (a, b) => { - return deepEquals(a, b); // TODO: more performant comparison - }, - stringify: value => { - return JSON.stringify(value, null, 2); // TODO: pretty print - }, -}) - .valueType("llamaLogitBias", { - paramType: {}, - schemaMaker: () => { - return llmLlamaLogitBiasConfigSchema; - }, - effectiveEquals: (a, b) => { - return deepEquals(a, b); // TODO: more performant comparison - }, - stringify: value => { - return JSON.stringify(value, null, 2); // TODO: pretty print - }, -}) - .valueType("llamaCacheQuantizationType", { - paramType: {}, - schemaMaker: () => { - return zod.z.object({ - checked: zod.z.boolean(), - value: llmLlamaCacheQuantizationTypeSchema, - }); - }, - effectiveEquals: (a, b) => { - if (a.checked !== b.checked) { - return false; - } - if (!a.checked) { - return true; - } - return a.value === b.value; - }, - stringify: (value, _typeParam, { t }) => { - if (!value.checked) { - return t("config:customInputs.llamaCacheQuantizationType.off", "OFF"); - } - return value.value; - }, -}) - .valueType("mlxKvCacheQuantizationType", { - paramType: {}, - schemaMaker: () => { - return llmMlxKvCacheQuantizationSchema; - }, - effectiveEquals: (a, b) => { - if (a.enabled !== b.enabled) { - return false; - } - if (!a.enabled) { - return true; - } - return (a.bits === b.bits && a.groupSize === b.groupSize && a.quantizedStart === b.quantizedStart); - }, - stringify: value => { - return JSON.stringify(value, null, 2); // TODO: pretty print - }, -}) - .valueType("retrievalChunkingMethod", { - paramType: {}, - schemaMaker: () => { - return retrievalChunkingMethodSchema; - }, - effectiveEquals: (a, b) => { - return deepEquals(a, b); // TODO: more performant comparison - }, - stringify: value => { - return JSON.stringify(value, null, 2); // TODO: pretty print - }, -}) - .valueType("envVars", { - paramType: {}, - schemaMaker: () => { - return allowableEnvVarsSchema; - }, - effectiveEquals: (a, b) => { - return deepEquals(a, b); - }, - stringify: value => { - return JSON.stringify(value, null, 2); - }, -}) - .valueType("gpuSplitConfig", { - paramType: {}, - schemaMaker: () => { - return gpuSplitConfigSchema; - }, - effectiveEquals: (a, b) => { - return deepEquals(a, b); - }, - stringify: value => { - return JSON.stringify(value, null, 2); - }, -}) - .build(); - -/** - * This file is divided into 4 sections: - * - * 1. globalConfigSchematics: The pool for all config keys and their types - * 2. Functionality scope definitions: i.e. what config keys are available in what functionality - * scope. An example functionality scope is llmPrediction. - * 3. Utility types that can be used to work with types of schema. - */ -// --------------------------- -// 1. globalConfigSchematics -// --------------------------- -const globalConfigSchematics = new KVConfigSchematicsBuilder(kvValueTypesLibrary) - .extension("ext.virtualModel.customField") - .field("envVars", "envVars", {}, {}) - .scope("llm.prediction", builder => builder - .field("temperature", "numeric", { - min: 0, - step: 0.01, - slider: { min: 0, max: 1, step: 0.01 }, - precision: 2, - shortHand: "temp", -}, 0.8) - .field("contextOverflowPolicy", "contextOverflowPolicy", {}, "truncateMiddle") - .field("maxPredictedTokens", "checkboxNumeric", { min: 1, int: true }, { checked: false, value: 1000 }) - .field("stopStrings", "stringArray", {}, []) - .field("toolCallStopStrings", "stringArray", {}, []) - .field("structured", "llamaStructuredOutput", {}, { type: "none" }) - .scope("speculativeDecoding", builder => builder - .field("draftModel", "speculativeDecodingDraftModel", { - modelCentric: true, -}, "") - .field("minDraftLengthToConsider", "numeric", { - modelCentric: true, - min: 0, - int: true, - slider: { min: 0, max: 10, step: 1 }, -}, 0) - .field("numReuseTokens", "numeric", { modelCentric: true, min: 1, int: true }, 256) - .field("minContinueDraftingProbability", "numeric", { - modelCentric: true, - min: 0, - max: 1, - step: 0.01, - precision: 2, - slider: { min: 0, max: 1, step: 0.01 }, -}, 0.75) - .field("maxTokensToDraft", "numeric", { modelCentric: true, min: 1, int: true, slider: { min: 10, max: 30, step: 1 } }, 16) - .field("numDraftTokensExact", "numeric", { - modelCentric: true, - min: 1, - int: true, - slider: { min: 1, max: 10, step: 1 }, -}, 2)) - .field("tools", "toolUse", {}, { type: "none" }) - .field("toolNaming", "toolNaming", {}, "removeSpecial") - .field("promptTemplate", "llmPromptTemplate", { modelCentric: true }, { - type: "manual", - manualPromptTemplate: { - beforeSystem: "Instruct: ", - afterSystem: "\n", - beforeAssistant: "AI: ", - afterAssistant: "\n", - beforeUser: "Human: ", - afterUser: "\n", - }, - stopStrings: [], -}) - .field("systemPrompt", "string", { isParagraph: true }, "") - .field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }) - .field("contextPrefill", "context", {}, []) - .field("topKSampling", "numeric", { min: -1, max: 500, int: true }, 40) - .field("repeatPenalty", "checkboxNumeric", { min: -1, step: 0.01 }, { checked: true, value: 1.1 }) - .field("minPSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: true, value: 0.05 }) - .field("topPSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: true, value: 0.95 }) - .field("logProbs", "checkboxNumeric", { min: 0, max: 100, int: true }, { checked: false, value: 0 }) - .scope("reasoning", builder => builder.field("parsing", "llmReasoningParsing", {}, { - enabled: true, - startString: "", - endString: "", -})) - .scope("llama", builder => builder - .field("cpuThreads", "numeric", { min: 1, int: true }, 4) - .field("frequencyPenalty", "checkboxNumeric", { precision: 2 }, { checked: false, value: 0.0 }) - .field("xtcProbability", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.5 }) - .field("xtcThreshold", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 0.5, step: 0.01 } }, { checked: false, value: 0.1 }) - .field("presencePenalty", "checkboxNumeric", { precision: 2 }, { checked: false, value: 0.0 }) - .field("mirostatSampling", "llamaMirostatSampling", {}, { - // Disabled by default - version: 0, - learningRate: 0.1, - targetEntropy: 5, -}) - .field("tailFreeSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.95 }) - .field("locallyTypicalSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.9 }) - .field("logitBias", "llamaLogitBias", {}, []))) - .scope("llm.load", builder => builder - .field("contextLength", "contextLength", { - machineDependent: true, -}, 2048) - .field("numExperts", "numeric", { min: 0, int: true }, 0) - .field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }) - .field("offloadKVCacheToGpu", "boolean", {}, true) - .field("numCpuExpertLayersRatio", "llamaAccelerationOffloadRatio", { machineDependent: true, isExperimental: true, }, "off") - .scope("llama", builder => builder - .scope("acceleration", builder => builder.field("offloadRatio", "llamaAccelerationOffloadRatio", { machineDependent: true }, "max")) - .field("cpuThreadPoolSize", "numeric", { min: 1, machineDependent: true }, 4) - .field("evalBatchSize", "numeric", { min: 1, int: true }, 512) - .field("flashAttention", "boolean", { isExperimental: true, warning: "config:flashAttentionWarning" }, false) - .field("ropeFrequencyBase", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyBaseUncheckedHint" }, { checked: false, value: 0 }) - .field("ropeFrequencyScale", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyScaleUncheckedHint" }, { checked: false, value: 0 }) - .field("keepModelInMemory", "boolean", {}, true) - .field("useFp16ForKVCache", "boolean", {}, true) - .field("tryMmap", "boolean", {}, true) - .field("kCacheQuantizationType", "llamaCacheQuantizationType", { isExperimental: true }, { checked: false, value: "f16" }) - .field("vCacheQuantizationType", "llamaCacheQuantizationType", { isExperimental: true, warning: "config:llamaKvCacheQuantizationWarning" }, { checked: false, value: "f16" })) - .scope("mlx", builder => builder.field("kvCacheQuantization", "mlxKvCacheQuantizationType", { isExperimental: true }, { enabled: false, bits: 8, groupSize: 64, quantizedStart: 5000 }))) - .scope("load", builder => builder - .field("gpuSplitConfig", "gpuSplitConfig", {}, defaultGPUSplitConfig) - .field("gpuStrictVramCap", "boolean", {}, false)) - .scope("embedding.load", builder => builder - .field("contextLength", "contextLength", { machineDependent: true }, 2048) - .field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }) - .scope("llama", builder => builder - .scope("acceleration", builder => builder.field("offloadRatio", "llamaAccelerationOffloadRatio", { machineDependent: true }, "max")) - .field("evalBatchSize", "numeric", { min: 1, int: true }, 512) - .field("ropeFrequencyBase", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyBaseUncheckedHint" }, { checked: false, value: 0 }) - .field("ropeFrequencyScale", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyScaleUncheckedHint" }, { checked: false, value: 0 }) - .field("keepModelInMemory", "boolean", {}, true) - .field("tryMmap", "boolean", {}, true))) - .scope("retrieval", builder => builder - .field("databaseFile", "string", { machineDependent: true }, "") - .field("chunkingMethod", "retrievalChunkingMethod", {}, { - type: "recursive-v1", - chunkSize: 512, - chunkOverlap: 100, -}) - .field("limit", "numeric", { min: 1, int: true }, 5) - .field("embeddingModel", "modelIdentifier", { domain: ["embedding"] }, "")) - .build(); -// ------------------------------------ -// 2. Functionality scope definitions -// ------------------------------------ -const llmPredictionConfigSchematics = globalConfigSchematics.scoped("llm.prediction"); -const llmSharedPredictionConfigSchematics = llmPredictionConfigSchematics.sliced("temperature", "maxPredictedTokens", "promptTemplate", "systemPrompt", "seed", "contextPrefill", "tools", "toolNaming", "reasoning.*"); -llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("llama.*", "contextOverflowPolicy", "stopStrings", "toolCallStopStrings", "structured", "topKSampling", "repeatPenalty", "minPSampling", "topPSampling", "logProbs", "speculativeDecoding.draftModel", "speculativeDecoding.minContinueDraftingProbability", "speculativeDecoding.minDraftLengthToConsider", "speculativeDecoding.maxTokensToDraft", "speculativeDecoding.numReuseTokens")); -llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("mlx.*", "contextOverflowPolicy", "stopStrings", "toolCallStopStrings", "structured", "repeatPenalty", "minPSampling", "topPSampling", "topKSampling", "speculativeDecoding.draftModel", "speculativeDecoding.numDraftTokensExact")); -llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("transformers.*")); -llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("onnx.*", "repeatPenalty", "topPSampling", "topKSampling")); -const llmLoadSchematics = globalConfigSchematics - .scoped("llm.load") - .union(globalConfigSchematics.sliced("envVars")); -const llmSharedLoadConfigSchematics = llmLoadSchematics.sliced("contextLength", "seed", "envVars"); -const llamaLoadConfigSchematics = globalConfigSchematics.sliced("llama.load.*", "load.*"); -const llmLlamaLoadConfigSchematics = llmSharedLoadConfigSchematics - .union(llmLoadSchematics.sliced("llama.*", "load.*", "offloadKVCacheToGpu")) - .union(llamaLoadConfigSchematics); -llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("mlx.*")); -llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("transformers.*")); -llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("onnx.*")); -const llmLlamaMoeAdditionalLoadConfigSchematics = llmLoadSchematics.sliced("numExperts", "numCpuExpertLayersRatio"); -const llmLlamaMoeLoadConfigSchematics = llmLlamaLoadConfigSchematics.union(llmLlamaMoeAdditionalLoadConfigSchematics); -const embeddingLoadSchematics = globalConfigSchematics - .scoped("embedding.load") - .union(globalConfigSchematics.sliced("load.*")); -const embeddingSharedLoadConfigSchematics = embeddingLoadSchematics.sliced("contextLength", "seed"); -const retrievalSchematics = globalConfigSchematics.scoped("retrieval"); -const embeddingLlamaLoadConfigSchematics = embeddingSharedLoadConfigSchematics - .union(embeddingLoadSchematics.sliced("llama.*")) - .union(llamaLoadConfigSchematics); -new KVConfigSchematicsBuilder(kvValueTypesLibrary).build(); - -/** - * Convert a number that can be false to checkbox numeric value. - * - * @param maybeFalseNumber - The value to translate. - * @param valueWhenUnchecked - The value to use when the checkbox is unchecked. - */ -function maybeFalseNumberToCheckboxNumeric(maybeFalseNumber, valueWhenUnchecked) { - if (maybeFalseNumber === undefined) { - return undefined; - } - if (maybeFalseNumber === false) { - return { checked: false, value: valueWhenUnchecked }; - } - return { checked: true, value: maybeFalseNumber }; -} - -function llmPredictionConfigToKVConfig(config) { - const top = llmPredictionConfigSchematics.buildPartialConfig({ - "temperature": config.temperature, - "contextOverflowPolicy": config.contextOverflowPolicy, - "maxPredictedTokens": maybeFalseNumberToCheckboxNumeric(config.maxTokens, 1), - "stopStrings": config.stopStrings, - "toolCallStopStrings": config.toolCallStopStrings, - "structured": config.structured, - "tools": config.rawTools, - "toolNaming": config.toolNaming, - "topKSampling": config.topKSampling, - "repeatPenalty": maybeFalseNumberToCheckboxNumeric(config.repeatPenalty, 1.1), - "minPSampling": maybeFalseNumberToCheckboxNumeric(config.minPSampling, 0.05), - "topPSampling": maybeFalseNumberToCheckboxNumeric(config.topPSampling, 0.95), - "llama.xtcProbability": maybeFalseNumberToCheckboxNumeric(config.xtcProbability, 0), - "llama.xtcThreshold": maybeFalseNumberToCheckboxNumeric(config.xtcThreshold, 0), - "logProbs": maybeFalseNumberToCheckboxNumeric(config.logProbs, 0), - "llama.cpuThreads": config.cpuThreads, - "promptTemplate": config.promptTemplate, - "speculativeDecoding.draftModel": config.draftModel, - "speculativeDecoding.numDraftTokensExact": config.speculativeDecodingNumDraftTokensExact, - "speculativeDecoding.minDraftLengthToConsider": config.speculativeDecodingMinDraftLengthToConsider, - "speculativeDecoding.minContinueDraftingProbability": config.speculativeDecodingMinContinueDraftingProbability, - "reasoning.parsing": config.reasoningParsing, - }); - if (config.raw !== undefined) { - return collapseKVStackRaw([config.raw, top]); - } - return top; -} - -/** - * @public - */ -function createConfigSchematics() { - return new KVConfigSchematicsBuilder(kvValueTypesLibrary); -} - -var lib = {}; - -var helpers = {}; - -var hasRequiredHelpers; - -function requireHelpers () { - if (hasRequiredHelpers) return helpers; - hasRequiredHelpers = 1; - - var ValidationError = helpers.ValidationError = function ValidationError (message, instance, schema, path, name, argument) { - if(Array.isArray(path)){ - this.path = path; - this.property = path.reduce(function(sum, item){ - return sum + makeSuffix(item); - }, 'instance'); - }else if(path !== undefined){ - this.property = path; - } - if (message) { - this.message = message; - } - if (schema) { - var id = schema.$id || schema.id; - this.schema = id || schema; - } - if (instance !== undefined) { - this.instance = instance; - } - this.name = name; - this.argument = argument; - this.stack = this.toString(); - }; - - ValidationError.prototype.toString = function toString() { - return this.property + ' ' + this.message; - }; - - var ValidatorResult = helpers.ValidatorResult = function ValidatorResult(instance, schema, options, ctx) { - this.instance = instance; - this.schema = schema; - this.options = options; - this.path = ctx.path; - this.propertyPath = ctx.propertyPath; - this.errors = []; - this.throwError = options && options.throwError; - this.throwFirst = options && options.throwFirst; - this.throwAll = options && options.throwAll; - this.disableFormat = options && options.disableFormat === true; - }; - - ValidatorResult.prototype.addError = function addError(detail) { - var err; - if (typeof detail == 'string') { - err = new ValidationError(detail, this.instance, this.schema, this.path); - } else { - if (!detail) throw new Error('Missing error detail'); - if (!detail.message) throw new Error('Missing error message'); - if (!detail.name) throw new Error('Missing validator type'); - err = new ValidationError(detail.message, this.instance, this.schema, this.path, detail.name, detail.argument); - } - - this.errors.push(err); - if (this.throwFirst) { - throw new ValidatorResultError(this); - }else if(this.throwError){ - throw err; - } - return err; - }; - - ValidatorResult.prototype.importErrors = function importErrors(res) { - if (typeof res == 'string' || (res && res.validatorType)) { - this.addError(res); - } else if (res && res.errors) { - this.errors = this.errors.concat(res.errors); - } - }; - - function stringizer (v,i){ - return i+': '+v.toString()+'\n'; - } - ValidatorResult.prototype.toString = function toString(res) { - return this.errors.map(stringizer).join(''); - }; - - Object.defineProperty(ValidatorResult.prototype, "valid", { get: function() { - return !this.errors.length; - } }); - - helpers.ValidatorResultError = ValidatorResultError; - function ValidatorResultError(result) { - if(typeof Error.captureStackTrace === 'function'){ - Error.captureStackTrace(this, ValidatorResultError); - } - this.instance = result.instance; - this.schema = result.schema; - this.options = result.options; - this.errors = result.errors; - } - ValidatorResultError.prototype = new Error(); - ValidatorResultError.prototype.constructor = ValidatorResultError; - ValidatorResultError.prototype.name = "Validation Error"; - - /** - * Describes a problem with a Schema which prevents validation of an instance - * @name SchemaError - * @constructor - */ - var SchemaError = helpers.SchemaError = function SchemaError (msg, schema) { - this.message = msg; - this.schema = schema; - Error.call(this, msg); - if(typeof Error.captureStackTrace === 'function'){ - Error.captureStackTrace(this, SchemaError); - } - }; - SchemaError.prototype = Object.create(Error.prototype, - { - constructor: {value: SchemaError, enumerable: false}, - name: {value: 'SchemaError', enumerable: false}, - }); - - var SchemaContext = helpers.SchemaContext = function SchemaContext (schema, options, path, base, schemas) { - this.schema = schema; - this.options = options; - if(Array.isArray(path)){ - this.path = path; - this.propertyPath = path.reduce(function(sum, item){ - return sum + makeSuffix(item); - }, 'instance'); - }else { - this.propertyPath = path; - } - this.base = base; - this.schemas = schemas; - }; - - SchemaContext.prototype.resolve = function resolve (target) { - return (() => resolveUrl(this.base,target))(); - }; - - SchemaContext.prototype.makeChild = function makeChild(schema, propertyName){ - var path = (propertyName===undefined) ? this.path : this.path.concat([propertyName]); - var id = schema.$id || schema.id; - let base = (() => resolveUrl(this.base,id||''))(); - var ctx = new SchemaContext(schema, this.options, path, base, Object.create(this.schemas)); - if(id && !ctx.schemas[base]){ - ctx.schemas[base] = schema; - } - return ctx; - }; - - var FORMAT_REGEXPS = helpers.FORMAT_REGEXPS = { - // 7.3.1. Dates, Times, and Duration - 'date-time': /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])[tT ](2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])(\.\d+)?([zZ]|[+-]([0-5][0-9]):(60|[0-5][0-9]))$/, - 'date': /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])$/, - 'time': /^(2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])$/, - 'duration': /P(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S)|\d+(D|M(\d+D)?|Y(\d+M(\d+D)?)?)(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S))?|\d+W)/i, - - // 7.3.2. Email Addresses - // TODO: fix the email production - 'email': /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/, - 'idn-email': /^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u, - - // 7.3.3. Hostnames - - // 7.3.4. IP Addresses - 'ip-address': /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, - // FIXME whitespace is invalid - 'ipv6': /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]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[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i, - - // 7.3.6. uri-template - 'uri-template': /(%[0-9a-f]{2}|[!#$&(-;=?@\[\]_a-z~]|\{[!#&+,./;=?@|]?(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?(,(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?)*\})*/iu, - - // 7.3.7. JSON Pointers - 'json-pointer': /^(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*$/iu, - 'relative-json-pointer': /^\d+(#|(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*)$/iu, - - // hostname regex from: http://stackoverflow.com/a/1420225/5628 - 'hostname': /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/, - 'host-name': /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/, - - 'utc-millisec': function (input) { - return (typeof input === 'string') && parseFloat(input) === parseInt(input, 10) && !isNaN(input); - }, - - // 7.3.8. regex - 'regex': function (input) { - var result = true; - try { - new RegExp(input); - } catch (e) { - result = false; - } - return result; - }, - - // Other definitions - // "style" was removed from JSON Schema in draft-4 and is deprecated - 'style': /[\r\n\t ]*[^\r\n\t ][^:]*:[\r\n\t ]*[^\r\n\t ;]*[\r\n\t ]*;?/, - // "color" was removed from JSON Schema in draft-4 and is deprecated - 'color': /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/, - 'phone': /^\+(?:[0-9] ?){6,14}[0-9]$/, - 'alpha': /^[a-zA-Z]+$/, - 'alphanumeric': /^[a-zA-Z0-9]+$/, - }; - - FORMAT_REGEXPS.regexp = FORMAT_REGEXPS.regex; - FORMAT_REGEXPS.pattern = FORMAT_REGEXPS.regex; - FORMAT_REGEXPS.ipv4 = FORMAT_REGEXPS['ip-address']; - - helpers.isFormat = function isFormat (input, format, validator) { - if (typeof input === 'string' && FORMAT_REGEXPS[format] !== undefined) { - if (FORMAT_REGEXPS[format] instanceof RegExp) { - return FORMAT_REGEXPS[format].test(input); - } - if (typeof FORMAT_REGEXPS[format] === 'function') { - return FORMAT_REGEXPS[format](input); - } - } else if (validator && validator.customFormats && - typeof validator.customFormats[format] === 'function') { - return validator.customFormats[format](input); - } - return true; - }; - - var makeSuffix = helpers.makeSuffix = function makeSuffix (key) { - key = key.toString(); - // This function could be capable of outputting valid a ECMAScript string, but the - // resulting code for testing which form to use would be tens of thousands of characters long - // That means this will use the name form for some illegal forms - if (!key.match(/[.\s\[\]]/) && !key.match(/^[\d]/)) { - return '.' + key; - } - if (key.match(/^\d+$/)) { - return '[' + key + ']'; - } - return '[' + JSON.stringify(key) + ']'; - }; - - helpers.deepCompareStrict = function deepCompareStrict (a, b) { - if (typeof a !== typeof b) { - return false; - } - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - return a.every(function (v, i) { - return deepCompareStrict(a[i], b[i]); - }); - } - if (typeof a === 'object') { - if (!a || !b) { - return a === b; - } - var aKeys = Object.keys(a); - var bKeys = Object.keys(b); - if (aKeys.length !== bKeys.length) { - return false; - } - return aKeys.every(function (v) { - return deepCompareStrict(a[v], b[v]); - }); - } - return a === b; - }; - - function deepMerger (target, dst, e, i) { - if (typeof e === 'object') { - dst[i] = deepMerge(target[i], e); - } else { - if (target.indexOf(e) === -1) { - dst.push(e); - } - } - } - - function copyist (src, dst, key) { - dst[key] = src[key]; - } - - function copyistWithDeepMerge (target, src, dst, key) { - if (typeof src[key] !== 'object' || !src[key]) { - dst[key] = src[key]; - } - else { - if (!target[key]) { - dst[key] = src[key]; - } else { - dst[key] = deepMerge(target[key], src[key]); - } - } - } - - function deepMerge (target, src) { - var array = Array.isArray(src); - var dst = array && [] || {}; - - if (array) { - target = target || []; - dst = dst.concat(target); - src.forEach(deepMerger.bind(null, target, dst)); - } else { - if (target && typeof target === 'object') { - Object.keys(target).forEach(copyist.bind(null, target, dst)); - } - Object.keys(src).forEach(copyistWithDeepMerge.bind(null, target, src, dst)); - } - - return dst; - } - - helpers.deepMerge = deepMerge; - - /** - * Validates instance against the provided schema - * Implements URI+JSON Pointer encoding, e.g. "%7e"="~0"=>"~", "~1"="%2f"=>"/" - * @param o - * @param s The path to walk o along - * @return any - */ - helpers.objectGetPath = function objectGetPath(o, s) { - var parts = s.split('/').slice(1); - var k; - while (typeof (k=parts.shift()) == 'string') { - var n = decodeURIComponent(k.replace(/~0/,'~').replace(/~1/g,'/')); - if (!(n in o)) return; - o = o[n]; - } - return o; - }; - - function pathEncoder (v) { - return '/'+encodeURIComponent(v).replace(/~/g,'%7E'); - } - /** - * Accept an Array of property names and return a JSON Pointer URI fragment - * @param Array a - * @return {String} - */ - helpers.encodePath = function encodePointer(a){ - // ~ must be encoded explicitly because hacks - // the slash is encoded by encodeURIComponent - return a.map(pathEncoder).join(''); - }; - - - /** - * Calculate the number of decimal places a number uses - * We need this to get correct results out of multipleOf and divisibleBy - * when either figure is has decimal places, due to IEEE-754 float issues. - * @param number - * @returns {number} - */ - helpers.getDecimalPlaces = function getDecimalPlaces(number) { - - var decimalPlaces = 0; - if (isNaN(number)) return decimalPlaces; - - if (typeof number !== 'number') { - number = Number(number); - } - - var parts = number.toString().split('e'); - if (parts.length === 2) { - if (parts[1][0] !== '-') { - return decimalPlaces; - } else { - decimalPlaces = Number(parts[1].slice(1)); - } - } - - var decimalParts = parts[0].split('.'); - if (decimalParts.length === 2) { - decimalPlaces += decimalParts[1].length; - } - - return decimalPlaces; - }; - - helpers.isSchema = function isSchema(val){ - return (typeof val === 'object' && val) || (typeof val === 'boolean'); - }; - - /** - * Resolve target URL from a base and relative URL. - * Similar to Node's URL Lib's legacy resolve function. - * Code from example in deprecation note in said library. - * @param string - * @param string - * @returns {string} - */ - var resolveUrl = helpers.resolveUrl = function resolveUrl(from, to) { - const resolvedUrl = new URL(to, new URL(from, 'resolve://')); - if (resolvedUrl.protocol === 'resolve:') { - const { pathname, search, hash } = resolvedUrl; - return pathname + search + hash; - } - return resolvedUrl.toString(); - }; - return helpers; -} - -var attribute_1; -var hasRequiredAttribute; - -function requireAttribute () { - if (hasRequiredAttribute) return attribute_1; - hasRequiredAttribute = 1; - - var helpers = requireHelpers(); - - /** @type ValidatorResult */ - var ValidatorResult = helpers.ValidatorResult; - /** @type SchemaError */ - var SchemaError = helpers.SchemaError; - - var attribute = {}; - - attribute.ignoreProperties = { - // informative properties - 'id': true, - 'default': true, - 'description': true, - 'title': true, - // arguments to other properties - 'additionalItems': true, - 'then': true, - 'else': true, - // special-handled properties - '$schema': true, - '$ref': true, - 'extends': true, - }; - - /** - * @name validators - */ - var validators = attribute.validators = {}; - - /** - * Validates whether the instance if of a certain type - * @param instance - * @param schema - * @param options - * @param ctx - * @return {ValidatorResult|null} - */ - validators.type = function validateType (instance, schema, options, ctx) { - // Ignore undefined instances - if (instance === undefined) { - return null; - } - var result = new ValidatorResult(instance, schema, options, ctx); - var types = Array.isArray(schema.type) ? schema.type : [schema.type]; - if (!types.some(this.testType.bind(this, instance, schema, options, ctx))) { - var list = types.map(function (v) { - if(!v) return; - var id = v.$id || v.id; - return id ? ('<' + id + '>') : (v+''); - }); - result.addError({ - name: 'type', - argument: list, - message: "is not of a type(s) " + list, - }); - } - return result; - }; - - function testSchemaNoThrow(instance, options, ctx, callback, schema){ - var throwError = options.throwError; - var throwAll = options.throwAll; - options.throwError = false; - options.throwAll = false; - var res = this.validateSchema(instance, schema, options, ctx); - options.throwError = throwError; - options.throwAll = throwAll; - - if (!res.valid && callback instanceof Function) { - callback(res); - } - return res.valid; - } - - /** - * Validates whether the instance matches some of the given schemas - * @param instance - * @param schema - * @param options - * @param ctx - * @return {ValidatorResult|null} - */ - validators.anyOf = function validateAnyOf (instance, schema, options, ctx) { - // Ignore undefined instances - if (instance === undefined) { - return null; - } - var result = new ValidatorResult(instance, schema, options, ctx); - var inner = new ValidatorResult(instance, schema, options, ctx); - if (!Array.isArray(schema.anyOf)){ - throw new SchemaError("anyOf must be an array"); - } - if (!schema.anyOf.some( - testSchemaNoThrow.bind( - this, instance, options, ctx, function(res){inner.importErrors(res);} - ))) { - var list = schema.anyOf.map(function (v, i) { - var id = v.$id || v.id; - if(id) return '<' + id + '>'; - return (v.title && JSON.stringify(v.title)) || (v['$ref'] && ('<' + v['$ref'] + '>')) || '[subschema '+i+']'; - }); - if (options.nestedErrors) { - result.importErrors(inner); - } - result.addError({ - name: 'anyOf', - argument: list, - message: "is not any of " + list.join(','), - }); - } - return result; - }; - - /** - * Validates whether the instance matches every given schema - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null} - */ - validators.allOf = function validateAllOf (instance, schema, options, ctx) { - // Ignore undefined instances - if (instance === undefined) { - return null; - } - if (!Array.isArray(schema.allOf)){ - throw new SchemaError("allOf must be an array"); - } - var result = new ValidatorResult(instance, schema, options, ctx); - var self = this; - schema.allOf.forEach(function(v, i){ - var valid = self.validateSchema(instance, v, options, ctx); - if(!valid.valid){ - var id = v.$id || v.id; - var msg = id || (v.title && JSON.stringify(v.title)) || (v['$ref'] && ('<' + v['$ref'] + '>')) || '[subschema '+i+']'; - result.addError({ - name: 'allOf', - argument: { id: msg, length: valid.errors.length, valid: valid }, - message: 'does not match allOf schema ' + msg + ' with ' + valid.errors.length + ' error[s]:', - }); - result.importErrors(valid); - } - }); - return result; - }; - - /** - * Validates whether the instance matches exactly one of the given schemas - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null} - */ - validators.oneOf = function validateOneOf (instance, schema, options, ctx) { - // Ignore undefined instances - if (instance === undefined) { - return null; - } - if (!Array.isArray(schema.oneOf)){ - throw new SchemaError("oneOf must be an array"); - } - var result = new ValidatorResult(instance, schema, options, ctx); - var inner = new ValidatorResult(instance, schema, options, ctx); - var count = schema.oneOf.filter( - testSchemaNoThrow.bind( - this, instance, options, ctx, function(res) {inner.importErrors(res);} - ) ).length; - var list = schema.oneOf.map(function (v, i) { - var id = v.$id || v.id; - return id || (v.title && JSON.stringify(v.title)) || (v['$ref'] && ('<' + v['$ref'] + '>')) || '[subschema '+i+']'; - }); - if (count!==1) { - if (options.nestedErrors) { - result.importErrors(inner); - } - result.addError({ - name: 'oneOf', - argument: list, - message: "is not exactly one from " + list.join(','), - }); - } - return result; - }; - - /** - * Validates "then" or "else" depending on the result of validating "if" - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null} - */ - validators.if = function validateIf (instance, schema, options, ctx) { - // Ignore undefined instances - if (instance === undefined) return null; - if (!helpers.isSchema(schema.if)) throw new Error('Expected "if" keyword to be a schema'); - var ifValid = testSchemaNoThrow.call(this, instance, options, ctx, null, schema.if); - var result = new ValidatorResult(instance, schema, options, ctx); - var res; - if(ifValid){ - if (schema.then === undefined) return; - if (!helpers.isSchema(schema.then)) throw new Error('Expected "then" keyword to be a schema'); - res = this.validateSchema(instance, schema.then, options, ctx.makeChild(schema.then)); - result.importErrors(res); - }else { - if (schema.else === undefined) return; - if (!helpers.isSchema(schema.else)) throw new Error('Expected "else" keyword to be a schema'); - res = this.validateSchema(instance, schema.else, options, ctx.makeChild(schema.else)); - result.importErrors(res); - } - return result; - }; - - function getEnumerableProperty(object, key){ - // Determine if `key` shows up in `for(var key in object)` - // First test Object.hasOwnProperty.call as an optimization: that guarantees it does - if(Object.hasOwnProperty.call(object, key)) return object[key]; - // Test `key in object` as an optimization; false means it won't - if(!(key in object)) return; - while( (object = Object.getPrototypeOf(object)) ){ - if(Object.propertyIsEnumerable.call(object, key)) return object[key]; - } - } - - /** - * Validates propertyNames - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null|ValidatorResult} - */ - validators.propertyNames = function validatePropertyNames (instance, schema, options, ctx) { - if(!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var subschema = schema.propertyNames!==undefined ? schema.propertyNames : {}; - if(!helpers.isSchema(subschema)) throw new SchemaError('Expected "propertyNames" to be a schema (object or boolean)'); - - for (var property in instance) { - if(getEnumerableProperty(instance, property) !== undefined){ - var res = this.validateSchema(property, subschema, options, ctx.makeChild(subschema)); - result.importErrors(res); - } - } - - return result; - }; - - /** - * Validates properties - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null|ValidatorResult} - */ - validators.properties = function validateProperties (instance, schema, options, ctx) { - if(!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var properties = schema.properties || {}; - for (var property in properties) { - var subschema = properties[property]; - if(subschema===undefined){ - continue; - }else if(subschema===null){ - throw new SchemaError('Unexpected null, expected schema in "properties"'); - } - if (typeof options.preValidateProperty == 'function') { - options.preValidateProperty(instance, property, subschema, options, ctx); - } - var prop = getEnumerableProperty(instance, property); - var res = this.validateSchema(prop, subschema, options, ctx.makeChild(subschema, property)); - if(res.instance !== result.instance[property]) result.instance[property] = res.instance; - result.importErrors(res); - } - return result; - }; - - /** - * Test a specific property within in instance against the additionalProperties schema attribute - * This ignores properties with definitions in the properties schema attribute, but no other attributes. - * If too many more types of property-existence tests pop up they may need their own class of tests (like `type` has) - * @private - * @return {boolean} - */ - function testAdditionalProperty (instance, schema, options, ctx, property, result) { - if(!this.types.object(instance)) return; - if (schema.properties && schema.properties[property] !== undefined) { - return; - } - if (schema.additionalProperties === false) { - result.addError({ - name: 'additionalProperties', - argument: property, - message: "is not allowed to have the additional property " + JSON.stringify(property), - }); - } else { - var additionalProperties = schema.additionalProperties || {}; - - if (typeof options.preValidateProperty == 'function') { - options.preValidateProperty(instance, property, additionalProperties, options, ctx); - } - - var res = this.validateSchema(instance[property], additionalProperties, options, ctx.makeChild(additionalProperties, property)); - if(res.instance !== result.instance[property]) result.instance[property] = res.instance; - result.importErrors(res); - } - } - - /** - * Validates patternProperties - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null|ValidatorResult} - */ - validators.patternProperties = function validatePatternProperties (instance, schema, options, ctx) { - if(!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var patternProperties = schema.patternProperties || {}; - - for (var property in instance) { - var test = true; - for (var pattern in patternProperties) { - var subschema = patternProperties[pattern]; - if(subschema===undefined){ - continue; - }else if(subschema===null){ - throw new SchemaError('Unexpected null, expected schema in "patternProperties"'); - } - try { - var regexp = new RegExp(pattern, 'u'); - } catch(_e) { - // In the event the stricter handling causes an error, fall back on the forgiving handling - // DEPRECATED - regexp = new RegExp(pattern); - } - if (!regexp.test(property)) { - continue; - } - test = false; - - if (typeof options.preValidateProperty == 'function') { - options.preValidateProperty(instance, property, subschema, options, ctx); - } - - var res = this.validateSchema(instance[property], subschema, options, ctx.makeChild(subschema, property)); - if(res.instance !== result.instance[property]) result.instance[property] = res.instance; - result.importErrors(res); - } - if (test) { - testAdditionalProperty.call(this, instance, schema, options, ctx, property, result); - } - } - - return result; - }; - - /** - * Validates additionalProperties - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null|ValidatorResult} - */ - validators.additionalProperties = function validateAdditionalProperties (instance, schema, options, ctx) { - if(!this.types.object(instance)) return; - // if patternProperties is defined then we'll test when that one is called instead - if (schema.patternProperties) { - return null; - } - var result = new ValidatorResult(instance, schema, options, ctx); - for (var property in instance) { - testAdditionalProperty.call(this, instance, schema, options, ctx, property, result); - } - return result; - }; - - /** - * Validates whether the instance value is at least of a certain length, when the instance value is a string. - * @param instance - * @param schema - * @return {String|null} - */ - validators.minProperties = function validateMinProperties (instance, schema, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var keys = Object.keys(instance); - if (!(keys.length >= schema.minProperties)) { - result.addError({ - name: 'minProperties', - argument: schema.minProperties, - message: "does not meet minimum property length of " + schema.minProperties, - }); - } - return result; - }; - - /** - * Validates whether the instance value is at most of a certain length, when the instance value is a string. - * @param instance - * @param schema - * @return {String|null} - */ - validators.maxProperties = function validateMaxProperties (instance, schema, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var keys = Object.keys(instance); - if (!(keys.length <= schema.maxProperties)) { - result.addError({ - name: 'maxProperties', - argument: schema.maxProperties, - message: "does not meet maximum property length of " + schema.maxProperties, - }); - } - return result; - }; - - /** - * Validates items when instance is an array - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null|ValidatorResult} - */ - validators.items = function validateItems (instance, schema, options, ctx) { - var self = this; - if (!this.types.array(instance)) return; - if (schema.items===undefined) return; - var result = new ValidatorResult(instance, schema, options, ctx); - instance.every(function (value, i) { - if(Array.isArray(schema.items)){ - var items = schema.items[i]===undefined ? schema.additionalItems : schema.items[i]; - }else { - var items = schema.items; - } - if (items === undefined) { - return true; - } - if (items === false) { - result.addError({ - name: 'items', - message: "additionalItems not permitted", - }); - return false; - } - var res = self.validateSchema(value, items, options, ctx.makeChild(items, i)); - if(res.instance !== result.instance[i]) result.instance[i] = res.instance; - result.importErrors(res); - return true; - }); - return result; - }; - - /** - * Validates the "contains" keyword - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null|ValidatorResult} - */ - validators.contains = function validateContains (instance, schema, options, ctx) { - var self = this; - if (!this.types.array(instance)) return; - if (schema.contains===undefined) return; - if (!helpers.isSchema(schema.contains)) throw new Error('Expected "contains" keyword to be a schema'); - var result = new ValidatorResult(instance, schema, options, ctx); - var count = instance.some(function (value, i) { - var res = self.validateSchema(value, schema.contains, options, ctx.makeChild(schema.contains, i)); - return res.errors.length===0; - }); - if(count===false){ - result.addError({ - name: 'contains', - argument: schema.contains, - message: "must contain an item matching given schema", - }); - } - return result; - }; - - /** - * Validates minimum and exclusiveMinimum when the type of the instance value is a number. - * @param instance - * @param schema - * @return {String|null} - */ - validators.minimum = function validateMinimum (instance, schema, options, ctx) { - if (!this.types.number(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - if (schema.exclusiveMinimum && schema.exclusiveMinimum === true) { - if(!(instance > schema.minimum)){ - result.addError({ - name: 'minimum', - argument: schema.minimum, - message: "must be greater than " + schema.minimum, - }); - } - } else { - if(!(instance >= schema.minimum)){ - result.addError({ - name: 'minimum', - argument: schema.minimum, - message: "must be greater than or equal to " + schema.minimum, - }); - } - } - return result; - }; - - /** - * Validates maximum and exclusiveMaximum when the type of the instance value is a number. - * @param instance - * @param schema - * @return {String|null} - */ - validators.maximum = function validateMaximum (instance, schema, options, ctx) { - if (!this.types.number(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - if (schema.exclusiveMaximum && schema.exclusiveMaximum === true) { - if(!(instance < schema.maximum)){ - result.addError({ - name: 'maximum', - argument: schema.maximum, - message: "must be less than " + schema.maximum, - }); - } - } else { - if(!(instance <= schema.maximum)){ - result.addError({ - name: 'maximum', - argument: schema.maximum, - message: "must be less than or equal to " + schema.maximum, - }); - } - } - return result; - }; - - /** - * Validates the number form of exclusiveMinimum when the type of the instance value is a number. - * @param instance - * @param schema - * @return {String|null} - */ - validators.exclusiveMinimum = function validateExclusiveMinimum (instance, schema, options, ctx) { - // Support the boolean form of exclusiveMinimum, which is handled by the "minimum" keyword. - if(typeof schema.exclusiveMinimum === 'boolean') return; - if (!this.types.number(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var valid = instance > schema.exclusiveMinimum; - if (!valid) { - result.addError({ - name: 'exclusiveMinimum', - argument: schema.exclusiveMinimum, - message: "must be strictly greater than " + schema.exclusiveMinimum, - }); - } - return result; - }; - - /** - * Validates the number form of exclusiveMaximum when the type of the instance value is a number. - * @param instance - * @param schema - * @return {String|null} - */ - validators.exclusiveMaximum = function validateExclusiveMaximum (instance, schema, options, ctx) { - // Support the boolean form of exclusiveMaximum, which is handled by the "maximum" keyword. - if(typeof schema.exclusiveMaximum === 'boolean') return; - if (!this.types.number(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var valid = instance < schema.exclusiveMaximum; - if (!valid) { - result.addError({ - name: 'exclusiveMaximum', - argument: schema.exclusiveMaximum, - message: "must be strictly less than " + schema.exclusiveMaximum, - }); - } - return result; - }; - - /** - * Perform validation for multipleOf and divisibleBy, which are essentially the same. - * @param instance - * @param schema - * @param validationType - * @param errorMessage - * @returns {String|null} - */ - var validateMultipleOfOrDivisbleBy = function validateMultipleOfOrDivisbleBy (instance, schema, options, ctx, validationType, errorMessage) { - if (!this.types.number(instance)) return; - - var validationArgument = schema[validationType]; - if (validationArgument == 0) { - throw new SchemaError(validationType + " cannot be zero"); - } - - var result = new ValidatorResult(instance, schema, options, ctx); - - var instanceDecimals = helpers.getDecimalPlaces(instance); - var divisorDecimals = helpers.getDecimalPlaces(validationArgument); - - var maxDecimals = Math.max(instanceDecimals , divisorDecimals); - var multiplier = Math.pow(10, maxDecimals); - - if (Math.round(instance * multiplier) % Math.round(validationArgument * multiplier) !== 0) { - result.addError({ - name: validationType, - argument: validationArgument, - message: errorMessage + JSON.stringify(validationArgument), - }); - } - - return result; - }; - - /** - * Validates divisibleBy when the type of the instance value is a number. - * @param instance - * @param schema - * @return {String|null} - */ - validators.multipleOf = function validateMultipleOf (instance, schema, options, ctx) { - return validateMultipleOfOrDivisbleBy.call(this, instance, schema, options, ctx, "multipleOf", "is not a multiple of (divisible by) "); - }; - - /** - * Validates multipleOf when the type of the instance value is a number. - * @param instance - * @param schema - * @return {String|null} - */ - validators.divisibleBy = function validateDivisibleBy (instance, schema, options, ctx) { - return validateMultipleOfOrDivisbleBy.call(this, instance, schema, options, ctx, "divisibleBy", "is not divisible by (multiple of) "); - }; - - /** - * Validates whether the instance value is present. - * @param instance - * @param schema - * @return {String|null} - */ - validators.required = function validateRequired (instance, schema, options, ctx) { - var result = new ValidatorResult(instance, schema, options, ctx); - if (instance === undefined && schema.required === true) { - // A boolean form is implemented for reverse-compatibility with schemas written against older drafts - result.addError({ - name: 'required', - message: "is required", - }); - } else if (this.types.object(instance) && Array.isArray(schema.required)) { - schema.required.forEach(function(n){ - if(getEnumerableProperty(instance, n)===undefined){ - result.addError({ - name: 'required', - argument: n, - message: "requires property " + JSON.stringify(n), - }); - } - }); - } - return result; - }; - - /** - * Validates whether the instance value matches the regular expression, when the instance value is a string. - * @param instance - * @param schema - * @return {String|null} - */ - validators.pattern = function validatePattern (instance, schema, options, ctx) { - if (!this.types.string(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var pattern = schema.pattern; - try { - var regexp = new RegExp(pattern, 'u'); - } catch(_e) { - // In the event the stricter handling causes an error, fall back on the forgiving handling - // DEPRECATED - regexp = new RegExp(pattern); - } - if (!instance.match(regexp)) { - result.addError({ - name: 'pattern', - argument: schema.pattern, - message: "does not match pattern " + JSON.stringify(schema.pattern.toString()), - }); - } - return result; - }; - - /** - * Validates whether the instance value is of a certain defined format or a custom - * format. - * The following formats are supported for string types: - * - date-time - * - date - * - time - * - ip-address - * - ipv6 - * - uri - * - color - * - host-name - * - alpha - * - alpha-numeric - * - utc-millisec - * @param instance - * @param schema - * @param [options] - * @param [ctx] - * @return {String|null} - */ - validators.format = function validateFormat (instance, schema, options, ctx) { - if (instance===undefined) return; - var result = new ValidatorResult(instance, schema, options, ctx); - if (!result.disableFormat && !helpers.isFormat(instance, schema.format, this)) { - result.addError({ - name: 'format', - argument: schema.format, - message: "does not conform to the " + JSON.stringify(schema.format) + " format", - }); - } - return result; - }; - - /** - * Validates whether the instance value is at least of a certain length, when the instance value is a string. - * @param instance - * @param schema - * @return {String|null} - */ - validators.minLength = function validateMinLength (instance, schema, options, ctx) { - if (!this.types.string(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var hsp = instance.match(/[\uDC00-\uDFFF]/g); - var length = instance.length - (hsp ? hsp.length : 0); - if (!(length >= schema.minLength)) { - result.addError({ - name: 'minLength', - argument: schema.minLength, - message: "does not meet minimum length of " + schema.minLength, - }); - } - return result; - }; - - /** - * Validates whether the instance value is at most of a certain length, when the instance value is a string. - * @param instance - * @param schema - * @return {String|null} - */ - validators.maxLength = function validateMaxLength (instance, schema, options, ctx) { - if (!this.types.string(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - // TODO if this was already computed in "minLength", use that value instead of re-computing - var hsp = instance.match(/[\uDC00-\uDFFF]/g); - var length = instance.length - (hsp ? hsp.length : 0); - if (!(length <= schema.maxLength)) { - result.addError({ - name: 'maxLength', - argument: schema.maxLength, - message: "does not meet maximum length of " + schema.maxLength, - }); - } - return result; - }; - - /** - * Validates whether instance contains at least a minimum number of items, when the instance is an Array. - * @param instance - * @param schema - * @return {String|null} - */ - validators.minItems = function validateMinItems (instance, schema, options, ctx) { - if (!this.types.array(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - if (!(instance.length >= schema.minItems)) { - result.addError({ - name: 'minItems', - argument: schema.minItems, - message: "does not meet minimum length of " + schema.minItems, - }); - } - return result; - }; - - /** - * Validates whether instance contains no more than a maximum number of items, when the instance is an Array. - * @param instance - * @param schema - * @return {String|null} - */ - validators.maxItems = function validateMaxItems (instance, schema, options, ctx) { - if (!this.types.array(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - if (!(instance.length <= schema.maxItems)) { - result.addError({ - name: 'maxItems', - argument: schema.maxItems, - message: "does not meet maximum length of " + schema.maxItems, - }); - } - return result; - }; - - /** - * Deep compares arrays for duplicates - * @param v - * @param i - * @param a - * @private - * @return {boolean} - */ - function testArrays (v, i, a) { - var j, len = a.length; - for (j = i + 1, len; j < len; j++) { - if (helpers.deepCompareStrict(v, a[j])) { - return false; - } - } - return true; - } - - /** - * Validates whether there are no duplicates, when the instance is an Array. - * @param instance - * @return {String|null} - */ - validators.uniqueItems = function validateUniqueItems (instance, schema, options, ctx) { - if (schema.uniqueItems!==true) return; - if (!this.types.array(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - if (!instance.every(testArrays)) { - result.addError({ - name: 'uniqueItems', - message: "contains duplicate item", - }); - } - return result; - }; - - /** - * Validate for the presence of dependency properties, if the instance is an object. - * @param instance - * @param schema - * @param options - * @param ctx - * @return {null|ValidatorResult} - */ - validators.dependencies = function validateDependencies (instance, schema, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - for (var property in schema.dependencies) { - if (instance[property] === undefined) { - continue; - } - var dep = schema.dependencies[property]; - var childContext = ctx.makeChild(dep, property); - if (typeof dep == 'string') { - dep = [dep]; - } - if (Array.isArray(dep)) { - dep.forEach(function (prop) { - if (instance[prop] === undefined) { - result.addError({ - // FIXME there's two different "dependencies" errors here with slightly different outputs - // Can we make these the same? Or should we create different error types? - name: 'dependencies', - argument: childContext.propertyPath, - message: "property " + prop + " not found, required by " + childContext.propertyPath, - }); - } - }); - } else { - var res = this.validateSchema(instance, dep, options, childContext); - if(result.instance !== res.instance) result.instance = res.instance; - if (res && res.errors.length) { - result.addError({ - name: 'dependencies', - argument: childContext.propertyPath, - message: "does not meet dependency required by " + childContext.propertyPath, - }); - result.importErrors(res); - } - } - } - return result; - }; - - /** - * Validates whether the instance value is one of the enumerated values. - * - * @param instance - * @param schema - * @return {ValidatorResult|null} - */ - validators['enum'] = function validateEnum (instance, schema, options, ctx) { - if (instance === undefined) { - return null; - } - if (!Array.isArray(schema['enum'])) { - throw new SchemaError("enum expects an array", schema); - } - var result = new ValidatorResult(instance, schema, options, ctx); - if (!schema['enum'].some(helpers.deepCompareStrict.bind(null, instance))) { - result.addError({ - name: 'enum', - argument: schema['enum'], - message: "is not one of enum values: " + schema['enum'].map(String).join(','), - }); - } - return result; - }; - - /** - * Validates whether the instance exactly matches a given value - * - * @param instance - * @param schema - * @return {ValidatorResult|null} - */ - validators['const'] = function validateEnum (instance, schema, options, ctx) { - if (instance === undefined) { - return null; - } - var result = new ValidatorResult(instance, schema, options, ctx); - if (!helpers.deepCompareStrict(schema['const'], instance)) { - result.addError({ - name: 'const', - argument: schema['const'], - message: "does not exactly match expected constant: " + schema['const'], - }); - } - return result; - }; - - /** - * Validates whether the instance if of a prohibited type. - * @param instance - * @param schema - * @param options - * @param ctx - * @return {null|ValidatorResult} - */ - validators.not = validators.disallow = function validateNot (instance, schema, options, ctx) { - var self = this; - if(instance===undefined) return null; - var result = new ValidatorResult(instance, schema, options, ctx); - var notTypes = schema.not || schema.disallow; - if(!notTypes) return null; - if(!Array.isArray(notTypes)) notTypes=[notTypes]; - notTypes.forEach(function (type) { - if (self.testType(instance, schema, options, ctx, type)) { - var id = type && (type.$id || type.id); - var schemaId = id || type; - result.addError({ - name: 'not', - argument: schemaId, - message: "is of prohibited type " + schemaId, - }); - } - }); - return result; - }; - - attribute_1 = attribute; - return attribute_1; -} - -var scan = {}; - -var hasRequiredScan; - -function requireScan () { - if (hasRequiredScan) return scan; - hasRequiredScan = 1; - - var helpers = requireHelpers(); - - scan.SchemaScanResult = SchemaScanResult; - function SchemaScanResult(found, ref){ - this.id = found; - this.ref = ref; - } - - /** - * Adds a schema with a certain urn to the Validator instance. - * @param string uri - * @param object schema - * @return {Object} - */ - scan.scan = function scan(base, schema){ - function scanSchema(baseuri, schema){ - if(!schema || typeof schema!='object') return; - // Mark all referenced schemas so we can tell later which schemas are referred to, but never defined - if(schema.$ref){ - let resolvedUri = helpers.resolveUrl(baseuri,schema.$ref); - ref[resolvedUri] = ref[resolvedUri] ? ref[resolvedUri]+1 : 0; - return; - } - var id = schema.$id || schema.id; - let resolvedBase = helpers.resolveUrl(baseuri,id); - var ourBase = id ? resolvedBase : baseuri; - if (ourBase) { - // If there's no fragment, append an empty one - if(ourBase.indexOf('#')<0) ourBase += '#'; - if(found[ourBase]){ - if(!helpers.deepCompareStrict(found[ourBase], schema)){ - throw new Error('Schema <'+ourBase+'> already exists with different definition'); - } - return found[ourBase]; - } - found[ourBase] = schema; - // strip trailing fragment - if(ourBase[ourBase.length-1]=='#'){ - found[ourBase.substring(0, ourBase.length-1)] = schema; - } - } - scanArray(ourBase+'/items', (Array.isArray(schema.items)?schema.items:[schema.items])); - scanArray(ourBase+'/extends', (Array.isArray(schema.extends)?schema.extends:[schema.extends])); - scanSchema(ourBase+'/additionalItems', schema.additionalItems); - scanObject(ourBase+'/properties', schema.properties); - scanSchema(ourBase+'/additionalProperties', schema.additionalProperties); - scanObject(ourBase+'/definitions', schema.definitions); - scanObject(ourBase+'/patternProperties', schema.patternProperties); - scanObject(ourBase+'/dependencies', schema.dependencies); - scanArray(ourBase+'/disallow', schema.disallow); - scanArray(ourBase+'/allOf', schema.allOf); - scanArray(ourBase+'/anyOf', schema.anyOf); - scanArray(ourBase+'/oneOf', schema.oneOf); - scanSchema(ourBase+'/not', schema.not); - } - function scanArray(baseuri, schemas){ - if(!Array.isArray(schemas)) return; - for(var i=0; i", schema); - } - var subschema = helpers.objectGetPath(ctx.schemas[document], fragment.substr(1)); - if(subschema===undefined){ - throw new SchemaError("no such schema " + fragment + " located in <" + document + ">", schema); - } - return {subschema: subschema, switchSchema: switchSchema}; - }; - - /** - * Tests whether the instance if of a certain type. - * @private - * @param instance - * @param schema - * @param options - * @param ctx - * @param type - * @return {boolean} - */ - Validator.prototype.testType = function validateType (instance, schema, options, ctx, type) { - if(type===undefined){ - return; - }else if(type===null){ - throw new SchemaError('Unexpected null in "type" keyword'); - } - if (typeof this.types[type] == 'function') { - return this.types[type].call(this, instance); - } - if (type && typeof type == 'object') { - var res = this.validateSchema(instance, type, options, ctx); - return res === undefined || !(res && res.errors.length); - } - // Undefined or properties not on the list are acceptable, same as not being defined - return true; - }; - - var types = Validator.prototype.types = {}; - types.string = function testString (instance) { - return typeof instance == 'string'; - }; - types.number = function testNumber (instance) { - // isFinite returns false for NaN, Infinity, and -Infinity - return typeof instance == 'number' && isFinite(instance); - }; - types.integer = function testInteger (instance) { - return (typeof instance == 'number') && instance % 1 === 0; - }; - types.boolean = function testBoolean (instance) { - return typeof instance == 'boolean'; - }; - types.array = function testArray (instance) { - return Array.isArray(instance); - }; - types['null'] = function testNull (instance) { - return instance === null; - }; - types.date = function testDate (instance) { - return instance instanceof Date; - }; - types.any = function testAny (instance) { - return true; - }; - types.object = function testObject (instance) { - // TODO: fix this - see #15 - return instance && (typeof instance === 'object') && !(Array.isArray(instance)) && !(instance instanceof Date); - }; - - validator = Validator; - return validator; -} - -var hasRequiredLib; - -function requireLib () { - if (hasRequiredLib) return lib; - hasRequiredLib = 1; - - var Validator = lib.Validator = requireValidator(); - - lib.ValidatorResult = requireHelpers().ValidatorResult; - lib.ValidatorResultError = requireHelpers().ValidatorResultError; - lib.ValidationError = requireHelpers().ValidationError; - lib.SchemaError = requireHelpers().SchemaError; - lib.SchemaScanResult = requireScan().SchemaScanResult; - lib.scan = requireScan().scan; - - lib.validate = function (instance, schema, options) { - var v = new Validator(); - return v.validate(instance, schema, options); - }; - return lib; -} - -var libExports = requireLib(); - -const toolBaseSchema = zod.z.object({ - name: zod.z.string(), - description: zod.z.string(), -}); -class SimpleToolCallContext { - constructor(logger, signal, callId) { - this.logger = logger; - this.signal = signal; - this.callId = callId; - } - status(text) { - this.logger.info(text); - } - warn(text) { - this.logger.warn(text); - } -} -const functionToolSchema = toolBaseSchema.extend({ - type: zod.z.literal("function"), - parametersSchema: zodSchemaSchema, - checkParameters: zod.z.function(), - implementation: zod.z.function(), -}); -const rawFunctionToolSchema = toolBaseSchema.extend({ - type: zod.z.literal("rawFunction"), - parametersSchema: zodSchemaSchema, - checkParameters: zod.z.function(), - implementation: zod.z.function(), -}); -const unimplementedRawFunctionToolSchema = toolBaseSchema.extend({ - type: zod.z.literal("unimplementedRawFunction"), - parametersJsonSchema: zodSchemaSchema, - checkParameters: zod.z.function(), - implementation: zod.z.function(), -}); -const remoteToolSchema = toolBaseSchema.extend({ - type: zod.z.literal("remoteTool"), - pluginIdentifier: zod.z.string(), - parametersJsonSchema: zodSchemaSchema, - checkParameters: zod.z.function(), - implementation: zod.z.function(), -}); -zod.z.discriminatedUnion("type", [ - functionToolSchema, - rawFunctionToolSchema, - unimplementedRawFunctionToolSchema, - remoteToolSchema, -]); -/** - * A function that can be used to create a function `Tool` given a function definition and its - * implementation. - * - * @public - */ -function tool({ name, description, parameters, implementation, }) { - const parametersSchema = zod.z.object(parameters); - return { - name, - description, - type: "function", - parametersSchema, - checkParameters(params) { - const parametersParseResult = parametersSchema.safeParse(params); - if (!parametersParseResult.success) { - throw new Error(text ` - Failed to parse arguments for tool "${name}": - ${parametersParseResult.error.message} - `); - } - }, - implementation: (params, ctx) => { - const parametersParseResult = parametersSchema.safeParse(params); - if (!parametersParseResult.success) { - throw new Error(text ` - Failed to parse arguments for tool "${name}": - ${parametersParseResult.error.message} - `); - } - return implementation(parametersParseResult.data, ctx); // Erase the types - }, - }; -} -function jsonSchemaValidationErrorToAIReadableText(root, validationErrors) { - return validationErrors - .map(validatioNError => { - const fullPath = [root, ...validatioNError.path].join("."); - return `${fullPath} ${validatioNError.message}`; - }) - .join("\n"); -} -/** - * A function that can be used to create a raw function `Tool` given a function definition and its - * implementation. - * - * @public - * @experimental Not stable, will likely change in the future. - */ -function rawFunctionTool({ name, description, parametersJsonSchema, implementation, }) { - const jsonSchemaValidator = new libExports.Validator(); - return { - name, - description, - type: "rawFunction", - parametersJsonSchema, - checkParameters(params) { - const validationResult = jsonSchemaValidator.validate(params, parametersJsonSchema); - if (validationResult.errors.length > 0) { - throw new Error(text ` - Failed to parse arguments for tool "${name}": - ${jsonSchemaValidationErrorToAIReadableText("params", validationResult.errors)} - `); - } - }, - implementation, - }; -} -class UnimplementedToolError extends Error { - constructor(toolName) { - super(`Tool "${toolName}" is not implemented.`); - } -} -/** - * A function that can be used to create a raw function `Tool` that is not implemented yet. When - * using `.act`, upon encountering an unimplemented tool, the `.act` will stop gracefully. - * - * @public - * @experimental Not stable, will likely change in the future. - */ -function unimplementedRawFunctionTool({ name, description, parametersJsonSchema, }) { - const jsonSchemaValidator = new libExports.Validator(); - return { - name, - description, - type: "unimplementedRawFunction", - parametersJsonSchema, - checkParameters(params) { - const validationResult = jsonSchemaValidator.validate(params, parametersJsonSchema); - if (validationResult.errors.length > 0) { - throw new Error(text ` - Failed to parse arguments for tool "${name}": - ${jsonSchemaValidationErrorToAIReadableText("params", validationResult.errors)} - `); - } - }, - implementation: () => { - throw new UnimplementedToolError(name); - }, - }; -} -/** - * Creates a tool that represents a remote tool exposed by an LMStudio plugin. This function is not - * exposed and is used internally by the plugins namespace. - */ -function internalCreateRemoteTool({ name, description, pluginIdentifier, parametersJsonSchema, implementation, }) { - return { - name, - description, - type: "remoteTool", - pluginIdentifier, - parametersJsonSchema, - checkParameters: params => { - const jsonSchemaValidator = new libExports.Validator(); - const validationResult = jsonSchemaValidator.validate(params, parametersJsonSchema); - if (validationResult.errors.length > 0) { - throw new Error(text ` - Failed to parse arguments for tool "${name}": - ${jsonSchemaValidationErrorToAIReadableText("params", validationResult.errors)} - `); - } - }, - implementation, - }; -} -function functionToolToLLMTool(tool) { - return { - type: "function", - function: { - name: tool.name, - description: tool.description, - parameters: zodToJsonSchema.zodToJsonSchema(tool.parametersSchema), - }, - }; -} -function rawFunctionToolToLLMTool(tool) { - return { - type: "function", - function: { - name: tool.name, - description: tool.description, - parameters: tool.parametersJsonSchema, - }, - }; -} -function remoteToolToLLMTool(tool) { - return { - type: "function", - function: { - name: tool.name, - description: tool.description, - parameters: tool.parametersJsonSchema, - }, - }; -} -/** - * Convert a `Tool` to a internal `LLMTool`. - */ -function toolToLLMTool(tool) { - const type = tool.type; - switch (type) { - case "function": - return functionToolToLLMTool(tool); - case "rawFunction": - case "unimplementedRawFunction": - return rawFunctionToolToLLMTool(tool); - case "remoteTool": - return remoteToolToLLMTool(tool); - default: { - const exhaustiveCheck = type; - throw new Error(`Unhandled type: ${exhaustiveCheck}`); - } - } -} - -/** - * Represents an error that is caused by invalid tool call request. - * - * @public - * @experimental [EXP-GRANULAR-ACT] More granular .act status reporting is experimental and may - * change in the future - */ -class ToolCallRequestError extends Error { - constructor(message, - /** - * The raw output that was generated by the model before the tool call. The exact nature of this - * fields depends on the error. It sometimes include the entire tool calls section, or sometimes - * just the single tool call that failed. - * - * This field is not always available, and may be `undefined`. - * - * @experimental [EXP-GRANULAR-ACT] More granular .act status reporting is experimental and may - * change in the future - * @experimental [EXP-NON-ACT-TOOL-CALLBACKS] Tool call callbacks in .respond/.complete is in an - * experimental feature. This may change in the future without warning. - */ - rawContent) { - super(message); - this.rawContent = rawContent; - } -} - -class BackendInterface { - constructor() { - this.unhandledEndpoints = new Set(); - this.existingEndpointNames = new Set(); - this.rpcEndpoints = new Map(); - this.channelEndpoints = new Map(); - this.signalEndpoints = new Map(); - this.writableSignalEndpoints = new Map(); - } - withContextType() { - return this; - } - assertEndpointNameNotExists(endpointName) { - if (this.existingEndpointNames.has(endpointName)) { - throw new Error(`Endpoint with name ${endpointName} already exists`); - } - } - /** - * Register an Rpc endpoint. - */ - addRpcEndpoint(endpointName, { parameter, returns, serialization = "raw", }) { - this.assertEndpointNameNotExists(endpointName); - this.existingEndpointNames.add(endpointName); - this.rpcEndpoints.set(endpointName, { - name: endpointName, - parameter, - returns, - serialization, - handler: null, - }); - return this; - } - addChannelEndpoint(endpointName, { creationParameter, toServerPacket, toClientPacket, serialization = "raw", }) { - this.assertEndpointNameNotExists(endpointName); - this.existingEndpointNames.add(endpointName); - this.channelEndpoints.set(endpointName, { - name: endpointName, - creationParameter, - toServerPacket, - toClientPacket, - serialization, - handler: null, - }); - return this; - } - addSignalEndpoint(endpointName, { creationParameter, signalData, serialization = "raw", }) { - this.assertEndpointNameNotExists(endpointName); - this.existingEndpointNames.add(endpointName); - this.signalEndpoints.set(endpointName, { - name: endpointName, - creationParameter, - signalData, - serialization, - handler: null, - }); - return this; - } - addWritableSignalEndpoint(endpointName, { creationParameter, signalData, serialization = "raw", }) { - this.assertEndpointNameNotExists(endpointName); - this.existingEndpointNames.add(endpointName); - this.writableSignalEndpoints.set(endpointName, { - name: endpointName, - creationParameter, - signalData, - serialization, - handler: null, - }); - return this; - } - /** - * Adds a handler for an Rpc endpoint. - * - * @param endpointName - The name of the endpoint. - * @param handler - The handler function. Will be called when the endpoint is invoked. When - * called, the first parameter is the context, and the second parameter is the "parameter" for the - * RPC call. Can return a value or a promise that resolves to the result. - */ - handleRpcEndpoint(endpointName, handler) { - const endpoint = this.rpcEndpoints.get(endpointName); - if (endpoint === undefined) { - throw new Error(`No Rpc endpoint with name ${endpointName}`); - } - if (endpoint.handler !== null) { - throw new Error(`Rpc endpoint with name ${endpointName} already has a handler`); - } - endpoint.handler = handler; - this.unhandledEndpoints.delete(endpointName); - } - /** - * Adds a handler for a channel endpoint. - * - * @param endpointName - The name of the endpoint. - * @param handler - The handler function. Will be called when the client creates a channel for - * this endpoint. When called, the first parameter is the context, the second parameter is the - * "creationParameter" for the channel, and the third parameter is a channel object that can be - * used to send and receive messages from the client. - * - * Must return a promise. Once that promise is settled, the channel will be closed. - */ - handleChannelEndpoint(endpointName, handler) { - const endpoint = this.channelEndpoints.get(endpointName); - if (endpoint === undefined) { - throw new Error(`No channel endpoint with name ${endpointName}`); - } - if (endpoint.handler !== null) { - throw new Error(`Channel endpoint with name ${endpointName} already has a handler`); - } - endpoint.handler = handler; - this.unhandledEndpoints.delete(endpointName); - } - /** - * Adds a handler for a signal endpoint. - * - * @param endpointName - The name of the endpoint. - * @param handler - The handler function. Will be called when the client creates a signal, and at - * least one subscriber is attached to that signal. When called, the first parameter is the - * context, and the second parameter is the "creationParameter" for the signal. This method should - * return a SignalLike, or a promise that resolves to a SignalLike. - * - * Note: There is no 1-to-1 correlation between the signal on the client side and the number of - * times this handler is called. Every time the number of client subscribers changes from 0 to 1, - * this handler will be called. Every time the number of client subscribers changes from 1 to 0, - * the signal returned from this handler will be unsubscribed. - * - * Caution: Do NOT create new subscriptions that don't self-terminate in this handler, as it will - * cause memory leaks. That is, either: - * - * - Return a signal that already exists - * - Create and return a LazySignal - */ - handleSignalEndpoint(endpointName, handler) { - const endpoint = this.signalEndpoints.get(endpointName); - if (endpoint === undefined) { - throw new Error(`No signal endpoint with name ${endpointName}`); - } - if (endpoint.handler !== null) { - throw new Error(`Signal endpoint with name ${endpointName} already has a handler`); - } - endpoint.handler = handler; - this.unhandledEndpoints.delete(endpointName); - } - /** - * Adds a handler for a writable signal endpoint. - * - * @param endpointName - The name of the endpoint. - * @param handler - The handler function. Will be called when the client creates a writable - * signal, and at least one subscriber is attached to that signal. When called, the first - * parameter is the context, and the second parameter is the "creationParameter" for the signal. - * This method should return a tuple of the signal and an update function. The update function - * should be called with the new data, patches, and tags to update the signal. - * - * Note: There is no 1-to-1 correlation between the signal on the client side and the number of - * times this handler is called. Every time the number of client subscribers changes from 0 to 1, - * this handler will be called. Every time the number of client subscribers changes from 1 to 0 - * the signal returned from this handler will be unsubscribed. - * - * Caution: Do NOT create new subscriptions that don't self-terminate in this handler, as it will - * cause memory leaks. That is, either: - * - * - Return a signal that already exists - * - Create and return a LazySignal - */ - handleWritableSignalEndpoint(endpointName, handler) { - const endpoint = this.writableSignalEndpoints.get(endpointName); - if (endpoint === undefined) { - throw new Error(`No writable signal endpoint with name ${endpointName}`); - } - if (endpoint.handler !== null) { - throw new Error(`Writable signal endpoint with name ${endpointName} already has a handler`); - } - endpoint.handler = handler; - this.unhandledEndpoints.delete(endpointName); - } - assertAllEndpointsHandled() { - if (this.unhandledEndpoints.size > 0) { - throw new Error(`The following endpoints were not handled: ${Array.from(this.unhandledEndpoints).join(", ")}`); - } - } - getRpcEndpoint(endpointName) { - return this.rpcEndpoints.get(endpointName); - } - getAllRpcEndpoints() { - return [...this.rpcEndpoints.values()]; - } - getChannelEndpoint(endpointName) { - return this.channelEndpoints.get(endpointName); - } - getAllChannelEndpoints() { - return [...this.channelEndpoints.values()]; - } - getSignalEndpoint(endpointName) { - return this.signalEndpoints.get(endpointName); - } - getAllSignalEndpoints() { - return [...this.signalEndpoints.values()]; - } - getWritableSignalEndpoint(endpointName) { - return this.writableSignalEndpoints.get(endpointName); - } - getAllWritableSignalEndpoints() { - return [...this.writableSignalEndpoints.values()]; - } -} - -var ConnectionStatus; -(function (ConnectionStatus) { - /** - * The underlying transport is connected and is communicating properly. - */ - ConnectionStatus["Connected"] = "CONNECTED"; - /** - * The underlying transport has errored out. - */ - ConnectionStatus["Errored"] = "ERRORED"; - /** - * The channel has been properly closed and no more messages will be sent or received. - */ - ConnectionStatus["Closed"] = "CLOSED"; -})(ConnectionStatus || (ConnectionStatus = {})); -const logger = new SimpleLogger("Channel"); -class Channel { - constructor(innerSend) { - this.innerSend = innerSend; - this.nextAckId = 0; - /** - * A map for messages that are waiting for an ACK. The values are the functions to resolve or - * reject the corresponding promise. - */ - this.waitingForAck = new Map(); - /** - * Returned as a part of create. It should be called by the controlling port. - */ - this.receivedACK = (ackId) => { - if (this.connectionStatus.get() !== ConnectionStatus.Connected) { - logger.warn("Received ACK while in status", this.connectionStatus.get()); - return; - } - const waiting = this.waitingForAck.get(ackId); - if (waiting === undefined) { - logger.warn("Received ACK for a message that is no longer waiting for ACK, ackId =", ackId); - return; - } - waiting.resolve(); - this.waitingForAck.delete(ackId); - }; - /** - * Returned as a part of create. It should be called by the controlling port. - */ - this.receivedMessage = (packet) => { - if (this.connectionStatus.get() !== ConnectionStatus.Connected) { - logger.warn("Received message while in status", this.connectionStatus.get()); - return; - } - this.emitOnMessage(packet); - }; - /** - * Returned as a part of create. It should be called by the controlling port. - */ - this.errored = (error) => { - if (this.connectionStatus.get() !== ConnectionStatus.Connected) { - logger.warn("Received error while in status", this.connectionStatus.get()); - return; - } - this.rejectAllWaitingForAck(error); - this.setConnectionStatus(ConnectionStatus.Errored); - this.emitOnError(error); - }; - /** - * Returned as a part of create. It should be called by the controlling port. - */ - this.closed = () => { - this.rejectAllWaitingForAck(new Error("Channel closed")); - this.setConnectionStatus(ConnectionStatus.Closed); - this.emitOnClose(); - }; - [this.onMessage, this.emitOnMessage] = BufferedEvent.create(); - [this.onError, this.emitOnError] = BufferedEvent.create(); - [this.onClose, this.emitOnClose] = BufferedEvent.create(); - [this.connectionStatus, this.setConnectionStatus] = Signal.create(ConnectionStatus.Connected); - } - rejectAllWaitingForAck(error) { - const rejects = Array.from(this.waitingForAck.values()).map(({ reject }) => reject); - this.waitingForAck.clear(); - for (const reject of rejects) { - reject(error); - } - } - static create(innerSend) { - const channel = new Channel(innerSend); - return { - channel, - receivedAck: channel.receivedACK, - receivedMessage: channel.receivedMessage, - errored: channel.errored, - closed: channel.closed, - }; - } - send(packet) { - this.innerSend(packet); - } - sendAndWaitForACK(packet) { - const { promise, resolve, reject } = makePromise(); - const ackId = this.nextAckId; - this.nextAckId++; - this.waitingForAck.set(ackId, { resolve, reject }); - this.innerSend(packet, ackId); - return promise; - } -} - -var DoubleIndexedKV = /** @class */ (function () { - function DoubleIndexedKV() { - this.keyToValue = new Map(); - this.valueToKey = new Map(); - } - DoubleIndexedKV.prototype.set = function (key, value) { - this.keyToValue.set(key, value); - this.valueToKey.set(value, key); - }; - DoubleIndexedKV.prototype.getByKey = function (key) { - return this.keyToValue.get(key); - }; - DoubleIndexedKV.prototype.getByValue = function (value) { - return this.valueToKey.get(value); - }; - DoubleIndexedKV.prototype.clear = function () { - this.keyToValue.clear(); - this.valueToKey.clear(); - }; - return DoubleIndexedKV; -}()); - -var Registry = /** @class */ (function () { - function Registry(generateIdentifier) { - this.generateIdentifier = generateIdentifier; - this.kv = new DoubleIndexedKV(); - } - Registry.prototype.register = function (value, identifier) { - if (this.kv.getByValue(value)) { - return; - } - if (!identifier) { - identifier = this.generateIdentifier(value); - } - this.kv.set(identifier, value); - }; - Registry.prototype.clear = function () { - this.kv.clear(); - }; - Registry.prototype.getIdentifier = function (value) { - return this.kv.getByValue(value); - }; - Registry.prototype.getValue = function (identifier) { - return this.kv.getByKey(identifier); - }; - return Registry; -}()); - -var __extends = (globalThis && globalThis.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var ClassRegistry = /** @class */ (function (_super) { - __extends(ClassRegistry, _super); - function ClassRegistry() { - var _this = _super.call(this, function (c) { return c.name; }) || this; - _this.classToAllowedProps = new Map(); - return _this; - } - ClassRegistry.prototype.register = function (value, options) { - if (typeof options === 'object') { - if (options.allowProps) { - this.classToAllowedProps.set(value, options.allowProps); - } - _super.prototype.register.call(this, value, options.identifier); - } - else { - _super.prototype.register.call(this, value, options); - } - }; - ClassRegistry.prototype.getAllowedProps = function (value) { - return this.classToAllowedProps.get(value); - }; - return ClassRegistry; -}(Registry)); - -var __read$3 = (globalThis && globalThis.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -}; -function valuesOfObj(record) { - if ('values' in Object) { - // eslint-disable-next-line es5/no-es6-methods - return Object.values(record); - } - var values = []; - // eslint-disable-next-line no-restricted-syntax - for (var key in record) { - if (record.hasOwnProperty(key)) { - values.push(record[key]); - } - } - return values; -} -function find(record, predicate) { - var values = valuesOfObj(record); - if ('find' in values) { - // eslint-disable-next-line es5/no-es6-methods - return values.find(predicate); - } - var valuesNotNever = values; - for (var i = 0; i < valuesNotNever.length; i++) { - var value = valuesNotNever[i]; - if (predicate(value)) { - return value; - } - } - return undefined; -} -function forEach(record, run) { - Object.entries(record).forEach(function (_a) { - var _b = __read$3(_a, 2), key = _b[0], value = _b[1]; - return run(value, key); - }); -} -function includes(arr, value) { - return arr.indexOf(value) !== -1; -} -function findArr(record, predicate) { - for (var i = 0; i < record.length; i++) { - var value = record[i]; - if (predicate(value)) { - return value; - } - } - return undefined; -} - -var CustomTransformerRegistry = /** @class */ (function () { - function CustomTransformerRegistry() { - this.transfomers = {}; - } - CustomTransformerRegistry.prototype.register = function (transformer) { - this.transfomers[transformer.name] = transformer; - }; - CustomTransformerRegistry.prototype.findApplicable = function (v) { - return find(this.transfomers, function (transformer) { - return transformer.isApplicable(v); - }); - }; - CustomTransformerRegistry.prototype.findByName = function (name) { - return this.transfomers[name]; - }; - return CustomTransformerRegistry; -}()); - -var getType$1 = function (payload) { - return Object.prototype.toString.call(payload).slice(8, -1); -}; -var isUndefined = function (payload) { - return typeof payload === 'undefined'; -}; -var isNull = function (payload) { return payload === null; }; -var isPlainObject$1 = function (payload) { - if (typeof payload !== 'object' || payload === null) - return false; - if (payload === Object.prototype) - return false; - if (Object.getPrototypeOf(payload) === null) - return true; - return Object.getPrototypeOf(payload) === Object.prototype; -}; -var isEmptyObject = function (payload) { - return isPlainObject$1(payload) && Object.keys(payload).length === 0; -}; -var isArray$1 = function (payload) { - return Array.isArray(payload); -}; -var isString = function (payload) { - return typeof payload === 'string'; -}; -var isNumber = function (payload) { - return typeof payload === 'number' && !isNaN(payload); -}; -var isBoolean = function (payload) { - return typeof payload === 'boolean'; -}; -var isRegExp = function (payload) { - return payload instanceof RegExp; -}; -var isMap = function (payload) { - return payload instanceof Map; -}; -var isSet = function (payload) { - return payload instanceof Set; -}; -var isSymbol = function (payload) { - return getType$1(payload) === 'Symbol'; -}; -var isDate = function (payload) { - return payload instanceof Date && !isNaN(payload.valueOf()); -}; -var isError = function (payload) { - return payload instanceof Error; -}; -var isNaNValue = function (payload) { - return typeof payload === 'number' && isNaN(payload); -}; -var isPrimitive = function (payload) { - return isBoolean(payload) || - isNull(payload) || - isUndefined(payload) || - isNumber(payload) || - isString(payload) || - isSymbol(payload); -}; -var isBigint = function (payload) { - return typeof payload === 'bigint'; -}; -var isInfinite = function (payload) { - return payload === Infinity || payload === -Infinity; -}; -var isTypedArray = function (payload) { - return ArrayBuffer.isView(payload) && !(payload instanceof DataView); -}; -var isURL = function (payload) { return payload instanceof URL; }; - -var escapeKey = function (key) { return key.replace(/\./g, '\\.'); }; -var stringifyPath = function (path) { - return path - .map(String) - .map(escapeKey) - .join('.'); -}; -var parsePath = function (string) { - var result = []; - var segment = ''; - for (var i = 0; i < string.length; i++) { - var char = string.charAt(i); - var isEscapedDot = char === '\\' && string.charAt(i + 1) === '.'; - if (isEscapedDot) { - segment += '.'; - i++; - continue; - } - var isEndOfSegment = char === '.'; - if (isEndOfSegment) { - result.push(segment); - segment = ''; - continue; - } - segment += char; - } - var lastSegment = segment; - result.push(lastSegment); - return result; -}; - -var __assign$1 = (globalThis && globalThis.__assign) || function () { - __assign$1 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); -}; -var __read$2 = (globalThis && globalThis.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -}; -var __spreadArray$2 = (globalThis && globalThis.__spreadArray) || function (to, from) { - for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) - to[j] = from[i]; - return to; -}; -function simpleTransformation(isApplicable, annotation, transform, untransform) { - return { - isApplicable: isApplicable, - annotation: annotation, - transform: transform, - untransform: untransform - }; -} -var simpleRules = [ - simpleTransformation(isUndefined, 'undefined', function () { return null; }, function () { return undefined; }), - simpleTransformation(isBigint, 'bigint', function (v) { return v.toString(); }, function (v) { - if (typeof BigInt !== 'undefined') { - return BigInt(v); - } - console.error('Please add a BigInt polyfill.'); - return v; - }), - simpleTransformation(isDate, 'Date', function (v) { return v.toISOString(); }, function (v) { return new Date(v); }), - simpleTransformation(isError, 'Error', function (v, superJson) { - var baseError = { - name: v.name, - message: v.message - }; - superJson.allowedErrorProps.forEach(function (prop) { - baseError[prop] = v[prop]; - }); - return baseError; - }, function (v, superJson) { - var e = new Error(v.message); - e.name = v.name; - e.stack = v.stack; - superJson.allowedErrorProps.forEach(function (prop) { - e[prop] = v[prop]; - }); - return e; - }), - simpleTransformation(isRegExp, 'regexp', function (v) { return '' + v; }, function (regex) { - var body = regex.slice(1, regex.lastIndexOf('/')); - var flags = regex.slice(regex.lastIndexOf('/') + 1); - return new RegExp(body, flags); - }), - simpleTransformation(isSet, 'set', - // (sets only exist in es6+) - // eslint-disable-next-line es5/no-es6-methods - function (v) { return __spreadArray$2([], __read$2(v.values())); }, function (v) { return new Set(v); }), - simpleTransformation(isMap, 'map', function (v) { return __spreadArray$2([], __read$2(v.entries())); }, function (v) { return new Map(v); }), - simpleTransformation(function (v) { return isNaNValue(v) || isInfinite(v); }, 'number', function (v) { - if (isNaNValue(v)) { - return 'NaN'; - } - if (v > 0) { - return 'Infinity'; - } - else { - return '-Infinity'; - } - }, Number), - simpleTransformation(function (v) { return v === 0 && 1 / v === -Infinity; }, 'number', function () { - return '-0'; - }, Number), - simpleTransformation(isURL, 'URL', function (v) { return v.toString(); }, function (v) { return new URL(v); }), -]; -function compositeTransformation(isApplicable, annotation, transform, untransform) { - return { - isApplicable: isApplicable, - annotation: annotation, - transform: transform, - untransform: untransform - }; -} -var symbolRule = compositeTransformation(function (s, superJson) { - if (isSymbol(s)) { - var isRegistered = !!superJson.symbolRegistry.getIdentifier(s); - return isRegistered; - } - return false; -}, function (s, superJson) { - var identifier = superJson.symbolRegistry.getIdentifier(s); - return ['symbol', identifier]; -}, function (v) { return v.description; }, function (_, a, superJson) { - var value = superJson.symbolRegistry.getValue(a[1]); - if (!value) { - throw new Error('Trying to deserialize unknown symbol'); - } - return value; -}); -var constructorToName = [ - Int8Array, - Uint8Array, - Int16Array, - Uint16Array, - Int32Array, - Uint32Array, - Float32Array, - Float64Array, - Uint8ClampedArray, -].reduce(function (obj, ctor) { - obj[ctor.name] = ctor; - return obj; -}, {}); -var typedArrayRule = compositeTransformation(isTypedArray, function (v) { return ['typed-array', v.constructor.name]; }, function (v) { return __spreadArray$2([], __read$2(v)); }, function (v, a) { - var ctor = constructorToName[a[1]]; - if (!ctor) { - throw new Error('Trying to deserialize unknown typed array'); - } - return new ctor(v); -}); -function isInstanceOfRegisteredClass(potentialClass, superJson) { - if (potentialClass === null || potentialClass === void 0 ? void 0 : potentialClass.constructor) { - var isRegistered = !!superJson.classRegistry.getIdentifier(potentialClass.constructor); - return isRegistered; - } - return false; -} -var classRule = compositeTransformation(isInstanceOfRegisteredClass, function (clazz, superJson) { - var identifier = superJson.classRegistry.getIdentifier(clazz.constructor); - return ['class', identifier]; -}, function (clazz, superJson) { - var allowedProps = superJson.classRegistry.getAllowedProps(clazz.constructor); - if (!allowedProps) { - return __assign$1({}, clazz); - } - var result = {}; - allowedProps.forEach(function (prop) { - result[prop] = clazz[prop]; - }); - return result; -}, function (v, a, superJson) { - var clazz = superJson.classRegistry.getValue(a[1]); - if (!clazz) { - throw new Error('Trying to deserialize unknown class - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564'); - } - return Object.assign(Object.create(clazz.prototype), v); -}); -var customRule = compositeTransformation(function (value, superJson) { - return !!superJson.customTransformerRegistry.findApplicable(value); -}, function (value, superJson) { - var transformer = superJson.customTransformerRegistry.findApplicable(value); - return ['custom', transformer.name]; -}, function (value, superJson) { - var transformer = superJson.customTransformerRegistry.findApplicable(value); - return transformer.serialize(value); -}, function (v, a, superJson) { - var transformer = superJson.customTransformerRegistry.findByName(a[1]); - if (!transformer) { - throw new Error('Trying to deserialize unknown custom value'); - } - return transformer.deserialize(v); -}); -var compositeRules = [classRule, symbolRule, customRule, typedArrayRule]; -var transformValue = function (value, superJson) { - var applicableCompositeRule = findArr(compositeRules, function (rule) { - return rule.isApplicable(value, superJson); - }); - if (applicableCompositeRule) { - return { - value: applicableCompositeRule.transform(value, superJson), - type: applicableCompositeRule.annotation(value, superJson) - }; - } - var applicableSimpleRule = findArr(simpleRules, function (rule) { - return rule.isApplicable(value, superJson); - }); - if (applicableSimpleRule) { - return { - value: applicableSimpleRule.transform(value, superJson), - type: applicableSimpleRule.annotation - }; - } - return undefined; -}; -var simpleRulesByAnnotation = {}; -simpleRules.forEach(function (rule) { - simpleRulesByAnnotation[rule.annotation] = rule; -}); -var untransformValue = function (json, type, superJson) { - if (isArray$1(type)) { - switch (type[0]) { - case 'symbol': - return symbolRule.untransform(json, type, superJson); - case 'class': - return classRule.untransform(json, type, superJson); - case 'custom': - return customRule.untransform(json, type, superJson); - case 'typed-array': - return typedArrayRule.untransform(json, type, superJson); - default: - throw new Error('Unknown transformation: ' + type); - } - } - else { - var transformation = simpleRulesByAnnotation[type]; - if (!transformation) { - throw new Error('Unknown transformation: ' + type); - } - return transformation.untransform(json, superJson); - } -}; - -var getNthKey = function (value, n) { - var keys = value.keys(); - while (n > 0) { - keys.next(); - n--; - } - return keys.next().value; -}; -function validatePath(path) { - if (includes(path, '__proto__')) { - throw new Error('__proto__ is not allowed as a property'); - } - if (includes(path, 'prototype')) { - throw new Error('prototype is not allowed as a property'); - } - if (includes(path, 'constructor')) { - throw new Error('constructor is not allowed as a property'); - } -} -var getDeep = function (object, path) { - validatePath(path); - for (var i = 0; i < path.length; i++) { - var key = path[i]; - if (isSet(object)) { - object = getNthKey(object, +key); - } - else if (isMap(object)) { - var row = +key; - var type = +path[++i] === 0 ? 'key' : 'value'; - var keyOfRow = getNthKey(object, row); - switch (type) { - case 'key': - object = keyOfRow; - break; - case 'value': - object = object.get(keyOfRow); - break; - } - } - else { - object = object[key]; - } - } - return object; -}; -var setDeep = function (object, path, mapper) { - validatePath(path); - if (path.length === 0) { - return mapper(object); - } - var parent = object; - for (var i = 0; i < path.length - 1; i++) { - var key = path[i]; - if (isArray$1(parent)) { - var index = +key; - parent = parent[index]; - } - else if (isPlainObject$1(parent)) { - parent = parent[key]; - } - else if (isSet(parent)) { - var row = +key; - parent = getNthKey(parent, row); - } - else if (isMap(parent)) { - var isEnd = i === path.length - 2; - if (isEnd) { - break; - } - var row = +key; - var type = +path[++i] === 0 ? 'key' : 'value'; - var keyOfRow = getNthKey(parent, row); - switch (type) { - case 'key': - parent = keyOfRow; - break; - case 'value': - parent = parent.get(keyOfRow); - break; - } - } - } - var lastKey = path[path.length - 1]; - if (isArray$1(parent)) { - parent[+lastKey] = mapper(parent[+lastKey]); - } - else if (isPlainObject$1(parent)) { - parent[lastKey] = mapper(parent[lastKey]); - } - if (isSet(parent)) { - var oldValue = getNthKey(parent, +lastKey); - var newValue = mapper(oldValue); - if (oldValue !== newValue) { - parent["delete"](oldValue); - parent.add(newValue); - } - } - if (isMap(parent)) { - var row = +path[path.length - 2]; - var keyToRow = getNthKey(parent, row); - var type = +lastKey === 0 ? 'key' : 'value'; - switch (type) { - case 'key': { - var newKey = mapper(keyToRow); - parent.set(newKey, parent.get(keyToRow)); - if (newKey !== keyToRow) { - parent["delete"](keyToRow); - } - break; - } - case 'value': { - parent.set(keyToRow, mapper(parent.get(keyToRow))); - break; - } - } - } - return object; -}; - -var __read$1 = (globalThis && globalThis.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -}; -var __spreadArray$1 = (globalThis && globalThis.__spreadArray) || function (to, from) { - for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) - to[j] = from[i]; - return to; -}; -function traverse(tree, walker, origin) { - if (origin === void 0) { origin = []; } - if (!tree) { - return; - } - if (!isArray$1(tree)) { - forEach(tree, function (subtree, key) { - return traverse(subtree, walker, __spreadArray$1(__spreadArray$1([], __read$1(origin)), __read$1(parsePath(key)))); - }); - return; - } - var _a = __read$1(tree, 2), nodeValue = _a[0], children = _a[1]; - if (children) { - forEach(children, function (child, key) { - traverse(child, walker, __spreadArray$1(__spreadArray$1([], __read$1(origin)), __read$1(parsePath(key)))); - }); - } - walker(nodeValue, origin); -} -function applyValueAnnotations(plain, annotations, superJson) { - traverse(annotations, function (type, path) { - plain = setDeep(plain, path, function (v) { return untransformValue(v, type, superJson); }); - }); - return plain; -} -function applyReferentialEqualityAnnotations(plain, annotations) { - function apply(identicalPaths, path) { - var object = getDeep(plain, parsePath(path)); - identicalPaths.map(parsePath).forEach(function (identicalObjectPath) { - plain = setDeep(plain, identicalObjectPath, function () { return object; }); - }); - } - if (isArray$1(annotations)) { - var _a = __read$1(annotations, 2), root = _a[0], other = _a[1]; - root.forEach(function (identicalPath) { - plain = setDeep(plain, parsePath(identicalPath), function () { return plain; }); - }); - if (other) { - forEach(other, apply); - } - } - else { - forEach(annotations, apply); - } - return plain; -} -var isDeep = function (object, superJson) { - return isPlainObject$1(object) || - isArray$1(object) || - isMap(object) || - isSet(object) || - isInstanceOfRegisteredClass(object, superJson); -}; -function addIdentity(object, path, identities) { - var existingSet = identities.get(object); - if (existingSet) { - existingSet.push(path); - } - else { - identities.set(object, [path]); - } -} -function generateReferentialEqualityAnnotations(identitites, dedupe) { - var result = {}; - var rootEqualityPaths = undefined; - identitites.forEach(function (paths) { - if (paths.length <= 1) { - return; - } - // if we're not deduping, all of these objects continue existing. - // putting the shortest path first makes it easier to parse for humans - // if we're deduping though, only the first entry will still exist, so we can't do this optimisation. - if (!dedupe) { - paths = paths - .map(function (path) { return path.map(String); }) - .sort(function (a, b) { return a.length - b.length; }); - } - var _a = __read$1(paths), representativePath = _a[0], identicalPaths = _a.slice(1); - if (representativePath.length === 0) { - rootEqualityPaths = identicalPaths.map(stringifyPath); - } - else { - result[stringifyPath(representativePath)] = identicalPaths.map(stringifyPath); - } - }); - if (rootEqualityPaths) { - if (isEmptyObject(result)) { - return [rootEqualityPaths]; - } - else { - return [rootEqualityPaths, result]; - } - } - else { - return isEmptyObject(result) ? undefined : result; - } -} -var walker = function (object, identities, superJson, dedupe, path, objectsInThisPath, seenObjects) { - var _a; - if (path === void 0) { path = []; } - if (objectsInThisPath === void 0) { objectsInThisPath = []; } - if (seenObjects === void 0) { seenObjects = new Map(); } - var primitive = isPrimitive(object); - if (!primitive) { - addIdentity(object, path, identities); - var seen = seenObjects.get(object); - if (seen) { - // short-circuit result if we've seen this object before - return dedupe - ? { - transformedValue: null - } - : seen; - } - } - if (!isDeep(object, superJson)) { - var transformed_1 = transformValue(object, superJson); - var result_1 = transformed_1 - ? { - transformedValue: transformed_1.value, - annotations: [transformed_1.type] - } - : { - transformedValue: object - }; - if (!primitive) { - seenObjects.set(object, result_1); - } - return result_1; - } - if (includes(objectsInThisPath, object)) { - // prevent circular references - return { - transformedValue: null - }; - } - var transformationResult = transformValue(object, superJson); - var transformed = (_a = transformationResult === null || transformationResult === void 0 ? void 0 : transformationResult.value) !== null && _a !== void 0 ? _a : object; - var transformedValue = isArray$1(transformed) ? [] : {}; - var innerAnnotations = {}; - forEach(transformed, function (value, index) { - var recursiveResult = walker(value, identities, superJson, dedupe, __spreadArray$1(__spreadArray$1([], __read$1(path)), [index]), __spreadArray$1(__spreadArray$1([], __read$1(objectsInThisPath)), [object]), seenObjects); - transformedValue[index] = recursiveResult.transformedValue; - if (isArray$1(recursiveResult.annotations)) { - innerAnnotations[index] = recursiveResult.annotations; - } - else if (isPlainObject$1(recursiveResult.annotations)) { - forEach(recursiveResult.annotations, function (tree, key) { - innerAnnotations[escapeKey(index) + '.' + key] = tree; - }); - } - }); - var result = isEmptyObject(innerAnnotations) - ? { - transformedValue: transformedValue, - annotations: !!transformationResult - ? [transformationResult.type] - : undefined - } - : { - transformedValue: transformedValue, - annotations: !!transformationResult - ? [transformationResult.type, innerAnnotations] - : innerAnnotations - }; - if (!primitive) { - seenObjects.set(object, result); - } - return result; -}; - -function getType(payload) { - return Object.prototype.toString.call(payload).slice(8, -1); -} - -function isArray(payload) { - return getType(payload) === "Array"; -} - -function isPlainObject(payload) { - if (getType(payload) !== "Object") - return false; - const prototype = Object.getPrototypeOf(payload); - return !!prototype && prototype.constructor === Object && prototype === Object.prototype; -} - -function assignProp(carry, key, newVal, originalObject, includeNonenumerable) { - const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable"; - if (propType === "enumerable") - carry[key] = newVal; - if (includeNonenumerable && propType === "nonenumerable") { - Object.defineProperty(carry, key, { - value: newVal, - enumerable: false, - writable: true, - configurable: true - }); - } -} -function copy(target, options = {}) { - if (isArray(target)) { - return target.map((item) => copy(item, options)); - } - if (!isPlainObject(target)) { - return target; - } - const props = Object.getOwnPropertyNames(target); - const symbols = Object.getOwnPropertySymbols(target); - return [...props, ...symbols].reduce((carry, key) => { - if (isArray(options.props) && !options.props.includes(key)) { - return carry; - } - const val = target[key]; - const newVal = copy(val, options); - assignProp(carry, key, newVal, target, options.nonenumerable); - return carry; - }, {}); -} - -var __assign = (globalThis && globalThis.__assign) || function () { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; -var __read = (globalThis && globalThis.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -}; -var __spreadArray = (globalThis && globalThis.__spreadArray) || function (to, from) { - for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) - to[j] = from[i]; - return to; -}; -var SuperJSON = /** @class */ (function () { - /** - * @param dedupeReferentialEqualities If true, SuperJSON will make sure only one instance of referentially equal objects are serialized and the rest are replaced with `null`. - */ - function SuperJSON(_a) { - var _b = _a === void 0 ? {} : _a, _c = _b.dedupe, dedupe = _c === void 0 ? false : _c; - this.classRegistry = new ClassRegistry(); - this.symbolRegistry = new Registry(function (s) { var _a; return (_a = s.description) !== null && _a !== void 0 ? _a : ''; }); - this.customTransformerRegistry = new CustomTransformerRegistry(); - this.allowedErrorProps = []; - this.dedupe = dedupe; - } - SuperJSON.prototype.serialize = function (object) { - var identities = new Map(); - var output = walker(object, identities, this, this.dedupe); - var res = { - json: output.transformedValue - }; - if (output.annotations) { - res.meta = __assign(__assign({}, res.meta), { values: output.annotations }); - } - var equalityAnnotations = generateReferentialEqualityAnnotations(identities, this.dedupe); - if (equalityAnnotations) { - res.meta = __assign(__assign({}, res.meta), { referentialEqualities: equalityAnnotations }); - } - return res; - }; - SuperJSON.prototype.deserialize = function (payload) { - var json = payload.json, meta = payload.meta; - var result = copy(json); - if (meta === null || meta === void 0 ? void 0 : meta.values) { - result = applyValueAnnotations(result, meta.values, this); - } - if (meta === null || meta === void 0 ? void 0 : meta.referentialEqualities) { - result = applyReferentialEqualityAnnotations(result, meta.referentialEqualities); - } - return result; - }; - SuperJSON.prototype.stringify = function (object) { - return JSON.stringify(this.serialize(object)); - }; - SuperJSON.prototype.parse = function (string) { - return this.deserialize(JSON.parse(string)); - }; - SuperJSON.prototype.registerClass = function (v, options) { - this.classRegistry.register(v, options); - }; - SuperJSON.prototype.registerSymbol = function (v, identifier) { - this.symbolRegistry.register(v, identifier); - }; - SuperJSON.prototype.registerCustom = function (transformer, name) { - this.customTransformerRegistry.register(__assign({ name: name }, transformer)); - }; - SuperJSON.prototype.allowErrorProps = function () { - var _a; - var props = []; - for (var _i = 0; _i < arguments.length; _i++) { - props[_i] = arguments[_i]; - } - (_a = this.allowedErrorProps).push.apply(_a, __spreadArray([], __read(props))); - }; - SuperJSON.defaultInstance = new SuperJSON(); - SuperJSON.serialize = SuperJSON.defaultInstance.serialize.bind(SuperJSON.defaultInstance); - SuperJSON.deserialize = SuperJSON.defaultInstance.deserialize.bind(SuperJSON.defaultInstance); - SuperJSON.stringify = SuperJSON.defaultInstance.stringify.bind(SuperJSON.defaultInstance); - SuperJSON.parse = SuperJSON.defaultInstance.parse.bind(SuperJSON.defaultInstance); - SuperJSON.registerClass = SuperJSON.defaultInstance.registerClass.bind(SuperJSON.defaultInstance); - SuperJSON.registerSymbol = SuperJSON.defaultInstance.registerSymbol.bind(SuperJSON.defaultInstance); - SuperJSON.registerCustom = SuperJSON.defaultInstance.registerCustom.bind(SuperJSON.defaultInstance); - SuperJSON.allowErrorProps = SuperJSON.defaultInstance.allowErrorProps.bind(SuperJSON.defaultInstance); - return SuperJSON; -}()); -var serialize$1 = SuperJSON.serialize; -var deserialize$1 = SuperJSON.deserialize; - -/** - * Serialize a value to another value using the specified serialization type. - */ -function serialize(type, value) { - switch (type) { - case "raw": - return value; - case "superjson": - return serialize$1(value); - } -} -function deserialize(type, value) { - switch (type) { - case "raw": - return value; - case "superjson": - return deserialize$1(value); - } -} -const serializedOpaqueSchema = zod.z.any(); - -const clientToServerMessageSchema = zod.z.discriminatedUnion("type", [ - // Communication - zod.z.object({ - type: zod.z.literal("communicationWarning"), - warning: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("keepAlive"), - }), - // Channel - zod.z.object({ - type: zod.z.literal("channelCreate"), - endpoint: zod.z.string(), - channelId: zod.z.number().int(), - creationParameter: serializedOpaqueSchema, - }), - zod.z.object({ - type: zod.z.literal("channelSend"), - channelId: zod.z.number().int(), - message: serializedOpaqueSchema, - ackId: zod.z.number().int().optional(), - }), - zod.z.object({ - type: zod.z.literal("channelAck"), - channelId: zod.z.number().int(), - ackId: zod.z.number().int(), - }), - // RPC - zod.z.object({ - type: zod.z.literal("rpcCall"), - endpoint: zod.z.string(), - callId: zod.z.number().int(), - parameter: serializedOpaqueSchema, - }), - // Readonly signal - zod.z.object({ - type: zod.z.literal("signalSubscribe"), - creationParameter: serializedOpaqueSchema, - endpoint: zod.z.string(), - subscribeId: zod.z.number().int(), - }), - zod.z.object({ - type: zod.z.literal("signalUnsubscribe"), - subscribeId: zod.z.number().int(), - }), - // Writable signal - zod.z.object({ - type: zod.z.literal("writableSignalSubscribe"), - creationParameter: serializedOpaqueSchema, - endpoint: zod.z.string(), - subscribeId: zod.z.number().int(), - }), - zod.z.object({ - type: zod.z.literal("writableSignalUnsubscribe"), - subscribeId: zod.z.number().int(), - }), - zod.z.object({ - type: zod.z.literal("writableSignalUpdate"), - subscribeId: zod.z.number().int(), - patches: zod.z.array(serializedOpaqueSchema), - tags: zod.z.array(zod.z.string()), - }), -]); -const serverToClientMessageSchema = zod.z.discriminatedUnion("type", [ - // Communication - zod.z.object({ - type: zod.z.literal("communicationWarning"), - warning: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("keepAliveAck"), - }), - // Channel - zod.z.object({ - type: zod.z.literal("channelSend"), - channelId: zod.z.number().int(), - message: serializedOpaqueSchema, - ackId: zod.z.number().int().optional(), - }), - zod.z.object({ - type: zod.z.literal("channelAck"), - channelId: zod.z.number().int(), - ackId: zod.z.number().int(), - }), - zod.z.object({ - type: zod.z.literal("channelClose"), - channelId: zod.z.number().int(), - }), - zod.z.object({ - type: zod.z.literal("channelError"), - channelId: zod.z.number().int(), - error: serializedLMSExtendedErrorSchema, - }), - // RPC - zod.z.object({ - type: zod.z.literal("rpcResult"), - callId: zod.z.number().int(), - result: serializedOpaqueSchema, - }), - zod.z.object({ - type: zod.z.literal("rpcError"), - callId: zod.z.number().int(), - error: serializedLMSExtendedErrorSchema, - }), - // Readonly signal - zod.z.object({ - type: zod.z.literal("signalUpdate"), - subscribeId: zod.z.number().int(), - patches: zod.z.array(serializedOpaqueSchema), - tags: zod.z.array(zod.z.string()), - }), - zod.z.object({ - type: zod.z.literal("signalError"), - subscribeId: zod.z.number().int(), - error: serializedLMSExtendedErrorSchema, - }), - // Writable signal - zod.z.object({ - type: zod.z.literal("writableSignalUpdate"), - subscribeId: zod.z.number().int(), - patches: zod.z.array(serializedOpaqueSchema), - tags: zod.z.array(zod.z.string()), - }), - zod.z.object({ - type: zod.z.literal("writableSignalError"), - subscribeId: zod.z.number().int(), - error: serializedLMSExtendedErrorSchema, - }), -]); -class Transport { - constructor() { - /** - * Whether this transport has been disposed. - */ - this.disposed = false; - } - async [Symbol.asyncDispose]() { - if (this.disposed) { - throw new Error("Cannot dispose twice"); - } - // Only sets disposed to true, transport implementations should override this method to - // perform actual cleanup. - this.disposed = true; - } -} -class ClientTransport extends Transport { - parseIncomingMessage(message) { - return serverToClientMessageSchema.parse(message); - } - send(message) { - const result = clientToServerMessageSchema.parse(message); - this.sendViaTransport(result); - } - /** - * Called by the client port when the number of open communications changes from 0 to 1. This - * usually indicates the `socket.ref()` should be called to prevent the process from exiting. - */ - onHavingOneOrMoreOpenCommunication() { } - // The following snippet is intentionally not a tsdoc (only 1 star as oppose to 2). There is - // likely a bug in TypeScript that when we change it to tsdoc, on darwin and linux, it causes the - // generated .d.ts file to be invalid. We have considered reporting this to TypeScript, but it is - // way too difficult to narrow down, thus we just hope this is the only case that this error - // occurs. - /* - * Called by the client port when the number of open communications changes from 1 or more to 0. - * This usually indicates the `socket.unref()` should be called to allow the process to exit. - */ - onHavingNoOpenCommunication() { } -} - -const wsAuthenticationResultSchema = zod.z.discriminatedUnion("success", [ - zod.z.object({ - success: zod.z.literal(true), - }), - zod.z.object({ - success: zod.z.literal(false), - error: zod.z.string(), - }), -]); - -var WsClientTransportStatus; -(function (WsClientTransportStatus) { - WsClientTransportStatus["Disconnected"] = "DISCONNECTED"; - WsClientTransportStatus["Connecting"] = "CONNECTING"; - WsClientTransportStatus["Connected"] = "CONNECTED"; -})(WsClientTransportStatus || (WsClientTransportStatus = {})); -class WsClientTransport extends ClientTransport { - constructor(url, receivedMessage, errored, { abortSignal, parentLogger } = {}) { - super(); - this.url = url; - this.receivedMessage = receivedMessage; - this.errored = errored; - this.ws = null; - this.queuedMessages = []; - this.status = WsClientTransportStatus.Disconnected; - this.resolvedUrl = null; - /** - * Whether the underlying socket should hold the process open. - */ - this.shouldRef = false; - this.resolveDisposed = null; - this.abortSignal = abortSignal; - this.logger = new SimpleLogger("WsClientTransport", parentLogger); - } - static createWsClientTransportFactory(url, { abortSignal, } = {}) { - return (receivedMessage, errored, parentLogger) => new WsClientTransport(url, receivedMessage, errored, { - abortSignal, - parentLogger, - }); - } - connect() { - if (this.status !== WsClientTransportStatus.Disconnected) { - this.logger.warn("connect() called while not disconnected"); - return; - } - if (this.disposed) { - throw new Error(text ` - Cannot establish WebSocket connection because the transport has been disposed. - `); - } - if (this.abortSignal !== undefined && this.abortSignal.aborted) { - throw new Error(this.abortSignal.reason); - } - this.status = WsClientTransportStatus.Connecting; - Promise.resolve(this.url).then(url => { - this.resolvedUrl = url; - this.ws = new lmsIsomorphic.WebSocket(url); - this.ws.addEventListener("open", this.onWsOpen.bind(this)); - this.ws.addEventListener("error", event => this.onWsError(event.error)); - this.ws.addEventListener("close", () => { - this.onWsError(new Error("WebSocket connection closed")); - }); - const abortSignal = this.abortSignal; - if (abortSignal !== undefined) { - if (abortSignal.aborted) { - this.onWsError(abortSignal.reason); - } - else { - const abortListener = () => { - this.onWsError(abortSignal.reason); - }; - abortSignal.addEventListener("abort", abortListener, { once: true }); - this.ws.addEventListener("close", () => { - abortSignal.removeEventListener("abort", abortListener); - }); - } - } - }); - } - onWsOpen() { - this.ws.addEventListener("message", this.onWsMessage.bind(this)); - this.status = WsClientTransportStatus.Connected; - this.queuedMessages.forEach(message => this.sendViaTransport(message)); - this.queuedMessages = []; - this.updateShouldRef(this.shouldRef); - // this.setupWebsocketKeepAlive(this.ws!, this.onWsTimeout.bind(this)); - } - onWsMessage(event) { - if (this.status !== WsClientTransportStatus.Connected) { - this.logger.warn("Received message while not connected. Message ignored:", event.data); - return; - } - let message; - try { - message = JSON.parse(String(event.data)); - } - catch (error) { - this.logger.warn("Received invalid JSON message from server:", event.data); - return; - } - let parsed; - try { - parsed = this.parseIncomingMessage(message); - } - catch (error) { - this.logger.warn("Received invalid message from server:", message); - return; - } - this.receivedMessage(parsed); - } - onWsError(error) { - if (this.status === WsClientTransportStatus.Disconnected) { - return; - } - this.logger.warn("WebSocket error:", error); - if (error.code === "ECONNREFUSED") { - this.logger.warnText ` - WebSocket connection refused. This can happen if the server is not running or the client - is trying to connect to the wrong path. The server path that this client is - attempting to connect to is: - ${this.resolvedUrl ?? "Unknown" /* Should never be Unknown */}. - - Please make sure the following: - - 1. LM Studio is running - - 2. The API server in LM Studio has started - - 3. The client is attempting to connect to the correct path - `; - } - try { - this.ws?.close(); - } - catch (error) { - // Ignore - } - this.status = WsClientTransportStatus.Disconnected; - this.errored(error); - } - onWsTimeout() { - if (this.status === WsClientTransportStatus.Disconnected) { - return; - } - this.logger.warn("Websocket timed out"); - try { - this.ws?.close(); - } - catch (error) { - // Ignore - } - this.status = WsClientTransportStatus.Disconnected; - this.errored(new Error("WebSocket timed out")); - } - onHavingNoOpenCommunication() { - this.updateShouldRef(false); - if (this.disposed && this.resolveDisposed !== null) { - // If the transport is disposed, we can resolve the disposed promise to allow the - // async dispose to complete. - this.resolveDisposed(); - this.resolveDisposed = null; - } - } - onHavingOneOrMoreOpenCommunication() { - this.updateShouldRef(true); - } - updateShouldRef(shouldRef) { - this.shouldRef = shouldRef; - if (this.ws === null) { - return; - } - if (!this.ws._socket) { - return; - } - if (shouldRef) { - this.ws._socket.ref(); - } - else { - this.ws._socket.unref(); - } - } - sendViaTransport(message) { - if (this.status === WsClientTransportStatus.Connected) { - this.ws.send(JSON.stringify(message)); - } - else { - this.queuedMessages.push(message); - if (this.status === WsClientTransportStatus.Disconnected) { - this.connect(); - } - } - } - async [Symbol.asyncDispose]() { - await super[Symbol.asyncDispose](); - if (this.shouldRef) { - // If the connection needs to held up, wait until all communications are terminates - const { promise: disposedPromise, resolve: resolveDisposed } = makePromise(); - this.resolveDisposed = resolveDisposed; - await disposedPromise; - } - if (this.ws !== null) { - try { - this.ws.close(); - } - catch (error) { - // Ignore - } - this.ws = null; - } - this.errored(new Error("WebSocket client transport disposed")); - this.status = WsClientTransportStatus.Disconnected; - } -} - -class AuthenticatedWsClientTransport extends WsClientTransport { - constructor(url, clientIdentifier, clientPasskey, receivedMessage, errored, { parentLogger, abortSignal } = {}) { - super(url, receivedMessage, errored, { parentLogger, abortSignal }); - this.clientIdentifier = clientIdentifier; - this.clientPasskey = clientPasskey; - this.logger = this.logger.subclass("AuthenticatedWsClientTransport"); - } - static createAuthenticatedWsClientTransportFactory({ url, clientIdentifier, clientPasskey, abortSignal, }) { - return (receivedMessage, errored, parentLogger) => new AuthenticatedWsClientTransport(url, clientIdentifier, clientPasskey, receivedMessage, errored, { parentLogger, abortSignal }); - } - onWsOpen() { - this.ws.send(JSON.stringify({ - authVersion: 1, - clientIdentifier: this.clientIdentifier, - clientPasskey: this.clientPasskey, - })); - this.ws.addEventListener("message", (event) => { - try { - const data = JSON.parse(event.data.toString("utf-8")); - const result = wsAuthenticationResultSchema.parse(data); - if (result.success) { - super.onWsOpen(); - } - else { - this.onWsError(new Error("Failed to authenticate: " + result.error)); - } - } - catch (error) { - this.onWsError(new Error("Failed to parse authentication result: " + error?.message)); - } - }, { - once: true, - }); - } -} - -function defaultErrorDeserializer(serialized, directCause, stack) { - return fromSerializedError(serialized, directCause, stack); -} -class ClientPort { - constructor(backendInterface, factory, { parentLogger, errorDeserializer, verboseErrorMessage, } = {}) { - this.backendInterface = backendInterface; - this.openChannels = new Map(); - this.ongoingRpcs = new Map(); - this.openSignalSubscriptions = new Map(); - this.openWritableSignalSubscriptions = new Map(); - this.openCommunicationsCount = 0; - this.nextChannelId = 0; - this.nextSubscribeId = 0; - this.nextWritableSubscribeId = 0; - this.producedCommunicationWarningsCount = 0; - this.receivedMessage = (message) => { - switch (message.type) { - case "channelSend": { - this.receivedChannelSend(message); - break; - } - case "channelAck": { - this.receivedChannelAck(message); - break; - } - case "channelClose": { - this.receivedChannelClose(message); - break; - } - case "channelError": { - this.receivedChannelError(message); - break; - } - case "rpcResult": { - this.receivedRpcResult(message); - break; - } - case "rpcError": { - this.receivedRpcError(message); - break; - } - case "signalUpdate": { - this.receivedSignalUpdate(message); - break; - } - case "signalError": { - this.receivedSignalError(message); - break; - } - case "writableSignalUpdate": { - this.receivedWritableSignalUpdate(message); - break; - } - case "writableSignalError": { - this.receivedWritableSignalError(message); - break; - } - case "communicationWarning": { - this.receivedCommunicationWarning(message); - break; - } - case "keepAliveAck": { - this.receivedKeepAliveAck(message); - break; - } - } - }; - this.errored = (error) => { - for (const openChannel of this.openChannels.values()) { - openChannel.errored(error); - } - this.openChannels.clear(); - for (const ongoingRpc of this.ongoingRpcs.values()) { - ongoingRpc.reject(error); - } - this.ongoingRpcs.clear(); - for (const openSignalSubscription of this.openSignalSubscriptions.values()) { - openSignalSubscription.errored(error); - } - this.openSignalSubscriptions.clear(); - for (const openWritableSignalSubscription of this.openWritableSignalSubscriptions.values()) { - openWritableSignalSubscription.errored(error); - } - this.openWritableSignalSubscriptions.clear(); - this.updateOpenCommunicationsCount(); - }; - this.logger = new SimpleLogger("ClientPort", parentLogger); - this.errorDeserializer = errorDeserializer ?? defaultErrorDeserializer; - this.verboseErrorMessage = verboseErrorMessage ?? true; - this.transport = factory(this.receivedMessage, this.errored, this.logger); - } - communicationWarning(warning) { - if (this.producedCommunicationWarningsCount >= 5) { - return; - } - this.logger.warnText ` - Produced communication warning: ${warning} - - This is usually caused by communication protocol incompatibility. Please make sure you are - using the up-to-date versions of the SDK and LM Studio. - `; - this.transport.send({ - type: "communicationWarning", - warning, - }); - this.producedCommunicationWarningsCount++; - if (this.producedCommunicationWarningsCount >= 5) { - this.logger.errorText ` - 5 communication warnings have been produced. Further warnings will not be printed. - `; - } - } - updateOpenCommunicationsCount() { - const previousCount = this.openCommunicationsCount; - this.openCommunicationsCount = - this.openChannels.size + - this.ongoingRpcs.size + - this.openSignalSubscriptions.size + - this.openWritableSignalSubscriptions.size; - if (this.openCommunicationsCount === 0 && previousCount > 0) { - this.transport.onHavingNoOpenCommunication(); - } - else if (this.openCommunicationsCount === 1 && previousCount === 0) { - this.transport.onHavingOneOrMoreOpenCommunication(); - } - } - receivedChannelSend(message) { - const openChannel = this.openChannels.get(message.channelId); - if (openChannel === undefined) { - this.communicationWarning(`Received channelSend for unknown channel, channelId = ${message.channelId}`); - return; - } - const deserializedMessage = deserialize(openChannel.endpoint.serialization, message.message); - const parsed = openChannel.endpoint.toClientPacket.safeParse(deserializedMessage); - if (!parsed.success) { - this.communicationWarning(text ` - Received invalid message for channel: endpointName = ${openChannel.endpoint.name}, message = - ${deserializedMessage}. Zod error: - - ${Validator.prettyPrintZod("message", parsed.error)} - `); - return; - } - openChannel.receivedMessage(parsed.data); - } - receivedChannelAck(message) { - const openChannel = this.openChannels.get(message.channelId); - if (openChannel === undefined) { - this.communicationWarning(`Received channelAck for unknown channel, channelId = ${message.channelId}`); - return; - } - openChannel.receivedAck(message.ackId); - } - receivedChannelClose(message) { - const openChannel = this.openChannels.get(message.channelId); - if (openChannel === undefined) { - this.communicationWarning(`Received channelClose for unknown channel, channelId = ${message.channelId}`); - return; - } - this.openChannels.delete(message.channelId); - openChannel.closed(); - this.updateOpenCommunicationsCount(); - } - receivedChannelError(message) { - const openChannel = this.openChannels.get(message.channelId); - if (openChannel === undefined) { - this.communicationWarning(`Received channelError for unknown channel, channelId = ${message.channelId}`); - return; - } - this.openChannels.delete(message.channelId); - const error = this.errorDeserializer(message.error, "Channel Error", this.verboseErrorMessage ? openChannel.stack : undefined); - openChannel.errored(error); - this.updateOpenCommunicationsCount(); - } - receivedRpcResult(message) { - const ongoingRpc = this.ongoingRpcs.get(message.callId); - if (ongoingRpc === undefined) { - this.communicationWarning(`Received rpcResult for unknown rpc, callId = ${message.callId}`); - return; - } - const deserializedResult = deserialize(ongoingRpc.endpoint.serialization, message.result); - const parsed = ongoingRpc.endpoint.returns.safeParse(deserializedResult); - if (!parsed.success) { - this.communicationWarning(text ` - Received invalid result for rpc, endpointName = ${ongoingRpc.endpoint.name}, result = - ${deserializedResult}. Zod error: - - ${Validator.prettyPrintZod("result", parsed.error)} - `); - return; - } - ongoingRpc.resolve(parsed.data); - this.ongoingRpcs.delete(message.callId); - this.updateOpenCommunicationsCount(); - } - receivedRpcError(message) { - const ongoingRpc = this.ongoingRpcs.get(message.callId); - if (ongoingRpc === undefined) { - this.communicationWarning(`Received rpcError for unknown rpc, callId = ${message.callId}`); - return; - } - const error = this.errorDeserializer(message.error, "RPC Error", this.verboseErrorMessage ? ongoingRpc.stack : undefined); - ongoingRpc.reject(error); - this.ongoingRpcs.delete(message.callId); - this.updateOpenCommunicationsCount(); - } - receivedSignalUpdate(message) { - const openSignalSubscription = this.openSignalSubscriptions.get(message.subscribeId); - if (openSignalSubscription === undefined) { - // This is caused by update and unsubscribe event happening at the same time. By the time the - // update has arrived at the client side, as far as the client is considered, the signal is - // already unsubscribed. This is a normal behavior and is especially prevalent when React - // StrictMode is enabled, because components are rendered twice where signals are oftentimes - // subscribed and then unsubscribed immediately after. - return; - } - const patches = message.patches.map(patch => deserialize(openSignalSubscription.endpoint.serialization, patch)); - const beforeValue = openSignalSubscription.getValue(); - let afterValue; - try { - afterValue = applyPatches(beforeValue, patches); - } - catch (error) { - this.communicationWarning(text ` - Failed to apply patches to signal on signalUpdate. subscribeId = ${message.subscribeId}. - - beforeValue = ${JSON.stringify(beforeValue, null, 2)}, - - patches = ${JSON.stringify(patches, null, 2)}. - - Error: ${String(error)} - `); - return; - } - const parseResult = openSignalSubscription.endpoint.signalData.safeParse(afterValue); - if (!parseResult.success) { - this.communicationWarning(text ` - Received invalid signal patch data, subscribeId = ${message.subscribeId} - - patches = ${patches}, - - beforeValue = ${beforeValue}, - - afterValue = ${afterValue}. - - Zod error: - - ${Validator.prettyPrintZod("value", parseResult.error)} - `); - return; - } - // Don't use the parsed value, as it loses the substructure identities - openSignalSubscription.receivedPatches(afterValue, patches, message.tags); - } - receivedSignalError(message) { - const openSignalSubscription = this.openSignalSubscriptions.get(message.subscribeId); - if (openSignalSubscription === undefined) { - this.communicationWarning(`Received signalError for unknown signal, subscribeId = ${message.subscribeId}`); - return; - } - const error = this.errorDeserializer(message.error, "Signal Error", this.verboseErrorMessage ? openSignalSubscription.stack : undefined); - openSignalSubscription.errored(error); - this.openSignalSubscriptions.delete(message.subscribeId); - this.updateOpenCommunicationsCount(); - } - receivedWritableSignalUpdate(message) { - const openSignalSubscription = this.openWritableSignalSubscriptions.get(message.subscribeId); - if (openSignalSubscription === undefined) { - // This is caused by update and unsubscribe event happening at the same time. By the time the - // update has arrived at the client side, as far as the client is considered, the signal is - // already unsubscribed. This is a normal behavior and is especially prevalent when React - // StrictMode is enabled, because components are rendered twice where signals are oftentimes - // subscribed and then unsubscribed immediately after. - return; - } - const patches = message.patches.map(patch => deserialize(openSignalSubscription.endpoint.serialization, patch)); - const beforeValue = openSignalSubscription.getValue(); - let afterValue; - try { - afterValue = applyPatches(openSignalSubscription.getValue(), patches); - } - catch (error) { - this.communicationWarning(text ` - Failed to apply patches to writable signal on writableSignalUpdate. subscribeId = - ${message.subscribeId}. - - beforeValue = ${JSON.stringify(beforeValue, null, 2)}, - - patches = ${JSON.stringify(patches, null, 2)}. - - Error: ${String(error)} - `); - } - const parseResult = openSignalSubscription.endpoint.signalData.safeParse(afterValue); - if (!parseResult.success) { - this.communicationWarning(text ` - Received invalid writable signal patch data, subscribeId = ${message.subscribeId} - - patches = ${patches}, - - beforeValue = ${beforeValue}, - - afterValue = ${afterValue}. - - Zod error: - - ${Validator.prettyPrintZod("value", parseResult.error)} - `); - return; - } - // Don't use the parsed value, as it loses the substructure identities - openSignalSubscription.firstUpdateReceived = true; - openSignalSubscription.receivedPatches(afterValue, patches, message.tags); - } - receivedWritableSignalError(message) { - const openSignalSubscription = this.openWritableSignalSubscriptions.get(message.subscribeId); - if (openSignalSubscription === undefined) { - this.communicationWarning(`Received writableSignalError for unknown signal, subscribeId = ${message.subscribeId}`); - return; - } - const error = this.errorDeserializer(message.error, "Writable Signal Error", this.verboseErrorMessage ? openSignalSubscription.stack : undefined); - openSignalSubscription.errored(error); - this.openWritableSignalSubscriptions.delete(message.subscribeId); - this.updateOpenCommunicationsCount(); - } - receivedCommunicationWarning(message) { - this.logger.warnText ` - Received communication warning from the server: ${message.warning} - - This is usually caused by communication protocol incompatibility. Please make sure you are - using the up-to-date versions of the SDK and LM Studio. - - Note: This warning was received from the server and is printed on the client for convenience. - `; - } - receivedKeepAliveAck(_message) { - // Do nothing - } - async callRpc(endpointName, param, { stack } = {}) { - const endpoint = this.backendInterface.getRpcEndpoint(endpointName); - if (endpoint === undefined) { - throw new Error(`No Rpc endpoint with name ${endpointName}`); - } - const parameter = endpoint.parameter.parse(param); - const serializedParameter = serialize(endpoint.serialization, parameter); - const callId = this.nextChannelId; - this.nextChannelId++; - const { promise, resolve, reject } = makePromise(); - stack = stack ?? getCurrentStack(1); - this.ongoingRpcs.set(callId, { - endpoint, - stack, - resolve, - reject, - }); - this.transport.send({ - type: "rpcCall", - endpoint: endpointName, - callId, - parameter: serializedParameter, - }); - this.updateOpenCommunicationsCount(); - return await promise; - } - createChannel(endpointName, param, onMessage, { stack } = {}) { - const channelEndpoint = this.backendInterface.getChannelEndpoint(endpointName); - if (channelEndpoint === undefined) { - throw new Error(`No channel endpoint with name ${endpointName}`); - } - const creationParameter = channelEndpoint.creationParameter.parse(param); - const serializedCreationParameter = serialize(channelEndpoint.serialization, creationParameter); - const channelId = this.nextChannelId; - this.nextChannelId++; - this.transport.send({ - type: "channelCreate", - endpoint: endpointName, - channelId, - creationParameter: serializedCreationParameter, - }); - stack = stack ?? getCurrentStack(1); - const openChannel = { - endpoint: channelEndpoint, - stack, - ...Channel.create(packet => { - const parsed = channelEndpoint.toServerPacket.parse(packet); - const serializedMessage = serialize(channelEndpoint.serialization, parsed); - this.transport.send({ - type: "channelSend", - channelId, - message: serializedMessage, - }); - }), - }; - if (onMessage !== undefined) { - openChannel.channel.onMessage.subscribe(onMessage); - } - this.openChannels.set(channelId, openChannel); - this.updateOpenCommunicationsCount(); - return openChannel.channel; - } - /** - * Creates a readonly lazy signal will subscribe to the signal endpoint with the given name. - */ - createSignal(endpointName, param, { stack } = {}) { - const signalEndpoint = this.backendInterface.getSignalEndpoint(endpointName); - if (signalEndpoint === undefined) { - throw new Error(`No signal endpoint with name ${endpointName}`); - } - const creationParameter = signalEndpoint.creationParameter.parse(param); - const serializedCreationParameter = serialize(signalEndpoint.serialization, creationParameter); - stack = stack ?? getCurrentStack(1); - const signal = LazySignal.createWithoutInitialValue((setDownstream, errorListener) => { - const subscribeId = this.nextSubscribeId; - this.nextSubscribeId++; - this.transport.send({ - type: "signalSubscribe", - endpoint: endpointName, - subscribeId, - creationParameter: serializedCreationParameter, - }); - this.openSignalSubscriptions.set(subscribeId, { - endpoint: signalEndpoint, - getValue: () => signal.get(), - receivedPatches: setDownstream.withValueAndPatches, - errored: errorListener, - stack, - }); - this.updateOpenCommunicationsCount(); - return () => { - this.transport.send({ - type: "signalUnsubscribe", - subscribeId, - }); - this.openSignalSubscriptions.delete(subscribeId); - }; - }); - return signal; - } - createWritableSignal(endpointName, param, { stack } = {}) { - const signalEndpoint = this.backendInterface.getWritableSignalEndpoint(endpointName); - if (signalEndpoint === undefined) { - throw new Error(`No writable signal endpoint with name ${endpointName}`); - } - const creationParameter = signalEndpoint.creationParameter.parse(param); - const serializedCreationParameter = serialize(signalEndpoint.serialization, creationParameter); - stack = stack ?? getCurrentStack(1); - let currentSubscribeId = null; - const writeUpstream = (_data, patches, tags) => { - if (currentSubscribeId === null) { - console.warn("writeUpstream called when not subscribed"); - return false; - } - const subscription = this.openWritableSignalSubscriptions.get(currentSubscribeId); - if (!subscription?.firstUpdateReceived) { - console.warn("writeUpstream called before the first update is received"); - return false; - } - this.transport.send({ - type: "writableSignalUpdate", - subscribeId: currentSubscribeId, - patches: patches.map(patch => serialize(signalEndpoint.serialization, patch)), - tags, - }); - return true; - }; - const [signal, setter] = OWLSignal.createWithoutInitialValue((setDownstream, errorListener) => { - const subscribeId = this.nextWritableSubscribeId; - currentSubscribeId = subscribeId; - this.nextWritableSubscribeId++; - this.transport.send({ - type: "writableSignalSubscribe", - endpoint: endpointName, - subscribeId, - creationParameter: serializedCreationParameter, - }); - this.openWritableSignalSubscriptions.set(subscribeId, { - endpoint: signalEndpoint, - getValue: () => signal.getPessimistic(), - receivedPatches: setDownstream.withValueAndPatches, - firstUpdateReceived: false, - errored: errorListener, - stack, - }); - this.updateOpenCommunicationsCount(); - return () => { - currentSubscribeId = null; - this.transport.send({ - type: "writableSignalUnsubscribe", - subscribeId, - }); - this.openWritableSignalSubscriptions.delete(subscribeId); - }; - }, writeUpstream); - return [signal, setter]; - } - async [Symbol.asyncDispose]() { - await this.transport[Symbol.asyncDispose](); - } -} - -class GenericClientTransport extends ClientTransport { - constructor(onMessage, onClose, sendMessage, receivedMessage, errored, parentLogger) { - super(); - this.sendMessage = sendMessage; - this.receivedMessage = receivedMessage; - this.errored = errored; - this.closed = false; - this.logger = new SimpleLogger("GenericClientTransport", parentLogger); - onMessage.subscribe(message => { - let parsed; - try { - parsed = this.parseIncomingMessage(message); - } - catch (error) { - this.logger.warn("Received invalid message from server:", message); - return; - } - this.receivedMessage(parsed); - }); - onClose.subscribeOnce(() => { - if (this.closed) { - return; - } - this.closed = true; - this.errored(new Error("Server closed the connection")); - }); - } - static createFactory(onMessage, onClose, sendMessage) { - return (receivedMessage, errored, parentLogger) => new GenericClientTransport(onMessage, onClose, sendMessage, receivedMessage, errored, parentLogger); - } - sendViaTransport(message) { - this.sendMessage(message); - } -} - -function getHostedEnv() { - let anyWindow; - try { - anyWindow = window; - } - catch (error) { - anyWindow = undefined; - } - if (anyWindow !== undefined && anyWindow.lmsHostedEnv !== undefined) { - return anyWindow.lmsHostedEnv; - } - return null; -} - -/** - * Create a base model backend interface that are used by all domain-specific model backend - * interfaces. - */ -function createBaseModelBackendInterface(specificModelInstanceInfoSchemaInput, specificModelInfoSchemaInput) { - const specificModelInstanceInfoSchema = specificModelInstanceInfoSchemaInput; - const specificModelInfoSchema = specificModelInfoSchemaInput; - return new BackendInterface() - .addChannelEndpoint("loadModel", { - creationParameter: zod.z.object({ - modelKey: zod.z.string(), - identifier: zod.z.string().optional(), - /** - * If provided, when the model is not used for this amount of time, it will be unloaded. - */ - ttlMs: zod.z.number().int().min(1).optional(), - loadConfigStack: kvConfigStackSchema, - }), - toClientPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("resolved"), - info: specificModelInfoSchema, - ambiguous: zod.z.array(zod.z.string()).optional(), - }), - zod.z.object({ - type: zod.z.literal("progress"), - progress: zod.z.number(), - }), - zod.z.object({ - type: zod.z.literal("success"), - info: specificModelInstanceInfoSchema, - }), - ]), - toServerPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("cancel"), - }), - ]), - }) - .addRpcEndpoint("unloadModel", { - parameter: zod.z.object({ - identifier: zod.z.string(), - }), - returns: zod.z.void(), - }) - .addRpcEndpoint("listLoaded", { - parameter: zod.z.undefined(), - returns: zod.z.array(specificModelInstanceInfoSchema), - }) - .addRpcEndpoint("getModelInfo", { - parameter: zod.z.object({ - specifier: modelSpecifierSchema, - throwIfNotFound: zod.z.boolean(), - }), - returns: specificModelInstanceInfoSchema.optional(), - }) - .addRpcEndpoint("getLoadConfig", { - parameter: zod.z.object({ - specifier: modelSpecifierSchema, - }), - returns: kvConfigSchema, - }) - .addChannelEndpoint("getOrLoad", { - creationParameter: zod.z.object({ - identifier: zod.z.string(), - /** - * If provided and a new instance is loaded as a result of this call, it will be unloaded - * after idling for this amount of time. - */ - loadTtlMs: zod.z.number().int().min(1).optional(), - loadConfigStack: kvConfigStackSchema, - }), - toClientPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("alreadyLoaded"), - info: specificModelInstanceInfoSchema, - }), - zod.z.object({ - type: zod.z.literal("startLoading"), - identifier: zod.z.string(), - info: specificModelInfoSchema, - }), - zod.z.object({ - // We are unloading other JIT model - type: zod.z.literal("unloadingOtherJITModel"), - info: modelInstanceInfoSchema, - }), - zod.z.object({ - type: zod.z.literal("loadProgress"), - progress: zod.z.number(), - }), - zod.z.object({ - type: zod.z.literal("loadSuccess"), - info: specificModelInstanceInfoSchema, - }), - ]), - toServerPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("cancel"), - }), - ]), - }); -} - -function createDiagnosticsBackendInterface() { - return new BackendInterface().addChannelEndpoint("streamLogs", { - creationParameter: zod.z.void(), - toServerPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("stop"), - }), - ]), - toClientPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("log"), - log: diagnosticsLogEventSchema, - }), - ]), - }); -} - -function createEmbeddingBackendInterface() { - const baseModelBackendInterface = createBaseModelBackendInterface(embeddingModelInstanceInfoSchema, embeddingModelInfoSchema); - return baseModelBackendInterface - .addRpcEndpoint("embedString", { - parameter: zod.z.object({ - modelSpecifier: modelSpecifierSchema, - inputString: zod.z.string(), - }), - returns: zod.z.object({ - embedding: zod.z.array(zod.z.number()), - }), - }) - .addRpcEndpoint("tokenize", { - parameter: zod.z.object({ - specifier: modelSpecifierSchema, - inputString: zod.z.string(), - }), - returns: zod.z.object({ - tokens: zod.z.array(zod.z.number()), - }), - }) - .addRpcEndpoint("countTokens", { - parameter: zod.z.object({ - specifier: modelSpecifierSchema, - inputString: zod.z.string(), - }), - returns: zod.z.object({ - tokenCount: zod.z.number().int(), - }), - }); -} - -function createFilesBackendInterface() { - return new BackendInterface() - .addRpcEndpoint("getLocalFileAbsolutePath", { - parameter: zod.z.object({ - fileName: zod.z.string(), - }), - returns: zod.z.object({ - path: zod.z.string(), - }), - }) - .addRpcEndpoint("uploadFileBase64", { - parameter: zod.z.object({ - name: zod.z.string(), - contentBase64: zod.z.string(), - }), - returns: zod.z.object({ - identifier: zod.z.string(), - fileType: fileTypeSchema, - sizeBytes: zod.z.number().int(), - }), - }) - .addChannelEndpoint("retrieve", { - creationParameter: zod.z.object({ - query: zod.z.string(), - fileIdentifiers: zod.z.array(zod.z.string()), - config: kvConfigSchema, - }), - toServerPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("stop"), - }), - ]), - toClientPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("onFileProcessList"), - indices: zod.z.array(zod.z.number().int()), - }), - zod.z.object({ - type: zod.z.literal("onFileProcessingStart"), - index: zod.z.number().int(), - }), - zod.z.object({ - type: zod.z.literal("onFileProcessingEnd"), - index: zod.z.number().int(), - }), - zod.z.object({ - type: zod.z.literal("onFileProcessingStepStart"), - index: zod.z.number().int(), - step: retrievalFileProcessingStepSchema, - }), - zod.z.object({ - type: zod.z.literal("onFileProcessingStepProgress"), - index: zod.z.number().int(), - step: retrievalFileProcessingStepSchema, - progress: zod.z.number(), - }), - zod.z.object({ - type: zod.z.literal("onFileProcessingStepEnd"), - index: zod.z.number().int(), - step: retrievalFileProcessingStepSchema, - }), - zod.z.object({ - type: zod.z.literal("onSearchingStart"), - }), - zod.z.object({ - type: zod.z.literal("onSearchingEnd"), - }), - zod.z.object({ - type: zod.z.literal("result"), - result: internalRetrievalResultSchema, - }), - ]), - }) - .addChannelEndpoint("parseDocument", { - creationParameter: zod.z.object({ - fileIdentifier: zod.z.string(), - parseOpts: documentParsingOptsSchema, - }), - toClientPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("parserLoaded"), - parser: documentParsingLibraryIdentifierSchema, - }), - zod.z.object({ - type: zod.z.literal("progress"), - progress: zod.z.number(), - }), - zod.z.object({ - type: zod.z.literal("result"), - content: zod.z.string(), - parser: documentParsingLibraryIdentifierSchema, - }), - ]), - toServerPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("cancel"), - }), - ]), - }) - .addRpcEndpoint("getDocumentParsingLibrary", { - parameter: zod.z.object({ - fileIdentifier: zod.z.string(), - }), - returns: zod.z.object({ - library: zod.z.string(), - version: zod.z.string(), - }), - }); -} - -function createLlmBackendInterface() { - const baseModelBackendInterface = createBaseModelBackendInterface(llmInstanceInfoSchema, llmInfoSchema); - return (baseModelBackendInterface - .addChannelEndpoint("predict", { - creationParameter: zod.z.object({ - modelSpecifier: modelSpecifierSchema, - history: chatHistoryDataSchema, - predictionConfigStack: kvConfigStackSchema, - /** - * Which preset to use. Supports limited fuzzy matching. - */ - fuzzyPresetIdentifier: zod.z.string().optional(), - ignoreServerSessionConfig: zod.z.boolean().optional(), - }), - toClientPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("fragment"), - fragment: llmPredictionFragmentSchema, - logprobs: zod.z - .array(zod.z.array(zod.z.object({ text: zod.z.string(), logprob: zod.z.number() }))) - .optional(), - }), - zod.z.object({ - type: zod.z.literal("promptProcessingProgress"), - progress: zod.z.number(), - }), - zod.z.object({ - type: zod.z.literal("toolCallGenerationStart"), - /** - * The LLM specific call id of the tool call. - */ - toolCallId: zod.z.string().optional(), - }), - zod.z.object({ - type: zod.z.literal("toolCallGenerationNameReceived"), - name: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("toolCallGenerationArgumentFragmentGenerated"), - content: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("toolCallGenerationEnd"), - toolCallRequest: toolCallRequestSchema, - /** - * The raw output that represents this tool call. It is recommended to present this to - * the user as is, if desired. - * - * @remarks It is not guaranteed to be valid JSON as the model does not necessarily use - * JSON to represent tool calls. - */ - rawContent: zod.z.string().optional(), - }), - zod.z.object({ - type: zod.z.literal("toolCallGenerationFailed"), - error: serializedLMSExtendedErrorSchema, - /** - * The raw output that was generated by the model before the tool call. The exact nature - * of this fields depends on the error. It sometimes include the entire tool calls - * section, or sometimes just the single tool call that failed. - * - * It is recommended to present this to the user as is, if desired. - */ - rawContent: zod.z.string().optional(), - }), - zod.z.object({ - type: zod.z.literal("success"), - stats: llmPredictionStatsSchema, - modelInfo: llmInstanceInfoSchema, - loadModelConfig: kvConfigSchema, - predictionConfig: kvConfigSchema, - }), - ]), - toServerPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("cancel"), - }), - ]), - }) - .addRpcEndpoint("applyPromptTemplate", { - parameter: zod.z.object({ - specifier: modelSpecifierSchema, - history: chatHistoryDataSchema, - predictionConfigStack: kvConfigStackSchema, - opts: llmApplyPromptTemplateOptsSchema, - }), - returns: zod.z.object({ - formatted: zod.z.string(), - }), - }) - .addRpcEndpoint("tokenize", { - parameter: zod.z.object({ - specifier: modelSpecifierSchema, - inputString: zod.z.string(), - }), - returns: zod.z.object({ - tokens: zod.z.array(zod.z.number()), - }), - }) - .addRpcEndpoint("countTokens", { - parameter: zod.z.object({ - specifier: modelSpecifierSchema, - inputString: zod.z.string(), - }), - returns: zod.z.object({ - tokenCount: zod.z.number().int(), - }), - }) - // Starts to eagerly preload a draft model. This is useful when you want a draft model to be - // ready for speculative decoding. - .addRpcEndpoint("preloadDraftModel", { - parameter: zod.z.object({ - specifier: modelSpecifierSchema, - draftModelKey: zod.z.string(), - }), - returns: zod.z.void(), - })); -} - -function createPluginsBackendInterface() { - return (new BackendInterface() - /** - * The following method is called by a client that wants to use plugins that are registered - * to LM Studio. - */ - .addChannelEndpoint("startToolUseSession", { - creationParameter: zod.z.object({ - pluginIdentifier: zod.z.string(), - pluginConfigSpecifier: pluginConfigSpecifierSchema, - }), - toClientPacket: zod.z.discriminatedUnion("type", [ - /** - * The session has been started successfully. The client can now use the session. Note, - * there are no sessionError message because if a session fails to start, the channel - * will error instead. - */ - zod.z.object({ - type: zod.z.literal("sessionReady"), - toolDefinitions: zod.z.array(llmToolSchema), - }), - /** - * A tool call has been completed. - */ - zod.z.object({ - type: zod.z.literal("toolCallComplete"), - callId: zod.z.number(), - result: jsonSerializableSchema, - }), - /** - * A tool call has failed. - */ - zod.z.object({ - type: zod.z.literal("toolCallError"), - callId: zod.z.number(), - error: serializedLMSExtendedErrorSchema, - }), - /** - * Status update for a tool call. - */ - zod.z.object({ - type: zod.z.literal("toolCallStatus"), - callId: zod.z.number(), - statusText: zod.z.string(), - }), - /** - * Warning message for a tool call. - */ - zod.z.object({ - type: zod.z.literal("toolCallWarn"), - callId: zod.z.number(), - warnText: zod.z.string(), - }), - ]), - toServerPacket: zod.z.discriminatedUnion("type", [ - /** - * Request to start a tool call. This call can be aborted using the `abortToolCall` - * packet. When the tool call is completed, either the `toolCallResult` or `toolCallError` - * packet will be sent. - */ - zod.z.object({ - type: zod.z.literal("callTool"), - callId: zod.z.number(), - name: zod.z.string(), - arguments: jsonSerializableSchema, - }), - /** - * Request to abort a tool call. Upon calling this, no toolCallComplete or toolCallError - * packets will be sent for the call. We assume abort is done immediately. - */ - zod.z.object({ - type: zod.z.literal("abortToolCall"), - callId: zod.z.number(), - }), - /** - * Client requests to discard the session. Upon calling this, the channel will be closed. - */ - zod.z.object({ - type: zod.z.literal("discardSession"), - }), - ]), - }) - .addChannelEndpoint("generateWithGenerator", { - creationParameter: zod.z.object({ - pluginIdentifier: zod.z.string(), - pluginConfigSpecifier: pluginConfigSpecifierSchema, - tools: zod.z.array(llmToolSchema), - history: chatHistoryDataSchema, - }), - toClientPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("fragment"), - fragment: llmPredictionFragmentSchema, - }), - zod.z.object({ - type: zod.z.literal("promptProcessingProgress"), - progress: zod.z.number(), - }), - zod.z.object({ - type: zod.z.literal("toolCallGenerationStart"), - /** - * The LLM specific call id of the tool call. - */ - toolCallId: zod.z.string().optional(), - }), - zod.z.object({ - type: zod.z.literal("toolCallGenerationNameReceived"), - name: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("toolCallGenerationArgumentFragmentGenerated"), - content: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("toolCallGenerationEnd"), - toolCallRequest: toolCallRequestSchema, - }), - zod.z.object({ - type: zod.z.literal("toolCallGenerationFailed"), - }), - zod.z.object({ - type: zod.z.literal("success"), - }), - ]), - toServerPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("cancel"), - }), - ]), - }) - /** - * The following method is called by the controlling client. (e.g. lms-cli) - */ - .addChannelEndpoint("registerDevelopmentPlugin", { - creationParameter: zod.z.object({ - manifest: pluginManifestSchema, - }), - toClientPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("ready"), - clientIdentifier: zod.z.string(), - clientPasskey: zod.z.string(), - }), - ]), - toServerPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("end"), - }), - ]), - }) - .addRpcEndpoint("reindexPlugins", { - parameter: zod.z.void(), - returns: zod.z.void(), - }) - /** - * The following method is called by the plugin client. (plugin:*) - */ - .addChannelEndpoint("setPromptPreprocessor", { - creationParameter: zod.z.void(), - toClientPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("preprocess"), - taskId: zod.z.string(), - input: chatMessageDataSchema, - config: kvConfigSchema, - pluginConfig: kvConfigSchema, - globalPluginConfig: kvConfigSchema, - workingDirectoryPath: zod.z.string().nullable(), - /** - * An array of all the plugins that are enabled for this prediction. - */ - enabledPluginInfos: zod.z.array(remotePluginInfoSchema), - /** Processing Context Identifier */ - pci: zod.z.string(), - token: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("abort"), - taskId: zod.z.string(), - }), - ]), - toServerPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("complete"), - taskId: zod.z.string(), - processed: chatMessageDataSchema, - }), - zod.z.object({ - type: zod.z.literal("aborted"), - taskId: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("error"), - taskId: zod.z.string(), - error: serializedLMSExtendedErrorSchema, - }), - ]), - }) - .addChannelEndpoint("setPredictionLoopHandler", { - creationParameter: zod.z.void(), - toClientPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("handlePredictionLoop"), - taskId: zod.z.string(), - config: kvConfigSchema, - pluginConfig: kvConfigSchema, - globalPluginConfig: kvConfigSchema, - workingDirectoryPath: zod.z.string().nullable(), - /** - * An array of all the plugins that are enabled for this prediction. - */ - enabledPluginInfos: zod.z.array(remotePluginInfoSchema), - /** Processing Context Identifier */ - pci: zod.z.string(), - token: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("abort"), - taskId: zod.z.string(), - }), - ]), - toServerPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("complete"), - taskId: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("aborted"), - taskId: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("error"), - taskId: zod.z.string(), - error: serializedLMSExtendedErrorSchema, - }), - ]), - }) - .addChannelEndpoint("setToolsProvider", { - creationParameter: zod.z.void(), - toClientPacket: zod.z.discriminatedUnion("type", [ - /** - * Starts a "tool providing session". Once this is received, the plugin should call the - * tools provider and pass the tools to the server using the `sessionInitialized` packet. - * - * If the initialization failed, the plugin should send the `sessionInitializationFailed` - * packet. - */ - zod.z.object({ - type: zod.z.literal("initSession"), - pluginConfig: kvConfigSchema, - globalPluginConfig: kvConfigSchema, - workingDirectoryPath: zod.z.string().nullable(), - sessionId: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("discardSession"), - sessionId: zod.z.string(), - }), - /** - * Call a tool within a session. The plugin should call the tool and return the result - * using the `toolCallComplete` packet. - * - * If the tool call fails in an unrecoverable way the plugin can send the `toolCallError` - * packet. - */ - zod.z.object({ - type: zod.z.literal("callTool"), - sessionId: zod.z.string(), - callId: zod.z.string(), - toolName: zod.z.string(), - parameters: jsonSerializableSchema, - }), - /** - * Abort a tool call. The plugin should abort the tool call and confirm the abort using - * the `toolCallAborted` packet. - */ - zod.z.object({ - type: zod.z.literal("abortToolCall"), - sessionId: zod.z.string(), - callId: zod.z.string(), - }), - ]), - toServerPacket: zod.z.discriminatedUnion("type", [ - /** - * The plugin has provided a list of tools in a new session. - */ - zod.z.object({ - type: zod.z.literal("sessionInitialized"), - sessionId: zod.z.string(), - toolDefinitions: zod.z.array(llmToolSchema), - }), - zod.z.object({ - type: zod.z.literal("sessionInitializationFailed"), - sessionId: zod.z.string(), - error: serializedLMSExtendedErrorSchema, - }), - zod.z.object({ - type: zod.z.literal("toolCallComplete"), - sessionId: zod.z.string(), - callId: zod.z.string(), - result: jsonSerializableSchema, - }), - zod.z.object({ - type: zod.z.literal("toolCallError"), - sessionId: zod.z.string(), - callId: zod.z.string(), - error: serializedLMSExtendedErrorSchema, - }), - zod.z.object({ - type: zod.z.literal("toolCallStatus"), - sessionId: zod.z.string(), - callId: zod.z.string(), - statusText: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("toolCallWarn"), - sessionId: zod.z.string(), - callId: zod.z.string(), - warnText: zod.z.string(), - }), - ]), - }) - .addChannelEndpoint("setGenerator", { - creationParameter: zod.z.void(), - toClientPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("generate"), - taskId: zod.z.string(), - input: chatHistoryDataSchema, - pluginConfig: kvConfigSchema, - globalPluginConfig: kvConfigSchema, - toolDefinitions: zod.z.array(llmToolSchema), - workingDirectoryPath: zod.z.string().nullable(), - }), - zod.z.object({ - type: zod.z.literal("abort"), - taskId: zod.z.string(), - }), - ]), - toServerPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("complete"), - taskId: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("aborted"), - taskId: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("error"), - taskId: zod.z.string(), - error: serializedLMSExtendedErrorSchema, - }), - zod.z.object({ - type: zod.z.literal("fragmentGenerated"), - taskId: zod.z.string(), - content: zod.z.string(), - opts: llmPredictionFragmentInputOptsSchema, - }), - zod.z.object({ - type: zod.z.literal("toolCallGenerationStarted"), - taskId: zod.z.string(), - toolCallId: zod.z.string().optional(), - }), - zod.z.object({ - type: zod.z.literal("toolCallGenerationNameReceived"), - taskId: zod.z.string(), - toolName: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("toolCallGenerationArgumentFragmentGenerated"), - taskId: zod.z.string(), - content: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("toolCallGenerationEnded"), - taskId: zod.z.string(), - toolCallRequest: toolCallRequestSchema, - }), - zod.z.object({ - type: zod.z.literal("toolCallGenerationFailed"), - taskId: zod.z.string(), - error: serializedLMSExtendedErrorSchema, - }), - ]), - }) - .addRpcEndpoint("processingHandleUpdate", { - parameter: zod.z.object({ - /** Processing Context Identifier */ - pci: zod.z.string(), - token: zod.z.string(), - update: processingUpdateSchema, - }), - returns: zod.z.void(), - }) - .addRpcEndpoint("processingHandleRequest", { - parameter: zod.z.object({ - /** Processing Context Identifier */ - pci: zod.z.string(), - token: zod.z.string(), - request: processingRequestSchema, - }), - returns: zod.z.object({ - response: processingRequestResponseSchema, - }), - }) - .addRpcEndpoint("processingPullHistory", { - parameter: zod.z.object({ - /** Processing Context Identifier */ - pci: zod.z.string(), - token: zod.z.string(), - includeCurrent: zod.z.boolean(), - }), - returns: chatHistoryDataSchema, - }) - .addRpcEndpoint("processingGetOrLoadTokenSource", { - parameter: zod.z.object({ - /** Processing Context Identifier */ - pci: zod.z.string(), - token: zod.z.string(), - }), - returns: zod.z.object({ - tokenSourceIdentifier: tokenSourceIdentifierSchema, - }), - }) - .addRpcEndpoint("processingHasStatus", { - parameter: zod.z.object({ - /** Processing Context Identifier */ - pci: zod.z.string(), - token: zod.z.string(), - }), - returns: zod.z.boolean(), - }) - .addRpcEndpoint("processingNeedsNaming", { - parameter: zod.z.object({ - /** Processing Context Identifier */ - pci: zod.z.string(), - token: zod.z.string(), - }), - returns: zod.z.boolean(), - }) - .addRpcEndpoint("processingSuggestName", { - parameter: zod.z.object({ - /** Processing Context Identifier */ - pci: zod.z.string(), - token: zod.z.string(), - name: zod.z.string(), - }), - returns: zod.z.void(), - }) - .addRpcEndpoint("processingSetSenderName", { - parameter: zod.z.object({ - /** Processing Context Identifier */ - pci: zod.z.string(), - token: zod.z.string(), - name: zod.z.string(), - }), - returns: zod.z.void(), - }) - .addRpcEndpoint("setConfigSchematics", { - parameter: zod.z.object({ - schematics: serializedKVConfigSchematicsSchema, - }), - returns: zod.z.void(), - }) - .addRpcEndpoint("setGlobalConfigSchematics", { - parameter: zod.z.object({ - schematics: serializedKVConfigSchematicsSchema, - }), - returns: zod.z.void(), - }) - .addRpcEndpoint("pluginInitCompleted", { - parameter: zod.z.void(), - returns: zod.z.void(), - })); -} - -function createRepositoryBackendInterface() { - return (new BackendInterface() - .addRpcEndpoint("searchModels", { - parameter: zod.z.object({ - opts: modelSearchOptsSchema, - }), - returns: zod.z.object({ - results: zod.z.array(modelSearchResultEntryDataSchema), - }), - }) - .addRpcEndpoint("getModelDownloadOptions", { - parameter: zod.z.object({ - modelSearchResultIdentifier: modelSearchResultIdentifierSchema, - }), - returns: zod.z.object({ - results: zod.z.array(modelSearchResultDownloadOptionDataSchema), - }), - }) - .addChannelEndpoint("downloadModel", { - creationParameter: zod.z.object({ - downloadIdentifier: zod.z.string(), - }), - toClientPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("downloadProgress"), - update: downloadProgressUpdateSchema, - }), - zod.z.object({ - type: zod.z.literal("startFinalizing"), - }), - zod.z.object({ - type: zod.z.literal("success"), - defaultIdentifier: zod.z.string(), - }), - ]), - toServerPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("cancel"), - }), - ]), - }) - /** - * Downloads one singular artifact at a certain revision. Ignore dependencies. - */ - .addChannelEndpoint("downloadArtifact", { - creationParameter: zod.z.object({ - artifactOwner: kebabCaseSchema, - artifactName: kebabCaseWithDotsSchema, - revisionNumber: zod.z.number().int().nullable(), - path: zod.z.string(), - }), - toClientPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("downloadProgress"), - update: downloadProgressUpdateSchema, - }), - zod.z.object({ - type: zod.z.literal("startFinalizing"), - }), - zod.z.object({ - type: zod.z.literal("success"), - }), - ]), - toServerPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("cancel"), - }), - ]), - }) - .addRpcEndpoint("installPluginDependencies", { - parameter: zod.z.object({ - pluginFolder: zod.z.string(), - }), - returns: zod.z.void(), - }) - /** - * Given the path to a local artifact folder, returns the list of files in that folder that - * would be pushed when invoking the pushArtifact endpoint. - */ - .addRpcEndpoint("getLocalArtifactFiles", { - parameter: zod.z.object({ - path: zod.z.string(), - }), - returns: zod.z.object({ - fileList: localArtifactFileListSchema, - }), - }) - .addChannelEndpoint("pushArtifact", { - creationParameter: zod.z.object({ - path: zod.z.string(), - description: zod.z.string().max(1000).optional(), - /** - * Request to make the artifact private. Only effective if the artifact did not exist - * before. Will not change the visibility of an existing artifact. - */ - makePrivate: zod.z.boolean().optional(), - /** - * If true, will write the revision number of the artifact after the push back to the - * artifact manifest.json. - */ - writeRevision: zod.z.boolean().optional(), - overrides: jsonSerializableSchema.optional(), - }), - toServerPacket: zod.z.void(), - toClientPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("message"), - message: zod.z.string(), - }), - ]), - }) - .addChannelEndpoint("ensureAuthenticated", { - creationParameter: zod.z.void(), - toServerPacket: zod.z.void(), - toClientPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("authenticationUrl"), - url: zod.z.string(), - }), - zod.z.object({ - type: zod.z.literal("authenticated"), - }), - ]), - }) - .addRpcEndpoint("loginWithPreAuthenticatedKeys", { - parameter: zod.z.object({ - keyId: zod.z.string(), - publicKey: zod.z.string(), - privateKey: zod.z.string(), - }), - returns: zod.z.object({ - userName: zod.z.string(), - }), - }) - /** - * Given the owner and name of an artifact, creates a download plan for the artifact. Throws - * an error is the artifact is not found. - */ - .addChannelEndpoint("createArtifactDownloadPlan", { - creationParameter: zod.z.object({ - owner: kebabCaseSchema, - name: kebabCaseWithDotsSchema, - }), - toServerPacket: zod.z.discriminatedUnion("type", [ - /** - * If called before committing the plan, the plan is aborted. If called after committing - * the plan, the download is canceled. - */ - zod.z.object({ - type: zod.z.literal("cancel"), - }), - /** - * Can only be called after plan ready. Once called, starts the plan. - */ - zod.z.object({ - type: zod.z.literal("commit"), - }), - ]), - toClientPacket: zod.z.discriminatedUnion("type", [ - zod.z.object({ - type: zod.z.literal("planUpdated"), - plan: artifactDownloadPlanSchema, - }), - zod.z.object({ - type: zod.z.literal("planReady"), - plan: artifactDownloadPlanSchema, - }), - zod.z.object({ - type: zod.z.literal("downloadProgress"), - update: downloadProgressUpdateSchema, - }), - zod.z.object({ - type: zod.z.literal("startFinalizing"), - }), - zod.z.object({ - type: zod.z.literal("success"), - }), - ]), - })); -} - -function createSystemBackendInterface() { - return (new BackendInterface() - .addRpcEndpoint("listDownloadedModels", { - parameter: zod.z.void(), - returns: zod.z.array(modelInfoSchema), - }) - .addChannelEndpoint("alive", { - creationParameter: zod.z.void(), - toServerPacket: zod.z.void(), - toClientPacket: zod.z.void(), - }) - .addRpcEndpoint("notify", { - parameter: backendNotificationSchema, - returns: zod.z.void(), - }) - /** - * Get the LM Studio version - */ - .addRpcEndpoint("version", { - parameter: zod.z.void(), - returns: zod.z.object({ - /** - * `major.minor.patch` - */ - version: zod.z.string(), - /** - * LM Studio build number - */ - build: zod.z.number(), - }), - }) - .addRpcEndpoint("setExperimentFlag", { - parameter: zod.z.object({ - code: zod.z.string(), - value: zod.z.boolean(), - }), - returns: zod.z.void(), - }) - .addRpcEndpoint("getExperimentFlags", { - parameter: zod.z.void(), - returns: zod.z.array(zod.z.string()), - }) - .addRpcEndpoint("startHttpServer", { - parameter: zod.z.object({ - port: zod.z.number().int().min(1).max(65535).optional(), - cors: zod.z.boolean().optional(), - }), - returns: zod.z.void(), - }) - .addRpcEndpoint("stopHttpServer", { - parameter: zod.z.void(), - returns: zod.z.void(), - })); -} - -function createAuthenticatedIpcTransportFactory(apiNamespace, hostedEnv, clientIdentifier, clientPasskey) { - const [onMessage, emitOnMessage] = BufferedEvent.create(); - const [onClose, emitOnClose] = BufferedEvent.create(); - const sendToServer = hostedEnv.getApiIpcTunnel(apiNamespace, { - authVersion: 1, - clientIdentifier: clientIdentifier, - clientPasskey: clientPasskey, - }, emitOnMessage, emitOnClose); - return GenericClientTransport.createFactory(onMessage, onClose, sendToServer); -} -function createAuthenticatedWsTransportFactory(apiNamespace, wsAddress, clientIdentifier, clientPasskey) { - return AuthenticatedWsClientTransport.createAuthenticatedWsClientTransportFactory({ - url: Promise.resolve(wsAddress).then(wsAddress => `${wsAddress}/${apiNamespace}`), - clientIdentifier: clientIdentifier, - clientPasskey: clientPasskey, - }); -} -function createAuthenticatedClientPort(backendInterface, wsAddress, apiNamespace, clientIdentifier, clientPasskey, logger, { errorDeserializer, verboseErrorMessage, } = {}) { - const hostedEnv = getHostedEnv(); - if (hostedEnv !== null) { - if (wsAddress !== undefined) { - logger.debug("Ignoring wsAddress parameter when constructing the client because the client is" + - " running in a hosted environment. This is not an error."); - } - return new ClientPort(backendInterface, createAuthenticatedIpcTransportFactory(apiNamespace, hostedEnv, clientIdentifier, clientPasskey), { parentLogger: logger, errorDeserializer, verboseErrorMessage }); - } - else { - return new ClientPort(backendInterface, createAuthenticatedWsTransportFactory(apiNamespace, wsAddress, clientIdentifier, clientPasskey), { parentLogger: logger, errorDeserializer, verboseErrorMessage }); - } -} - -/** @public */ -class DiagnosticsNamespace { - /** @internal */ - constructor(diagnosticsPort, validator, parentLogger) { - this.diagnosticsPort = diagnosticsPort; - this.validator = validator; - this.logger = new SimpleLogger("Diagnostics", parentLogger); - } - /** - * Register a callback to receive log events. Return a function to stop receiving log events. - * - * This method is in alpha. Do not use this method in production yet. - * @alpha - */ - unstable_streamLogs(listener) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("client.diagnostics", "unstable_streamLogs", "listener", zod.z.function(), listener, stack); - const channel = this.diagnosticsPort.createChannel("streamLogs", undefined, undefined, { - stack, - }); - const unsubscribe = channel.onMessage.subscribe(message => { - if (message.type === "log") { - listener(message.log); - } - }); - return () => { - unsubscribe(); - channel.send({ - type: "stop", - }); - }; - } -} - -function makeLoadModelOptsSchema(loadModelConfigSchema) { - return zod.z.object({ - identifier: zod.z.string().optional(), - config: loadModelConfigSchema.optional(), - signal: zod.z.instanceof(AbortSignal).optional(), - ttl: zod.z.number().optional(), - verbose: zod.z.union([zod.z.boolean(), logLevelSchema]).optional(), - onProgress: zod.z.function().optional(), - }); -} -/** - * Abstract namespace for namespaces that deal with models. - * - * @public - */ -class ModelNamespace { - /** @internal */ - getLoadModelOptsSchema() { - if (this.loadModelOptsSchema === null) { - this.loadModelOptsSchema = makeLoadModelOptsSchema(this.loadModelConfigSchema); - } - return this.loadModelOptsSchema; - } - /** @internal */ - constructor( - /** @internal */ - client, - /** @internal */ - port, - /** @internal */ - logger, - /** @internal */ - validator) { - this.client = client; - this.port = port; - this.logger = logger; - this.validator = validator; - /** @internal */ - this.loadModelOptsSchema = null; - } - /** - * Load a model for inferencing. The first parameter is the model key. The second parameter is an - * optional object with additional options. - * - * To find out what models are available, you can use the `lms ls` command, or programmatically - * use the `client.system.listDownloadedModels` method. - * - * Here are some examples: - * - * Loading Llama 3.2: - * - * ```typescript - * const model = await client.llm.load("llama-3.2-3b-instruct"); - * ``` - * - * Once loaded, see {@link LLMDynamicHandle} or {@link EmbeddingDynamicHandle} for how to use the - * model for inferencing or other things you can do with the model. - * - * @param modelKey - The path of the model to load. - * @param opts - Options for loading the model. - * @returns A promise that resolves to the model that can be used for inferencing - */ - async load(modelKey, opts = {}) { - const stack = getCurrentStack(1); - [modelKey, opts] = this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`, "load", ["modelKey", "opts"], [reasonableKeyStringSchema, this.getLoadModelOptsSchema()], [modelKey, opts], stack); - const { identifier, signal, verbose = "info", config, onProgress } = opts; - let lastVerboseCallTime = 0; - const { promise, resolve, reject } = makePromise(); - const verboseLevel = typeof verbose === "boolean" ? "info" : verbose; - const startTime = Date.now(); - if (verbose) { - this.logger.logAtLevel(verboseLevel, text ` - Verbose logging is enabled. To hide progress logs, set the "verbose" option to false in - client.llm.load. - `); - } - let fullPath = modelKey; - const channel = this.port.createChannel("loadModel", { - modelKey, - identifier, - ttlMs: opts.ttl === undefined ? undefined : opts.ttl * 1000, - loadConfigStack: singleLayerKVConfigStackOf("apiOverride", this.loadConfigToKVConfig(config ?? this.defaultLoadConfig)), - }, message => { - switch (message.type) { - case "resolved": { - fullPath = message.info.modelKey; - if (message.ambiguous !== undefined) { - this.logger.warn(text ` - Multiple models found for key ${modelKey}: - - ${message.ambiguous.map(x => ` - ${x}`).join("\n")} - - Using the first one. - `); - } - if (verbose) { - this.logger.logAtLevel(verboseLevel, text ` - Start loading model ${fullPath}... - `); - } - break; - } - case "success": { - if (verbose) { - this.logger.logAtLevel(verboseLevel, text ` - Successfully loaded model ${fullPath} in ${Date.now() - startTime}ms - `); - } - resolve(this.createDomainSpecificModel(this.port, message.info, this.validator, this.logger)); - break; - } - case "progress": { - const { progress } = message; - if (onProgress !== undefined) { - safeCallCallback(this.logger, "onProgress", onProgress, [progress]); - } - else if (verbose) { - const now = Date.now(); - if (now - lastVerboseCallTime > 500 || progress === 1) { - const progressText = (progress * 100).toFixed(1); - this.logger.logAtLevel(verboseLevel, `Loading the model, progress: ${progressText}%`); - lastVerboseCallTime = now; - } - } - } - } - }, { stack }); - channel.onError.subscribeOnce(reject); - if (signal !== undefined) { - if (signal.aborted) { - // If the signal is already aborted, we should reject immediately. - channel.send({ type: "cancel" }); - reject(signal.reason); - } - else { - signal.addEventListener("abort", () => { - channel.send({ type: "cancel" }); - reject(signal.reason); - }, { once: true }); - } - } - return await promise; - } - /** - * Unload a model. Once a model is unloaded, it can no longer be used. If you wish to use the - * model afterwards, you will need to load it with {@link LLMNamespace#loadModel} again. - * - * @param identifier - The identifier of the model to unload. - */ - unload(identifier) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow(`client.${this.namespace}`, "unload", "identifier", reasonableKeyStringSchema, identifier, stack); - return this.port.callRpc("unloadModel", { identifier }, { stack }); - } - /** - * List all the currently loaded models. - */ - async listLoaded() { - const stack = getCurrentStack(1); - const infos = await this.port.callRpc("listLoaded", undefined, { stack }); - return infos.map(info => this.createDomainSpecificModel(this.port, info, this.validator, this.logger)); - } - /** - * Get any loaded model of this domain. - */ - async getAny(stack) { - const info = await this.port.callRpc("getModelInfo", { specifier: { type: "query", query: {} }, throwIfNotFound: true }, { stack }); - if (info === undefined) { - throw new Error("Backend should have thrown."); - } - return this.createDomainSpecificModel(this.port, info, this.validator, new SimpleLogger("LLM", this.logger)); - } - createDynamicHandle(param) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow(`client.${this.namespace}`, "createDynamicHandle", "param", zod.z.union([reasonableKeyStringSchema, modelQuerySchema]), param, stack); - let query; - if (typeof param === "string") { - query = { - identifier: param, - }; - } - else { - query = param; - } - if (query.path?.includes("\\")) { - throw makePrettyError(text ` - Model path should not contain backslashes, even if you are on Windows. Use forward - slashes instead. - `, stack); - } - return this.createDomainDynamicHandle(this.port, { - type: "query", - query, - }, this.validator, new SimpleLogger("DynamicHandle", this.logger)); - } - /** - * Create a dynamic handle from the internal instance reference. - * - * @alpha - */ - createDynamicHandleFromInstanceReference(instanceReference) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow(`client.${this.namespace}`, "createDynamicHandleFromInstanceReference", "instanceReference", zod.z.string(), instanceReference, stack); - return this.createDomainDynamicHandle(this.port, { - type: "instanceReference", - instanceReference, - }, this.validator, new SimpleLogger("DynamicHandle", this.logger)); - } - async model(modelKey, opts = {}) { - const stack = getCurrentStack(1); - if (modelKey === undefined) { - // We want to get any loaded model. - return await this.getAny(stack); - } - [modelKey, opts] = this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`, "model", ["modelKey", "opts"], [reasonableKeyStringSchema, this.getLoadModelOptsSchema()], [modelKey, opts], stack); - const { identifier, signal, verbose = "info", config, onProgress } = opts; - if (identifier !== undefined) { - throw new Error("The identifier option is not allowed when using `.model`."); - } - let lastVerboseCallTime = 0; - const { promise, resolve, reject } = makePromise(); - const verboseLevel = typeof verbose === "boolean" ? "info" : verbose; - const startTime = Date.now(); - const channel = this.port.createChannel("getOrLoad", { - identifier: modelKey, - loadTtlMs: opts.ttl === undefined ? undefined : opts.ttl * 1000, - loadConfigStack: singleLayerKVConfigStackOf("apiOverride", this.loadConfigToKVConfig(config ?? this.defaultLoadConfig)), - }, message => { - switch (message.type) { - case "alreadyLoaded": { - return resolve(this.createDomainSpecificModel(this.port, message.info, this.validator, this.logger)); - } - case "unloadingOtherJITModel": { - if (verbose) { - this.logger.logAtLevel(verboseLevel, text ` - Unloading other JIT model ${message.info.modelKey}. (You can disable this behavior - by going to LM Studio -> Settings -> Developer -> Turn OFF JIT models auto-evict) - `); - } - break; - } - case "startLoading": { - if (verbose) { - this.logger.logAtLevel(verboseLevel, text ` - Verbose logging is enabled. To hide progress logs, set the "verbose" option to - false in .model(). - `); - this.logger.logAtLevel(verboseLevel, text ` - Model ${modelKey} is not loaded. Start loading... - `); - } - break; - } - case "loadProgress": { - const { progress } = message; - if (onProgress !== undefined) { - safeCallCallback(this.logger, "onProgress", onProgress, [progress]); - } - else if (verbose) { - const now = Date.now(); - if (now - lastVerboseCallTime > 500 || progress === 1) { - const progressText = (progress * 100).toFixed(1); - this.logger.logAtLevel(verboseLevel, `Loading the model, progress: ${progressText}%`); - lastVerboseCallTime = now; - } - } - break; - } - case "loadSuccess": { - if (verbose) { - this.logger.logAtLevel(verboseLevel, text ` - Successfully loaded model ${message.info.modelKey} in ${Date.now() - startTime}ms - `); - } - resolve(this.createDomainSpecificModel(this.port, message.info, this.validator, this.logger)); - } - } - }, { stack }); - channel.onError.subscribeOnce(reject); - signal?.addEventListener("abort", () => { - channel.send({ type: "cancel" }); - reject(signal.reason); - }); - return await promise; - } -} - -/** - * Translate a number to a checkbox numeric value. - * - * @param value - The value to translate. - * @param uncheckedValue - The value to use when the checkbox is unchecked. - * @param valueWhenUnchecked - The value to use when the checkbox is unchecked. - */ -function numberToCheckboxNumeric(value, uncheckedValue, valueWhenUnchecked) { - if (value === undefined) { - return undefined; - } - if (value === uncheckedValue) { - return { checked: false, value: valueWhenUnchecked }; - } - return { checked: true, value }; -} - -/** - * This represents a set of requirements for a model. It is not tied to a specific model, but rather - * to a set of requirements that a model must satisfy. - * - * For example, if you got the model via `client.llm.get("my-identifier")`, you will get a - * `LLMModel` for the model with the identifier `my-identifier`. If the model is unloaded, and - * another model is loaded with the same identifier, using the same `LLMModel` will use the new - * model. - * - * @public - */ -class DynamicHandle { - /** - * Don't construct this on your own. Use {@link LLMNamespace#get} or {@link LLMNamespace#load} - * instead. - * - * @internal - */ - constructor( - /** @internal */ - port, - /** @internal */ - specifier) { - this.port = port; - this.specifier = specifier; - } - /** - * Gets the information of the model that is currently associated with this `DynamicHandle`. If no - * model is currently associated, this will return `undefined`. - * - * Note: As models are loaded/unloaded, the model associated with this `LLMModel` may change at - * any moment. - */ - async getModelInfo() { - const info = await this.port.callRpc("getModelInfo", { specifier: this.specifier, throwIfNotFound: false }, { stack: getCurrentStack(1) }); - if (info === undefined) { - return undefined; - } - return info; - } - async getLoadConfig(stack) { - const loadConfig = await this.port.callRpc("getLoadConfig", { specifier: this.specifier }, { stack }); - return loadConfig; - } -} - -/** - * This represents a set of requirements for a model. It is not tied to a specific model, but rather - * to a set of requirements that a model must satisfy. - * - * For example, if you got the model via `client.embedding.get("my-identifier")`, you will get a - * `EmbeddingModel` for the model with the identifier `my-identifier`. If the model is unloaded, and - * another model is loaded with the same identifier, using the same `EmbeddingModel` will use the - * new model. - * - * @public - */ -class EmbeddingDynamicHandle extends DynamicHandle { - /** - * Don't construct this on your own. Use {@link EmbeddingNamespace#get} or - * {@link EmbeddingNamespace#load} - * instead. - * - * @internal - */ - constructor( - /** @internal */ - port, - /** @internal */ - specifier, - /** @internal */ - validator, - /** @internal */ - logger = new SimpleLogger(`EmbeddingModel`)) { - super(port, specifier); - this.validator = validator; - this.logger = logger; - } - async embed(inputString) { - const stack = getCurrentStack(1); - inputString = this.validator.validateMethodParamOrThrow("client.embedding", "embed", "inputString", zod.z.string().or(zod.z.array(zod.z.string())), inputString, stack); - if (Array.isArray(inputString)) { - return await Promise.all(inputString.map(s => this.port.callRpc("embedString", { inputString: s, modelSpecifier: this.specifier }, { stack }))); - } - else { - return await this.port.callRpc("embedString", { inputString, modelSpecifier: this.specifier }, { stack }); - } - } - async getContextLength() { - const stack = getCurrentStack(1); - const loadConfig = await this.getLoadConfig(stack); - return embeddingSharedLoadConfigSchematics.access(loadConfig, "contextLength"); - } - async getEvalBatchSize() { - const stack = getCurrentStack(1); - const loadConfig = await this.getLoadConfig(stack); - return globalConfigSchematics.access(loadConfig, "embedding.load.llama.evalBatchSize"); - } - async tokenize(inputString) { - const stack = getCurrentStack(1); - inputString = this.validator.validateMethodParamOrThrow("model", "tokenize", "inputString", zod.z.string().or(zod.z.array(zod.z.string())), inputString, stack); - if (Array.isArray(inputString)) { - return (await Promise.all(inputString.map(s => this.port.callRpc("tokenize", { specifier: this.specifier, inputString: s }, { stack })))).map(r => r.tokens); - } - else { - return (await this.port.callRpc("tokenize", { - specifier: this.specifier, - inputString, - }, { stack })).tokens; - } - } - async countTokens(inputString) { - const stack = getCurrentStack(1); - inputString = this.validator.validateMethodParamOrThrow("model", "countTokens", "inputString", zod.z.string(), inputString, stack); - return (await this.port.callRpc("countTokens", { - specifier: this.specifier, - inputString, - }, { stack })).tokenCount; - } -} - -/** - * Represents a specific loaded Embedding. Most Embedding related operations are inherited from - * {@link EmbeddingDynamicHandle}. - * - * @public - */ -class EmbeddingModel extends EmbeddingDynamicHandle { - /** @internal */ - constructor(embeddingPort, info, validator, logger = new SimpleLogger(`EmbeddingModel`)) { - const specifier = { - type: "instanceReference", - instanceReference: info.instanceReference, - }; - super(embeddingPort, specifier, validator, logger); - this.identifier = info.identifier; - this.path = info.path; - this.modelKey = info.modelKey; - this.format = info.format; - this.displayName = info.displayName; - this.sizeBytes = info.sizeBytes; - } - async unload() { - const stack = getCurrentStack(1); - await this.port.callRpc("unloadModel", { identifier: this.identifier }, { stack }); - } - async getModelInfo() { - const info = await super.getModelInfo(); - if (info === undefined) { - const stack = getCurrentStack(1); - throw makePrettyError("This model has already been unloaded", stack); - } - return info; - } -} - -/** @public */ -class EmbeddingNamespace extends ModelNamespace { - constructor() { - super(...arguments); - /** @internal */ - this.namespace = "embedding"; - /** @internal */ - this.defaultLoadConfig = {}; - /** @internal */ - this.loadModelConfigSchema = embeddingLoadModelConfigSchema; - } - /** @internal */ - loadConfigToKVConfig(config) { - return embeddingLlamaLoadConfigSchematics.buildPartialConfig({ - "llama.acceleration.offloadRatio": config.gpu?.ratio, - "load.gpuSplitConfig": convertGPUSettingToGPUSplitConfig(config.gpu), - "contextLength": config.contextLength, - "llama.ropeFrequencyBase": numberToCheckboxNumeric(config.ropeFrequencyBase, 0, 0), - "llama.ropeFrequencyScale": numberToCheckboxNumeric(config.ropeFrequencyScale, 0, 0), - "llama.keepModelInMemory": config.keepModelInMemory, - "llama.tryMmap": config.tryMmap, - }); - } - /** @internal */ - createDomainSpecificModel(port, info, validator, logger) { - return new EmbeddingModel(port, info, validator, logger); - } - /** @internal */ - createDomainDynamicHandle(port, specifier, validator, logger) { - return new EmbeddingDynamicHandle(port, specifier, validator, logger); - } -} - -const parseDocumentOptsSchema = documentParsingOptsSchema.extend({ - onProgress: zod.z.function().optional(), - signal: zod.z.instanceof(AbortSignal).optional(), -}); - -const retrievalCallbacksSchema = zod.z.object({ - onFileProcessList: zod.z.function().optional(), - onFileProcessingStart: zod.z.function().optional(), - onFileProcessingEnd: zod.z.function().optional(), - onFileProcessingStepStart: zod.z.function().optional(), - onFileProcessingStepProgress: zod.z.function().optional(), - onFileProcessingStepEnd: zod.z.function().optional(), - onSearchingStart: zod.z.function().optional(), - onSearchingEnd: zod.z.function().optional(), - verbose: zod.z.union([zod.z.boolean(), zod.z.string()]).optional(), -}); -const retrievalOptsSchema = zod.z.object({ - chunkingMethod: retrievalChunkingMethodSchema.optional(), - limit: zod.z.number().int().optional(), - embeddingModel: zod.z.instanceof(EmbeddingDynamicHandle).optional(), - databasePath: zod.z.string().optional(), - signal: zod.z.instanceof(AbortSignal).optional(), - ...retrievalCallbacksSchema.shape, -}); - -function getProcessingStepName(processingStep) { - switch (processingStep) { - case "loading": - return "Loading"; - case "chunking": - return "Chunking"; - case "embedding": - return "Embedding"; - default: { - const exhaustiveCheck = processingStep; - throw new Error(`Unexpected processing step: ${exhaustiveCheck}`); - } - } -} -/** - * @public - * - * The namespace for file-related operations. - */ -class FilesNamespace { - /** @internal */ - constructor( - /** @internal */ - filesPort, validator, parentLogger) { - this.filesPort = filesPort; - this.validator = validator; - this.logger = new SimpleLogger("File", parentLogger); - } - /** - * Gets the absolute path to a local file. - * - * @internal - */ - async getLocalFileAbsolutePath(fileName, stack) { - return await this.filesPort.callRpc("getLocalFileAbsolutePath", { fileName }, { stack }); - } - /** - * Creates a file handle from a chat message part file data. Used internally. - * - * @internal - */ - createFileHandleFromChatMessagePartFileData(data) { - return new FileHandle(this, data.identifier, data.fileType, data.sizeBytes, data.name); - } - /** - * Adds a temporary image to LM Studio, and returns a FileHandle that can be used to reference - * this image. This image will be deleted when the client disconnects. - * - * This method can only be used in environments that have file system access (such as Node.js). - */ - async prepareImage(path) { - const result = await lmsIsomorphic.readFileAsBase64(path); - if (result.success === false) { - throw new Error(text ` - Your current JavaScript environment does not support reading files. If you can read the file - using other methods, please use "prepareImageBase64". - `); - } - const fileName = path.split(/[\\/]/).at(-1); - const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", { - name: fileName, - contentBase64: result.base64, - }); - return new FileHandle(this, identifier, fileType, sizeBytes, fileName); - } - /** - * Adds a temporary image to LM Studio. The content of the file is specified using base64. If you - * are using Node.js and have a file laying around, consider using `prepareImage` instead. - */ - async prepareImageBase64(fileName, contentBase64) { - const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", { - name: fileName, - contentBase64, - }); - return new FileHandle(this, identifier, fileType, sizeBytes, fileName); - } - /** - * Adds a temporary file to LM Studio, and returns a FileHandle that can be used to reference this - * file. This file will be deleted when the client disconnects. - * - * This method can only be used in environments that have file system access (such as Node.js). - * - * @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for - * updates. - */ - async prepareFile(path) { - // Currently, exactly the same as prepareImage. - const result = await lmsIsomorphic.readFileAsBase64(path); - if (result.success === false) { - throw new Error(text ` - Your current JavaScript environment does not support reading files. If you can read the file - using other methods, please use "prepareFileBase64". - `); - } - const fileName = path.split(/[\\/]/).at(-1); - const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", { - name: fileName, - contentBase64: result.base64, - }); - return new FileHandle(this, identifier, fileType, sizeBytes, fileName); - } - /** - * Adds a temporary file to LM Studio. The content of the file is specified using base64. If you - * are using Node.js and have a file laying around, consider using `prepareFile` instead. - * - * @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for - * updates. */ - async prepareFileBase64(fileName, contentBase64) { - // Currently, exactly the same as prepareImageBase64. - const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", { - name: fileName, - contentBase64, - }); - return new FileHandle(this, identifier, fileType, sizeBytes, fileName); - } - /** - * @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for - * updates. */ - async retrieve(query, files, opts = {}) { - const logger = this.logger; - const stack = getCurrentStack(1); - this.validator.validateMethodParamsOrThrow("client.retrieval", "retrieve", ["query", "filePaths", "opts"], [zod.z.string(), zod.z.array(zod.z.instanceof(FileHandle)), retrievalOptsSchema], [query, files, opts], stack); - const { verbose = "info" } = opts; - const verboseLevel = typeof verbose === "boolean" ? "info" : verbose; - const shouldLog = verbose && - opts.onFileProcessList === undefined && - opts.onFileProcessingStart === undefined && - opts.onFileProcessingEnd === undefined && - opts.onFileProcessingStepStart === undefined && - opts.onFileProcessingStepProgress === undefined && - opts.onFileProcessingStepEnd === undefined && - opts.onSearchingStart === undefined && - opts.onSearchingEnd === undefined; - if (opts.embeddingModel === undefined) { - throw new Error("Embedding model currently is required."); - } - const resolveFileIndex = (index) => { - const file = files[index]; - if (file === undefined) { - throw new Error(`File not found: ${index}`); - } - return file; - }; - const resolveFileIndices = (indices) => { - return indices.map(resolveFileIndex); - }; - const kvConfig = retrievalSchematics.buildPartialConfig({ - chunkingMethod: opts.chunkingMethod, - databaseFile: opts.databasePath, - embeddingModel: (await opts.embeddingModel.getModelInfo())?.identifier, - limit: opts.limit, - }); - let filesToProcess; - const filesProcessingStartTimes = []; - let searchingStartTime = 0; - let lastVerboseCallTime = 0; - let lastVerboseLine = ""; - return await new Promise((resolve, reject) => { - const channel = this.filesPort.createChannel("retrieve", { query, fileIdentifiers: files.map(file => file.identifier), config: kvConfig }, message => { - switch (message.type) { - case "onFileProcessList": - filesToProcess = resolveFileIndices(message.indices); - safeCallCallback(logger, "onFileProcessList", opts.onFileProcessList, [ - filesToProcess, - ]); - if (shouldLog) { - logger.logAtLevel(verboseLevel, text ` - Found ${filesToProcess.length} files need processing: - ${filesToProcess.map(file => file.name).join(", ")} - `); - } - break; - case "onFileProcessingStart": { - if (filesToProcess === null) { - throw new Error("onFileProcessList must be called before onFileProcessingStart"); - } - const file = resolveFileIndex(message.index); - safeCallCallback(logger, "onFileProcessingStart", opts.onFileProcessingStart, [ - file, - filesToProcess.indexOf(file), - filesToProcess, - ]); - if (shouldLog) { - filesProcessingStartTimes[message.index] = Date.now(); - logger.logAtLevel(verboseLevel, text ` - Start processing file: ${file.name} - (${message.index + 1}/${filesToProcess.length}) - `); - } - break; - } - case "onFileProcessingEnd": { - if (filesToProcess === null) { - throw new Error("onFileProcessList must be called before onFileProcessingEnd"); - } - const file = resolveFileIndex(message.index); - safeCallCallback(logger, "onFileProcessingEnd", opts.onFileProcessingEnd, [ - file, - filesToProcess.indexOf(file), - filesToProcess, - ]); - if (shouldLog) { - logger.logAtLevel(verboseLevel, text ` - File processed: ${file.name}. - Time took: ${Date.now() - filesProcessingStartTimes[message.index]}ms - `); - } - break; - } - case "onFileProcessingStepStart": - safeCallCallback(logger, "onFileProcessingStepStart", opts.onFileProcessingStepStart, [resolveFileIndex(message.index), message.step]); - break; - case "onFileProcessingStepProgress": { - safeCallCallback(logger, "onFileProcessingStepProgress", opts.onFileProcessingStepProgress, [resolveFileIndex(message.index), message.step, message.progress]); - const now = Date.now(); - if (shouldLog && (now - lastVerboseCallTime > 500 || message.progress === 1)) { - lastVerboseCallTime = now; - const line = text ` - > ${getProcessingStepName(message.step)}: ${Math.round(message.progress * 100)}% - `; - if (lastVerboseLine !== line) { - lastVerboseLine = line; - logger.logAtLevel(verboseLevel, line); - } - } - break; - } - case "onFileProcessingStepEnd": - safeCallCallback(logger, "onFileProcessingStepEnd", opts.onFileProcessingStepEnd, [ - resolveFileIndex(message.index), - message.step, - ]); - break; - case "onSearchingStart": - safeCallCallback(logger, "onSearchingStart", opts.onSearchingStart, []); - if (shouldLog) { - searchingStartTime = Date.now(); - logger.logAtLevel(verboseLevel, "Start searching in the vector database..."); - } - break; - case "onSearchingEnd": - safeCallCallback(logger, "onSearchingEnd", opts.onSearchingEnd, []); - if (shouldLog) { - logger.logAtLevel(verboseLevel, text ` - Finished searching in the vector database. - Time took: ${Date.now() - searchingStartTime}ms - `); - } - break; - case "result": { - resolve({ - entries: message.result.entries.map(entry => ({ - content: entry.content, - score: entry.score, - source: files[entry.sourceIndex], - })), - }); - break; - } - } - }); - if (opts.signal !== undefined) { - if (opts.signal.aborted) { - reject(opts.signal.reason); - channel.send({ type: "stop" }); - } - else { - opts.signal?.addEventListener("abort", () => { - reject(opts.signal.reason); - channel.send({ type: "stop" }); - }); - } - } - channel.onError.subscribeOnce(reject); - }); - } - /** - * Parse a document - * - * @deprecated [DEP-DOC-PARSE] Document parsing API is still in active development. Stay tuned for - * updates. - */ - async parseDocument(fileHandle, opts = {}) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamsOrThrow("client.files", "parseDocument", ["fileHandle", "opts"], [zod.z.instanceof(FileHandle), parseDocumentOptsSchema], [fileHandle, opts], stack); - const { onParserLoaded, onProgress, signal, ...config } = opts; - const { promise, resolve, reject } = makePromise(); - opts.signal?.throwIfAborted(); - let finished = false; - const channel = this.filesPort.createChannel("parseDocument", { fileIdentifier: fileHandle.identifier, parseOpts: config }, message => { - const messageType = message.type; - switch (messageType) { - case "progress": { - safeCallCallback(this.logger, "onProgress", onProgress, [message.progress]); - break; - } - case "parserLoaded": { - safeCallCallback(this.logger, "onParserLoaded", onParserLoaded, [message.parser]); - break; - } - case "result": { - resolve({ - content: message.content, - parser: message.parser, - }); - finished = true; - break; - } - } - }, { stack }); - signal?.addEventListener("abort", () => { - if (finished) { - return; - } - reject(signal.reason); - channel.send({ type: "cancel" }); - }); - channel.onError.subscribeOnce(reject); - channel.onClose.subscribeOnce(() => { - if (!finished) { - reject(new Error("Channel closed before receiving a result.")); - } - }); - return await promise; - } - /** - * Get the parsing method for a document. - * - * @deprecated [DEP-DOC-PARSE] Document parsing API is still in active development. Stay tuned for - * updates. - */ - async getDocumentParsingLibrary(fileHandle) { - const stack = getCurrentStack(1); - return await this.filesPort.callRpc("getDocumentParsingLibrary", { fileIdentifier: fileHandle.identifier }, { stack }); - } -} - -function deserializeOtherError(serialized, stack) { - let content = chalk.redBright(` ${serialized.title} `); - if (serialized.suggestion !== undefined) { - content += - "\n\n\n " + - chalk.bgWhite.black(" (!) SUGGESTION ") + - "\n\n" + - chalk.white(serialized.suggestion); - } - if (serialized.cause !== undefined) { - content += - "\n\n\n " + chalk.bgWhite.black(" (X) CAUSE ") + "\n\n" + chalk.gray(serialized.cause); - } - return makePrettyError(content, stack); -} -const errorDeserializersMap = new Map(); -function registerErrorDeserializer(code, deserializer) { - errorDeserializersMap.set(code, deserializer); -} -function formatAvailableLLMs(availablePathsSample, totalModels) { - if (availablePathsSample.length === 0) { - return chalk.gray(" You don't have any LLMs downloaded."); - } - let text = availablePathsSample.map(path => chalk.cyanBright(" • " + path)).join("\n"); - if (availablePathsSample.length < totalModels) { - text += chalk.gray(`\n ... (and ${totalModels - availablePathsSample.length} more)`); - } - return text; -} -registerErrorDeserializer("generic.pathNotFound", ({ availablePathsSample, path, totalModels }, stack) => { - return makeTitledPrettyError(`Cannot find a model with path "${chalk.yellowBright(path)}"`, text ` - Here are your available models: - - ${formatAvailableLLMs(availablePathsSample, totalModels)} - - Run - - ${chalk.yellowBright("lms ls")} - - to see a full list of loadable models - `, stack); -}); -function formatLoadedModels(loadedModelsSample, totalLoadedModels) { - if (loadedModelsSample.length === 0) { - return chalk.gray(" You don't have any models loaded."); - } - let text = loadedModelsSample.map(path => chalk.cyanBright(" • " + path)).join("\n"); - if (loadedModelsSample.length < totalLoadedModels) { - text += chalk.gray(`\n ... (and ${totalLoadedModels - loadedModelsSample.length} more)`); - } - return text; -} -registerErrorDeserializer("generic.identifierNotFound", ({ loadedModelsSample, identifier, totalLoadedModels }, stack) => { - return makeTitledPrettyError(`Cannot find a model with identifier "${chalk.yellowBright(identifier)}"`, text ` - Here are your loaded models: - - ${formatLoadedModels(loadedModelsSample, totalLoadedModels)} - - Run - - ${chalk.yellowBright("lms ps")} - - to see a full list of loaded models - `, stack); -}); -registerErrorDeserializer("generic.specificModelUnloaded", (_, stack) => { - return makePrettyError(chalk.bgRed.white(text ` - This model has already been unloaded. - `), stack); -}); -function getModelDomainTypeDisplayNameSingular(domain) { - switch (domain) { - case "llm": - return "an LLM"; - case "embedding": - return "an embedding model"; - case "imageGen": - return "an image generation model"; - case "transcription": - return "a transcription model"; - case "tts": - return "a text-to-speech model"; - default: { - const exhaustiveCheck = domain; - console.error(`Unexpected domain type: ${exhaustiveCheck}`); - return "Unknown Model Domain"; - } - } -} -function formatQuery(query) { - const requirements = []; - if (query.domain !== undefined) { - requirements.push(text ` - The model must be ${chalk.yellowBright(getModelDomainTypeDisplayNameSingular(query.domain))} - `); - } - if (query.identifier !== undefined) { - requirements.push(`The identifier must be exactly "${chalk.yellowBright(query.identifier)}"`); - } - if (query.path !== undefined) { - requirements.push(`The path must match "${chalk.yellowBright(query.path)}"`); - } - if (requirements.length === 0) { - return chalk.gray(" • Any Model"); - } - return requirements.map(req => chalk.white(" • " + req)).join("\n"); -} -registerErrorDeserializer("generic.noModelMatchingQuery", ({ loadedModelsSample, totalLoadedModels, query }, stack) => { - return makePrettyError(text ` - ${chalk.bgRed.white(" No loaded model satisfies all requirements specified in the query. ")} - - Loaded Models: - - ${formatLoadedModels(loadedModelsSample, totalLoadedModels)} - - Your query: - - ${formatQuery(query)} - - Run - - ${chalk.yellowBright("lms ps")} - - to see a full list of loaded models with details - `, stack); -}); -registerErrorDeserializer("generic.domainMismatch", ({ actualDomain, expectedDomain, path }, stack) => { - return makePrettyError(text ` - ${chalk.bgRed.white(" Model has wrong domain. ")} - - Expecting ${chalk.greenBright(path)} to be ${chalk.yellowBright(getModelDomainTypeDisplayNameSingular(expectedDomain))}, but it is actually ${chalk.yellowBright(getModelDomainTypeDisplayNameSingular(actualDomain))}. - `, stack); -}); -function formatAvailablePresets(presets, totalAvailablePresets) { - if (presets.length === 0) { - return chalk.gray(" You don't have any presets available."); - } - let text = presets - .map(({ identifier, name }) => chalk.cyanBright(` • ${name} (${chalk.cyan(identifier)})`)) - .join("\n"); - if (presets.length < totalAvailablePresets) { - text += chalk.gray(`\n ... (and ${totalAvailablePresets - presets.length} more)`); - } - return text; -} -registerErrorDeserializer("generic.presetNotFound", ({ specifiedFuzzyPresetIdentifier, availablePresetsSample, totalAvailablePresets }) => { - return makeTitledPrettyError(`Cannot find a preset with identifier "${chalk.yellowBright(specifiedFuzzyPresetIdentifier)}"`, text ` - Here are your available presets: - - ${formatAvailablePresets(availablePresetsSample, totalAvailablePresets)} - - Note: To specify a preset in the SDK, you need to use its identifier (in parentheses). You - can get a preset's identifier by right-clicking on it and then select "Copy Preset - Identifier". - `); -}); -function friendlyErrorDeserializer(serialized, _directCause, stack) { - if (serialized.displayData === undefined) { - return deserializeOtherError(serialized, stack); - } - let error; - const specificDeserializer = errorDeserializersMap.get(serialized.displayData.code); - if (specificDeserializer !== undefined) { - error = specificDeserializer(serialized.displayData, stack); - attachSerializedErrorData(error, serialized); - return error; - } - else { - return deserializeOtherError(serialized, stack); - } -} - -function cacheQuantizationTypeToCheckbox({ value, falseDefault, }) { - return value === undefined - ? undefined - : value === false - ? { checked: false, value: falseDefault } - : { checked: true, value: value }; -} - -/** - * Represents the result of running `llm.act`. Currently only contains minimum amount of - * information. - * - * If you think more information/fields should be added, please open an issue or a PR on GitHub. - * - * @public - */ -class ActResult { - constructor( - /** - * Number of rounds performed. - * - * For example, in the following scenario: - * - * - User asks the model to add 1234 and 5678. - * - The model requests to use a calculator tool. - * - The calculator tool outputs 6912. - * - The calculator's output is then fed back to the model for a second round of prediction. - * - The model sees the output and generates a paragraph explaining the result. - * - * There are 2 rounds. On the beginning of a round, the callback `onRoundStart` is triggered. - * On the end of a round, the callback `onRoundEnd` is triggered. - */ - rounds, - /** - * Total time taken to run `.act` in seconds. measured from beginning of the `.act` invocation - * to when the entire operation is finished. - */ - totalExecutionTimeSeconds) { - this.rounds = rounds; - this.totalExecutionTimeSeconds = totalExecutionTimeSeconds; - } -} - -/** - * Each call uses a globally unique call ID that starts somewhere before the half of the - * `Number.MAX_SAFE_INTEGER`. - */ -const callIdGiver = new IdGiver(Math.floor(Math.random() * (Number.MAX_SAFE_INTEGER / 2 / 10000)) * 10000); -class NoQueueQueue { - needsQueueing() { - return false; - } - async runInQueue(fn, signal) { - if (signal?.aborted) { - throw new Error("Operation aborted"); - } - return fn(); - } -} -class FIFOQueue { - constructor() { - this.queue = []; - this.executing = false; - this.poisoned = false; - this.poisonError = null; - } - needsQueueing() { - return this.executing || this.queue.length > 0; - } - async runInQueue(fn, signal) { - // Check if the operation is already aborted - if (signal?.aborted) { - throw new Error("Operation aborted"); - } - // If the queue is poisoned, fail immediately with the saved error - if (this.poisoned) { - throw this.poisonError ?? new Error("Queue has been poisoned by a previous error"); - } - if (!this.needsQueueing()) { - // If nothing is in the queue, execute immediately - this.executing = true; - try { - // Check for abort before execution - if (signal?.aborted) { - throw new Error("Operation aborted"); - } - return await fn(); - } - catch (error) { - // Poison the queue - this.poisoned = true; - this.poisonError = error; - // Clear the queue since nothing will run after this - this.clearQueue(error); - throw error; - } - finally { - this.executing = false; - this.processQueue(); - } - } - // Otherwise, add to queue and wait for execution - return new Promise((resolve, reject) => { - // Add abort listener if a signal was provided - if (signal) { - if (signal.aborted) { - return reject(new Error("Operation aborted")); - } - signal.addEventListener("abort", () => { - // Remove from queue if it hasn't started yet - const index = this.queue.findIndex(item => item.resolve === resolve && item.reject === reject); - if (index !== -1) { - this.queue.splice(index, 1); - reject(new Error("Operation aborted")); - } - }, { once: true }); - } - this.queue.push({ - fn: async () => { - try { - // Check for abort before execution - if (signal?.aborted) { - throw new Error("Operation aborted"); - } - const result = await fn(); - resolve(result); - return result; - } - catch (error) { - reject(error); - throw error; - } - }, - resolve, - reject, - signal, - }); - }); - } - async processQueue() { - if (this.executing || this.queue.length === 0 || this.poisoned) { - return; - } - const nextItem = this.queue.shift(); - if (!nextItem) - return; - // Skip if this task has been aborted - if (nextItem.signal?.aborted) { - nextItem.reject(new Error("Operation aborted")); - this.processQueue(); - return; - } - this.executing = true; - try { - await nextItem.fn(); - } - catch (error) { - // Poison the queue - this.poisoned = true; - this.poisonError = error; - // Clear the queue since nothing will run after this - this.clearQueue(error); - } - finally { - this.executing = false; - // Only continue processing if not poisoned - if (!this.poisoned) { - this.processQueue(); - } - } - } - clearQueue(error) { - // Reject all pending promises in the queue - for (const item of this.queue) { - item.reject(error); - } - this.queue = []; - } -} -/** - * Controller object used to allow/modify/deny a tool call. - */ -class GuardToolCallController { - /** - * Don't construct this object yourself. - */ - constructor(toolCallRequest, tool, resultContainer) { - this.toolCallRequest = toolCallRequest; - this.tool = tool; - this.resultContainer = resultContainer; - /** - * Allows the tool call to proceed without any modifications. - */ - this.allow = () => { - this.assertNoResultYet("allow", getCurrentStack(1)); - this.resultContainer[0] = { type: "allow" }; - }; - /** - * Allows the tool call to proceed, but overrides the parameters with the provided ones. - */ - this.allowAndOverrideParameters = (newParameters) => { - this.assertNoResultYet("allowAndOverrideParameters", getCurrentStack(1)); - this.resultContainer[0] = { type: "allowAndOverrideParameters", parameters: newParameters }; - }; - /** - * Denys the tool call with a specified reason. This will not interrupt the `.act` call. Instead, - * the reason you provide will be provided to the model as the tool call result. - * - * If `reason` is not provided, a generic default reason will be used. - * - * If you wish to immediately fail the `.act` call, you can throw an error instead. - */ - this.deny = (reason) => { - this.assertNoResultYet("deny", getCurrentStack(1)); - this.resultContainer[0] = { type: "deny", reason }; - }; - } - assertNoResultYet(calledMethodName, stack) { - if (this.resultContainer[0] === null) { - return; - } - // Oh no, the result has already been set! Make an error message. - throw makeTitledPrettyError(`Cannot call ${calledMethodName} after a result has been set`, text ` - This tool call guard has already set a result previously (${this.resultContainer[0].type}). - You cannot set a result more than once. - `, stack); - } -} -const llmActBaseOptsSchema = zod.z.object({ - onFirstToken: zod.z.function().optional(), - onPredictionFragment: zod.z.function().optional(), - onMessage: zod.z.function().optional(), - onRoundStart: zod.z.function().optional(), - onRoundEnd: zod.z.function().optional(), - onPredictionCompleted: zod.z.function().optional(), - onPromptProcessingProgress: zod.z.function().optional(), - onToolCallRequestStart: zod.z.function().optional(), - onToolCallRequestNameReceived: zod.z.function().optional(), - onToolCallRequestArgumentFragmentGenerated: zod.z.function().optional(), - onToolCallRequestEnd: zod.z.function().optional(), - onToolCallRequestFinalized: zod.z.function().optional(), - onToolCallRequestFailure: zod.z.function().optional(), - onToolCallRequestDequeued: zod.z.function().optional(), - guardToolCall: zod.z.function().optional(), - handleInvalidToolRequest: zod.z.function().optional(), - maxPredictionRounds: zod.z.number().int().min(1).optional(), - signal: zod.z.instanceof(AbortSignal).optional(), - allowParallelToolExecution: zod.z.boolean().optional(), -}); -const defaultHandleInvalidToolRequest = (error, request) => { - if (request) { - return error.message; - } - throw error; -}; -/** - * The internal method for performing .act(). This is used by both `LLMDynamicHandle` and - * `LLMGeneratorHandle`. - * - * @param TPredictionResult - The type of the prediction result. - * @param TEndPacket - The type of the success packet that is returned. This type is received from - * `handlePredictionEnd` and is passed to the `makePredictionResult` function to create the - * `TPredictionResult`. - * @param chat - The chat to use for the prediction. - * @param tools - The tools to use for the prediction. This is an array of tools that the model can - * use during the prediction. - * @param baseOpts - The base options for the prediction. This includes callbacks and other - * options that control the prediction process. - * @param stack - The stack trace to use for the prediction. This is used for generating errors. - * @param logger - The logger to use for the prediction. This is used for logging messages during - * the prediction. - * @param startTime - The start time of the prediction. This is used to calculate the duration of - * the act. - * @param predictImpl - The implementation of the prediction. This is a function that takes the - * prediction arguments and performs the prediction. This is the main abstraction - `internalAct` - * performs the prediction loop while this function handles the actual prediction itself. - * @param makePredictionResult - A function that takes the end packet and the content of the - * prediction and creates the `TPredictionResult`. This is used to create the prediction result - * object for each round of the prediction. - */ -async function internalAct(chat, tools, baseOpts, stack, logger, startTime, predictImpl, makePredictionResult) { - const abortController = new AbortController(); - const mutableChat = Chat.from(chat); // Make a copy - let currentCallId = -1; - /** - * A flag that will be set if any unimplemented tool is called. In which case, the loop will - * terminate after all the parallel tool calls are resolved. - */ - let hasCalledUnimplementedTool = false; - if (baseOpts.signal !== undefined) { - if (baseOpts.signal.aborted) { - // If the signal is already aborted, we should not continue. - abortController.abort(baseOpts.signal.reason); - } - else { - baseOpts.signal.addEventListener("abort", () => { - abortController.abort(baseOpts.signal?.reason); - }, { once: true }); - } - } - let shouldContinue = false; - let predictionsPerformed = 0; - const toolsMap = new Map(); - for (const tool of tools) { - if (toolsMap.has(tool.name)) { - logger.warnText ` - Duplicate tool (${tool.name}) found in the tools array. The last tool with the same name - will be used. - `; - } - toolsMap.set(tool.name, tool); - } - do { - // Main loop - execute as many times as the model requests tools - let allowTools = true; - if ( - // If there is a defined number of max predictions, - baseOpts.maxPredictionRounds !== undefined && - // ... and this is the last chance to perform predictions, don't allow the model to use - // tools. - predictionsPerformed + 1 >= baseOpts.maxPredictionRounds) { - allowTools = false; - } - // Start the prediction - let finished = false; - let firstTokenTriggered = false; - const contentArray = []; - const reasoningContentArray = []; - const nonReasoningContentArray = []; - const toolCallRequests = []; - let nextToolCallIndex = 0; - const toolCallResults = []; - /** - * All promises that need to be awaited. Once they are done, they will add their own results - * to the toolCallResults array in-place. - */ - const toolCallPromises = []; - /** - * The promise that represents the prediction itself (The RPC call). - */ - const { promise: predictionPromise, resolve: predictionResolve, reject: predictionReject, } = makePromise(); - /** - * The final promise that will be awaited on for this prediction. It is resolved when the - * prediction is done and all tool calls have been resolved. - */ - const { promise: finalPromise, resolve: finalResolve, reject: finalReject, } = makePromise(); - const internalHandleInvalidToolCallRequest = async (error, request, - /** - * In the case this tool call got a replacement, the index to use. - */ - toolCallIndex) => { - let result; - try { - result = await (baseOpts.handleInvalidToolRequest ?? defaultHandleInvalidToolRequest)(error, request); - } - catch (error) { - if (abortController.signal.aborted) { - throw abortController.signal.reason; - } - abortController.abort(); - throw error; // Rethrow the error. - } - if (result === undefined) { - // No replacement. - return; - } - let resultString; - try { - resultString = JSON.stringify(result); - } - catch (error) { - abortController.abort(); - throw makePrettyError("handleInvalidToolRequest returned a value that cannot be converted to JSON.", stack); - } - // The handleInvalidToolRequest has returned a "replacement" - if (request === undefined) { - // We cannot provide a result to a tool call that has failed to parse. - logger.warnText ` - The "handleInvalidToolRequest" callback has returned a result, but the tool request has - completely failed to parse, thus LM Studio cannot provide the result to the tool call. - Please avoid returning a result when the second parameter of the callback is undefined. - See the documentation for "handleInvalidToolRequest" for more information. - `; - } - else { - toolCallResults.push({ - index: toolCallIndex, - data: { - type: "toolCallResult", - toolCallId: request.id, - content: resultString, - }, - }); - nextToolCallIndex++; - } - }; - abortController.signal.throwIfAborted(); - // Round start callback - safeCallCallback(logger, "onRoundStart", baseOpts.onRoundStart, [predictionsPerformed]); - let isGeneratingToolCall = false; - /** - * Abort controller for the current round. - */ - const roundAbortController = new AbortController(); - const queue = baseOpts.allowParallelToolExecution - ? new NoQueueQueue() - : new FIFOQueue(); - let receivedEagerToolNameReporting = false; - let receivedToolArgumentsStreaming = false; - predictImpl({ - allowTools, - history: accessMaybeMutableInternals(mutableChat)._internalGetData(), - signal: roundAbortController.signal, - handleFragment: fragment => { - if (!firstTokenTriggered) { - firstTokenTriggered = true; - safeCallCallback(logger, "onFirstToken", baseOpts.onFirstToken, [predictionsPerformed]); - } - safeCallCallback(logger, "onFragment", baseOpts.onPredictionFragment, [ - { roundIndex: predictionsPerformed, ...fragment }, - ]); - contentArray.push(fragment.content); - if (!fragment.isStructural) { - if (fragment.reasoningType === "reasoning") { - reasoningContentArray.push(fragment.content); - } - else { - nonReasoningContentArray.push(fragment.content); - } - } - }, - handlePromptProcessingProgress: progress => { - safeCallCallback(logger, "onPromptProcessingProgress", baseOpts.onPromptProcessingProgress, [predictionsPerformed, progress]); - }, - handleToolCallGenerationStart: toolCallId => { - currentCallId = callIdGiver.next(); - receivedEagerToolNameReporting = false; - receivedToolArgumentsStreaming = false; - isGeneratingToolCall = true; - safeCallCallback(logger, "onToolCallRequestStart", baseOpts.onToolCallRequestStart, [ - predictionsPerformed, - currentCallId, - { toolCallId: toolCallId }, - ]); - }, - handleToolCallGenerationNameReceived: name => { - receivedEagerToolNameReporting = true; - safeCallCallback(logger, "onToolCallRequestNameReceived", baseOpts.onToolCallRequestNameReceived, [predictionsPerformed, currentCallId, name]); - }, - handleToolCallGenerationArgumentFragmentGenerated: content => { - receivedToolArgumentsStreaming = true; - safeCallCallback(logger, "onToolCallRequestArgumentFragmentGenerated", baseOpts.onToolCallRequestArgumentFragmentGenerated, [predictionsPerformed, currentCallId, content]); - }, - handleToolCallGenerationEnd: (request, rawContent) => { - const callId = currentCallId; - isGeneratingToolCall = false; - const toolCallIndex = nextToolCallIndex; - nextToolCallIndex++; - if (!receivedEagerToolNameReporting) { - // If eager name reporting not received, report it. - safeCallCallback(logger, "onToolCallRequestNameReceived", baseOpts.onToolCallRequestNameReceived, [predictionsPerformed, callId, request.name]); - } - if (!receivedToolArgumentsStreaming) { - // If arguments streaming not received, just pretend we have received all the arguments - // as a single JSON - safeCallCallback(logger, "onToolCallRequestArgumentFragmentGenerated", baseOpts.onToolCallRequestArgumentFragmentGenerated, [predictionsPerformed, callId, JSON.stringify(request.arguments ?? {}, null, 2)]); - } - const pushedRequest = { ...request }; - // We have now received a tool call request. Now let's see if we can call the tool and - // get the result. - toolCallRequests.push(pushedRequest); - const tool = toolsMap.get(request.name); - if (tool === undefined) { - // Tool does not exist. - const toolCallRequestError = new ToolCallRequestError(`Cannot find tool with name ${request.name}.`, rawContent); - toolCallPromises.push(internalHandleInvalidToolCallRequest(toolCallRequestError, request, toolCallIndex).catch(finalReject)); - safeCallCallback(logger, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [ - predictionsPerformed, - callId, - toolCallRequestError, - ]); - return; - } - // Try check the parameters: - try { - tool.checkParameters(pushedRequest.arguments); // Defaults to empty object - } - catch (error) { - // Failed to parse the parameters - const toolCallRequestError = new ToolCallRequestError(error.message, rawContent); - toolCallPromises.push(internalHandleInvalidToolCallRequest(toolCallRequestError, request, toolCallIndex).catch(finalReject)); - safeCallCallback(logger, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [ - predictionsPerformed, - callId, - toolCallRequestError, - ]); - return; - } - const toolCallContext = new SimpleToolCallContext(new SimpleLogger(`Tool(${request.name})`, logger), abortController.signal, callId); - const isQueued = queue.needsQueueing(); - safeCallCallback(logger, "onToolCallRequestEnd", baseOpts.onToolCallRequestEnd, [ - predictionsPerformed, - callId, - { - isQueued, - toolCallRequest: request, - rawContent, - }, - ]); - // We have successfully parsed the parameters. Let's call the tool. - toolCallPromises.push(queue - .runInQueue(async () => { - // Emit the dequeued event if the tool call was queued. - if (isQueued) { - safeCallCallback(logger, "onToolCallRequestDequeued", baseOpts.onToolCallRequestDequeued, [predictionsPerformed, callId]); - } - // Guard the tool call if have a tool call guard. - if (baseOpts.guardToolCall !== undefined) { - const resultContainer = [null]; - await baseOpts.guardToolCall(predictionsPerformed, callId, new GuardToolCallController(request, tool, resultContainer)); - if (resultContainer[0] === null) { - // The guard did not return anything, thus we will report this error. - throw makeTitledPrettyError("Tool call guard did not allow or deny the tool call.", text ` - The \`guardToolCall\` handler must call one of the methods on the controller - to allow or deny the tool call. - `, stack); - } - const guardResult = resultContainer[0]; - const guardResultType = guardResult.type; - switch (guardResultType) { - case "allow": { - // 1. The guard allowed the tool call without overriding the parameters. In this - // case, we will use the original parameters. - break; - } - case "allowAndOverrideParameters": { - // 2. The guard allowed the tool call and provided new parameters. In this case, - // we will use the new parameters. This will update the request in-place. - pushedRequest.arguments = guardResult.parameters; - break; - } - case "deny": { - // 3. The guard denied the tool call. In this case, we will early return and not - // call the tool. - toolCallResults.push({ - index: toolCallIndex, - data: { - type: "toolCallResult", - toolCallId: request.id, - content: JSON.stringify({ - error: guardResult.reason, - }), - }, - }); - return; - } - } - } - // Now we need to call RequestFinalized - safeCallCallback(logger, "onToolCallRequestFinalized", baseOpts.onToolCallRequestFinalized, [ - predictionsPerformed, - callId, - { - toolCallRequest: request, - rawContent, - }, - ]); - let result; - try { - result = await tool.implementation(pushedRequest.arguments ?? {}, toolCallContext); - } - catch (error) { - if (!(error instanceof UnimplementedToolError)) { - throw error; - } - hasCalledUnimplementedTool = true; - } - let resultString; - if (result === undefined) { - resultString = "undefined"; - } - else { - try { - resultString = JSON.stringify(result); - } - catch (error) { - throw makePrettyError(`Return value of tool ${tool.name} cannot be converted to JSON.`, stack); - } - } - toolCallResults.push({ - index: toolCallIndex, - data: { - type: "toolCallResult", - toolCallId: request.id, - content: resultString, - }, - }); - }, abortController.signal) - .catch(finalReject)); - }, - handleToolCallGenerationFailed: (error, rawContent) => { - isGeneratingToolCall = false; - const toolCallRequestError = new ToolCallRequestError(error.message, rawContent); - toolCallPromises.push(internalHandleInvalidToolCallRequest(toolCallRequestError, - // We don't have a request in this because the model has failed miserably. - undefined, - // Tool call index. Doesn't matter because if there is no request, there cannot be - // a replacement. - 0).catch(finalReject)); - safeCallCallback(logger, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [ - predictionsPerformed, - currentCallId, - toolCallRequestError, - ]); - }, - handlePredictionEnd: endPacket => { - const predictionResult = makePredictionResult({ - endPacket, - content: contentArray.join(""), - reasoningContent: reasoningContentArray.join(""), - nonReasoningContent: nonReasoningContentArray.join(""), - predictionsPerformed, - }); - safeCallCallback(logger, "onPredictionCompleted", baseOpts.onPredictionCompleted, [ - predictionResult, - ]); - predictionResolve(); - }, - handleError: error => { - if (isGeneratingToolCall) { - const toolCallRequestError = new ToolCallRequestError(`Generation failed: ${error.message}`, undefined); - // Notify tool call generation failure. - isGeneratingToolCall = false; - safeCallCallback(logger, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [ - predictionsPerformed, - currentCallId, - toolCallRequestError, - ]); - } - finished = true; - predictionReject(error); - }, - }); - const abortListener = () => { - if (finished) { - return; - } - finished = true; - roundAbortController.abort(abortController.signal.reason); - }; - abortController.signal.addEventListener("abort", abortListener); - predictionPromise - .then(() => { - // Append and emit the assistant message. - const assistantMessage = ChatMessage.from({ - role: "assistant", - content: [ - { - type: "text", - text: contentArray.join(""), - }, - ...toolCallRequests.map(toolCallRequest => ({ - type: "toolCallRequest", - toolCallRequest, - })), - ], - }); - mutableChat.append(assistantMessage.asMutableCopy()); - safeCallCallback(logger, "onMessage", baseOpts.onMessage, [assistantMessage]); - }) - // When the prediction is completed, wait for all tool calls to be completed. - .then(() => Promise.all(toolCallPromises)) - .then(() => finalResolve(), finalReject); - await finalPromise; - shouldContinue = false; - if (toolCallResults.length > 0) { - // Sort the tool call results back into the order they were requested. - toolCallResults.sort((a, b) => a.index - b.index); - // Emit the tool call results. - const toolMessage = ChatMessage.from({ - role: "tool", - content: toolCallResults.map(r => r.data), - }); - mutableChat.append(toolMessage.asMutableCopy()); - safeCallCallback(logger, "onMessage", baseOpts.onMessage, [toolMessage]); - shouldContinue = true; - } - safeCallCallback(logger, "onRoundEnd", baseOpts.onRoundEnd, [predictionsPerformed]); - predictionsPerformed++; - // Don't continue if we've reached the max predictions. - if (baseOpts.maxPredictionRounds !== undefined && - predictionsPerformed >= baseOpts.maxPredictionRounds) { - shouldContinue = false; - } - shouldContinue &&= !hasCalledUnimplementedTool; // Stop loop if unimplemented tool was called. - } while (shouldContinue); - return new ActResult(predictionsPerformed, (performance.now() - startTime) / 1_000); -} - -/** - * Represents the result of an LLM prediction. - * - * The most notably property is {@link PredictionResult#content}, which contains the generated text. - * Additionally, the {@link PredictionResult#stats} property contains statistics about the - * prediction. - * - * @public - */ -class PredictionResult { - constructor( - /** - * The newly generated text as predicted by the LLM. - */ - content, - /** - * Part of the generated text that is "reasoning" content. For example, text inside - * tags. You can adjust what is considered reasoning content by changing the `reasoningParsing` - * field when performing the prediction. - */ - reasoningContent, - /** - * Part of the generated that is not "reasoning" content. For example, text outside - * tags. You can adjust what is considered reasoning content by changing the `reasoningParsing` - * field when performing the prediction. - */ - nonReasoningContent, - /** - * Statistics about the prediction. - */ - stats, - /** - * Information about the model used for the prediction. - */ - modelInfo, - /** - * The 0-indexed round index of the prediction in multi-round scenario (for example, - * `.act`). Will always be 0 for single-round predictions such as `.respond` or `.complete`. - */ - roundIndex, - /** - * The configuration used to load the model. Not stable, subject to change. - * - * @deprecated [DEP-RAW-CONFIG] Raw config access API is still in active development. Stay - * turned for updates. - */ - loadConfig, - /** - * The configuration used for the prediction. Not stable, subject to change. - * - * @deprecated [DEP-RAW-CONFIG] Raw config access API is still in active development. Stay - * turned for updates. - */ - predictionConfig) { - this.content = content; - this.reasoningContent = reasoningContent; - this.nonReasoningContent = nonReasoningContent; - this.stats = stats; - this.modelInfo = modelInfo; - this.roundIndex = roundIndex; - this.loadConfig = loadConfig; - this.predictionConfig = predictionConfig; - } -} -/** - * Result of a typed structured prediction. In addition to a regular {@link PredictionResult}, there - * is one additional field: {@link StructuredPredictionResult#parsed}. - * - * To enable typed structured prediction, you should pass in a zod schema as the structured option - * when constructing the prediction config. - * - * @public - */ -class StructuredPredictionResult extends PredictionResult { - constructor(content, reasoningContent, nonReasoningContent, stats, modelInfo, roundIndex, loadConfig, predictionConfig, - /** - * Parsed result of the structured output. - */ - parsed) { - super(content, reasoningContent, nonReasoningContent, stats, modelInfo, roundIndex, loadConfig, predictionConfig); - this.parsed = parsed; - } -} - -/** - * Represents an ongoing prediction. - * - * Note, this class is Promise-like, meaning you can use it as a promise. It resolves to a - * {@link PredictionResult}, which contains the generated text in the `.content` property. Example - * usage: - * - * ```typescript - * const result = await model.complete("When will The Winds of Winter be released?"); - * console.log(result.content); - * ``` - * - * Or you can use instances methods like `then` and `catch` to handle the result or error of the - * prediction. - * - * ```typescript - * model.complete("When will The Winds of Winter be released?") - * .then(result =\> console.log(result.content)) - * .catch(error =\> console.error(error)); - * ``` - * - * Alternatively, you can also stream the result (process the results as more content is being - * generated). For example: - * - * ```typescript - * for await (const { content } of model.complete("When will The Winds of Winter be released?")) { - * process.stdout.write(content); - * } - * ``` - * - * @public - */ -class OngoingPrediction extends StreamablePromise { - async collect(fragments) { - const content = fragments.map(({ content }) => content).join(""); - const reasoningContent = fragments - .filter(({ isStructural }) => !isStructural) - .filter(({ reasoningType }) => reasoningType === "reasoning") - .map(({ content }) => content) - .join(""); - const nonReasoningContent = fragments - .filter(({ isStructural }) => !isStructural) - .filter(({ reasoningType }) => reasoningType === "none") - .map(({ content }) => content) - .join(""); - if (this.stats === null) { - throw new Error("Stats should not be null"); - } - if (this.modelInfo === null) { - throw new Error("Model info should not be null"); - } - if (this.loadModelConfig === null) { - throw new Error("Load model config should not be null"); - } - if (this.predictionConfig === null) { - throw new Error("Prediction config should not be null"); - } - if (this.parser === null) { - return new PredictionResult(content, reasoningContent, nonReasoningContent, this.stats, this.modelInfo, - // Currently, OngoingPrediction is only used with single round predictions. Thus always - // use roundIndex 0. - /* roundIndex */ 0, this.loadModelConfig, this.predictionConfig); - } - else { - return new StructuredPredictionResult(content, reasoningContent, nonReasoningContent, this.stats, this.modelInfo, - // Currently, OngoingPrediction is only used with single round predictions. Thus always - // use roundIndex 0. - /* predictionIndex */ 0, this.loadModelConfig, this.predictionConfig, this.parser(content)); - } - } - constructor(onCancel, parser) { - super(); - this.onCancel = onCancel; - this.parser = parser; - this.stats = null; - this.modelInfo = null; - this.loadModelConfig = null; - this.predictionConfig = null; - } - /** @internal */ - static create(onCancel, parser) { - const ongoingPrediction = new OngoingPrediction(onCancel, parser); - const finished = (stats, modelInfo, loadModelConfig, predictionConfig) => { - ongoingPrediction.stats = stats; - ongoingPrediction.modelInfo = modelInfo; - ongoingPrediction.loadModelConfig = loadModelConfig; - ongoingPrediction.predictionConfig = predictionConfig; - ongoingPrediction.finished(); - }; - const failed = (error) => ongoingPrediction.finished(error); - const push = (fragment) => ongoingPrediction.push(fragment); - return { ongoingPrediction, finished, failed, push }; - } - /** - * Get the final prediction results. If you have been streaming the results, awaiting on this - * method will take no extra effort, as the results are already available in the internal buffer. - * - * Example: - * - * ```typescript - * const prediction = model.complete("When will The Winds of Winter be released?"); - * for await (const { content } of prediction) { - * process.stdout.write(content); - * } - * const result = await prediction.result(); - * console.log(result.stats); - * ``` - * - * Technically, awaiting on this method is the same as awaiting on the instance itself: - * - * ```typescript - * await prediction.result(); - * - * // Is the same as: - * - * await prediction; - * ``` - */ - async result() { - return (await this); - } - /** - * Cancels the prediction. This will stop the prediction with stop reason `userStopped`. See - * {@link LLMPredictionStopReason} for other reasons that a prediction might stop. - */ - async cancel() { - this.onCancel(); - } -} - -const llmPredictionOptsSchema = llmPredictionConfigInputSchema.extend({ - onPromptProcessingProgress: zod.z.function().optional(), - onFirstToken: zod.z.function().optional(), - onPredictionFragment: zod.z.function().optional(), - onToolCallRequestStart: zod.z.function().optional(), - onToolCallRequestNameReceived: zod.z.function().optional(), - onToolCallRequestArgumentFragmentGenerated: zod.z.function().optional(), - onToolCallRequestEnd: zod.z.function().optional(), - onToolCallRequestFailure: zod.z.function().optional(), - signal: zod.z.instanceof(AbortSignal).optional(), - preset: zod.z.string().optional(), -}); -function splitPredictionOpts(opts) { - const { onPromptProcessingProgress, onFirstToken, onPredictionFragment, onToolCallRequestStart, onToolCallRequestNameReceived, onToolCallRequestArgumentFragmentGenerated, onToolCallRequestEnd, onToolCallRequestFailure, signal, preset, ...config } = opts; - return [ - config, - { - onPromptProcessingProgress, - onFirstToken, - onPredictionFragment, - onToolCallRequestStart, - onToolCallRequestNameReceived, - onToolCallRequestArgumentFragmentGenerated, - onToolCallRequestEnd, - onToolCallRequestFailure, - signal, - preset, - }, - ]; -} -const llmRespondOptsSchema = llmPredictionOptsSchema.extend({ - onMessage: zod.z.function().optional(), - onToolCallRequestStart: zod.z.function().optional(), - onToolCallRequestNameReceived: zod.z.function().optional(), - onToolCallRequestArgumentFragmentGenerated: zod.z.function().optional(), - onToolCallRequestEnd: zod.z.function().optional(), - onToolCallRequestFailure: zod.z.function().optional(), -}); -/** - * Split a llmRespondOpts into its parts. - */ -function splitRespondOpts(opts) { - const { onMessage, ...remaining } = opts; - const [config, llmPredictionOpts] = splitPredictionOpts(remaining); - return [ - config, - llmPredictionOpts, - { - onMessage, - }, - ]; -} -const llmActionOptsSchema = llmPredictionConfigInputSchema - .extend(llmActBaseOptsSchema.shape) - .extend({ - preset: zod.z.string().optional(), -}); -function splitActOpts(opts) { - const { onFirstToken, onPredictionFragment, onMessage, onRoundStart, onRoundEnd, onPredictionCompleted, onPromptProcessingProgress, onToolCallRequestStart, onToolCallRequestNameReceived, onToolCallRequestArgumentFragmentGenerated, onToolCallRequestEnd, onToolCallRequestFinalized, onToolCallRequestFailure, onToolCallRequestDequeued, guardToolCall, handleInvalidToolRequest, maxPredictionRounds, signal, preset, allowParallelToolExecution, ...config } = opts; - return [ - config, - { - onFirstToken, - onPredictionFragment, - onMessage, - onRoundStart, - onRoundEnd, - onPredictionCompleted, - onPromptProcessingProgress, - onToolCallRequestStart, - onToolCallRequestNameReceived, - onToolCallRequestArgumentFragmentGenerated, - onToolCallRequestEnd, - onToolCallRequestFinalized, - onToolCallRequestFailure, - onToolCallRequestDequeued, - guardToolCall, - handleInvalidToolRequest, - maxPredictionRounds, - signal, - preset, - allowParallelToolExecution, - }, - ]; -} -const noFormattingTemplate = text ` - {% for message in messages %}{{ message['content'] }}{% endfor %} -`; -/** - * This represents a set of requirements for a model. It is not tied to a specific model, but rather - * to a set of requirements that a model must satisfy. - * - * For example, if you got the model via `client.llm.model("my-identifier")`, you will get a - * `LLMDynamicHandle` for the model with the identifier `my-identifier`. If the model is unloaded, - * and another model is loaded with the same identifier, using the same `LLMDynamicHandle` will use - * the new model. - * - * @public - */ -class LLMDynamicHandle extends DynamicHandle { - /** - * Don't construct this on your own. Use {@link LLMNamespace#model} or - * {@link LLMNamespace#createDynamicHandle} instead. - * - * @internal - */ - constructor( - /** @internal */ - port, - /** @internal */ - specifier, - /** @internal */ - validator, - /** @internal */ - logger = new SimpleLogger(`LLMModel`)) { - super(port, specifier); - this.validator = validator; - this.logger = logger; - /** @internal */ - this.internalKVConfigStack = { layers: [] }; - /** @internal */ - this.internalIgnoreServerSessionConfig = undefined; - } - /** @internal */ - internalPredict(history, predictionConfigStack, cancelEvent, extraOpts, onFragment, onFinished, onError) { - let finished = false; - let firstTokenTriggered = false; - let currentCallId = null; - let receivedEagerToolNameReporting = false; - let receivedToolArgumentsStreaming = false; - const channel = this.port.createChannel("predict", { - modelSpecifier: this.specifier, - history, - predictionConfigStack, - fuzzyPresetIdentifier: extraOpts.preset, - ignoreServerSessionConfig: this.internalIgnoreServerSessionConfig, - }, message => { - switch (message.type) { - case "fragment": { - if (!firstTokenTriggered) { - firstTokenTriggered = true; - safeCallCallback(this.logger, "onFirstToken", extraOpts.onFirstToken, []); - } - safeCallCallback(this.logger, "onFragment", extraOpts.onPredictionFragment, [ - message.fragment, - ]); - onFragment(message.fragment); - break; - } - case "promptProcessingProgress": { - safeCallCallback(this.logger, "onPromptProcessingProgress", extraOpts.onPromptProcessingProgress, [message.progress]); - break; - } - case "toolCallGenerationStart": { - if (currentCallId === null) { - currentCallId = 0; - } - else { - currentCallId++; - } - receivedEagerToolNameReporting = false; - receivedToolArgumentsStreaming = false; - safeCallCallback(this.logger, "onToolCallGenerationStart", extraOpts.onToolCallRequestStart, [currentCallId, { toolCallId: message.toolCallId }]); - break; - } - case "toolCallGenerationNameReceived": { - receivedEagerToolNameReporting = true; - safeCallCallback(this.logger, "onToolCallGenerationNameReceived", extraOpts.onToolCallRequestNameReceived, [currentCallId ?? -1, message.name]); - break; - } - case "toolCallGenerationArgumentFragmentGenerated": { - receivedToolArgumentsStreaming = true; - safeCallCallback(this.logger, "onToolCallGenerationArgumentFragmentGenerated", extraOpts.onToolCallRequestArgumentFragmentGenerated, [currentCallId ?? -1, message.content]); - break; - } - case "toolCallGenerationEnd": { - if (!receivedEagerToolNameReporting) { - // If eager name reporting not received, report it. - safeCallCallback(this.logger, "onToolCallGenerationNameReceived", extraOpts.onToolCallRequestNameReceived, [currentCallId ?? -1, message.toolCallRequest.name]); - } - if (!receivedToolArgumentsStreaming) { - // If arguments streaming not received, just pretend we have received all the - // arguments as a single JSON - safeCallCallback(this.logger, "onToolCallGenerationArgumentFragmentGenerated", extraOpts.onToolCallRequestArgumentFragmentGenerated, [ - currentCallId ?? -1, - JSON.stringify(message.toolCallRequest.arguments ?? {}, null, 2), - ]); - } - safeCallCallback(this.logger, "onToolCallGenerationEnd", extraOpts.onToolCallRequestEnd, [ - currentCallId ?? -1, - { toolCallRequest: message.toolCallRequest, rawContent: message.rawContent }, - ]); - break; - } - case "toolCallGenerationFailed": { - const toolCallRequestError = new ToolCallRequestError(fromSerializedError(message.error).message, message.rawContent); - safeCallCallback(this.logger, "onToolCallGenerationFailed", extraOpts.onToolCallRequestFailure, [currentCallId ?? -1, toolCallRequestError]); - break; - } - case "success": { - finished = true; - onFinished(message.stats, message.modelInfo, message.loadModelConfig, message.predictionConfig); - break; - } - } - }, { stack: getCurrentStack(2) }); - cancelEvent.subscribeOnce(() => { - if (finished) { - return; - } - channel.send({ type: "cancel" }); - }); - channel.onError.subscribeOnce(onError); - } - predictionConfigInputToKVConfig(config) { - let structuredField = undefined; - if (typeof config.structured?.parse === "function") { - structuredField = { - type: "json", - jsonSchema: zodToJsonSchema.zodToJsonSchema(config.structured), - }; - } - else { - structuredField = config.structured; - } - const convertedConfig = { - ...config, - structured: structuredField, - }; - return llmPredictionConfigToKVConfig(convertedConfig); - } - createZodParser(zodSchema) { - return content => { - try { - return zodSchema.parse(JSON.parse(content)); - } - catch (e) { - throw new Error("Failed to parse structured output: " + JSON.stringify(content), { - cause: e, - }); - } - }; - } - /** - * Use the loaded model to predict text. - * - * This method returns an {@link OngoingPrediction} object. An ongoing prediction can be used as a - * promise (if you only care about the final result) or as an async iterable (if you want to - * stream the results as they are being generated). - * - * Example usage as a promise (Resolves to a {@link PredictionResult}): - * - * ```typescript - * const result = await model.complete("When will The Winds of Winter be released?"); - * console.log(result.content); - * ``` - * - * Or - * - * ```typescript - * model.complete("When will The Winds of Winter be released?") - * .then(result =\> console.log(result.content)) - * .catch(error =\> console.error(error)); - * ``` - * - * Example usage as an async iterable (streaming): - * - * ```typescript - * for await (const { content } of model.complete("When will The Winds of Winter be released?")) { - * process.stdout.write(content); - * } - * ``` - * - * If you wish to stream the result, but also getting the final prediction results (for example, - * you wish to get the prediction stats), you can use the following pattern: - * - * ```typescript - * const prediction = model.complete("When will The Winds of Winter be released?"); - * for await (const { content } of prediction) { - * process.stdout.write(content); - * } - * const result = await prediction.result(); - * console.log(result.stats); - * ``` - * - * @param prompt - The prompt to use for prediction. - * @param opts - Options for the prediction. - */ - complete(prompt, opts = {}) { - const stack = getCurrentStack(1); - [prompt, opts] = this.validator.validateMethodParamsOrThrow("model", "complete", ["prompt", "opts"], [zod.z.string(), llmPredictionOptsSchema], [prompt, opts], stack); - const [config, extraOpts] = splitPredictionOpts(opts); - const [cancelEvent, emitCancelEvent] = BufferedEvent.create(); - if (extraOpts.signal !== undefined) { - if (extraOpts.signal.aborted) { - // If the signal is already aborted, we need to cancel the prediction immediately. - emitCancelEvent(); - } - else { - extraOpts.signal.addEventListener("abort", () => { - emitCancelEvent(); - }, { once: true }); - } - } - const zodSchemaParseResult = zodSchemaSchema.safeParse(config.structured); - const { ongoingPrediction, finished, failed, push } = OngoingPrediction.create(emitCancelEvent, !zodSchemaParseResult.success ? null : this.createZodParser(zodSchemaParseResult.data)); - this.internalPredict(this.resolveCompletionContext(prompt), { - layers: [ - ...this.internalKVConfigStack.layers, - { - layerName: "apiOverride", - config: this.predictionConfigInputToKVConfig({ - // If the user did not specify `stopStrings`, we default to an empty array. This is to - // prevent the model from using the value set in the preset. - stopStrings: [], - ...config, - }), - }, - { - layerName: "completeModeFormatting", - config: llmSharedPredictionConfigSchematics.buildPartialConfig({ - promptTemplate: { - type: "jinja", - jinjaPromptTemplate: { - template: noFormattingTemplate, - }, - stopStrings: [], - }, - }), - }, - ], - }, cancelEvent, extraOpts, fragment => push(fragment), (stats, modelInfo, loadModelConfig, predictionConfig) => finished(stats, modelInfo, loadModelConfig, predictionConfig), error => failed(error)); - return ongoingPrediction; - } - resolveCompletionContext(contextInput) { - return { - messages: [ - { - role: "user", - content: [{ type: "text", text: contextInput }], - }, - ], - }; - } - /** - * Use the loaded model to generate a response based on the given history. - * - * This method returns an {@link OngoingPrediction} object. An ongoing prediction can be used as a - * promise (if you only care about the final result) or as an async iterable (if you want to - * stream the results as they are being generated). - * - * Example usage as a promise (Resolves to a {@link PredictionResult}): - * - * ```typescript - * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }]; - * const result = await model.respond(history); - * console.log(result.content); - * ``` - * - * Or - * - * ```typescript - * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }]; - * model.respond(history) - * .then(result => console.log(result.content)) - * .catch(error => console.error(error)); - * ``` - * - * Example usage as an async iterable (streaming): - * - * ```typescript - * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }]; - * for await (const { content } of model.respond(history)) { - * process.stdout.write(content); - * } - * ``` - * - * If you wish to stream the result, but also getting the final prediction results (for example, - * you wish to get the prediction stats), you can use the following pattern: - * - * ```typescript - * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }]; - * const prediction = model.respond(history); - * for await (const { content } of prediction) { - * process.stdout.write(content); - * } - * const result = await prediction; - * console.log(result.stats); - * ``` - * - * @param chat - The LLMChatHistory array to use for generating a response. - * @param opts - Options for the prediction. - */ - respond(chat, opts = {}) { - const stack = getCurrentStack(1); - [chat, opts] = this.validator.validateMethodParamsOrThrow("model", "respond", ["chat", "opts"], [chatHistoryLikeSchema, llmRespondOptsSchema], [chat, opts], stack); - const [cancelEvent, emitCancelEvent] = BufferedEvent.create(); - const [config, predictionOpts, respondOpts] = splitRespondOpts(opts); - if (predictionOpts.signal !== undefined) { - if (predictionOpts.signal.aborted) { - // If the signal is already aborted, we need to cancel the prediction immediately. - emitCancelEvent(); - } - else { - predictionOpts.signal.addEventListener("abort", () => { - emitCancelEvent(); - }, { once: true }); - } - } - const zodSchemaParseResult = zodSchemaSchema.safeParse(config.structured); - const { ongoingPrediction, finished, failed, push } = OngoingPrediction.create(emitCancelEvent, !zodSchemaParseResult.success ? null : this.createZodParser(zodSchemaParseResult.data)); - this.internalPredict(accessMaybeMutableInternals(Chat.from(chat))._internalGetData(), addKVConfigToStack(this.internalKVConfigStack, "apiOverride", this.predictionConfigInputToKVConfig(config)), cancelEvent, predictionOpts, fragment => push(fragment), (stats, modelInfo, loadModelConfig, predictionConfig) => finished(stats, modelInfo, loadModelConfig, predictionConfig), error => failed(error)); - ongoingPrediction.then(result => { - // Call the onMessage callback with the result. - safeCallCallback(this.logger, "onMessage", respondOpts.onMessage, [ - ChatMessage.create("assistant", result.content), - ]); - }, () => { }); - return ongoingPrediction; - } - /** - * @param chat - The LLMChatHistory array to act from as the base - * @param tool - An array of tools that the model can use during the operation. You can create - * tools by using the `tool` function. - * @param opts - Additional options - * - * Example: - * - * ``` - * import { LMStudioClient, tool } from "@lmstudio/sdk"; - * import { z } from "zod"; - * - * const client = new LMStudioClient(); - * const model = await client.llm.model(); - * - * const additionTool = tool({ - * name: "add", - * description: "Add two numbers", - * parameters: { - * a: z.number(), - * b: z.number(), - * }, - * implementation: ({ a, b }) => a + b, - * }); - * - * await model.act("What is 1234 + 4321?", [additionTool], { - * onMessage: message => console.log(message.toString()), - * }); - * ``` - */ - async act(chat, tools, opts = {}) { - const startTime = performance.now(); - const stack = getCurrentStack(1); - [chat, opts] = this.validator.validateMethodParamsOrThrow("model", "act", ["chat", "opts"], [chatHistoryLikeSchema, llmActionOptsSchema], [chat, opts], stack); - const [config, { preset, ...baseOpts }] = splitActOpts(opts); - if (config.structured !== undefined && - config.structured.type !== "none" && - tools.length > 0) { - throw makePrettyError("Structured output is currently not supported in .act() when there are tools.", stack); - } - if (config.structured !== undefined && config.structured.parse !== undefined) { - throw makePrettyError("zod schema is not supported in .act().", stack); - } - if (config.rawTools !== undefined) { - throw makePrettyError("`rawTools` is not supported in act. Use `tools` instead", stack); - } - let rawTools; - if (tools.length === 0) { - rawTools = { type: "none" }; - } - else { - rawTools = { - type: "toolArray", - tools: tools.map(toolToLLMTool), - }; - } - const configWithTools = addKVConfigToStack(this.internalKVConfigStack, "apiOverride", this.predictionConfigInputToKVConfig({ - ...config, - rawTools, - })); - const configWithoutTools = addKVConfigToStack(this.internalKVConfigStack, "apiOverride", this.predictionConfigInputToKVConfig({ - ...config, - rawTools: { type: "none" }, - })); - return await internalAct(chat, tools, baseOpts, stack, this.logger, startTime, - // Implementation of the prediction function. This performs the prediction by creating a - // predict channel and redirect the messages to the appropriate handlers. - async ({ allowTools, history, signal, handleFragment, handlePromptProcessingProgress, handleToolCallGenerationStart, handleToolCallGenerationNameReceived, handleToolCallGenerationArgumentFragmentGenerated, handleToolCallGenerationEnd, handleToolCallGenerationFailed, handlePredictionEnd, handleError, }) => { - // Use predict channel - const channel = this.port.createChannel("predict", { - modelSpecifier: this.specifier, - history, - predictionConfigStack: allowTools ? configWithTools : configWithoutTools, - fuzzyPresetIdentifier: preset, - ignoreServerSessionConfig: this.internalIgnoreServerSessionConfig, - }, message => { - const messageType = message.type; - switch (messageType) { - case "fragment": { - handleFragment(message.fragment); - break; - } - case "promptProcessingProgress": { - handlePromptProcessingProgress(message.progress); - break; - } - case "toolCallGenerationStart": { - handleToolCallGenerationStart(message.toolCallId); - break; - } - case "toolCallGenerationNameReceived": { - handleToolCallGenerationNameReceived(message.name); - break; - } - case "toolCallGenerationArgumentFragmentGenerated": { - handleToolCallGenerationArgumentFragmentGenerated(message.content); - break; - } - case "toolCallGenerationEnd": { - handleToolCallGenerationEnd(message.toolCallRequest, message.rawContent); - break; - } - case "toolCallGenerationFailed": { - handleToolCallGenerationFailed(fromSerializedError(message.error), message.rawContent); - break; - } - case "success": { - // This is the end of the prediction. The following object is passed to the - // `makePredictionResult` function to create the final PredictionResult. (see below) - handlePredictionEnd({ - stats: message.stats, - modelInfo: message.modelInfo, - loadModelConfig: message.loadModelConfig, - predictionConfig: message.predictionConfig, - }); - break; - } - } - }, { stack }); - if (signal.aborted) { - // If the signal is already aborted, we need to cancel the prediction immediately. - channel.send({ type: "cancel" }); - } - else { - signal.addEventListener("abort", () => { - channel.send({ type: "cancel" }); - }, { once: true }); - } - channel.onError.subscribeOnce(handleError); - }, ({ endPacket, content, nonReasoningContent, reasoningContent, predictionsPerformed }) => { - return new PredictionResult(content, reasoningContent, nonReasoningContent, endPacket.stats, endPacket.modelInfo, predictionsPerformed, endPacket.loadModelConfig, endPacket.predictionConfig); - }); - } - async getContextLength() { - const stack = getCurrentStack(1); - const loadConfig = await this.getLoadConfig(stack); - return llmSharedLoadConfigSchematics.access(loadConfig, "contextLength"); - } - async applyPromptTemplate(history, opts = {}) { - const stack = getCurrentStack(1); - [history, opts] = this.validator.validateMethodParamsOrThrow("model", "applyPromptTemplate", ["history", "opts"], [chatHistoryLikeSchema, llmApplyPromptTemplateOptsSchema], [history, opts], stack); - return (await this.port.callRpc("applyPromptTemplate", { - specifier: this.specifier, - history: accessMaybeMutableInternals(Chat.from(history))._internalGetData(), - predictionConfigStack: this.internalKVConfigStack, - opts, - }, { - stack, - })).formatted; - } - async tokenize(inputString) { - const stack = getCurrentStack(1); - inputString = this.validator.validateMethodParamOrThrow("model", "tokenize", "inputString", zod.z.string().or(zod.z.array(zod.z.string())), inputString, stack); - if (Array.isArray(inputString)) { - return (await Promise.all(inputString.map(s => this.port.callRpc("tokenize", { specifier: this.specifier, inputString: s }, { stack })))).map(r => r.tokens); - } - else { - return (await this.port.callRpc("tokenize", { - specifier: this.specifier, - inputString, - }, { stack })).tokens; - } - } - async countTokens(inputString) { - const stack = getCurrentStack(1); - inputString = this.validator.validateMethodParamOrThrow("model", "countTokens", "inputString", zod.z.string(), inputString, stack); - return (await this.port.callRpc("countTokens", { - specifier: this.specifier, - inputString, - }, { stack })).tokenCount; - } - /** - * Starts to eagerly preload a draft model. This is useful when you want a draft model to be ready - * for speculative decoding. - * - * Preloading is done on a best-effort basis and may not always succeed. It is not guaranteed that - * the draft model is actually loaded when this method returns. Thus, this method should only be - * used as an optimization. The actual draft model used only depends on the parameter set when - * performing the prediction. - */ - async unstable_preloadDraftModel(draftModelKey) { - const stack = getCurrentStack(1); - draftModelKey = this.validator.validateMethodParamOrThrow("model", "unstable_preloadDraftModel", "draftModelKey", zod.z.string(), draftModelKey, stack); - await this.port.callRpc("preloadDraftModel", { specifier: this.specifier, draftModelKey }, { stack }); - } -} - -/** - * Represents a specific loaded LLM. Most LLM related operations are inherited from - * {@link LLMDynamicHandle}. - * - * @public - */ -class LLM extends LLMDynamicHandle { - /** @internal */ - constructor(llmPort, info, validator, logger = new SimpleLogger(`LLM`)) { - const specifier = { - type: "instanceReference", - instanceReference: info.instanceReference, - }; - super(llmPort, specifier, validator, logger); - this.identifier = info.identifier; - this.path = info.path; - this.modelKey = info.modelKey; - this.format = info.format; - this.displayName = info.displayName; - this.sizeBytes = info.sizeBytes; - this.vision = info.vision; - this.trainedForToolUse = info.trainedForToolUse; - } - async unload() { - const stack = getCurrentStack(1); - await this.port.callRpc("unloadModel", { identifier: this.identifier }, { stack }); - } - async getModelInfo() { - const info = await super.getModelInfo(); - if (info === undefined) { - const stack = getCurrentStack(1); - throw makePrettyError("This model has already been unloaded", stack); - } - return info; - } -} - -/** @public */ -class LLMNamespace extends ModelNamespace { - constructor() { - super(...arguments); - /** @internal */ - this.namespace = "llm"; - /** @internal */ - this.defaultLoadConfig = {}; - /** @internal */ - this.loadModelConfigSchema = llmLoadModelConfigSchema; - } - /** @internal */ - loadConfigToKVConfig(config) { - return llmLlamaMoeLoadConfigSchematics.buildPartialConfig({ - "contextLength": config.contextLength, - "llama.evalBatchSize": config.evalBatchSize, - "llama.acceleration.offloadRatio": config.gpu?.ratio, - "numCpuExpertLayersRatio": config.gpu?.numCpuExpertLayersRatio, - "load.gpuSplitConfig": convertGPUSettingToGPUSplitConfig(config.gpu), - "llama.flashAttention": config.flashAttention, - "llama.ropeFrequencyBase": numberToCheckboxNumeric(config.ropeFrequencyBase, 0, 0), - "llama.ropeFrequencyScale": numberToCheckboxNumeric(config.ropeFrequencyScale, 0, 0), - "llama.keepModelInMemory": config.keepModelInMemory, - "seed": numberToCheckboxNumeric(config.seed, -1, 0), - "llama.useFp16ForKVCache": config.useFp16ForKVCache, - "llama.tryMmap": config.tryMmap, - "numExperts": config.numExperts, - "llama.kCacheQuantizationType": cacheQuantizationTypeToCheckbox({ - value: config.llamaKCacheQuantizationType, - falseDefault: "f16", - }), - "llama.vCacheQuantizationType": cacheQuantizationTypeToCheckbox({ - value: config.llamaVCacheQuantizationType, - falseDefault: "f16", - }), - }); - } - /** @internal */ - createDomainSpecificModel(port, info, validator, logger) { - return new LLM(port, info, validator, logger); - } - /** @internal */ - createDomainDynamicHandle(port, specifier, validator, logger) { - return new LLMDynamicHandle(port, specifier, validator, logger); - } -} - -/** - * Represents the result of a prediction from a generator plugin. - * - * The most notably property is {@link GeneratorPredictionResult#content}, which contains the - * generated text. - * - * @public - * @experimental [EXP-GEN-PREDICT] Using generator plugins programmatically is still in development. - * This may change in the future without warning. - */ -class GeneratorPredictionResult { - constructor( - /** - * The newly generated text as generated by the generator plugin. - */ - content, - /** - * Part of the generated text that is "reasoning" content. For example, text inside - * tags. The generator is responsible for determining what is considered reasoning content. - */ - reasoningContent, - /** - * Part of the generated text that is not "reasoning" content. For example, text outside - * tags. The generator is responsible for determining what is considered reasoning - * content. - */ - nonReasoningContent, - /** - * The identifier of the plugin that generated this result. - */ - pluginIdentifier) { - this.content = content; - this.reasoningContent = reasoningContent; - this.nonReasoningContent = nonReasoningContent; - this.pluginIdentifier = pluginIdentifier; - } -} - -/** - * Represents an ongoing prediction from a generator. - * - * Note, this class is Promise-like, meaning you can use it as a promise. It resolves to a - * {@link GeneratorPredictionResult}, which contains the generated text in the `.content` property. Example - * usage: - * - * ```typescript - * const result = await generator.complete("When will The Winds of Winter be released?"); - * console.log(result.content); - * ``` - * - * Or you can use instances methods like `then` and `catch` to handle the result or error of the - * prediction. - * - * ```typescript - * generator.complete("When will The Winds of Winter be released?") - * .then(result =\> console.log(result.content)) - * .catch(error =\> console.error(error)); - * ``` - * - * Alternatively, you can also stream the result (process the results as more content is being - * generated). For example: - * - * ```typescript - * for await (const { content } of generator.complete("When will The Winds of Winter be released?")) { - * process.stdout.write(content); - * } - * ``` - * - * @public - * @experimental [EXP-GEN-PREDICT] Using generator plugins programmatically is still in development. - * This may change in the future without warning. - */ -class OngoingGeneratorPrediction extends StreamablePromise { - async collect(fragments) { - const content = fragments.map(({ content }) => content).join(""); - const reasoningContent = fragments - .filter(({ isStructural }) => !isStructural) - .filter(({ reasoningType }) => reasoningType === "reasoning") - .map(({ content }) => content) - .join(""); - const nonReasoningContent = fragments - .filter(({ isStructural }) => !isStructural) - .filter(({ reasoningType }) => reasoningType === "none") - .map(({ content }) => content) - .join(""); - return new GeneratorPredictionResult(content, reasoningContent, nonReasoningContent, this.pluginIdentifier); - } - constructor(pluginIdentifier, onCancel) { - super(); - this.pluginIdentifier = pluginIdentifier; - this.onCancel = onCancel; - } - /** @internal */ - static create(pluginIdentifier, onCancel) { - const ongoingPrediction = new OngoingGeneratorPrediction(pluginIdentifier, onCancel); - const finished = () => ongoingPrediction.finished(); - const failed = (error) => ongoingPrediction.finished(error); - const push = (fragment) => ongoingPrediction.push(fragment); - return { ongoingPrediction, finished, failed, push }; - } - /** - * Get the final prediction results. If you have been streaming the results, awaiting on this - * method will take no extra effort, as the results are already available in the internal buffer. - * - * Example: - * - * ```typescript - * const prediction = generator.complete("When will The Winds of Winter be released?"); - * for await (const { content } of prediction) { - * process.stdout.write(content); - * } - * const result = await prediction.result(); - * console.log(result.stats); - * ``` - * - * Technically, awaiting on this method is the same as awaiting on the instance itself: - * - * ```typescript - * await prediction.result(); - * - * // Is the same as: - * - * await prediction; - * ``` - */ - async result() { - return await this; - } - /** - * Cancels the prediction. - */ - async cancel() { - this.onCancel(); - } -} - -const llmGeneratorPredictionOptsSchema = zod.z.object({ - onFirstToken: zod.z.function().optional(), - onPredictionFragment: zod.z.function().optional(), - onMessage: zod.z.function().optional(), - signal: zod.z.instanceof(AbortSignal).optional(), - pluginConfig: kvConfigSchema.optional(), - workingDirectory: zod.z.string().optional(), -}); -const llmGeneratorActOptsSchema = llmActBaseOptsSchema.extend({ - pluginConfig: kvConfigSchema.optional(), - workingDirectory: zod.z.string().optional(), -}); -/** - * Represents a handle for a generator that can act as a LLM. - * - * @public - * @experimental [EXP-GEN-PREDICT] Using generator plugins programmatically is still in development. - * This may change in the future without warning. - */ -class LLMGeneratorHandle { - /** - * Don't use this method directly, use {@link LLMNamespace#createGeneratorHandle} instead. - * - * @internal - */ - constructor( - /** @internal */ - port, - /** @internal */ - pluginIdentifier, - /** @internal */ - validator, - /** @internal */ - associatedPredictionProcess, - /** @internal */ - logger = new SimpleLogger(`LLMGeneratorHandle`)) { - this.port = port; - this.pluginIdentifier = pluginIdentifier; - this.validator = validator; - this.associatedPredictionProcess = associatedPredictionProcess; - this.logger = logger; - /** - * The identifier of the plugin that this handle is associated with. - */ - this.identifier = this.pluginIdentifier; - } - getPluginConfigSpecifier(userSuppliedPluginConfig, userSuppliedWorkingDirectory, stack) { - if (this.associatedPredictionProcess === null) { - // If there is no associated prediction process, we can use the user-supplied config directly. - return { - type: "direct", - config: userSuppliedPluginConfig ?? emptyKVConfig, - workingDirectoryPath: userSuppliedWorkingDirectory ?? undefined, - }; - } - // If there is an associated prediction process, we first need to make sure that the user has - // not supplied a plugin config or working directory, as these are not allowed in this case. - // (The plugin config/working directory of the prediction process will be used instead.) - if (userSuppliedPluginConfig !== undefined) { - throw makeTitledPrettyError("Cannot use plugin config with prediction process", text ` - You cannot provide a plugin config to the generator handle when it is associated with a - prediction process. The plugin config that was configured for the prediction process will - be used instead. - - If you want to use a different plugin config, you will need to create a separate - GeneratorHandle instead. - `, stack); - } - if (userSuppliedWorkingDirectory !== undefined) { - throw makeTitledPrettyError("Cannot use working directory with prediction process", text ` - You cannot provide a working directory to the generator handle when it is associated with - a prediction process. The working directory that was configured for the prediction process - will be used instead. - - If you want to use a different working directory, you will need to create a separate - GeneratorHandle instead. - `, stack); - } - // If we reach here, we can safely return the plugin config specifier for the prediction - // process. - return { - type: "predictionProcess", - pci: this.associatedPredictionProcess.pci, - token: this.associatedPredictionProcess.token, - }; - } - /** - * Use the generator to produce a response based on the given history. - */ - respond(chat, opts = {}) { - const stack = getCurrentStack(1); - [chat, opts] = this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle", "respond", ["chat", "opts"], [chatHistoryLikeSchema, llmGeneratorPredictionOptsSchema], [chat, opts], stack); - const { onFirstToken, onPredictionFragment, onMessage, signal, pluginConfig, workingDirectory, } = opts; - let resolved = false; - let firstTokenTriggered = false; - const cancelEvent = new CancelEvent(); - if (signal !== undefined) { - if (signal.aborted) { - // If the signal is already aborted, we can immediately cancel the event. - cancelEvent.cancel(); - } - else { - signal.addEventListener("abort", () => cancelEvent.cancel(), { once: true }); - } - } - const { ongoingPrediction, finished, failed, push } = OngoingGeneratorPrediction.create(this.pluginIdentifier, () => { - cancelEvent.cancel(); - }); - const channel = this.port.createChannel("generateWithGenerator", { - pluginIdentifier: this.pluginIdentifier, - pluginConfigSpecifier: this.getPluginConfigSpecifier(pluginConfig, workingDirectory, stack), - tools: [], - history: accessMaybeMutableInternals(Chat.from(chat))._internalGetData(), - }, message => { - const messageType = message.type; - switch (messageType) { - case "fragment": { - if (!firstTokenTriggered) { - firstTokenTriggered = true; - safeCallCallback(this.logger, "onFirstToken", onFirstToken, []); - } - safeCallCallback(this.logger, "onPredictionFragment", onPredictionFragment, [ - message.fragment, - ]); - push(message.fragment); - break; - } - case "success": { - resolved = true; - finished(); - break; - } - } - }, { stack }); - channel.onError.subscribeOnce(error => { - if (resolved) { - return; - } - resolved = true; - failed(error); - }); - cancelEvent.subscribeOnce(() => { - if (resolved) { - return; - } - channel.send({ type: "cancel" }); - }); - ongoingPrediction.then(result => { - // Call the onMessage callback with the result. - safeCallCallback(this.logger, "onMessage", onMessage, [ - ChatMessage.create("assistant", result.content), - ]); - }, () => { }); - return ongoingPrediction; - } - async act(chat, tools, opts = {}) { - const startTime = performance.now(); - const stack = getCurrentStack(1); - [chat, opts] = this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle", "act", ["chat", "opts"], [chatHistoryLikeSchema, llmGeneratorActOptsSchema], [chat, opts], stack); - const { pluginConfig, workingDirectory, ...baseOpts } = opts; - const toolDefinitions = tools.map(toolToLLMTool); - return await internalAct(chat, tools, baseOpts, stack, this.logger, startTime, - // Implementation of the prediction function. This performs the prediction by creating a - // predict channel and redirect the messages to the appropriate handlers. - async ({ allowTools, history, signal, handleFragment, handlePromptProcessingProgress, handleToolCallGenerationStart, handleToolCallGenerationNameReceived, handleToolCallGenerationArgumentFragmentGenerated, handleToolCallGenerationEnd, handleToolCallGenerationFailed, handlePredictionEnd, handleError, }) => { - // Use predict channel - const channel = this.port.createChannel("generateWithGenerator", { - pluginIdentifier: this.pluginIdentifier, - pluginConfigSpecifier: this.getPluginConfigSpecifier(pluginConfig, workingDirectory, stack), - tools: allowTools ? toolDefinitions : [], - history, - }, message => { - const messageType = message.type; - switch (messageType) { - case "fragment": { - handleFragment(message.fragment); - break; - } - case "promptProcessingProgress": { - handlePromptProcessingProgress(message.progress); - break; - } - case "toolCallGenerationStart": { - handleToolCallGenerationStart(message.toolCallId); - break; - } - case "toolCallGenerationNameReceived": { - handleToolCallGenerationNameReceived(message.name); - break; - } - case "toolCallGenerationArgumentFragmentGenerated": { - handleToolCallGenerationArgumentFragmentGenerated(message.content); - break; - } - case "toolCallGenerationEnd": { - handleToolCallGenerationEnd(message.toolCallRequest, undefined); - break; - } - case "toolCallGenerationFailed": { - handleToolCallGenerationFailed(new Error("Tool call generation failed"), // Placeholder error for now - undefined); - break; - } - case "success": { - // Nothing to hand to the `makePredictionResult` function. Just pass in `undefined`. - handlePredictionEnd(undefined); - break; - } - } - }, { stack }); - if (signal.aborted) { - // If the signal is already aborted, we can immediately cancel the channel. - channel.send({ type: "cancel" }); - } - else { - signal.addEventListener("abort", () => { - channel.send({ type: "cancel" }); - }, { once: true }); - } - channel.onError.subscribeOnce(handleError); - }, ({ content, nonReasoningContent, reasoningContent }) => new GeneratorPredictionResult(content, reasoningContent, nonReasoningContent, this.pluginIdentifier)); - } -} - -const generatorSchema = zod.z.function(); - -/** - * The base class for all controllers. - * - * @public - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ -class BaseController { - constructor( - /** - * The LM Studio client instance. Use this to interact with the LM Studio API. - */ - client, - /** - * The abort signal that you should listen to for cancellation requests. - * - * See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal for more information about - * abort signals. - */ - abortSignal, pluginConfig, globalPluginConfig, workingDirectoryPath) { - this.client = client; - this.abortSignal = abortSignal; - this.pluginConfig = pluginConfig; - this.globalPluginConfig = globalPluginConfig; - this.workingDirectoryPath = workingDirectoryPath; - } - /** - * Gets the working directory for the current prediction. If your plugin produces files, you - * should aim to put them in this directory. - */ - getWorkingDirectory() { - if (this.workingDirectoryPath === null) { - throw new Error("This prediction process is not attached to a working directory."); - } - return this.workingDirectoryPath; - } - /** - * Get the per-chat config for the plugin. Takes in the configSchematics. You can get the - * values of fields like so: - * - * ```ts - * const config = ctl.getPluginConfig(configSchematics); - * const value = config.get("fieldKey"); - * ``` - * - * @remarks - * - * If you need to name the type of the returned value, use: - * - * `InferParsedConfig`. - * - * Example: - * - * ```ts - * function myFunction(config: InferParsedConfig) { - * // ... - * } - * - * myFunction(ctl.getPluginConfig(configSchematics)); - * ``` - */ - getPluginConfig(configSchematics) { - return configSchematics.parse(this.pluginConfig); - } - /** - * Get the application-wide config for the plugin. Takes in the globalConfigSchematics. You can - * get the values of fields like so: - * - * ```ts - * const config = ctl.getGlobalPluginConfig(globalConfigSchematics); - * const value = config.get("fieldKey"); - * ``` - * - * @remarks - * - * If you need to name the type of the returned value, use: - * - * `InferParsedConfig`. - * - * Example: - * - * ```ts - * function myFunction(config: InferParsedConfig) { - * // ... - * } - * - * myFunction(ctl.getGlobalPluginConfig(globalConfigSchematics)); - * ``` - */ - getGlobalPluginConfig(globalConfigSchematics) { - return globalConfigSchematics.parse(this.globalPluginConfig); - } - /** - * Provides a callback that will be called when the prediction is aborted. If the prediction is - * already aborted, the callback will be called immediately. - * - * You can also use {@link BaseController.abortSignal} if you are using an async function that - * supports abort signals. - * - * See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal for more information about - * abort signals. - */ - onAborted(callback) { - if (this.abortSignal.aborted) { - callback(); - } - else { - this.abortSignal.addEventListener("abort", callback, { once: true }); - } - } -} - -/** - * Controller for a generator. - * - * @public - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ -class GeneratorController extends BaseController { - /** - * @internal Do not construct this class yourself. - */ - constructor(client, pluginConfig, globalPluginConfig, workingDirectoryPath, abortSignal, toolDefinitions, connector, validator) { - super(client, abortSignal, pluginConfig, globalPluginConfig, workingDirectoryPath); - this.toolDefinitions = toolDefinitions; - this.connector = connector; - this.validator = validator; - } - /** - * Get the definitions of the tools available for this generation. - */ - getToolDefinitions() { - return this.toolDefinitions; - } - /** - * Use this function to report a text fragment has been generated. - * - * @param content - The content that has been generated. - * @param opts - Additional info about the generated content, such as how many tokens it contains. - * See {@link LLMPredictionFragmentInputOpts} for more info. All the fields are optional. - */ - fragmentGenerated(content, opts = {}) { - const stack = getCurrentStack(1); - [content, opts] = this.validator.validateMethodParamsOrThrow("GeneratorController", "fragmentGenerated", ["content", "opts"], [zod.z.string(), llmPredictionFragmentInputOptsSchema], [content, opts], stack); - this.connector.fragmentGenerated(content, opts); - } - /** - * Use this function to report that a tool call generation has started. Each - * `toolCallGenerationStarted` must be paired up with a `toolCallGenerationEnded` call for - * successfully generated tool calls, or a `toolCallGenerationFailed` call for - * failed tool calls. - */ - toolCallGenerationStarted({ toolCallId, } = {}) { - this.connector.toolCallGenerationStarted(toolCallId); - } - /** - * Use this function to report that the name of the tool call has been generated. This function - * should only be called once for each `toolCallGenerationStarted`. - * - * @param toolName - The name of the tool that has been generated. - */ - toolCallGenerationNameReceived(toolName) { - const stack = getCurrentStack(1); - toolName = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationNameReceived", "toolName", zod.z.string(), toolName, stack); - this.connector.toolCallGenerationNameReceived(toolName); - } - /** - * Use this function to report that a new argument fragment has been generated for the tool call. - * This function can be called multiple times for each `toolCallGenerationStarted`. - * - * @param content - The new fragment that has been generated for the tool call. - */ - toolCallGenerationArgumentFragmentGenerated(content) { - const stack = getCurrentStack(1); - content = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationArgumentFragmentGenerated", "content", zod.z.string(), content, stack); - this.connector.toolCallGenerationArgumentFragmentGenerated(content); - } - /** - * Use this function to report that a tool call generation has successfully ended. This function - * should only be called after a `toolCallGenerationStarted` call. - */ - toolCallGenerationEnded(toolCallRequest) { - const stack = getCurrentStack(1); - toolCallRequest = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationEnded", "toolCallRequest", toolCallRequestSchema, toolCallRequest, stack); - this.connector.toolCallGenerationEnded(toolCallRequest); - } - /** - * Use this function to report that a tool call generation has failed. This function should only - * be called after a `toolCallGenerationStarted` call. - * - * @param error - The error that occurred during the tool call generation. - */ - toolCallGenerationFailed(error) { - const stack = getCurrentStack(1); - error = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationFailed", "error", zod.z.instanceof(Error), error, stack); - this.connector.toolCallGenerationFailed(error); - } -} - -var __addDisposableResource$1 = (globalThis && globalThis.__addDisposableResource) || function (env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose, inner; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; - } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - if (async) inner = dispose; - } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; - env.stack.push({ value: value, dispose: dispose, async: async }); - } - else if (async) { - env.stack.push({ async: true }); - } - return value; -}; -var __disposeResources$1 = (globalThis && globalThis.__disposeResources) || (function (SuppressedError) { - return function (env) { - function fail(e) { - env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; - } - var r, s = 0; - function next() { - while (r = env.stack.pop()) { - try { - if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); - if (r.dispose) { - var result = r.dispose.call(r.value); - if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); - } - else s |= 1; - } - catch (e) { - fail(e); - } - } - if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); - if (env.hasError) throw env.error; - } - return next(); - }; -})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; -}); -function stringifyAny(message) { - switch (typeof message) { - case "string": - return message; - case "number": - return message.toString(); - case "boolean": - return message ? "true" : "false"; - case "undefined": - return "undefined"; - case "object": - if (message === null) { - return "null"; - } - if (message instanceof Error) { - return message.stack; - } - return JSON.stringify(message, null, 2); - case "bigint": - return message.toString(); - case "symbol": - return message.toString(); - case "function": - return message.toString(); - default: - return "unknown"; - } -} -function concatenateDebugMessages(...messages) { - return messages.map(stringifyAny).join(" "); -} -function createId() { - return `${Date.now()}-${Math.random()}`; -} -class ProcessingConnector { - constructor(pluginsPort, abortSignal, processingContextIdentifier, token, logger) { - this.pluginsPort = pluginsPort; - this.abortSignal = abortSignal; - this.processingContextIdentifier = processingContextIdentifier; - this.token = token; - this.logger = logger; - } - handleUpdate(update) { - this.pluginsPort - .callRpc("processingHandleUpdate", { - pci: this.processingContextIdentifier, - token: this.token, - update, - }) - .catch(error => { - this.logger.error("Failed to send update", error); - }); - } - async handleRequest(request) { - const { response } = await this.pluginsPort.callRpc("processingHandleRequest", { - pci: this.processingContextIdentifier, - token: this.token, - request, - }); - return response; - } - async pullHistory(includeCurrent) { - const chatHistoryData = await this.pluginsPort.callRpc("processingPullHistory", { - pci: this.processingContextIdentifier, - token: this.token, - includeCurrent, - }); - // We know the result of callRpc is immutable, so we can safely pass false as the second - // argument. - return Chat.createRaw(chatHistoryData, /* mutable */ false).asMutableCopy(); - } - async getOrLoadTokenSource() { - const result = await this.pluginsPort.callRpc("processingGetOrLoadTokenSource", { - pci: this.processingContextIdentifier, - token: this.token, - }); - return result.tokenSourceIdentifier; - } - async hasStatus() { - return await this.pluginsPort.callRpc("processingHasStatus", { - pci: this.processingContextIdentifier, - token: this.token, - }); - } - async needsNaming() { - return await this.pluginsPort.callRpc("processingNeedsNaming", { - pci: this.processingContextIdentifier, - token: this.token, - }); - } - async suggestName(name) { - await this.pluginsPort.callRpc("processingSuggestName", { - pci: this.processingContextIdentifier, - token: this.token, - name, - }); - } -} -/** - * @public - */ -class ProcessingController extends BaseController { - /** @internal */ - constructor(client, pluginConfig, globalPluginConfig, workingDirectoryPath, enabledPluginInfos, - /** @internal */ - connector, - /** @internal */ - config, - /** - * When getting history, should the latest user input be included in the history? - * - * @internal - */ - shouldIncludeCurrentInHistory) { - super(client, connector.abortSignal, pluginConfig, globalPluginConfig, workingDirectoryPath); - this.enabledPluginInfos = enabledPluginInfos; - this.connector = connector; - this.config = config; - this.shouldIncludeCurrentInHistory = shouldIncludeCurrentInHistory; - this.processingControllerHandle = { - abortSignal: connector.abortSignal, - sendUpdate: update => { - connector.handleUpdate(update); - }, - sendRequest: async (request) => { - const type = request.type; - const response = await connector.handleRequest(request); - if (response.type !== type) { - throw new Error(`Expected response type ${type}, but got ${response.type}. This is a bug.`); - } - return response; - }, - }; - } - sendUpdate(update) { - this.processingControllerHandle.sendUpdate(update); - } - /** - * Gets a mutable copy of the current history. The returned history is a copy, so mutating it will - * not affect the actual history. It is mutable for convenience reasons. - * - * - If you are a promptPreprocessor, this will not include the user message you are currently - * preprocessing. - * - If you are a prediction loop handler, this will include the user message, and can be fed into - * the {@link LLMDynamicHandle#respond} method directly. - */ - async pullHistory() { - return await this.connector.pullHistory(this.shouldIncludeCurrentInHistory); - } - createStatus(initialState) { - const id = createId(); - this.sendUpdate({ - type: "status.create", - id, - state: initialState, - }); - const statusController = new PredictionProcessStatusController(this.processingControllerHandle, initialState, id); - return statusController; - } - addCitations(arg) { - if (Array.isArray(arg)) { - for (const entry of arg) { - this.createCitationBlock(entry.content, { - fileName: entry.source.name, - fileIdentifier: entry.source.identifier, - }); - } - } - else { - for (const entry of arg.entries) { - this.createCitationBlock(entry.content, { - fileName: entry.source.name, - fileIdentifier: entry.source.identifier, - }); - } - } - } - createCitationBlock(citedText, source) { - const id = createId(); - this.sendUpdate({ - type: "citationBlock.create", - id, - citedText, - ...source, - }); - const citationBlockController = new PredictionProcessCitationBlockController(this.processingControllerHandle, id); - return citationBlockController; - } - /** - * @internal - */ - createDebugInfoBlock(debugInfo) { - const id = createId(); - this.sendUpdate({ - type: "debugInfoBlock.create", - id, - debugInfo, - }); - const debugInfoBlockController = new PredictionProcessDebugInfoBlockController(this.processingControllerHandle, id); - return debugInfoBlockController; - } - createContentBlock({ roleOverride, includeInContext = true, style, prefix, suffix, } = {}) { - const id = createId(); - this.sendUpdate({ - type: "contentBlock.create", - id, - roleOverride, - includeInContext, - style, - prefix, - suffix, - }); - const contentBlockController = new PredictionProcessContentBlockController(this.processingControllerHandle, id, roleOverride ?? "assistant"); - return contentBlockController; - } - debug(...messages) { - this.createDebugInfoBlock(concatenateDebugMessages(...messages)); - } - /** - * Gets the token source associated with this prediction process (i.e. what the user has selected - * on the top navigation bar). - * - * The token source can either be a model or a generator plugin. In both cases, the returned - * object will contain a ".act" and a ".respond" method, which can be used to generate text. - * - * The token source is already pre-configured to use user's prediction config - you don't need to - * pass through any additional configuration. - */ - async tokenSource() { - const tokenSourceIdentifier = await this.connector.getOrLoadTokenSource(); - const tokenSourceIdentifierType = tokenSourceIdentifier.type; - switch (tokenSourceIdentifierType) { - case "model": { - const model = await this.client.llm.model(tokenSourceIdentifier.identifier); - // Don't use the server session config for this model - model.internalIgnoreServerSessionConfig = true; - // Inject the prediction config - model.internalKVConfigStack = { - layers: [ - { - layerName: "conversationSpecific", - config: this.config, - }, - ], - }; - return model; - } - case "generator": { - const generator = this.client.plugins.createGeneratorHandleAssociatedWithPredictionProcess(tokenSourceIdentifier.pluginIdentifier, this.connector.processingContextIdentifier, this.connector.token); - return generator; - } - } - } - /** - * Sets the sender name for this message. The sender name shown above the message in the chat. - */ - async setSenderName(name) { - this.sendUpdate({ - type: "setSenderName", - name, - }); - } - /** - * Throws an error if the prediction process has been aborted. Sprinkle this throughout your code - * to ensure that the prediction process is aborted as soon as possible. - */ - guardAbort() { - this.abortSignal.throwIfAborted(); - } - /** - * Whether this prediction process has had any status. - */ - async hasStatus() { - return await this.connector.hasStatus(); - } - /** - * Returns whether this conversation needs a name. - */ - async needsNaming() { - return await this.connector.needsNaming(); - } - /** - * Suggests a name for this conversation. - */ - async suggestName(name) { - await this.connector.suggestName(name); - } - async requestConfirmToolCall({ callId, pluginIdentifier, name, parameters, }) { - const { result } = await raceWithAbortSignal(this.processingControllerHandle.sendRequest({ - type: "confirmToolCall", - callId, - pluginIdentifier, - name, - parameters, - }), this.abortSignal); - const resultType = result.type; - switch (resultType) { - case "allow": { - return { - type: "allow", - toolArgsOverride: result.toolArgsOverride, - }; - } - case "deny": { - return { - type: "deny", - denyReason: result.denyReason, - }; - } - default: { - const exhaustiveCheck = resultType; - throw new Error(`Unexpected result type ${exhaustiveCheck}. This is a bug. Please report it.`); - } - } - } - createToolStatus(callId, initialStatus) { - const id = createId(); - this.sendUpdate({ - type: "toolStatus.create", - id, - callId, - state: { - status: initialStatus, - customStatus: "", - customWarnings: [], - }, - }); - const toolStatusController = new PredictionProcessToolStatusController(this.processingControllerHandle, id, initialStatus); - return toolStatusController; - } - /** - * Starts a tool use session with tools available in the prediction process. Note, this method - * should be used with "Explicit Resource Management". That is, you should use it like so: - * - * ```typescript - * using toolUseSession = await ctl.startToolUseSession(); - * // ^ Notice the `using` keyword here. - * ``` - * - * If you do not `using`, you should call `toolUseSession[Symbol.dispose]()` after you are done. - * - * If you don't, lmstudio-js will close the session upon the end of the prediction step - * automatically. However, it is not recommended. - * - * @public - * @deprecated WIP - */ - async startToolUseSession() { - const identifiersOfPluginsWithTools = this.enabledPluginInfos - .filter(({ hasToolsProvider }) => hasToolsProvider) - .map(({ identifier }) => identifier); - return await this.client.plugins.startToolUseSessionUsingPredictionProcess( - // We start a tool use session with all the plugins that have tools available - identifiersOfPluginsWithTools, this.connector.processingContextIdentifier, this.connector.token); - } -} -/** - * Controller for a status block in the prediction process. - * - * @public - */ -class PredictionProcessStatusController { - /** @internal */ - constructor( - /** @internal */ - handle, initialState, id, indentation = 0) { - this.handle = handle; - this.id = id; - this.indentation = indentation; - this.lastSubStatus = this; - this.lastState = initialState; - } - setText(text) { - this.lastState.text = text; - this.handle.sendUpdate({ - type: "status.update", - id: this.id, - state: this.lastState, - }); - } - setState(state) { - this.lastState = state; - this.handle.sendUpdate({ - type: "status.update", - id: this.id, - state, - }); - } - remove() { - this.handle.sendUpdate({ - type: "status.remove", - id: this.id, - }); - } - getNestedLastSubStatusBlockId() { - let current = this.lastSubStatus; - while (current !== current.lastSubStatus) { - current = current.lastSubStatus; - } - return current.id; - } - addSubStatus(initialState) { - const id = createId(); - this.handle.sendUpdate({ - type: "status.create", - id, - state: initialState, - location: { - type: "afterId", - id: this.getNestedLastSubStatusBlockId(), - }, - indentation: this.indentation + 1, - }); - const controller = new PredictionProcessStatusController(this.handle, initialState, id, this.indentation + 1); - this.lastSubStatus = controller; - return controller; - } -} -/** - * Controller for a citation block in the prediction process. Currently cannot do anything. - * - * @public - */ -class PredictionProcessCitationBlockController { - /** @internal */ - constructor( - /** @internal */ - handle, id) { - this.handle = handle; - this.id = id; - } -} -/** - * Controller for a debug info block in the prediction process. Currently cannot do anything. - * - * @public - */ -class PredictionProcessDebugInfoBlockController { - /** @internal */ - constructor( - /** @internal */ - handle, id) { - this.handle = handle; - this.id = id; - } -} -/** - * @public - * - * TODO: Documentation - */ -class PredictionProcessContentBlockController { - /** @internal */ - constructor( - /** @internal */ - handle, id, role) { - this.handle = handle; - this.id = id; - this.role = role; - } - appendText(text, { tokensCount, fromDraftModel, isStructural } = {}) { - if (this.role === "tool") { - throw new Error("Text cannot be appended to tool blocks."); - } - this.handle.sendUpdate({ - type: "contentBlock.appendText", - id: this.id, - text, - tokensCount, - fromDraftModel, - isStructural, - }); - } - appendToolRequest({ callId, toolCallRequestId, name, parameters, pluginIdentifier, }) { - if (this.role !== "assistant") { - throw new Error(`Tool requests can only be appended to assistant blocks. This is a ${this.role} block.`); - } - this.handle.sendUpdate({ - type: "contentBlock.appendToolRequest", - id: this.id, - callId, - toolCallRequestId, - name, - parameters, - pluginIdentifier, - }); - } - replaceToolRequest({ callId, toolCallRequestId, name, parameters, pluginIdentifier, }) { - if (this.role !== "assistant") { - throw new Error(`Tool requests can only be replaced in assistant blocks. This is a ${this.role} block.`); - } - this.handle.sendUpdate({ - type: "contentBlock.replaceToolRequest", - id: this.id, - callId, - toolCallRequestId, - name, - parameters, - pluginIdentifier, - }); - } - appendToolResult({ callId, toolCallRequestId, content, }) { - if (this.role !== "tool") { - throw new Error(`Tool results can only be appended to tool blocks. This is a ${this.role} block.`); - } - this.handle.sendUpdate({ - type: "contentBlock.appendToolResult", - id: this.id, - callId, - toolCallRequestId, - content, - }); - } - replaceText(text) { - if (this.role === "tool") { - throw new Error("Text cannot be set in tool blocks."); - } - this.handle.sendUpdate({ - type: "contentBlock.replaceText", - id: this.id, - text, - }); - } - setStyle(style) { - this.handle.sendUpdate({ - type: "contentBlock.setStyle", - id: this.id, - style, - }); - } - setPrefix(prefix) { - this.handle.sendUpdate({ - type: "contentBlock.setPrefix", - id: this.id, - prefix, - }); - } - setSuffix(suffix) { - this.handle.sendUpdate({ - type: "contentBlock.setSuffix", - id: this.id, - suffix, - }); - } - attachGenInfo(genInfo) { - this.handle.sendUpdate({ - type: "contentBlock.attachGenInfo", - id: this.id, - genInfo, - }); - } - async pipeFrom(prediction) { - const env_1 = { stack: [], error: void 0, hasError: false }; - try { - const cleaner = __addDisposableResource$1(env_1, new Cleaner(), false); - const abortListener = () => { - prediction.cancel(); - }; - this.handle.abortSignal.addEventListener("abort", abortListener); - cleaner.register(() => { - this.handle.abortSignal.removeEventListener("abort", abortListener); - }); - for await (const { content } of prediction) { - this.appendText(content); - } - const result = await prediction; - this.attachGenInfo({ - indexedModelIdentifier: result.modelInfo.path, - identifier: result.modelInfo.identifier, - loadModelConfig: result.loadConfig, - predictionConfig: result.predictionConfig, - stats: result.stats, - }); - this.handle.abortSignal.throwIfAborted(); - return result; - } - catch (e_1) { - env_1.error = e_1; - env_1.hasError = true; - } - finally { - __disposeResources$1(env_1); - } - } -} -/** - * Controller for a tool status block in the prediction process. - * - * @public - */ -class PredictionProcessToolStatusController { - /** @internal */ - constructor( - /** @internal */ - handle, id, initialStatus) { - this.handle = handle; - this.id = id; - this.customStatus = ""; - this.customWarnings = []; - this.status = initialStatus; - } - updateState() { - this.handle.sendUpdate({ - type: "toolStatus.update", - id: this.id, - state: { - status: this.status, - customStatus: this.customStatus, - customWarnings: this.customWarnings, - }, - }); - } - setCustomStatusText(status) { - this.customStatus = status; - this.updateState(); - } - addWarning(warning) { - this.customWarnings.push(warning); - this.updateState(); - } - setStatus(status) { - this.status = status; - this.updateState(); - } - appendArgumentFragment(content) { - this.handle.sendUpdate({ - type: "toolStatus.argumentFragment", - id: this.id, - content, - }); - } -} - -/** - * Controller for tools provider. - * - * @public - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ -class ToolsProviderController extends BaseController { - /** - * @internal Do not construct this class yourself. - */ - constructor(client, signal, pluginConfig, globalPluginConfig, workingDirectoryPath) { - super(client, signal, pluginConfig, globalPluginConfig, workingDirectoryPath); - } -} - -class GeneratorConnectorImpl { - constructor(channel, taskId) { - this.channel = channel; - this.taskId = taskId; - } - fragmentGenerated(content, opts) { - this.channel.send({ - type: "fragmentGenerated", - taskId: this.taskId, - content, - opts: opts, - }); - } - toolCallGenerationStarted(toolCallId) { - this.channel.send({ - type: "toolCallGenerationStarted", - taskId: this.taskId, - toolCallId, - }); - } - toolCallGenerationNameReceived(toolName) { - this.channel.send({ - type: "toolCallGenerationNameReceived", - taskId: this.taskId, - toolName, - }); - } - toolCallGenerationArgumentFragmentGenerated(content) { - this.channel.send({ - type: "toolCallGenerationArgumentFragmentGenerated", - taskId: this.taskId, - content, - }); - } - toolCallGenerationEnded(toolCallRequest) { - this.channel.send({ - type: "toolCallGenerationEnded", - taskId: this.taskId, - toolCallRequest, - }); - } - toolCallGenerationFailed(error) { - this.channel.send({ - type: "toolCallGenerationFailed", - taskId: this.taskId, - error: serializeError(error), - }); - } -} -/** - * @deprecated This class is used internally by a plugin to register hooks. Do not use directly. - * @public - */ -class PluginSelfRegistrationHost { - constructor(port, client, rootLogger, validator) { - this.port = port; - this.client = client; - this.rootLogger = rootLogger; - this.validator = validator; - } - /** - * Sets the promptPreprocessor to be used by the plugin represented by this client. - * - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - setPromptPreprocessor(promptPreprocessor) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("plugins", "registerPromptPreprocessor", "promptPreprocessor", zod.z.function(), promptPreprocessor, stack); - const logger = new SimpleLogger(`PromptPreprocessor`, this.rootLogger); - logger.info("Register with LM Studio"); - const tasks = new Map(); - const channel = this.port.createChannel("setPromptPreprocessor", undefined, message => { - switch (message.type) { - case "preprocess": { - const taskLogger = new SimpleLogger(`Request (${message.taskId.substring(0, 6)})`, logger); - taskLogger.info(`New preprocess request received.`); - const abortController = new AbortController(); - const connector = new ProcessingConnector(this.port, abortController.signal, message.pci, message.token, taskLogger); - const input = ChatMessage.createRaw(message.input, /* mutable */ false); - const controller = new ProcessingController(this.client, message.pluginConfig, message.globalPluginConfig, message.workingDirectoryPath, message.enabledPluginInfos, connector, message.config, - /* shouldIncludeInputInHistory */ false); - tasks.set(message.taskId, { - cancel: () => { - abortController.abort(); - }, - taskLogger, - }); - // We know the input from the channel is immutable, so we can safely pass false as the - // second argument. - promptPreprocessor(controller, input.asMutableCopy()) - .then(result => { - taskLogger.info(`Preprocess request completed.`); - const parsedReturned = zod.z - .union([zod.z.string(), zod.z.custom(v => v instanceof ChatMessage)]) - .safeParse(result); - if (!parsedReturned.success) { - throw new Error("PromptPreprocessor returned an invalid value:" + - Validator.prettyPrintZod("result", parsedReturned.error)); - } - const returned = parsedReturned.data; - let processed; - if (typeof returned === "string") { - const messageCopy = input.asMutableCopy(); - messageCopy.replaceText(returned); - processed = messageCopy.getRaw(); - } - else { - processed = returned.getRaw(); - } - channel.send({ - type: "complete", - taskId: message.taskId, - processed, - }); - }) - .catch(error => { - if (error.name === "AbortError") { - logger.info(`Request successfully aborted.`); - channel.send({ - type: "aborted", - taskId: message.taskId, - }); - return; - } - logger.warn(`Preprocessing failed.`, error); - channel.send({ - type: "error", - taskId: message.taskId, - error: serializeError(error), - }); - }) - .finally(() => { - tasks.delete(message.taskId); - }); - break; - } - case "abort": { - const task = tasks.get(message.taskId); - if (task !== undefined) { - task.taskLogger.info(`Received abort request.`); - task.cancel(); - tasks.delete(message.taskId); - } - break; - } - } - }, { stack }); - } - /** - * Sets the prediction loop handler to be used by the plugin represented by this client. - * - * @deprecated [DEP-PLUGIN-PREDICTION-LOOP-HANDLER] Prediction loop handler support is still in - * development. Stay tuned for updates. - */ - setPredictionLoopHandler(predictionLoopHandler) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("plugins", "setPredictionLoopHandler", "predictionLoopHandler", zod.z.function(), predictionLoopHandler, stack); - const logger = new SimpleLogger(` PredictionLoopHandler`, this.rootLogger); - logger.info("Register with LM Studio"); - const tasks = new Map(); - const channel = this.port.createChannel("setPredictionLoopHandler", undefined, message => { - switch (message.type) { - case "handlePredictionLoop": { - const taskLogger = new SimpleLogger(`Request (${message.taskId.substring(0, 6)})`, logger); - taskLogger.info(`New prediction loop handling request received.`); - const abortController = new AbortController(); - const connector = new ProcessingConnector(this.port, abortController.signal, message.pci, message.token, taskLogger); - const controller = new ProcessingController(this.client, message.pluginConfig, message.globalPluginConfig, message.workingDirectoryPath, message.enabledPluginInfos, connector, message.config, - /* shouldIncludeInputInHistory */ true); - tasks.set(message.taskId, { - cancel: () => { - abortController.abort(); - }, - taskLogger, - }); - // We know the input from the channel is immutable, so we can safely pass false as the - // second argument. - predictionLoopHandler(controller) - .then(() => { - channel.send({ - type: "complete", - taskId: message.taskId, - }); - }) - .catch(error => { - if (error.name === "AbortError") { - logger.info(`Request successfully aborted.`); - channel.send({ - type: "aborted", - taskId: message.taskId, - }); - return; - } - logger.warn(`Generation failed.`, error); - channel.send({ - type: "error", - taskId: message.taskId, - error: serializeError(error), - }); - }) - .finally(() => { - tasks.delete(message.taskId); - }); - break; - } - case "abort": { - const task = tasks.get(message.taskId); - if (task !== undefined) { - task.taskLogger.info(`Received abort request.`); - task.cancel(); - tasks.delete(message.taskId); - } - break; - } - } - }, { stack }); - } - /** - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - async setConfigSchematics(configSchematics) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("plugins", "setConfigSchematics", "configSchematics", zod.z.instanceof(KVConfigSchematics), configSchematics, stack); - await this.port.callRpc("setConfigSchematics", { - schematics: configSchematics.serialize(), - }, { stack }); - } - /** - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - async setGlobalConfigSchematics(globalConfigSchematics) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("plugins", "setGlobalConfigSchematics", "globalConfigSchematics", zod.z.instanceof(KVConfigSchematics), globalConfigSchematics, stack); - await this.port.callRpc("setGlobalConfigSchematics", { - schematics: globalConfigSchematics.serialize(), - }, { stack }); - } - /** - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - setToolsProvider(toolsProvider) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("plugins", "setToolsProvider", "toolsProvider", zod.z.function(), toolsProvider, stack); - const logger = new SimpleLogger(`Tools Prvdr.`, this.rootLogger); - logger.info("Register with LM Studio"); - /** - * Map from sessionId to the open session. - */ - const openSessions = new Map(); - const channel = this.port.createChannel("setToolsProvider", undefined, message => { - const messageType = message.type; - switch (messageType) { - case "initSession": { - const sessionId = message.sessionId; - const sessionAbortController = new AbortController(); - const openSession = { - tools: null, - ongoingToolCalls: new Map(), - discarded: false, - abortController: sessionAbortController, - }; - openSessions.set(sessionId, openSession); - const controller = new ToolsProviderController(this.client, sessionAbortController.signal, message.pluginConfig, message.globalPluginConfig, message.workingDirectoryPath); - toolsProvider(controller).then(tools => { - const llmTools = tools.map(toolToLLMTool); - if (openSession.discarded) { - // By the time initialization is done, the session was already discarded. Don't - // do anything. - return; - } - channel.send({ - type: "sessionInitialized", - sessionId, - toolDefinitions: llmTools, - }); - openSession.tools = new Map(tools.map(tool => [tool.name, tool])); - }, error => { - if (openSession.discarded) { - // If the session was already discarded, don't do anything. - return; - } - channel.send({ - type: "sessionInitializationFailed", - sessionId, - error: serializeError(error), - }); - openSession.discarded = true; - openSessions.delete(sessionId); - }); - break; - } - case "discardSession": { - const sessionId = message.sessionId; - const openSession = openSessions.get(sessionId); - if (openSession === undefined) { - // Session was already discarded or doesn't exist. Ignore. - return; - } - openSession.discarded = true; - openSession.abortController.abort(); - openSessions.delete(sessionId); - break; - } - case "callTool": { - const sessionId = message.sessionId; - const openSession = openSessions.get(sessionId); - if (openSession === undefined) { - // Session was already discarded or doesn't exist. Ignore. - return; - } - if (openSession.tools === null) { - throw new Error("Tool called before initialization completed. This is unexpected."); - } - const tool = openSession.tools.get(message.toolName); - if (tool === undefined) { - throw new Error(`Tool ${message.toolName} not found.`); - } - const callId = message.callId; - const ongoingToolCall = { - settled: false, - abortController: new AbortController(), - }; - openSession.ongoingToolCalls.set(callId, ongoingToolCall); - new SimpleLogger(`Tool (${message.toolName})`, this.rootLogger); - const toolCallContext = { - status(text) { - channel.send({ - type: "toolCallStatus", - sessionId, - callId, - statusText: text, - }); - }, - warn(text) { - channel.send({ - type: "toolCallWarn", - sessionId, - callId, - warnText: text, - }); - }, - signal: ongoingToolCall.abortController.signal, - // Call ID is used to match up life cycle events of the same tool call. In this case, - // each call does not have different parts, thus call ID is useless. We can just use 0. - // If the user wants a "unique" ID, they can just have variable that goes up by one - // each time the function is called. - callId: 0, - }; - (async () => { - return await tool.implementation(message.parameters, toolCallContext); - })().then(result => { - if (openSession.discarded) { - // Session was already discarded. Ignore. - return; - } - if (ongoingToolCall.settled) { - // Tool call was already settled. Ignore. - return; - } - if (ongoingToolCall.abortController.signal.aborted) { - // Tool call was aborted. Ignore. - return; - } - if (result === undefined) { - result = "undefined"; // Default to "undefined" if no result is provided. - channel.send({ - type: "toolCallWarn", - sessionId, - callId, - warnText: text ` - Tool call returned undefined. This is not expected as the model always expects - a result. If you don't want to return anything, you can just return a string - reporting that the tool call was successful. For example: "operation - successful." In this case, we will give the model string "${result}". - `, - }); - } - // Try to see if the result is JSON serializable. If it is not, we will print a - // warning. - try { - JSON.stringify(result); - } - catch (error) { - result = text ` - Error: Tool call completed but returned a value that cannot be serialized to JSON - `; - channel.send({ - type: "toolCallWarn", - sessionId, - callId, - warnText: text ` - Tool call succeeded, but returned a value that is not JSON serializable. In - order to provide the result to the model, return values of tools must be JSON - serializable. In this case, we will give the model string "${result}". - `, - }); - } - channel.send({ - type: "toolCallComplete", - sessionId, - callId, - result, - }); - ongoingToolCall.settled = true; - openSession.ongoingToolCalls.delete(callId); - }, error => { - if (openSession.discarded) { - // Session was already discarded. Ignore. - return; - } - if (ongoingToolCall.settled) { - // Tool call was already settled. Ignore. - return; - } - if (ongoingToolCall.abortController.signal.aborted) { - // Tool call was aborted. Ignore. - return; - } - channel.send({ - type: "toolCallError", - sessionId, - callId, - error: serializeError(error), - }); - ongoingToolCall.settled = true; - openSession.ongoingToolCalls.delete(callId); - }); - break; - } - case "abortToolCall": { - const sessionId = message.sessionId; - const callId = message.callId; - const openSession = openSessions.get(sessionId); - if (openSession === undefined) { - // Session was already discarded or doesn't exist. Ignore. - return; - } - const ongoingToolCall = openSession.ongoingToolCalls.get(callId); - if (ongoingToolCall === undefined) { - // Tool call was already completed or doesn't exist. Ignore. - return; - } - ongoingToolCall.settled = true; - ongoingToolCall.abortController.abort(); - openSession.ongoingToolCalls.delete(callId); - break; - } - default: { - const exhaustiveCheck = messageType; - throw new Error(`Unexpected message type: ${exhaustiveCheck}`); - } - } - }); - } - /** - * Sets the generator to be used by the plugin represented by this client. - * - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - setGenerator(generator) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("plugins", "setGenerator", "generator", generatorSchema, generator, stack); - const logger = new SimpleLogger(`Generator`, this.rootLogger); - logger.info("Register with LM Studio"); - const tasks = new Map(); - const channel = this.port.createChannel("setGenerator", undefined, message => { - const messageType = message.type; - switch (messageType) { - case "generate": { - const taskLogger = new SimpleLogger(`Request (${message.taskId.substring(0, 6)})`, logger); - taskLogger.info(`New generate request received.`); - const abortController = new AbortController(); - const connector = new GeneratorConnectorImpl(channel, message.taskId); - const controller = new GeneratorController(this.client, message.pluginConfig, message.globalPluginConfig, message.workingDirectoryPath, abortController.signal, message.toolDefinitions, connector, this.validator); - tasks.set(message.taskId, { - cancel: () => { - abortController.abort(); - }, - taskLogger, - }); - const history = Chat.createRaw(message.input, false); - generator(controller, history) - .then(result => { - if (result !== undefined) { - taskLogger.warnText ` - The generator has returned a value. This it not expected. You should report - generated content using method on the controller. The returned value will be - ignored. - `; - } - channel.send({ - type: "complete", - taskId: message.taskId, - }); - }, error => { - if (error.name === "AbortError") { - taskLogger.info(`Request successfully aborted.`); - channel.send({ - type: "aborted", - taskId: message.taskId, - }); - } - else { - channel.send({ - type: "error", - taskId: message.taskId, - error: serializeError(error), - }); - taskLogger.warn(`Generation failed.`, error); - } - }) - .finally(() => { - tasks.delete(message.taskId); - }); - break; - } - case "abort": { - const task = tasks.get(message.taskId); - if (task !== undefined) { - task.taskLogger.info(`Received abort request.`); - task.cancel(); - tasks.delete(message.taskId); - } - break; - } - default: { - const exhaustiveCheck = messageType; - throw new Error(`Unexpected message type: ${exhaustiveCheck}`); - } - } - }); - } - /** - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - async initCompleted() { - const stack = getCurrentStack(1); - await this.port.callRpc("pluginInitCompleted", undefined, { stack }); - } -} - -var __addDisposableResource = (globalThis && globalThis.__addDisposableResource) || function (env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose, inner; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; - } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - if (async) inner = dispose; - } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; - env.stack.push({ value: value, dispose: dispose, async: async }); - } - else if (async) { - env.stack.push({ async: true }); - } - return value; -}; -var __disposeResources = (globalThis && globalThis.__disposeResources) || (function (SuppressedError) { - return function (env) { - function fail(e) { - env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; - } - var r, s = 0; - function next() { - while (r = env.stack.pop()) { - try { - if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); - if (r.dispose) { - var result = r.dispose.call(r.value); - if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); - } - else s |= 1; - } - catch (e) { - fail(e); - } - } - if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); - if (env.hasError) throw env.error; - } - return next(); - }; -})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; -}); -/** - * Represents a tool use session backed by a single plugin. Don't construct this class yourself. - * - * @public - */ -class SingleRemoteToolUseSession { - static async create(pluginsPort, pluginIdentifier, pluginConfigSpecifier, logger, stack) { - const session = new SingleRemoteToolUseSession(pluginsPort, pluginIdentifier, pluginConfigSpecifier, logger); - await session.init(stack); - return session; - } - constructor(pluginsPort, pluginIdentifier, pluginConfigSpecifier, logger) { - this.pluginsPort = pluginsPort; - this.pluginIdentifier = pluginIdentifier; - this.pluginConfigSpecifier = pluginConfigSpecifier; - this.logger = logger; - this.status = "initializing"; - /** - * Whether this session is "poisoned". A session is poisoned either when the underlying channel - * has errored/closed. - */ - this.poison = null; - /** - * Map to track all the ongoing tool calls. - */ - this.ongoingToolCalls = new Map(); - this.callIdGiver = new IdGiver(0); - } - async init(stack) { - const { promise: initPromise, resolve: resolveInit, reject: rejectInit } = makePromise(); - const channel = this.pluginsPort.createChannel("startToolUseSession", { - pluginIdentifier: this.pluginIdentifier, - pluginConfigSpecifier: this.pluginConfigSpecifier, - }, message => { - const messageType = message.type; - switch (messageType) { - // Upon receiving session ready, mark self as ready and resolve the promise. - case "sessionReady": { - if (this.status !== "initializing") { - this.logger.error("Received sessionReady message while not initializing"); - return; - } - this.status = "ready"; - resolveInit(); - this.tools = message.toolDefinitions.map(toolDefinition => this.makeTool(toolDefinition)); - break; - } - case "toolCallComplete": { - const ongoingCall = this.ongoingToolCalls.get(message.callId); - if (ongoingCall === undefined) { - return; - } - ongoingCall.resolve(message.result); - break; - } - case "toolCallError": { - const ongoingCall = this.ongoingToolCalls.get(message.callId); - if (ongoingCall === undefined) { - return; - } - ongoingCall.reject(fromSerializedError(message.error)); - break; - } - case "toolCallStatus": { - const ongoingCall = this.ongoingToolCalls.get(message.callId); - if (ongoingCall === undefined) { - return; - } - ongoingCall.reportStatus(message.statusText); - break; - } - case "toolCallWarn": { - const ongoingCall = this.ongoingToolCalls.get(message.callId); - if (ongoingCall === undefined) { - return; - } - ongoingCall.reportWarning(message.warnText); - break; - } - default: { - const exhaustiveCheck = messageType; - this.logger.warn(`Received unexpected message type in tool use session: ${exhaustiveCheck}`); - } - } - }, { stack }); - channel.onError.subscribeOnce(error => { - if (this.status === "initializing") { - // If still initializing, reject the promise with the error. - rejectInit(error); - } - else { - this.logger.error("Tool use session error.", error); - this.poison = error; - } - // Reject all ongoing tool calls with the error. - for (const ongoingCall of this.ongoingToolCalls.values()) { - ongoingCall.reject(error); - } - this.status = "disposed"; - }); - channel.onClose.subscribeOnce(() => { - let error; - if (this.status === "initializing") { - // If still initializing, reject the promise with the error. - error = new Error("Tool use session channel closed unexpectedly during initialization."); - rejectInit(error); - } - else { - error = new Error("Tool use session has already ended."); - // We don't print an error here because channel can close normally. We only poison this - // session so it throws the error when used. - this.poison = error; - } - // Reject all ongoing tool calls with the error. - for (const ongoingCall of this.ongoingToolCalls.values()) { - ongoingCall.reject(error); - } - this.status = "disposed"; - }); - this.channel = channel; - await initPromise; - } - [Symbol.dispose]() { - // As long as we are not already disposed, we send a discard message to the channel. - if (this.status !== "disposed") { - this.channel.send({ type: "discardSession" }); - this.status = "disposed"; - const error = new Error("Session disposed by client."); - // Reject all ongoing tool calls with the error. - for (const ongoingCall of this.ongoingToolCalls.values()) { - ongoingCall.reject(error); - } - this.poison = error; - } - } - makeTool(toolDefinition) { - return internalCreateRemoteTool({ - name: toolDefinition.function.name, - description: toolDefinition.function.description ?? "", - pluginIdentifier: this.pluginIdentifier, - parametersJsonSchema: toolDefinition.function.parameters ?? {}, - implementation: async (args, ctx) => { - const env_1 = { stack: [], error: void 0, hasError: false }; - try { - // We now need to provide an implementation that basically proxies the execution of the tool - // to the backend. - if (this.poison !== null) { - // If the session is already poisoned, throw the error. - throw this.poison; - } - // Handling the case where the request is already aborted before we start the tool call. - if (ctx.signal.aborted) { - throw ctx.signal.reason; - } - const callId = this.callIdGiver.next(); - const { promise, resolve, reject } = makePromise(); - const cleaner = __addDisposableResource(env_1, new Cleaner(), false); - this.ongoingToolCalls.set(callId, { - callId, - resolve, - reject, - reportStatus: status => ctx.status(status), - reportWarning: warning => ctx.warn(warning), - }); - cleaner.register(() => { - this.ongoingToolCalls.delete(callId); - }); - this.channel.send({ - type: "callTool", - callId, - name: toolDefinition.function.name, - arguments: args, - }); - ctx.signal.addEventListener("abort", () => { - if (this.status === "disposed") { - return; - } - this.channel.send({ - type: "abortToolCall", - callId, - }); - reject(ctx.signal.reason); - }, { once: true }); - return await promise; - } - catch (e_1) { - env_1.error = e_1; - env_1.hasError = true; - } - finally { - __disposeResources(env_1); - } - }, - }); - } -} -/** - * Represents a tool use session backed by multiple plugins. Don't construct this class yourself. - * - * @public - */ -class MultiRemoteToolUseSession { - static async createUsingPredictionProcess(pluginsPort, pluginIdentifiers, predictionContextIdentifier, token, logger, stack) { - // Start initializing all the sessions in parallel. This is OK because usually all the plugins - // are already loaded for the prediction process anyway. - const results = await Promise.allSettled(pluginIdentifiers.map(pluginIdentifier => SingleRemoteToolUseSession.create(pluginsPort, pluginIdentifier, { - type: "predictionProcess", - pci: predictionContextIdentifier, - token, - }, logger, stack))); - const failed = results.filter(result => result.status === "rejected"); - if (failed.length > 0) { - // Some sessions failed to initialize. We need to terminate all the sessions that - // successfully initialized. - for (const result of results) { - if (result.status === "fulfilled") { - try { - result.value[Symbol.dispose](); - } - catch (error) { - logger.error("Failed to dispose a session after initialization failure.", error); - } - } - } - throw new AggregateError(failed.map(result => result.reason), "Failed to initialize some tool use sessions."); - } - return new MultiRemoteToolUseSession(results.map(result => result.value), logger); - } - constructor(sessions, logger) { - this.sessions = sessions; - this.logger = logger; - this.tools = []; - this.tools = sessions.flatMap(session => session.tools); - } - [Symbol.dispose]() { - // Dispose all the sessions. - for (const session of this.sessions) { - try { - session[Symbol.dispose](); - } - catch (error) { - this.logger.error("Failed to dispose a session.", error); - } - } - } -} - -const pluginToolsOptsSchema = zod.z.object({ - pluginConfig: kvConfigSchema.optional(), - workingDirectory: zod.z.string().optional(), -}); -const registerDevelopmentPluginOptsSchema = zod.z.object({ - manifest: pluginManifestSchema, -}); -/** - * @public - * - * The namespace for file-related operations. Currently no public-facing methods. - */ -class PluginsNamespace { - /** @internal */ - constructor( - /** @internal */ - port, client, validator, parentLogger, rootLogger) { - this.port = port; - this.client = client; - this.validator = validator; - this.rootLogger = rootLogger; - this.logger = new SimpleLogger("Plugins", parentLogger); - } - /** - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - async registerDevelopmentPlugin(opts) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("plugins", "registerDevelopmentPlugin", "opts", registerDevelopmentPluginOptsSchema, opts, stack); - const { promise, resolve } = makePromise(); - const channel = this.port.createChannel("registerDevelopmentPlugin", opts, message => { - if (message.type === "ready") { - resolve({ - clientIdentifier: message.clientIdentifier, - clientPasskey: message.clientPasskey, - }); - } - }, { stack }); - let unregisterCalled = false; - const unregister = async () => { - if (unregisterCalled) { - return; - } - unregisterCalled = true; - channel.send({ type: "end" }); - const { promise, resolve } = makePromise(); - channel.onClose.subscribeOnce(resolve); - await promise; - }; - const base = await promise; - return { - ...base, - unregister, - }; - } - /** - * Requests LM Studio to reindex all the plugins. - * - * CAVEAT: Currently, we do not wait for the reindex to complete before returning. In the future, - * we will change this behavior and only return after the reindex is completed. - * - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - async reindexPlugins() { - const stack = getCurrentStack(1); - await this.port.callRpc("reindexPlugins", undefined, { stack }); - } - /** - * If this client is currently running as a plugin, get the self registration host which can be - * used to register hooks. - * - * @deprecated This method is used by plugins internally to register hooks. Do not use directly. - */ - getSelfRegistrationHost() { - return new PluginSelfRegistrationHost(this.port, this.client, this.rootLogger, this.validator); - } - /** - * Starts a tool use session use any config specifier. - */ - async internalStartToolUseSession(pluginIdentifier, pluginConfigSpecifier, _stack) { - return await SingleRemoteToolUseSession.create(this.port, pluginIdentifier, pluginConfigSpecifier, this.logger); - } - /** - * Start a tool use session with a plugin. Note, this method must be used with "Explicit Resource - * Management". That is, you should use it like so: - * - * ```typescript - * using pluginTools = await client.plugins.pluginTools("owner/name", { ... }); - * // ^ Notice the `using` keyword here. - * ``` - * - * If you do not use `using`, you must call `pluginTools[Symbol.dispose]()` after you are done. - * Otherwise, there will be a memory leak and the plugins you requested tools from will be loaded - * indefinitely. - * - * @experimental [EXP-USE-USE-PLUGIN-TOOLS] Using tools from other applications is still in - * development. This may change in the future without warning. - */ - async pluginTools(pluginIdentifier, opts = {}) { - const stack = getCurrentStack(1); - [pluginIdentifier, opts] = this.validator.validateMethodParamsOrThrow("plugins", "pluginTools", ["pluginIdentifier", "opts"], [artifactIdentifierSchema, pluginToolsOptsSchema], [pluginIdentifier, opts], stack); - return await this.internalStartToolUseSession(pluginIdentifier, { - type: "direct", - config: opts.pluginConfig ?? emptyKVConfig, - workingDirectoryPath: opts.workingDirectory, - }); - } - /** - * Start a tool use session associated with a prediction process. - * - * This method is used internally by processing controllers and will be stripped by the internal - * tag. - * - * @internal - */ - async startToolUseSessionUsingPredictionProcess(pluginIdentifiers, predictionContextIdentifier, token, stack) { - return await MultiRemoteToolUseSession.createUsingPredictionProcess(this.port, pluginIdentifiers, predictionContextIdentifier, token, this.logger, stack); - } - /** - * @experimental [EXP-GEN-PREDICT] Using generator plugins programmatically is still in - * development. This may change in the future without warning. - */ - createGeneratorHandle(pluginIdentifier) { - return new LLMGeneratorHandle(this.port, pluginIdentifier, this.validator, null, this.logger); - } - /** - * Creates a generator handle that is already associated with a prediction process. - * - * This method is used internally by the processing controllers to create generator handles. It is - * marked as internal and will be stripped. - * - * @internal - */ - createGeneratorHandleAssociatedWithPredictionProcess(pluginIdentifier, predictionContextIdentifier, token) { - return new LLMGeneratorHandle(this.port, pluginIdentifier, this.validator, { pci: predictionContextIdentifier, token }, this.logger); - } -} - -const artifactDownloadPlannerDownloadOptsSchema = zod.z.object({ - onStartFinalizing: zod.z.function().optional(), - onProgress: zod.z.function().optional(), - signal: zod.z.instanceof(AbortSignal).optional(), -}); -/** - * Represents a planner to download an artifact. The plan is not guaranteed to be ready until you - * await on the method "untilReady". - * - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - * @public - */ -class ArtifactDownloadPlanner { - /** - * @internal Do not construct this class yourself. - */ - constructor(owner, name, onPlanUpdated, - /** @internal */ - channel, validator, onDisposed) { - this.owner = owner; - this.name = name; - this.onPlanUpdated = onPlanUpdated; - this.channel = channel; - this.validator = validator; - this.onDisposed = onDisposed; - this.readyDeferredPromise = makePromise(); - this.isReadyBoolean = false; - this.currentDownload = null; - /** - * If we received an error after the download starts, we will just raise the error in the download - * promise. - * - * However, if the error was received before download was called (e.g. plan resolution failed), - * we will store the error here and throw it as soon as `.download` is called. In addition, we - * will also raise the error in the ready promise. However, since it is not required to attach - * a listener there - */ - this.errorReceivedBeforeDownloadStart = null; - this.logger = new SimpleLogger(`ArtifactDownloadPlanner(${owner}/${name})`); - // Don't unhandled rejection - we don't require user to await on this promise. - this.readyDeferredPromise.promise.catch(() => { }); - this.planValue = { - nodes: [ - { - type: "artifact", - owner, - name, - state: "pending", - dependencyNodes: [], - }, - ], - downloadSizeBytes: 0, - }; - this.channel.onMessage.subscribe(message => { - const messageType = message.type; - switch (messageType) { - case "planReady": { - this.isReadyBoolean = true; - this.readyDeferredPromise.resolve(); - this.planValue = message.plan; - break; - } - case "planUpdated": { - this.planValue = message.plan; - safeCallCallback(this.logger, "onPlanUpdated", this.onPlanUpdated, [message.plan]); - break; - } - case "success": { - if (this.currentDownload === null) { - throw new Error("Unexpected: received success message without a download."); - } - this.currentDownload.downloadFinished(); - break; - } - case "downloadProgress": { - if (this.currentDownload === null) { - throw new Error("Unexpected: received progress message without a download."); - } - this.currentDownload.progressUpdate(message.update); - break; - } - case "startFinalizing": { - if (this.currentDownload === null) { - throw new Error("Unexpected: received startFinalizing message without a download."); - } - this.currentDownload.startFinalizing(); - break; - } - } - }); - this.channel.onError.subscribeOnce(error => { - if (this.currentDownload === null) { - this.errorReceivedBeforeDownloadStart = error; - this.readyDeferredPromise.reject(error); - } - else { - this.currentDownload.downloadFailed(error); - } - }); - } - [Symbol.dispose]() { - this.channel.send({ type: "cancel" }); - this.onDisposed(); - } - isReady() { - return this.isReadyBoolean; - } - async untilReady() { - return await this.readyDeferredPromise.promise; - } - getPlan() { - return this.planValue; - } - /** - * Download this artifact. `download` can only be called once. - */ - async download(opts) { - const stack = getCurrentStack(1); - opts = this.validator.validateMethodParamOrThrow("ArtifactDownloadPlanner", "download", "opts", artifactDownloadPlannerDownloadOptsSchema, opts, stack); - const { onProgress, onStartFinalizing, signal = new AbortController().signal } = opts; - if (this.currentDownload !== null) { - throw new Error("You can only call `download` once for each planner."); - } - if (this.errorReceivedBeforeDownloadStart !== null) { - // There has been an error. Raise it immediately. - const error = this.errorReceivedBeforeDownloadStart; - this.errorReceivedBeforeDownloadStart = null; - throw error; - } - const { promise, resolve, reject } = makePromise(); - this.currentDownload = { - downloadFinished: () => { - resolve(); - }, - startFinalizing: () => { - safeCallCallback(this.logger, "onStartFinalizing", onStartFinalizing, []); - }, - progressUpdate: update => { - safeCallCallback(this.logger, "onProgress", onProgress, [update]); - }, - downloadFailed: error => { - reject(error); - }, - }; - this.channel.send({ type: "commit" }); - if (signal.aborted) { - this.channel.send({ type: "cancel" }); - } - else { - signal.addEventListener("abort", () => { - this.channel.send({ type: "cancel" }); - }); - } - return await promise.catch(error => { - if (signal.aborted) { - // If the signal was aborted, we need to reject with the reason of the abort. - throw signal.reason; - } - else { - // Otherwise, we just reject with the error. - throw error; - } - }); - } -} - -const downloadOptsSchema = zod.z.object({ - onProgress: zod.z.function().optional(), - onStartFinalizing: zod.z.function().optional(), - signal: zod.z.instanceof(AbortSignal).optional(), -}); -/** @public */ -class ModelSearchResultDownloadOption { - /** @internal */ - constructor( - /** @internal */ - repositoryPort, - /** @internal */ - validator, logger, data) { - this.repositoryPort = repositoryPort; - this.validator = validator; - this.logger = logger; - this.data = data; - this.quantization = data.quantization; - this.name = data.name; - this.sizeBytes = data.sizeBytes; - this.fitEstimation = this.data.fitEstimation; - this.indexedModelIdentifier = this.data.indexedModelIdentifier; - } - isRecommended() { - return this.data.recommended ?? false; - } - /** - * Download the model. Returns the model key which can be used to load the model. - */ - async download(opts = {}) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("ModelSearchResultDownloadOption", "download", "opts", downloadOptsSchema, opts, stack); - const { promise, resolve, reject } = makePromise(); - const channel = this.repositoryPort.createChannel("downloadModel", { - downloadIdentifier: this.data.downloadIdentifier, - }, message => { - switch (message.type) { - case "downloadProgress": { - safeCallCallback(this.logger, "onProgress", opts.onProgress, [message.update]); - break; - } - case "startFinalizing": { - safeCallCallback(this.logger, "onStartFinalizing", opts.onStartFinalizing, []); - break; - } - case "success": { - resolve(message.defaultIdentifier); - break; - } - default: { - const exhaustiveCheck = message; - throw new Error(`Unexpected message type: ${exhaustiveCheck}`); - } - } - }, { stack }); - channel.onError.subscribeOnce(error => { - if (opts.signal?.aborted) { - reject(opts.signal.reason); - } - else { - reject(error); - } - }); - channel.onClose.subscribeOnce(() => { - if (opts.signal?.aborted) { - reject(opts.signal.reason); - } - else { - reject(new Error("Channel closed unexpectedly.")); - } - }); - const abortListener = () => { - channel.send({ type: "cancel" }); - }; - opts.signal?.addEventListener("abort", abortListener); - promise.finally(() => { - opts.signal?.removeEventListener("abort", abortListener); - }); - return await promise; - } -} - -/** @public */ -class ModelSearchResultEntry { - /** - * @internal - */ - constructor( - /** @internal */ - repositoryPort, - /** @internal */ - validator, logger, data) { - this.repositoryPort = repositoryPort; - this.validator = validator; - this.logger = logger; - this.data = data; - this.name = data.name; - } - isExactMatch() { - return this.data.exact ?? false; - } - isStaffPick() { - return this.data.staffPick ?? false; - } - async getDownloadOptions() { - const { results } = await this.repositoryPort.callRpc("getModelDownloadOptions", { - modelSearchResultIdentifier: this.data.identifier, - }); - return results.map(data => new ModelSearchResultDownloadOption(this.repositoryPort, this.validator, this.logger, data)); - } -} - -const downloadArtifactOptsSchema = zod.z.object({ - owner: zod.z.string(), - name: zod.z.string(), - revisionNumber: zod.z.number(), - path: zod.z.string(), - onProgress: zod.z.function().optional(), - onStartFinalizing: zod.z.function().optional(), - signal: zod.z.instanceof(AbortSignal).optional(), -}); -const pushArtifactOptsSchema = zod.z.object({ - path: zod.z.string(), - description: zod.z.string().optional(), - makePrivate: zod.z.boolean().optional(), - writeRevision: zod.z.boolean().optional(), - overrides: jsonSerializableSchema.optional(), - onMessage: zod.z.function().optional(), -}); -const ensureAuthenticatedOptsSchema = zod.z.object({ - onAuthenticationUrl: zod.z.function(), -}); -const loginWithPreAuthenticatedKeysOptsSchema = zod.z.object({ - keyId: zod.z.string(), - publicKey: zod.z.string(), - privateKey: zod.z.string(), -}); -zod.z.object({ - userName: zod.z.string(), -}); -const createArtifactDownloadPlannerOptsSchema = zod.z.object({ - owner: zod.z.string(), - name: zod.z.string(), - onPlanUpdated: zod.z.function().optional(), -}); -/** @public */ -class RepositoryNamespace { - /** @internal */ - constructor(repositoryPort, validator, parentLogger) { - this.repositoryPort = repositoryPort; - this.validator = validator; - this.downloadPlanFinalizationRegistry = new FinalizationRegistry(({ owner, name }) => { - this.logger.warn(` - A download plan for artifact ${owner}/${name} has been garbage collected without being - disposed. Please make sure you are creating the download plan with the "using" keyword. - - This is a memory leak and needs to be fixed. - `); - }); - this.logger = new SimpleLogger("Repository", parentLogger); - } - async searchModels(opts) { - const stack = getCurrentStack(1); - opts = this.validator.validateMethodParamOrThrow("repository", "search", "opts", modelSearchOptsSchema, opts, stack); - const { results } = await this.repositoryPort.callRpc("searchModels", { opts }, { stack }); - return results.map(data => new ModelSearchResultEntry(this.repositoryPort, this.validator, this.logger, data)); - } - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - async installPluginDependencies(pluginFolder) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("repository", "installPluginDependencies", "pluginFolder", zod.z.string(), pluginFolder, stack); - await this.repositoryPort.callRpc("installPluginDependencies", { pluginFolder }, { stack }); - } - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - async downloadArtifact(opts) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("client.repository", "downloadArtifact", "opts", downloadArtifactOptsSchema, opts, stack); - const { owner, name, revisionNumber, path, onProgress, onStartFinalizing, signal } = opts; - const { promise, resolve, reject } = makePromise(); - const channel = this.repositoryPort.createChannel("downloadArtifact", { artifactOwner: owner, artifactName: name, revisionNumber, path }, message => { - switch (message.type) { - case "downloadProgress": { - safeCallCallback(this.logger, "onProgress", onProgress, [message.update]); - break; - } - case "startFinalizing": { - safeCallCallback(this.logger, "onStartFinalizing", onStartFinalizing, []); - break; - } - case "success": { - resolve(); - break; - } - default: { - const exhaustiveCheck = message; - throw new Error(`Unexpected message type: ${exhaustiveCheck}`); - } - } - }, { stack }); - channel.onError.subscribeOnce(reject); - channel.onClose.subscribeOnce(() => { - if (signal?.aborted) { - reject(signal.reason); - } - else { - reject(new Error("Channel closed unexpectedly.")); - } - }); - const abortListener = () => { - channel.send({ type: "cancel" }); - }; - signal?.addEventListener("abort", abortListener); - promise.finally(() => { - signal?.removeEventListener("abort", abortListener); - }); - return await promise; - } - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - async pushArtifact(opts) { - const stack = getCurrentStack(1); - const { path, description, makePrivate, writeRevision, overrides, onMessage } = this.validator.validateMethodParamOrThrow("repository", "pushArtifact", "opts", pushArtifactOptsSchema, opts, stack); - const channel = this.repositoryPort.createChannel("pushArtifact", { path, description, makePrivate, writeRevision, overrides }, message => { - const type = message.type; - switch (type) { - case "message": { - safeCallCallback(this.logger, "onMessage", onMessage, [message.message]); - break; - } - default: { - const exhaustiveCheck = type; - throw new Error(`Unexpected message type: ${exhaustiveCheck}`); - } - } - }, { stack }); - const { promise, resolve, reject } = makePromise(); - channel.onError.subscribeOnce(reject); - channel.onClose.subscribeOnce(resolve); - await promise; - } - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - async getLocalArtifactFileList(path) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("repository", "getLocalArtifactFileList", "path", zod.z.string(), path, stack); - const { fileList } = await this.repositoryPort.callRpc("getLocalArtifactFiles", { path }, { stack }); - return fileList; - } - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - async ensureAuthenticated(opts) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("repository", "ensureAuthenticated", "opts", ensureAuthenticatedOptsSchema, opts, stack); - const { promise, resolve, reject } = makePromise(); - const channel = this.repositoryPort.createChannel("ensureAuthenticated", undefined, message => { - const type = message.type; - switch (type) { - case "authenticationUrl": { - safeCallCallback(this.logger, "onAuthenticationUrl", opts.onAuthenticationUrl, [ - message.url, - ]); - break; - } - case "authenticated": { - resolve(); - break; - } - default: { - const exhaustiveCheck = type; - throw new Error(`Unexpected message type: ${exhaustiveCheck}`); - } - } - }); - channel.onError.subscribeOnce(reject); - await promise; - } - async loginWithPreAuthenticatedKeys(opts) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("repository", "loginWithPreAuthenticatedKeys", "opts", loginWithPreAuthenticatedKeysOptsSchema, opts, stack); - const { keyId, publicKey, privateKey } = opts; - const { userName } = await this.repositoryPort.callRpc("loginWithPreAuthenticatedKeys", { keyId, publicKey, privateKey }, { stack }); - return { userName }; - } - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - createArtifactDownloadPlanner(opts) { - const { owner, name, onPlanUpdated } = this.validator.validateMethodParamOrThrow("repository", "createArtifactDownloadPlanner", "opts", createArtifactDownloadPlannerOptsSchema, opts); - const stack = getCurrentStack(1); - const channel = this.repositoryPort.createChannel("createArtifactDownloadPlan", { owner, name }, undefined, // Don't listen to the messages yet. - { stack }); - const planner = new ArtifactDownloadPlanner(owner, name, onPlanUpdated, channel, this.validator, () => { - this.downloadPlanFinalizationRegistry.unregister(planner); - }); - this.downloadPlanFinalizationRegistry.register(planner, { owner, name }, planner); - return planner; - } -} - -const startHttpServerOptsSchema = zod.z.object({ - port: zod.z - .number() - .int() - .min(1) - .max(65535) - .describe("Port to run the API server on. Must be between 1 and 65535."), - cors: zod.z - .boolean() - .describe("Enable CORS on the API server. Allows any website to access the server."), -}); -/** @public */ -class SystemNamespace { - /** @internal */ - constructor(systemPort, validator, parentLogger) { - this.systemPort = systemPort; - this.validator = validator; - this.logger = new SimpleLogger("System", parentLogger); - } - async listDownloadedModels(domain) { - const stack = getCurrentStack(1); - domain = this.validator.validateMethodParamOrThrow("client.system", "listDownloadedModels", "domain", zod.z.union([zod.z.literal("llm"), zod.z.literal("embedding"), zod.z.undefined()]), domain, stack); - const models = await this.systemPort.callRpc("listDownloadedModels", undefined, { - stack: getCurrentStack(1), - }); - if (domain === undefined) { - return models; - } - return models.filter(model => model.type === domain); - } - async whenDisconnected() { - const stack = getCurrentStack(1); - const channel = this.systemPort.createChannel("alive", undefined, undefined, { stack }); - const { promise, resolve } = makePromise(); - channel.onError.subscribeOnce(resolve); - channel.onClose.subscribeOnce(resolve); - await promise; - } - async notify(notification) { - const stack = getCurrentStack(1); - notification = this.validator.validateMethodParamOrThrow("client.system", "notify", "notification", backendNotificationSchema, notification, stack); - await this.systemPort.callRpc("notify", notification, { stack }); - } - async getLMStudioVersion() { - const stack = getCurrentStack(1); - return await this.systemPort.callRpc("version", undefined, { stack }); - } - /** - * Sets an experiment flags for LM Studio. This is an unstable API and may change without notice. - * - * @experimental - */ - async unstable_setExperimentFlag(flag, value) { - const stack = getCurrentStack(1); - [flag, value] = this.validator.validateMethodParamsOrThrow("client.system", "setExperimentFlag", ["flag", "value"], [zod.z.string(), zod.z.boolean()], [flag, value], stack); - await this.systemPort.callRpc("setExperimentFlag", { code: flag, value }, { stack }); - } - /** - * Gets all experiment flags for LM Studio. This is an unstable API and may change without notice. - * - * @experimental - */ - async unstable_getExperimentFlags() { - const stack = getCurrentStack(1); - return await this.systemPort.callRpc("getExperimentFlags", undefined, { stack }); - } - /** - * Starts the API server on the specified port. - * - * @experimental - */ - async startHttpServer(opts) { - const stack = getCurrentStack(1); - opts = this.validator.validateMethodParamOrThrow("client.system", "startHttpServer", "args", startHttpServerOptsSchema, opts); - return await this.systemPort.callRpc("startHttpServer", { port: opts.port, cors: opts.cors }, { - stack, - }); - } - /** - * Stops the API server if it is running. - * - * @experimental - */ - async stopHttpServer() { - const stack = getCurrentStack(1); - return await this.systemPort.callRpc("stopHttpServer", undefined, { stack }); - } -} - -const constructorOptsSchema = zod.z - .object({ - logger: zod.z.any().optional(), - baseUrl: zod.z.string().optional(), - verboseErrorMessages: zod.z.boolean().optional(), - clientIdentifier: zod.z.string().optional(), - clientPasskey: zod.z.string().optional(), - // Internal testing options - disableConnection: zod.z.boolean().optional(), - llmPort: zod.z.any().optional(), - embeddingPort: zod.z.any().optional(), - systemPort: zod.z.any().optional(), - diagnosticsPort: zod.z.any().optional(), - retrievalPort: zod.z.any().optional(), - filesPort: zod.z.any().optional(), - repositoryPort: zod.z.any().optional(), - pluginsPort: zod.z.any().optional(), -}) - .strict(); -/** @public */ -class LMStudioClient { - /** @internal */ - validateBaseUrlOrThrow(baseUrl) { - let url; - try { - url = new URL(baseUrl); - } - catch (e) { - this.logger.throw(text ` - Failed to construct LMStudioClient. The baseUrl passed in is invalid. Received: ${baseUrl} - `); - } - if (!["ws:", "wss:"].includes(url.protocol)) { - this.logger.throw(text ` - Failed to construct LMStudioClient. The baseUrl passed in must have protocol "ws" or "wss". - Received: ${baseUrl} - `); - } - if (url.search !== "") { - this.logger.throw(text ` - Failed to construct LMStudioClient. The baseUrl passed contains search parameters - ("${url.search}"). - `); - } - if (url.hash !== "") { - this.logger.throw(text ` - Failed to construct LMStudioClient. The baseUrl passed contains a hash ("${url.hash}"). - `); - } - if (url.username !== "" || url.password !== "") { - this.logger.throw(text ` - Failed to construct LMStudioClient. The baseUrl passed contains a username or password. We - do not support these in the baseUrl. Received: ${baseUrl} - `); - } - if (baseUrl.endsWith("/")) { - this.logger.throw(text ` - Failed to construct LMStudioClient. The baseUrl passed in must not end with a "/". If you - are reverse-proxying, you should remove the trailing slash from the baseUrl. Received: - ${baseUrl} - `); - } - } - async isLocalhostWithGivenPortLMStudioServer(port) { - const response = await fetch(`http://127.0.0.1:${port}/lmstudio-greeting`); - if (response.status !== 200) { - throw new Error("Status is not 200."); - } - const json = await response.json(); - if (json?.lmstudio !== true) { - throw new Error("Not an LM Studio server."); - } - return port; - } - /** - * Guess the base URL of the LM Studio server by visiting localhost on various default ports. - */ - async guessBaseUrl(stack) { - if (getHostedEnv() !== null) { - return Promise.resolve("Using hosted env"); - } - // On browser, those apiServerPorts are not accessible anyway. We will just try to see if we can - // reach the server on 127.0.0.1:1234 (the default port). - if (process$1.browser) { - try { - this.isLocalhostWithGivenPortLMStudioServer(1234); - return "ws://127.0.0.1:1234"; - } - catch (error) { - text ` - ${chalk.redBright("Failed to connect to LM Studio.")} - - Is LM Studio running? If not, please start it by running: - - ${chalk.yellow("lms server start --cors")} - - If you are attempting to connect to LM Studio on a separate machine, please provide the - baseUrl option when creating the LMStudioClient: - - ${chalk.blueBright(text ` - const client = new LMStudioClient({ baseUrl: 'ws://:' }); - `)} - - ${chalk.white("(i) For more information, refer to the LM Studio documentation:")} - - ${chalk.gray("https://lmstudio.ai/docs/local-server")} - `; - } - } - return Promise.any(apiServerPorts.map(this.isLocalhostWithGivenPortLMStudioServer)).then(port => `ws://127.0.0.1:${port}`, () => { - throw makePrettyError(text ` - ${chalk.redBright("Failed to connect to LM Studio.")} - - Please make sure LM Studio is running on your machine. - - If you are attempting to connect to LM Studio on a separate machine, please provide the - baseUrl option when creating the LMStudioClient: - - ${chalk.blueBright(text ` - const client = new LMStudioClient({ baseUrl: 'ws://:' }); - `)} - - ${chalk.white("(i) For more information, refer to the LM Studio documentation:")} - - ${chalk.gray("https://lmstudio.ai/docs/local-server")} - `, stack); - }); - } - createPort(namespace, name, backendInterface) { - return createAuthenticatedClientPort(backendInterface, this.resolvingBaseUrl, namespace, this.clientIdentifier, this.clientPasskey, new SimpleLogger(name, this.logger), { - errorDeserializer: friendlyErrorDeserializer, - verboseErrorMessage: this.verboseErrorMessages, - }); - } - constructor(opts = {}) { - const { logger, baseUrl, verboseErrorMessages, clientIdentifier, clientPasskey, disableConnection, llmPort, embeddingPort, systemPort, diagnosticsPort, retrievalPort, filesPort, repositoryPort, pluginsPort, } = new Validator().validateConstructorParamOrThrow("LMStudioClient", "opts", constructorOptsSchema, opts); - if (globalThis.__LMS_PLUGIN_CONTEXT && opts.baseUrl === undefined) { - throw new Error(text ` - You cannot create a local LMStudioClient in a plugin context. To use LM Studio APIs, use - the "client" property attached to the Controllers. - - For example, instead of: - - ${"const client = new LMStudioClient(); // <-- Error\n" + - "export async function generate(ctl: GeneratorController) {\n" + - " const model = await client.llm.model(...);\n" + - "}"} - - Do this: - - ${"export async function generate(ctl: GeneratorController) {\n" + - " const model = await ctl.client.llm.model(...);\n" + - "}"} - - If you need to connect to a remote LM Studio, you should pass in the \`baseUrl\` option to - the LMStudioClient constructor: - - ${"const client = new LMStudioClient({ baseUrl: 'ws://:' });"} - `); - } - this.logger = new SimpleLogger("LMStudioClient", logger); - this.clientIdentifier = clientIdentifier ?? lmsIsomorphic.generateRandomBase64(18); - this.clientPasskey = clientPasskey ?? lmsIsomorphic.generateRandomBase64(18); - const stack = getCurrentStack(1); - if (disableConnection) { - this.resolvingBaseUrl = new Promise(() => undefined); - } - else { - if (baseUrl === undefined) { - this.resolvingBaseUrl = this.guessBaseUrl(verboseErrorMessages ? stack : undefined); - } - else { - this.validateBaseUrlOrThrow(baseUrl); - this.resolvingBaseUrl = baseUrl; - } - } - this.verboseErrorMessages = verboseErrorMessages ?? true; - this.llmPort = llmPort ?? this.createPort("llm", "LLM", createLlmBackendInterface()); - this.embeddingPort = - embeddingPort ?? this.createPort("embedding", "Embedding", createEmbeddingBackendInterface()); - this.systemPort = - systemPort ?? this.createPort("system", "System", createSystemBackendInterface()); - this.diagnosticsPort = - diagnosticsPort ?? - this.createPort("diagnostics", "Diagnostics", createDiagnosticsBackendInterface()); - this.filesPort = filesPort ?? this.createPort("files", "Files", createFilesBackendInterface()); - this.repositoryPort = - repositoryPort ?? - this.createPort("repository", "Repository", createRepositoryBackendInterface()); - this.pluginsPort = - pluginsPort ?? this.createPort("plugins", "Plugins", createPluginsBackendInterface()); - const validator = new Validator(); - this.llm = new LLMNamespace(this, this.llmPort, new SimpleLogger("LLM", this.logger), validator); - this.embedding = new EmbeddingNamespace(this, this.embeddingPort, new SimpleLogger("Embedding", this.logger), validator); - this.system = new SystemNamespace(this.systemPort, validator, this.logger); - this.diagnostics = new DiagnosticsNamespace(this.diagnosticsPort, validator, this.logger); - this.files = new FilesNamespace(this.filesPort, validator, this.logger); - this.repository = new RepositoryNamespace(this.repositoryPort, validator, this.logger); - this.plugins = new PluginsNamespace(this.pluginsPort, this, validator, this.logger, logger); - } - async [Symbol.asyncDispose]() { - await Promise.all([ - this.llmPort[Symbol.asyncDispose](), - this.embeddingPort[Symbol.asyncDispose](), - this.systemPort[Symbol.asyncDispose](), - this.diagnosticsPort[Symbol.asyncDispose](), - this.filesPort[Symbol.asyncDispose](), - this.repositoryPort[Symbol.asyncDispose](), - this.pluginsPort[Symbol.asyncDispose](), - ]); - } -} - -exports.Chat = Chat; -exports.ChatMessage = ChatMessage; -exports.FileHandle = FileHandle; -exports.LMStudioClient = LMStudioClient; -exports.MaybeMutable = MaybeMutable; -exports.ToolCallRequestError = ToolCallRequestError; -exports.createConfigSchematics = createConfigSchematics; -exports.kvValueTypesLibrary = kvValueTypesLibrary; -exports.rawFunctionTool = rawFunctionTool; -exports.text = text; -exports.tool = tool; -exports.unimplementedRawFunctionTool = unimplementedRawFunctionTool; diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/dist/index.d.ts b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/dist/index.d.ts deleted file mode 100644 index 4a8243bcf..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/dist/index.d.ts +++ /dev/null @@ -1,9920 +0,0 @@ -import { Patch } from '@lmstudio/immer-with-plugins'; -import { z } from 'zod'; -import { ZodError } from 'zod'; -import { ZodSchema } from 'zod'; -import { ZodType } from 'zod'; - -/** - * Represents the result of running `llm.act`. Currently only contains minimum amount of - * information. - * - * If you think more information/fields should be added, please open an issue or a PR on GitHub. - * - * @public - */ -export declare class ActResult { - /** - * Number of rounds performed. - * - * For example, in the following scenario: - * - * - User asks the model to add 1234 and 5678. - * - The model requests to use a calculator tool. - * - The calculator tool outputs 6912. - * - The calculator's output is then fed back to the model for a second round of prediction. - * - The model sees the output and generates a paragraph explaining the result. - * - * There are 2 rounds. On the beginning of a round, the callback `onRoundStart` is triggered. - * On the end of a round, the callback `onRoundEnd` is triggered. - */ - readonly rounds: number; - /** - * Total time taken to run `.act` in seconds. measured from beginning of the `.act` invocation - * to when the entire operation is finished. - */ - readonly totalExecutionTimeSeconds: number; - constructor( - /** - * Number of rounds performed. - * - * For example, in the following scenario: - * - * - User asks the model to add 1234 and 5678. - * - The model requests to use a calculator tool. - * - The calculator tool outputs 6912. - * - The calculator's output is then fed back to the model for a second round of prediction. - * - The model sees the output and generates a paragraph explaining the result. - * - * There are 2 rounds. On the beginning of a round, the callback `onRoundStart` is triggered. - * On the end of a round, the callback `onRoundEnd` is triggered. - */ - rounds: number, - /** - * Total time taken to run `.act` in seconds. measured from beginning of the `.act` invocation - * to when the entire operation is finished. - */ - totalExecutionTimeSeconds: number); -} - -/** - * Type representing the environment variables that can be set by the user. - * - * @public - */ -export declare type AllowableEnvVarKeys = "HSA_OVERRIDE_GFX_VERSION"; - -/** - * Allow-list only record of environment variables and their values. - * - * @public - */ -export declare type AllowableEnvVars = Partial>; - -/** - * Represents a dependency on other artifacts. - * - * @public - */ -export declare interface ArtifactArtifactDependency extends ArtifactDependencyBase { - type: "artifact"; - owner: string; - name: string; -} - -/** - * Represents a dependency of an artifact. - * - * @public - */ -export declare type ArtifactDependency = ArtifactModelDependency | ArtifactArtifactDependency; - -/** - * Represents the base type for an artifact dependency. - * - * @public - */ -export declare interface ArtifactDependencyBase { - purpose: ArtifactDependencyPurpose; -} - -/** - * Represents the purpose of an artifact dependency. - * - * @public - */ -export declare type ArtifactDependencyPurpose = "baseModel" | "draftModel" | "custom"; - -/** - * Represents a plan for downloading artifacts. - * - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - * @public - */ -export declare interface ArtifactDownloadPlan { - nodes: Array; - downloadSizeBytes: number; -} - -/** - * Represents information about a model in an artifact download plan. - * - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - * @public - */ -export declare type ArtifactDownloadPlanModelInfo = { - displayName: string; - sizeBytes: number; - quantName?: string; - compatibilityType: ModelCompatibilityType; -}; - -/** - * Represents a planner to download an artifact. The plan is not guaranteed to be ready until you - * await on the method "untilReady". - * - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - * @public - */ -export declare class ArtifactDownloadPlanner { - readonly owner: string; - readonly name: string; - private readonly onPlanUpdated; - private readonly validator; - private readonly onDisposed; - private readyDeferredPromise; - private readonly logger; - private isReadyBoolean; - private planValue; - private currentDownload; - /** - * If we received an error after the download starts, we will just raise the error in the download - * promise. - * - * However, if the error was received before download was called (e.g. plan resolution failed), - * we will store the error here and throw it as soon as `.download` is called. In addition, we - * will also raise the error in the ready promise. However, since it is not required to attach - * a listener there - */ - private errorReceivedBeforeDownloadStart; - [Symbol.dispose](): void; - isReady(): boolean; - untilReady(): Promise; - getPlan(): ArtifactDownloadPlan; - /** - * Download this artifact. `download` can only be called once. - */ - download(opts: ArtifactDownloadPlannerDownloadOpts): Promise; -} - -/** - * Options for the {@link ArtifactDownloadPlanner#download} method. - * - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - * @public - */ -export declare interface ArtifactDownloadPlannerDownloadOpts { - onStartFinalizing?: () => void; - onProgress?: (update: DownloadProgressUpdate) => void; - signal?: AbortSignal; -} - -/** - * Represents the state of a node in an artifact download plan. - * - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - * @public - */ -export declare type ArtifactDownloadPlanNode = { - type: "artifact"; - owner: string; - name: string; - state: ArtifactDownloadPlanNodeState; - artifactType?: ArtifactType; - sizeBytes?: number; - dependencyNodes: Array; -} | { - type: "model"; - state: ArtifactDownloadPlanNodeState; - resolvedSources?: number; - totalSources?: number; - alreadyOwned?: ArtifactDownloadPlanModelInfo; - selected?: ArtifactDownloadPlanModelInfo; -}; - -/** - * Represents the state of a node in an artifact download plan. - * - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - * @public - */ -export declare type ArtifactDownloadPlanNodeState = "pending" | "fetching" | "satisfied" | "completed"; - -/** - * Base type for the manifest of an artifact. - * - * @public - */ -export declare interface ArtifactManifestBase { - owner: string; - name: string; - revision?: number; - dependencies?: Array; - tags?: Array; -} - -/** - * Represents a dependency on a concrete model. - * - * @public - */ -export declare interface ArtifactModelDependency extends ArtifactDependencyBase { - type: "model"; - /** - * The model key. This is used to identify if whether the dependency has been downloaded or not. - * Any model matching any of the model keys listed here will be considered a match, and can - * satisfy the entire model dependency. - */ - modelKeys: Array; - /** - * Describes how to download the model. Currently only supports downloading from a URL. - */ - sources: Array; -} - -/** - * Represents the type of an artifact. - * - * @public - */ -export declare type ArtifactType = "plugin" | "preset" | "model"; - -/** - * When deriving with an async function, how to reconcile multiple updates coming in out of order. - * - * - "eager": Always apply the change as long as the update is newer than the last one. - */ -declare type AsyncDeriveFromStrategy = "eager"; - -declare class BackendInterface { - private unhandledEndpoints; - private existingEndpointNames; - private rpcEndpoints; - private channelEndpoints; - private signalEndpoints; - private writableSignalEndpoints; - constructor(); - withContextType(): BackendInterface; - private assertEndpointNameNotExists; - /** - * Register an Rpc endpoint. - */ - addRpcEndpoint(endpointName: TEndpointName, { parameter, returns, serialization, }: { - parameter: TParametersZod; - returns: TReturnsZod; - serialization?: SerializationType; - }): BackendInterface; - returns: z.infer; - }; - }, TChannelEndpoints, TSignalEndpoints, TWritableSignalEndpoints>; - addChannelEndpoint(endpointName: TEndpointName, { creationParameter, toServerPacket, toClientPacket, serialization, }: { - creationParameter: TCreationParameterZod; - toServerPacket: TToServerPacketZod; - toClientPacket: TToClientPacketZod; - serialization?: SerializationType; - }): BackendInterface; - toServerPacket: z.infer; - toClientPacket: z.infer; - }; - }, TSignalEndpoints, TWritableSignalEndpoints>; - addSignalEndpoint(endpointName: TEndpointName, { creationParameter, signalData, serialization, }: { - creationParameter: TCreationParameterZod; - signalData: TSignalDataZod; - serialization?: SerializationType; - }): BackendInterface; - signalData: z.infer; - }; - }, TWritableSignalEndpoints>; - addWritableSignalEndpoint(endpointName: TEndpointName, { creationParameter, signalData, serialization, }: { - creationParameter: TCreationParameterZod; - signalData: TSignalDataZod; - serialization?: SerializationType; - }): BackendInterface; - signalData: z.infer; - }; - }>; - /** - * Adds a handler for an Rpc endpoint. - * - * @param endpointName - The name of the endpoint. - * @param handler - The handler function. Will be called when the endpoint is invoked. When - * called, the first parameter is the context, and the second parameter is the "parameter" for the - * RPC call. Can return a value or a promise that resolves to the result. - */ - handleRpcEndpoint(endpointName: TEndpointName, handler: RpcEndpointHandler): void; - /** - * Adds a handler for a channel endpoint. - * - * @param endpointName - The name of the endpoint. - * @param handler - The handler function. Will be called when the client creates a channel for - * this endpoint. When called, the first parameter is the context, the second parameter is the - * "creationParameter" for the channel, and the third parameter is a channel object that can be - * used to send and receive messages from the client. - * - * Must return a promise. Once that promise is settled, the channel will be closed. - */ - handleChannelEndpoint(endpointName: TEndpointName, handler: ChannelEndpointHandler): void; - /** - * Adds a handler for a signal endpoint. - * - * @param endpointName - The name of the endpoint. - * @param handler - The handler function. Will be called when the client creates a signal, and at - * least one subscriber is attached to that signal. When called, the first parameter is the - * context, and the second parameter is the "creationParameter" for the signal. This method should - * return a SignalLike, or a promise that resolves to a SignalLike. - * - * Note: There is no 1-to-1 correlation between the signal on the client side and the number of - * times this handler is called. Every time the number of client subscribers changes from 0 to 1, - * this handler will be called. Every time the number of client subscribers changes from 1 to 0, - * the signal returned from this handler will be unsubscribed. - * - * Caution: Do NOT create new subscriptions that don't self-terminate in this handler, as it will - * cause memory leaks. That is, either: - * - * - Return a signal that already exists - * - Create and return a LazySignal - */ - handleSignalEndpoint(endpointName: TEndpointName, handler: SignalEndpointHandler): void; - /** - * Adds a handler for a writable signal endpoint. - * - * @param endpointName - The name of the endpoint. - * @param handler - The handler function. Will be called when the client creates a writable - * signal, and at least one subscriber is attached to that signal. When called, the first - * parameter is the context, and the second parameter is the "creationParameter" for the signal. - * This method should return a tuple of the signal and an update function. The update function - * should be called with the new data, patches, and tags to update the signal. - * - * Note: There is no 1-to-1 correlation between the signal on the client side and the number of - * times this handler is called. Every time the number of client subscribers changes from 0 to 1, - * this handler will be called. Every time the number of client subscribers changes from 1 to 0 - * the signal returned from this handler will be unsubscribed. - * - * Caution: Do NOT create new subscriptions that don't self-terminate in this handler, as it will - * cause memory leaks. That is, either: - * - * - Return a signal that already exists - * - Create and return a LazySignal - */ - handleWritableSignalEndpoint(endpointName: TEndpointName, handler: WritableSignalEndpointHandler): void; - assertAllEndpointsHandled(): void; - getRpcEndpoint(endpointName: string): RpcEndpoint | undefined; - getAllRpcEndpoints(): RpcEndpoint[]; - getChannelEndpoint(endpointName: string): ChannelEndpoint | undefined; - getAllChannelEndpoints(): ChannelEndpoint[]; - getSignalEndpoint(endpointName: string): SignalEndpoint | undefined; - getAllSignalEndpoints(): SignalEndpoint[]; - getWritableSignalEndpoint(endpointName: string): WritableSignalEndpoint | undefined; - getAllWritableSignalEndpoints(): WritableSignalEndpoint[]; -} - -/** - * @public - */ -export declare interface BackendNotification { - title: string; - description?: string; - noAutoDismiss?: boolean; -} - -/** - * The base class for all controllers. - * - * @public - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ -export declare abstract class BaseController { - /** - * The LM Studio client instance. Use this to interact with the LM Studio API. - */ - readonly client: LMStudioClient; - /** - * The abort signal that you should listen to for cancellation requests. - * - * See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal for more information about - * abort signals. - */ - readonly abortSignal: AbortSignal; - private readonly pluginConfig; - private readonly globalPluginConfig; - private readonly workingDirectoryPath; - constructor( - /** - * The LM Studio client instance. Use this to interact with the LM Studio API. - */ - client: LMStudioClient, - /** - * The abort signal that you should listen to for cancellation requests. - * - * See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal for more information about - * abort signals. - */ - abortSignal: AbortSignal, pluginConfig: KVConfig, globalPluginConfig: KVConfig, workingDirectoryPath: string | null); - /** - * Gets the working directory for the current prediction. If your plugin produces files, you - * should aim to put them in this directory. - */ - getWorkingDirectory(): string; - /** - * Get the per-chat config for the plugin. Takes in the configSchematics. You can get the - * values of fields like so: - * - * ```ts - * const config = ctl.getPluginConfig(configSchematics); - * const value = config.get("fieldKey"); - * ``` - * - * @remarks - * - * If you need to name the type of the returned value, use: - * - * `InferParsedConfig`. - * - * Example: - * - * ```ts - * function myFunction(config: InferParsedConfig) { - * // ... - * } - * - * myFunction(ctl.getPluginConfig(configSchematics)); - * ``` - */ - getPluginConfig(configSchematics: ConfigSchematics): ParsedConfig; - /** - * Get the application-wide config for the plugin. Takes in the globalConfigSchematics. You can - * get the values of fields like so: - * - * ```ts - * const config = ctl.getGlobalPluginConfig(globalConfigSchematics); - * const value = config.get("fieldKey"); - * ``` - * - * @remarks - * - * If you need to name the type of the returned value, use: - * - * `InferParsedConfig`. - * - * Example: - * - * ```ts - * function myFunction(config: InferParsedConfig) { - * // ... - * } - * - * myFunction(ctl.getGlobalPluginConfig(globalConfigSchematics)); - * ``` - */ - getGlobalPluginConfig(globalConfigSchematics: ConfigSchematics): ParsedConfig; - /** - * Provides a callback that will be called when the prediction is aborted. If the prediction is - * already aborted, the callback will be called immediately. - * - * You can also use {@link BaseController.abortSignal} if you are using an async function that - * supports abort signals. - * - * See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal for more information about - * abort signals. - */ - onAborted(callback: () => void): void; -} - -/** @public */ -export declare interface BaseLoadModelOpts { - /** - * The identifier to use for the loaded model. - * - * By default, the identifier is the same as the path (1st parameter). If the identifier already - * exists, a number will be attached. This option allows you to specify the identifier to use. - * - * However, when the identifier is specified and it is in use, an error will be thrown. If the - * call is successful, it is guaranteed that the loaded model will have the specified identifier. - */ - identifier?: string; - /** - * The configuration to use when loading the model. - */ - config?: TLoadModelConfig; - /** - * An `AbortSignal` to cancel the model loading. This is useful if you wish to add a functionality - * to cancel the model loading. - * - * Example usage: - * - * ```typescript - * const ac = new AbortController(); - * const model = await client.llm.load({ - * model: "lmstudio-community/Meta-Llama-3-8B-Instruct-GGUF", - * signal: ac.signal, - * }); - * - * // Later, to cancel the model loading - * ac.abort(); - * ``` - * - * AbortController/AbortSignal is the standard method for cancelling an asynchronous operation in - * JavaScript. For more information, visit - * https://developer.mozilla.org/en-US/docs/Web/API/AbortController - */ - signal?: AbortSignal; - /** - * Idle time to live (TTL) in seconds. If specified, when the model is not used for the specified number - * of seconds, the model will be automatically unloaded. If the model is used before the TTL, the - * timer will be reset. - */ - ttl?: number; - /** - * Controls the logging of model loading progress. - * - * - If set to `true`, logs progress at the "info" level. - * - If set to `false`, no logs are emitted. This is the default. - * - If a specific logging level is desired, it can be provided as a string. Acceptable values are - * "debug", "info", "warn", and "error". - * - * Logs are directed to the logger specified during the `LMStudioClient` construction. - * - * Progress logs will be disabled if an `onProgress` callback is provided. - * - * Default value is "info", which logs progress at the "info" level. - */ - verbose?: boolean | LogLevel; - /** - * A function that is called with the progress of the model loading. The function is called with a - * number between 0 and 1, inclusive, representing the progress of the model loading. - * - * If an `onProgress` callback is provided, verbose progress logs will be disabled. - */ - onProgress?: (progress: number) => void; -} - -/** - * Base interface for all prediction result types, including those that are produced by an LLM and - * those that are produced by a generator plugin. - * - * @public - */ -export declare interface BasePredictionResult { - /** - * The generated content of the prediction result. - */ - content: string; - /** - * Part of the generated text that is "reasoning" content. For example, text inside - * tags. - */ - reasoningContent: string; - /** - * Part of the generated text that is not "reasoning" content. For example, text outside - * tags. - */ - nonReasoningContent: string; -} - -/** - * @public - */ -declare type BasicKVFieldValueTypeLibraryMap = BasicKVValueTypesLibrary extends KVFieldValueTypeLibrary ? TKVFieldValueTypeLibraryMap : never; - -declare type BasicKVValueTypesLibrary = typeof basicKVValueTypesLibrary; - -/** - * Basic key-value field value types library. These are the types that are exposed to plugins. - * - * @public - */ -declare const basicKVValueTypesLibrary: KVFieldValueTypeLibrary<{ - numeric: { - value: number; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - min?: number | undefined; - max?: number | undefined; - step?: number | undefined; - int?: boolean | undefined; - precision?: number | undefined; - slider?: { - min: number; - max: number; - step: number; - } | undefined; - shortHand?: string | undefined; - }; - }; -} & { - string: { - value: string; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - minLength?: number | undefined; - maxLength?: number | undefined; - isParagraph?: boolean | undefined; - isProtected?: boolean | undefined; - isToken?: boolean | undefined; - placeholder?: string | undefined; - }; - }; -} & { - select: { - value: string; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: { - key: string; - condition: { - type: "equals"; - value: any; - } | { - type: "notEquals"; - value: any; - }; - }[] | undefined; - options: (string | { - value: string; - displayName: string; - })[]; - }; - }; -} & { - boolean: { - value: boolean; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - }; - }; -} & { - stringArray: { - value: string[]; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - maxNumItems?: number | undefined; - allowEmptyStrings?: boolean | undefined; - }; - }; -}>; - -declare type BlockLocation = { - type: "beforeId"; - id: string; -} | { - type: "afterId"; - id: string; -}; - -/** - * A buffered event will buffer events in a queue if no subscribers are present. When a subscriber - * is added, all buffered events will trigger sequentially in the next microtask. - * - * Similar to Event, events are always emitted during the next microtask. - * - * Attempting to add more than one subscriber will resulting in an error. - */ -declare class BufferedEvent extends Subscribable { - private subscriber; - private queued; - private isNotifying; - static create(): readonly [BufferedEvent, (data: TData) => void]; - private constructor(); - private emit; - private notifier; - subscribe(listener: Listener): () => void; - /** - * Convert this buffered event to an event by stop buffering and triggering events on the new - * returned event. - */ - flow(): Event_2; -} - -declare class Channel { - private readonly innerSend; - /** - * Trigger when a message is received. - */ - readonly onMessage: BufferedEvent; - private readonly emitOnMessage; - /** - * Triggers when the underlying transport has errored out. - */ - readonly onError: BufferedEvent; - private readonly emitOnError; - /** - * Triggers when the channel has been properly closed and no more messages will be sent or - * received. - */ - readonly onClose: BufferedEvent; - private readonly emitOnClose; - readonly connectionStatus: Signal; - readonly setConnectionStatus: (status: ConnectionStatus) => void; - private nextAckId; - /** - * A map for messages that are waiting for an ACK. The values are the functions to resolve or - * reject the corresponding promise. - */ - private readonly waitingForAck; - private constructor(); - private rejectAllWaitingForAck; - /** - * Returned as a part of create. It should be called by the controlling port. - */ - private receivedACK; - /** - * Returned as a part of create. It should be called by the controlling port. - */ - private receivedMessage; - /** - * Returned as a part of create. It should be called by the controlling port. - */ - private errored; - /** - * Returned as a part of create. It should be called by the controlling port. - */ - private closed; - static create(innerSend: (packet: TOutgoingPacket, ackId?: number) => void): { - channel: Channel; - receivedAck: (ackId: number) => void; - receivedMessage: (packet: TIncomingPacket) => void; - errored: (error: any) => void; - closed: () => void; - }; - send(packet: TOutgoingPacket): void; - sendAndWaitForACK(packet: TOutgoingPacket): Promise; -} - -declare interface ChannelEndpoint { - name: string; - creationParameter: z.ZodType; - toServerPacket: z.ZodType; - toClientPacket: z.ZodType; - serialization: SerializationType; - handler: ChannelEndpointHandler | null; -} - -declare type ChannelEndpointHandler = (ctx: TContext, creationParameter: TCreationParameter, channel: Channel) => Promise; - -declare interface ChannelEndpointSpecBase { - creationParameter: any; - toServerPacket: any; - toClientPacket: any; -} - -declare type ChannelEndpointsSpecBase = { - [endpointName: string]: ChannelEndpointSpecBase; -}; - -/** - * Represents a chat history. - * - * @public - */ -export declare class Chat extends MaybeMutable { - protected getClassName(): string; - protected create(data: ChatHistoryData, mutable: boolean): this; - protected cloneData(data: ChatHistoryData): ChatHistoryData; - /** - * Don't use this constructor directly. - * - * - To create an empty chat history, use `Chat.empty()`. - * - To create a chat history with existing data, use `Chat.from()`. - */ - protected constructor(data: ChatHistoryData, mutable: boolean); - /** - * Creates an empty mutable chat history. - */ - static empty(): Chat; - /** - * Quickly create a mutable chat history with something that can be converted to a chat history. - * - * The created chat history will be a mutable copy of the input. - * - * @example - * ```ts - * const history = Chat.from([ - * { role: "user", content: "Hello" }, - * { role: "assistant", content: "Hi!" }, - * { role: "user", content: "What is your name?" }, - * ]); - * ``` - */ - static from(initializer: ChatLike): Chat; - /** - * Append a text message to the history. - */ - append(role: ChatMessageRoleData, content: string, opts?: ChatAppendOpts): void; - /** - * Append a message to the history. - */ - append(message: ChatMessageLike): void; - /** - * Make a copy of this history and append a text message to the copy. Return the copy. - */ - withAppended(role: ChatMessageRoleData, content: string, opts?: ChatAppendOpts): Chat; - /** - * Make a copy of this history and append a message to the copy. Return the copy. - */ - withAppended(message: ChatMessageLike): Chat; - /** - * Get the number of messages in the history. - */ - getLength(): number; - /** - * Get the number of messages in the history. - */ - get length(): number; - /** - * Remove the last message from the history. If the history is empty, this method will throw. - */ - pop(): ChatMessage; - /** - * Gets all files contained in this history. - * - * @param client - LMStudio client - */ - getAllFiles(client: LMStudioClient): Array; - /** - * Allows iterating over the files in the history. - */ - files(client: LMStudioClient): Generator; - /** - * Returns true if this history contains any files. - */ - hasFiles(): boolean; - /** - * Gets the message at the given index. If the index is negative, it will be counted from the end. - * - * If the index is out of bounds, this method will throw as oppose to returning undefined. This is - * to help catch bugs early. - */ - at(index: number): ChatMessage; - /** - * Get all the messages in the history as an array of ChatMessage objects. - */ - getMessagesArray(): Array; - /** - * Maps over the messages in the history and returns an array of the results. - */ - map(mapper: (message: ChatMessage, index: number, array: Array) => TOutput): Array; - /** - * Maps over the messages in the history and returns a flattened array of the results. - * - * This is similar to `Array.prototype.flatMap`, but it works with ChatMessage objects. - */ - flatMap(mapper: (message: ChatMessage, index: number, array: Array) => ReadonlyArray | TOutput): Array; - /** - * Allows iterating over the messages in the history. - */ - [Symbol.iterator](): Generator; - /** - * Given a predicate, the predicate is called for each file in the history. - * - * - If the predicate returns true, the file is removed from the history and is collected into the - * returned array. - * - If the predicate returns false, the file is kept in the history. - * - * This method is useful if you are implementing a promptPreprocessor that needs to convert certain - * types of files. - * - * If the predicate needs to be async, use the {@link Chat#consumeFilesAsync} method. - * - * @param client - LMStudio client - * @param predicate - The predicate to call for each file. - * @returns The files that were consumed. - */ - consumeFiles(client: LMStudioClient, predicate: (file: FileHandle) => boolean): FileHandle[]; - /** - * Given an async predicate, the predicate is called for each file in the history. - * - * - If the predicate returns true, the file is removed from the history and is collected into the - * returned array. - * - If the predicate returns false, the file is kept in the history. - * - * This method is useful if you are implementing a promptPreprocessor that needs to convert certain - * types of files. - * - * If you need a synchronous version, use the {@link Chat#consumeFiles} method. - * - * @param client - LMStudio client - * @param predicate - The predicate to call for each file. - * @returns The files that were consumed. - */ - consumeFilesAsync(client: LMStudioClient, predicate: (file: FileHandle) => Promise): Promise; - getSystemPrompt(): string; - replaceSystemPrompt(content: string): void; - filterInPlace(predicate: (message: ChatMessage) => boolean): void; - toString(): string; -} - -/** - * Options to use with {@link Chat#append}. - * - * @public - */ -export declare interface ChatAppendOpts { - images?: Array; -} - -/** - * @public - */ -export declare interface ChatHistoryData { - messages: Array; -} - -/** - * This type provides an easy way of specifying a chat history. - * - * Example: - * - * ```ts - * const chat = Chat.from([ - * { role: "user", content: "Hello" }, - * { role: "assistant", content: "Hi" }, - * { role: "user", content: "How are you?" }, - * ]); - * ``` - * - * @public - */ -export declare type ChatInput = Array; - -/** - * Represents anything that can be converted to a Chat. If you want to quickly construct a - * Chat, use {@link ChatInput}. - * - * If a string is provided, it will be converted to a chat history with a single user message with - * the provided text. - * - * @public - */ -export declare type ChatLike = ChatInput | string | Chat | ChatMessageInput | ChatHistoryData; - -/** - * Represents a single message in the history. - * - * @public - */ -export declare class ChatMessage extends MaybeMutable { - protected getClassName(): string; - protected create(data: ChatMessageData, mutable: boolean): this; - protected cloneData(data: ChatMessageData): ChatMessageData; - protected constructor(data: ChatMessageData, mutable: boolean); - /** - * Create a mutable text only message. - */ - static create(role: ChatMessageRoleData, content: string): ChatMessage; - /** - * Quickly create a mutable message with something that can be converted to a message. - */ - static from(initializer: ChatMessageLike): ChatMessage; - getRole(): "user" | "assistant" | "system" | "tool"; - setRole(role: ChatMessageRoleData): void; - private getFileParts; - /** - * Gets all text contained in this message. - */ - getText(): string; - /** - * Get all tool call results within this message. - */ - getToolCallResults(): Array; - /** - * Gets all file parts contained in this message. - */ - getToolCallRequests(): Array; - /** - * Gets all files contained in this message. - * - * @param client - LMStudio client - */ - getFiles(client: LMStudioClient): FileHandle[]; - /** - * Allows iterating over the files in the message. - */ - files(client: LMStudioClient): Generator; - /** - * Given a predicate, the predicate is called for each file in the message. - * - * - If the predicate returns true, the file is removed from the message and is collected into the - * returned array. - * - If the predicate returns false, the file is kept in the message. - * - * This method is useful if you are implementing a promptPreprocessor that needs to convert certain - * types of files. - * - * If the predicate needs to be async, use the {@link ChatMessage#consumeFilesAsync} method. - * - * @param client - LMStudio client - * @param predicate - The predicate to call for each file. - * @returns The files that were consumed. - */ - consumeFiles(client: LMStudioClient, predicate: (file: FileHandle) => boolean): FileHandle[]; - /** - * Given an async predicate, the predicate is called for each file in the message. - * - * - If the predicate returns true, the file is removed from the message and is collected into the - * returned array. - * - If the predicate returns false, the file is kept in the message. - * - * This method is useful if you are implementing a promptPreprocessor that needs to convert certain - * types of files. - * - * If you need a synchronous version, use the {@link ChatMessage#consumeFiles} method. - * - * @param client - LMStudio client - * @param predicate - The predicate to call for each file. - * @returns The files that were consumed. - */ - consumeFilesAsync(client: LMStudioClient, predicate: (file: FileHandle) => Promise): Promise; - /** - * Returns true if this message contains any files. - */ - hasFiles(): boolean; - /** - * Append text to the message. - */ - appendText(text: string): void; - /** - * Append a file to the message. Takes in a FileHandle. You can obtain a FileHandle from - * `client.files.prepareImage`. - */ - appendFile(file: FileHandle): void; - /** - * Replaces all text in the messages. - * - * If the message contains other components (such as files), they will kept. The replaced text - * will be inserted to the beginning of the message. - */ - replaceText(text: string): void; - isSystemPrompt(): boolean; - isUserMessage(): boolean; - isAssistantMessage(): boolean; - toString(): string; -} - -/** - * @public - */ -export declare type ChatMessageData = { - role: "assistant"; - content: Array; -} | { - role: "user"; - content: Array; -} | { - role: "system"; - content: Array; -} | { - role: "tool"; - content: Array; -}; - -/** - * This type provides an easy way of specifying a single chat message. - * - * @public - */ -export declare interface ChatMessageInput { - /** - * The sender of this message. Only "user", "assistant", and "system" is allowed. Defaults to - * "user" if not specified. - */ - role?: "user" | "assistant" | "system"; - /** - * Text content of the message. - */ - content?: string; - /** - * Images to be sent with the message to be used with vision models. To get a FileHandle, use - * `client.files.prepareImage`. - */ - images?: Array; -} - -/** - * Represents something that can be converted to a ChatMessage. - * - * If a string is provided, it will be converted to a message sent by the user. - * - * @public - */ -export declare type ChatMessageLike = ChatMessageInput | string | ChatMessage | ChatMessageData; - -/** - * @public - */ -export declare type ChatMessagePartData = ChatMessagePartTextData | ChatMessagePartFileData | ChatMessagePartToolCallRequestData | ChatMessagePartToolCallResultData; - -/** - * @public - */ -export declare interface ChatMessagePartFileData { - type: "file"; - /** - * Original file name that is uploaded. - */ - name: string; - /** - * Internal identifier for the file. Autogenerated, and is unique. - */ - identifier: string; - /** - * Size of the file in bytes. - */ - sizeBytes: number; - /** - * Type of the file. - */ - fileType: FileType; -} - -/** - * @public - */ -export declare interface ChatMessagePartTextData { - type: "text"; - text: string; -} - -/** - * @public - */ -export declare interface ChatMessagePartToolCallRequestData { - type: "toolCallRequest"; - /** - * Tool calls requested - */ - toolCallRequest: ToolCallRequest; -} - -/** - * @public - */ -export declare interface ChatMessagePartToolCallResultData extends ToolCallResult { - type: "toolCallResult"; -} - -/** - * @public - */ -export declare type ChatMessageRoleData = "assistant" | "user" | "system" | "tool"; - -/** - * Represents a source of a citation. - * - * @public - */ -export declare interface CitationSource { - fileName: string; - absoluteFilePath?: string; - pageNumber?: number | [start: number, end: number]; - lineNumber?: number | [start: number, end: number]; -} - -declare class Cleaner { - private eagerCleaned; - private readonly disposed; - private readonly cleanups; - register(fn: () => void): void; - private runCleanersInternal; - [Symbol.dispose](): void; - eagerClean(): void; -} - -declare class ClientPort { - readonly backendInterface: BackendInterface; - private readonly transport; - private readonly logger; - private openChannels; - private ongoingRpcs; - private openSignalSubscriptions; - private openWritableSignalSubscriptions; - private openCommunicationsCount; - private nextChannelId; - private nextSubscribeId; - private nextWritableSubscribeId; - private producedCommunicationWarningsCount; - private errorDeserializer; - private verboseErrorMessage; - constructor(backendInterface: BackendInterface, factory: ClientTransportFactory, { parentLogger, errorDeserializer, verboseErrorMessage, }?: { - parentLogger?: LoggerInterface; - errorDeserializer?: (serialized: SerializedLMSExtendedError, directCause: string, stack?: string) => Error; - verboseErrorMessage?: boolean; - }); - private communicationWarning; - private updateOpenCommunicationsCount; - private receivedChannelSend; - private receivedChannelAck; - private receivedChannelClose; - private receivedChannelError; - private receivedRpcResult; - private receivedRpcError; - private receivedSignalUpdate; - private receivedSignalError; - private receivedWritableSignalUpdate; - private receivedWritableSignalError; - private receivedCommunicationWarning; - private receivedKeepAliveAck; - private receivedMessage; - private errored; - callRpc(endpointName: TEndpointName, param: TRpcEndpoints[TEndpointName]["parameter"], { stack }?: { - stack?: string; - }): Promise; - createChannel(endpointName: TEndpointName, param: TChannelEndpoints[TEndpointName]["creationParameter"], onMessage?: (message: TChannelEndpoints[TEndpointName]["toClientPacket"]) => void, { stack }?: { - stack?: string; - }): Channel; - /** - * Creates a readonly lazy signal will subscribe to the signal endpoint with the given name. - */ - createSignal(endpointName: TEndpointName, param: TSignalEndpoints[TEndpointName]["creationParameter"], { stack }?: { - stack?: string; - }): LazySignal; - createWritableSignal(endpointName: TEndpointName, param: TWritableSignalEndpoints[TEndpointName]["creationParameter"], { stack }?: { - stack?: string; - }): [ - signal: OWLSignal, - setter: Setter - ]; - [Symbol.asyncDispose](): Promise; -} - -declare type ClientToServerMessage = z.infer; - -declare const clientToServerMessageSchema: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{ - type: z.ZodLiteral<"communicationWarning">; - warning: z.ZodString; -}, "strip", z.ZodTypeAny, { - type: "communicationWarning"; - warning: string; -}, { - type: "communicationWarning"; - warning: string; -}>, z.ZodObject<{ - type: z.ZodLiteral<"keepAlive">; -}, "strip", z.ZodTypeAny, { - type: "keepAlive"; -}, { - type: "keepAlive"; -}>, z.ZodObject<{ - type: z.ZodLiteral<"channelCreate">; - endpoint: z.ZodString; - channelId: z.ZodNumber; - creationParameter: z.ZodType, z.ZodTypeDef, SerializedOpaque>; -}, "strip", z.ZodTypeAny, { - creationParameter: SerializedOpaque; - type: "channelCreate"; - endpoint: string; - channelId: number; -}, { - creationParameter: SerializedOpaque; - type: "channelCreate"; - endpoint: string; - channelId: number; -}>, z.ZodObject<{ - type: z.ZodLiteral<"channelSend">; - channelId: z.ZodNumber; - message: z.ZodType, z.ZodTypeDef, SerializedOpaque>; - ackId: z.ZodOptional; -}, "strip", z.ZodTypeAny, { - message: SerializedOpaque; - type: "channelSend"; - channelId: number; - ackId?: number | undefined; -}, { - message: SerializedOpaque; - type: "channelSend"; - channelId: number; - ackId?: number | undefined; -}>, z.ZodObject<{ - type: z.ZodLiteral<"channelAck">; - channelId: z.ZodNumber; - ackId: z.ZodNumber; -}, "strip", z.ZodTypeAny, { - type: "channelAck"; - channelId: number; - ackId: number; -}, { - type: "channelAck"; - channelId: number; - ackId: number; -}>, z.ZodObject<{ - type: z.ZodLiteral<"rpcCall">; - endpoint: z.ZodString; - callId: z.ZodNumber; - parameter: z.ZodType, z.ZodTypeDef, SerializedOpaque>; -}, "strip", z.ZodTypeAny, { - parameter: SerializedOpaque; - type: "rpcCall"; - endpoint: string; - callId: number; -}, { - parameter: SerializedOpaque; - type: "rpcCall"; - endpoint: string; - callId: number; -}>, z.ZodObject<{ - type: z.ZodLiteral<"signalSubscribe">; - creationParameter: z.ZodType, z.ZodTypeDef, SerializedOpaque>; - endpoint: z.ZodString; - subscribeId: z.ZodNumber; -}, "strip", z.ZodTypeAny, { - creationParameter: SerializedOpaque; - type: "signalSubscribe"; - endpoint: string; - subscribeId: number; -}, { - creationParameter: SerializedOpaque; - type: "signalSubscribe"; - endpoint: string; - subscribeId: number; -}>, z.ZodObject<{ - type: z.ZodLiteral<"signalUnsubscribe">; - subscribeId: z.ZodNumber; -}, "strip", z.ZodTypeAny, { - type: "signalUnsubscribe"; - subscribeId: number; -}, { - type: "signalUnsubscribe"; - subscribeId: number; -}>, z.ZodObject<{ - type: z.ZodLiteral<"writableSignalSubscribe">; - creationParameter: z.ZodType, z.ZodTypeDef, SerializedOpaque>; - endpoint: z.ZodString; - subscribeId: z.ZodNumber; -}, "strip", z.ZodTypeAny, { - creationParameter: SerializedOpaque; - type: "writableSignalSubscribe"; - endpoint: string; - subscribeId: number; -}, { - creationParameter: SerializedOpaque; - type: "writableSignalSubscribe"; - endpoint: string; - subscribeId: number; -}>, z.ZodObject<{ - type: z.ZodLiteral<"writableSignalUnsubscribe">; - subscribeId: z.ZodNumber; -}, "strip", z.ZodTypeAny, { - type: "writableSignalUnsubscribe"; - subscribeId: number; -}, { - type: "writableSignalUnsubscribe"; - subscribeId: number; -}>, z.ZodObject<{ - type: z.ZodLiteral<"writableSignalUpdate">; - subscribeId: z.ZodNumber; - patches: z.ZodArray, z.ZodTypeDef, SerializedOpaque>, "many">; - tags: z.ZodArray; -}, "strip", z.ZodTypeAny, { - type: "writableSignalUpdate"; - subscribeId: number; - patches: SerializedOpaque[]; - tags: string[]; -}, { - type: "writableSignalUpdate"; - subscribeId: number; - patches: SerializedOpaque[]; - tags: string[]; -}>]>; - -declare abstract class ClientTransport extends Transport { - protected parseIncomingMessage(message: any): ServerToClientMessage; - send(message: ClientToServerMessage): void; - /** - * Called by the client port when the number of open communications changes from 0 to 1. This - * usually indicates the `socket.ref()` should be called to prevent the process from exiting. - */ - onHavingOneOrMoreOpenCommunication(): void; - onHavingNoOpenCommunication(): void; -} - -declare type ClientTransportFactory = (receivedMessage: (message: ServerToClientMessage) => void, errored: (error: any) => void, parentLogger: LoggerInterface) => ClientTransport; - -/** - * Theme color options. - * - * @public - */ -export declare type ColorPalette = "red" | "green" | "blue" | "yellow" | "orange" | "purple" | "default"; - -/** - * @public - */ -export declare interface ConfigSchematics { - [configSchematicsBrand]?: TVirtualConfigSchematics; -} - -declare const configSchematicsBrand: unique symbol; - -/** - * The opaque type for KVConfigSchematicsBuilder that is exposed in lmstudio.js SDK. Notably, this - * has significantly simplified types and is easier to use. - * - * @public - */ -export declare interface ConfigSchematicsBuilder { - [configSchematicsBuilderBrand]?: TVirtualConfigSchematics; - /** - * Adds a field to the config schematics. - */ - field(key: TKey, valueTypeKey: TValueTypeKey, valueTypeParams: BasicKVFieldValueTypeLibraryMap[TValueTypeKey]["param"], defaultValue: BasicKVFieldValueTypeLibraryMap[TValueTypeKey]["value"]): ConfigSchematicsBuilder; - /** - * Adds a "scope" to the config schematics. This is useful for grouping fields together. - */ - scope(scopeKey: TScopeKey, fn: (builder: ConfigSchematicsBuilder<{}>) => ConfigSchematicsBuilder): ConfigSchematicsBuilder; - build(): ConfigSchematics; -} - -declare const configSchematicsBuilderBrand: unique symbol; - -declare enum ConnectionStatus { - /** - * The underlying transport is connected and is communicating properly. - */ - Connected = "CONNECTED", - /** - * The underlying transport has errored out. - */ - Errored = "ERRORED", - /** - * The channel has been properly closed and no more messages will be sent or received. - */ - Closed = "CLOSED" -} - -/** - * Options to use with {@link PredictionProcessContentBlockController#appendText}. - * - * @public - */ -export declare interface ContentBlockAppendTextOpts { - tokensCount?: number; - fromDraftModel?: boolean; - /** - * @experimental WIP - do not use yet. - */ - isStructural?: boolean; -} - -/** - * Options to use with {@link PredictionProcessContentBlockController#appendToolRequest}. - * - * @public - */ -export declare interface ContentBlockAppendToolRequestOpts { - callId: number; - toolCallRequestId?: string; - name: string; - parameters: Record; - pluginIdentifier?: string; -} - -/** - * Options to use with {@link PredictionProcessContentBlockController#appendToolResult}. - * - * @public - */ -export declare interface ContentBlockAppendToolResultOpts { - callId: number; - toolCallRequestId?: string; - content: string; -} - -/** - * Options to use with {@link PredictionProcessContentBlockController#replaceToolRequest}. - * - * @public - */ -export declare interface ContentBlockReplaceToolRequestOpts { - callId: number; - toolCallRequestId?: string; - name: string; - parameters: Record; - pluginIdentifier?: string; -} - -/** - * The style of a content block. - * - * @public - */ -export declare type ContentBlockStyle = { - type: "default"; -} | { - type: "customLabel"; - label: string; - color?: ColorPalette; -} | { - type: "thinking"; - ended?: boolean; - title?: string; -}; - -/** - * Options to use with {@link RepositoryNamespace#createArtifactDownloadPlanner}. - * - * @public - */ -export declare interface CreateArtifactDownloadPlannerOpts { - owner: string; - name: string; - onPlanUpdated?: (plan: ArtifactDownloadPlan) => void; -} - -/** - * Options to use with {@link ProcessingController#createCitationBlock}. - * - * @public - */ -export declare interface CreateCitationBlockOpts { - fileName: string; - fileIdentifier: string; - pageNumber?: number | [start: number, end: number]; - lineNumber?: number | [start: number, end: number]; -} - -/** - * @public - */ -export declare function createConfigSchematics(): ConfigSchematicsBuilder<{}>; - -/** - * Options to use with {@link ProcessingController#createContentBlock}. - * - * @public - */ -export declare interface CreateContentBlockOpts { - roleOverride?: "user" | "assistant" | "system" | "tool"; - includeInContext?: boolean; - style?: ContentBlockStyle; - prefix?: string; - suffix?: string; -} - -declare function createPluginsBackendInterface(): BackendInterface; - required? /** - * Client requests to discard the session. Upon calling this, the channel will be closed. - */: string[] | undefined; - additionalProperties?: boolean | undefined; - $defs?: Record | undefined; - } | undefined; - }; - type: "function"; - }[]; - } | { - type: "toolCallComplete"; - callId: number; - result?: any; - } | { - type: "toolCallError"; - error: { - title: string; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }; - callId: number; - } | { - type: "toolCallStatus"; - callId: number; - statusText: string; - } | { - type: "toolCallWarn"; - callId: number; - warnText: string; - }; - }; -} & { - generateWithGenerator: { - creationParameter: { - history: { - messages: ({ - content: ({ - type: "text"; - text: string; - } | { - type: "file"; - name: string; - identifier: string; - sizeBytes: number; - fileType: "unknown" | "image" | "text/plain" | "application/pdf" | "application/word" | "text/other"; - } | { - type: "toolCallRequest"; - toolCallRequest: FunctionToolCallRequest; - })[]; - role: "assistant"; - } | { - content: ({ - type: "text"; - text: string; - } | { - type: "file"; - name: string; - identifier: string; - sizeBytes: number; - fileType: "unknown" | "image" | "text/plain" | "application/pdf" | "application/word" | "text/other"; - })[]; - role: "user"; - } | { - content: ({ - type: "text"; - text: string; - } | { - type: "file"; - name: string; - identifier: string; - sizeBytes: number; - fileType: "unknown" | "image" | "text/plain" | "application/pdf" | "application/word" | "text/other"; - })[]; - role: "system"; - } | { - content: { - type: "toolCallResult"; - content: string; - toolCallId?: string | undefined; - }[]; - role: "tool"; - })[]; - }; - pluginIdentifier: string; - pluginConfigSpecifier: { - type: "direct"; - config: { - fields: { - key: string; - value?: any; - }[]; - }; - workingDirectoryPath?: string | undefined; - } | { - type: "predictionProcess"; - pci: string; - token: string; - }; - tools: { - function: { - name: string; - description?: string | undefined; - parameters?: { - type: "object"; - properties: Record; - required? /** - * Client requests to discard the session. Upon calling this, the channel will be closed. - */: string[] | undefined; - additionalProperties?: boolean | undefined; - $defs?: Record | undefined; - } | undefined; - }; - type: "function"; - }[]; - }; - toServerPacket: { - type: "cancel"; - }; - toClientPacket: { - type: "fragment"; - fragment: { - content: string; - tokensCount: number; - containsDrafted: boolean; - reasoningType: "none" | "reasoning" | "reasoningStartTag" | "reasoningEndTag"; - isStructural: boolean; - }; - } | { - type: "promptProcessingProgress"; - progress: number; - } | { - type: "toolCallGenerationStart"; - toolCallId?: string | undefined; - } | { - type: "toolCallGenerationNameReceived"; - name: string; - } | { - type: "toolCallGenerationArgumentFragmentGenerated"; - content: string; - } | { - type: "toolCallGenerationEnd"; - toolCallRequest: FunctionToolCallRequest; - } | { - type: "toolCallGenerationFailed"; - } | { - type: "success"; - }; - }; -} & { - registerDevelopmentPlugin: { - creationParameter: { - manifest: { - type: "plugin"; - owner: string; - name: string; - runner: "ecmascript" | "node" | "mcpBridge"; - revision?: number | undefined; - dependencies?: ArtifactDependency[] | undefined; - tags?: string[] | undefined; - }; - }; - toServerPacket: { - type: "end"; - }; - toClientPacket: { - type: "ready"; - clientIdentifier: string; - clientPasskey: string; - }; - }; -} & { - setPromptPreprocessor: { - creationParameter: void; - toServerPacket: { - type: "complete"; - taskId: string; - processed: { - content: ({ - type: "text"; - text: string; - } | { - type: "file"; - name: string; - identifier: string; - sizeBytes: number; - fileType: "unknown" | "image" | "text/plain" | "application/pdf" | "application/word" | "text/other"; - } | { - type: "toolCallRequest"; - toolCallRequest: FunctionToolCallRequest; - })[]; - role: "assistant"; - } | { - content: ({ - type: "text"; - text: string; - } | { - type: "file"; - name: string; - identifier: string; - sizeBytes: number; - fileType: "unknown" | "image" | "text/plain" | "application/pdf" | "application/word" | "text/other"; - })[]; - role: "user"; - } | { - content: ({ - type: "text"; - text: string; - } | { - type: "file"; - name: string; - identifier: string; - sizeBytes: number; - fileType: "unknown" | "image" | "text/plain" | "application/pdf" | "application/word" | "text/other"; - })[]; - role: "system"; - } | { - content: { - type: "toolCallResult"; - content: string; - toolCallId?: string | undefined; - }[]; - role: "tool"; - }; - } | { - type: "aborted"; - taskId: string; - } | { - type: "error"; - error: { - title: string; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }; - taskId: string; - }; - toClientPacket: { - type: "preprocess"; - config: { - fields: { - key: string; - value?: any; - }[]; - }; - taskId: string; - input: { - content: ({ - type: "text"; - text: string; - } | { - type: "file"; - name: string; - identifier: string; - sizeBytes: number; - fileType: "unknown" | "image" | "text/plain" | "application/pdf" | "application/word" | "text/other"; - } | { - type: "toolCallRequest"; - toolCallRequest: FunctionToolCallRequest; - })[]; - role: "assistant"; - } | { - content: ({ - type: "text"; - text: string; - } | { - type: "file"; - name: string; - identifier: string; - sizeBytes: number; - fileType: "unknown" | "image" | "text/plain" | "application/pdf" | "application/word" | "text/other"; - })[]; - role: "user"; - } | { - content: ({ - type: "text"; - text: string; - } | { - type: "file"; - name: string; - identifier: string; - sizeBytes: number; - fileType: "unknown" | "image" | "text/plain" | "application/pdf" | "application/word" | "text/other"; - })[]; - role: "system"; - } | { - content: { - type: "toolCallResult"; - content: string; - toolCallId?: string | undefined; - }[]; - role: "tool"; - }; - pluginConfig: { - fields: { - key: string; - value?: any; - }[]; - }; - globalPluginConfig: { - fields: { - key: string; - value?: any; - }[]; - }; - workingDirectoryPath: string | null; - enabledPluginInfos: RemotePluginInfo[]; - pci: string; - token: string; - } | { - type: "abort"; - taskId: string; - }; - }; -} & { - setPredictionLoopHandler: { - creationParameter: void; - toServerPacket: { - type: "complete"; - taskId: string; - } | { - type: "aborted"; - taskId: string; - } | { - type: "error"; - error: { - title: string; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }; - taskId: string; - }; - toClientPacket: { - type: "handlePredictionLoop"; - config: { - fields: { - key: string; - value?: any; - }[]; - }; - taskId: string; - pluginConfig: { - fields: { - key: string; - value?: any; - }[]; - }; - globalPluginConfig: { - fields: { - key: string; - value?: any; - }[]; - }; - workingDirectoryPath: string | null; - enabledPluginInfos: RemotePluginInfo[]; - pci: string; - token: string; - } | { - type: "abort"; - taskId: string; - }; - }; -} & { - setToolsProvider: { - creationParameter: void; - toServerPacket: { - type: "sessionInitialized"; - toolDefinitions: { - function: { - name: string; - description?: string | undefined; - parameters?: { - type: "object"; - properties: Record; - required? /** - * Client requests to discard the session. Upon calling this, the channel will be closed. - */: string[] | undefined; - additionalProperties?: boolean | undefined; - $defs?: Record | undefined; - } | undefined; - }; - type: "function"; - }[]; - sessionId: string; - } | { - type: "sessionInitializationFailed"; - error: { - title: string; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }; - sessionId: string; - } | { - type: "toolCallComplete"; - callId: string; - sessionId: string; - result?: any; - } | { - type: "toolCallError"; - error: { - title: string; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }; - callId: string; - sessionId: string; - } | { - type: "toolCallStatus"; - callId: string; - statusText: string; - sessionId: string; - } | { - type: "toolCallWarn"; - callId: string; - warnText: string; - sessionId: string; - }; - toClientPacket: { - type: "initSession"; - pluginConfig: { - fields: { - key: string; - value?: any; - }[]; - }; - globalPluginConfig: { - fields: { - key: string; - value?: any; - }[]; - }; - workingDirectoryPath: string | null; - sessionId: string; - } | { - type: "discardSession"; - sessionId: string; - } | { - type: "callTool"; - callId: string; - sessionId: string; - toolName: string; - parameters?: any; - } | { - type: "abortToolCall"; - callId: string; - sessionId: string; - }; - }; -} & { - setGenerator: { - creationParameter: void; - toServerPacket: { - type: "complete"; - taskId: string; - } | { - type: "aborted"; - taskId: string; - } | { - type: "error"; - error: { - title: string; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }; - taskId: string; - } | { - type: "fragmentGenerated"; - content: string; - opts: LLMPredictionFragmentInputOpts; - taskId: string; - } | { - type: "toolCallGenerationStarted"; - taskId: string; - toolCallId?: string | undefined; - } | { - type: "toolCallGenerationNameReceived"; - taskId: string; - toolName: string; - } | { - type: "toolCallGenerationArgumentFragmentGenerated"; - content: string; - taskId: string; - } | { - type: "toolCallGenerationEnded"; - toolCallRequest: FunctionToolCallRequest; - taskId: string; - } | { - type: "toolCallGenerationFailed"; - error: { - title: string; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }; - taskId: string; - }; - toClientPacket: { - type: "generate"; - toolDefinitions: { - function: { - name: string; - description?: string | undefined; - parameters?: { - type: "object"; - properties: Record; - required? /** - * Client requests to discard the session. Upon calling this, the channel will be closed. - */: string[] | undefined; - additionalProperties?: boolean | undefined; - $defs?: Record | undefined; - } | undefined; - }; - type: "function"; - }[]; - taskId: string; - input: { - messages: ({ - content: ({ - type: "text"; - text: string; - } | { - type: "file"; - name: string; - identifier: string; - sizeBytes: number; - fileType: "unknown" | "image" | "text/plain" | "application/pdf" | "application/word" | "text/other"; - } | { - type: "toolCallRequest"; - toolCallRequest: FunctionToolCallRequest; - })[]; - role: "assistant"; - } | { - content: ({ - type: "text"; - text: string; - } | { - type: "file"; - name: string; - identifier: string; - sizeBytes: number; - fileType: "unknown" | "image" | "text/plain" | "application/pdf" | "application/word" | "text/other"; - })[]; - role: "user"; - } | { - content: ({ - type: "text"; - text: string; - } | { - type: "file"; - name: string; - identifier: string; - sizeBytes: number; - fileType: "unknown" | "image" | "text/plain" | "application/pdf" | "application/word" | "text/other"; - })[]; - role: "system"; - } | { - content: { - type: "toolCallResult"; - content: string; - toolCallId?: string | undefined; - }[]; - role: "tool"; - })[]; - }; - pluginConfig: { - fields: { - key: string; - value?: any; - }[]; - }; - globalPluginConfig: { - fields: { - key: string; - value?: any; - }[]; - }; - workingDirectoryPath: string | null; - } | { - type: "abort"; - taskId: string; - }; - }; -}, {}, {}>; - -/** - * @public - */ -export declare type DiagnosticsLogEvent = { - timestamp: number; - data: DiagnosticsLogEventData; -}; - -/** - * @public - */ -export declare type DiagnosticsLogEventData = { - type: "llm.prediction.input"; - modelPath: string; - modelIdentifier: string; - input: string; -}; - -/** @public */ -export declare class DiagnosticsNamespace { - private readonly diagnosticsPort; - private readonly validator; - /** - * Register a callback to receive log events. Return a function to stop receiving log events. - * - * This method is in alpha. Do not use this method in production yet. - * @alpha - */ - unstable_streamLogs(listener: (logEvent: DiagnosticsLogEvent) => void): () => void; -} - -/** - * Represents the library and version of a document parsing library. - * - * @public - * @deprecated [DEP-DOC-PARSE] Document parsing API is still in active development. Stay tuned for - * updates. - */ -export declare type DocumentParsingLibraryIdentifier = { - /** - * The identifier of the document parsing library. - */ - library: string; - /** - * The version of the document parsing library. - */ - version: string; -}; - -/** - * Options for parsing a document. - * - * @public - * @deprecated [DEP-DOC-PARSE] Document parsing API is still in active development. Stay tuned for - * updates. - */ -export declare type DocumentParsingOpts = { - /** - * The parser backend to use for parsing the document. If not specified, the best available parser - * will be used. - */ - parserId?: DocumentParsingLibraryIdentifier; -}; - -/** - * Options to use with {@link RepositoryNamespace#downloadArtifact} - * - * @public - */ -export declare interface DownloadArtifactOpts { - owner: string; - name: string; - revisionNumber: number; - /** - * Where to save the artifact. - */ - path: string; - onProgress?: (update: DownloadProgressUpdate) => void; - onStartFinalizing?: () => void; - signal?: AbortSignal; -} - -/** @public */ -export declare interface DownloadOpts { - onProgress?: (update: DownloadProgressUpdate) => void; - onStartFinalizing?: () => void; - signal?: AbortSignal; -} - -/** - * @public - */ -export declare interface DownloadProgressUpdate { - downloadedBytes: number; - totalBytes: number; - speedBytesPerSecond: number; -} - -/** - * This represents a set of requirements for a model. It is not tied to a specific model, but rather - * to a set of requirements that a model must satisfy. - * - * For example, if you got the model via `client.llm.get("my-identifier")`, you will get a - * `LLMModel` for the model with the identifier `my-identifier`. If the model is unloaded, and - * another model is loaded with the same identifier, using the same `LLMModel` will use the new - * model. - * - * @public - */ -export declare abstract class DynamicHandle { - /** - * Gets the information of the model that is currently associated with this `DynamicHandle`. If no - * model is currently associated, this will return `undefined`. - * - * Note: As models are loaded/unloaded, the model associated with this `LLMModel` may change at - * any moment. - */ - getModelInfo(): Promise; - protected getLoadConfig(stack: string): Promise; -} - -/** - * This represents a set of requirements for a model. It is not tied to a specific model, but rather - * to a set of requirements that a model must satisfy. - * - * For example, if you got the model via `client.embedding.get("my-identifier")`, you will get a - * `EmbeddingModel` for the model with the identifier `my-identifier`. If the model is unloaded, and - * another model is loaded with the same identifier, using the same `EmbeddingModel` will use the - * new model. - * - * @public - */ -export declare class EmbeddingDynamicHandle extends DynamicHandle { - embed(inputString: string): Promise<{ - embedding: Array; - }>; - embed(inputStrings: Array): Promise; - }>>; - getContextLength(): Promise; - getEvalBatchSize(): Promise; - tokenize(inputString: string): Promise>; - tokenize(inputStrings: Array): Promise>>; - countTokens(inputString: string): Promise; -} - -/** - * @public - */ -export declare interface EmbeddingLoadModelConfig { - gpu?: GPUSetting; - contextLength?: number; - ropeFrequencyBase?: number; - ropeFrequencyScale?: number; - keepModelInMemory?: boolean; - tryMmap?: boolean; -} - -/** - * Represents a specific loaded Embedding. Most Embedding related operations are inherited from - * {@link EmbeddingDynamicHandle}. - * - * @public - */ -export declare class EmbeddingModel extends EmbeddingDynamicHandle implements SpecificModel { - readonly identifier: string; - readonly path: string; - readonly modelKey: string; - readonly format: ModelCompatibilityType; - readonly displayName: string; - readonly sizeBytes: number; - unload(): Promise; - getModelInfo(): Promise; -} - -/** - * Embedding model specific information. - * - * @public - */ -export declare interface EmbeddingModelAdditionalInfo { - /** - * The maximum context length supported by the model. - */ - maxContextLength: number; -} - -/** - * Info of an embedding model. It is a combination of {@link ModelInfoBase} and - * {@link EmbeddingModelAdditionalInfo}. - * - * @public - */ -export declare type EmbeddingModelInfo = { - type: "embedding"; -} & ModelInfoBase & EmbeddingModelAdditionalInfo; - -/** - * Additional information of an embedding model instance. - * - * @public - */ -export declare interface EmbeddingModelInstanceAdditionalInfo { - /** - * The currently loaded context length. - */ - contextLength: number; -} - -/** - * Info of a loaded embedding model instance. It is a combination of {@link ModelInstanceInfoBase}, - * {@link EmbeddingModelAdditionalInfo} and {@link EmbeddingModelInstanceAdditionalInfo}. - * - * @public - */ -export declare type EmbeddingModelInstanceInfo = { - type: "embedding"; -} & ModelInstanceInfoBase & EmbeddingModelAdditionalInfo & EmbeddingModelInstanceAdditionalInfo; - -/** @public */ -export declare class EmbeddingNamespace extends ModelNamespace { -} - -/** - * Options to use with {@link RepositoryNamespace#ensureAuthenticated}. - * - * @public - */ -export declare interface EnsureAuthenticatedOpts { - onAuthenticationUrl: (url: string) => void; -} - -/** - * Represents an event that can be subscribed to. Emitted events will trigger all subscribers in the - * next microtask. If multiple events are emitted, they will be triggered in the same microtask. - */ -declare class Event_2 extends Subscribable { - private subscribers; - /** - * Internal callback that is called when the number of subscribers goes from 0 to 1. - */ - private onSubscribed; - /** - * Internal callback that is called when the number of subscribers goes from 1 to 0. - */ - private onUnsubscribed; - /** - * Internal state that tracks whether the event has any subscribers. - */ - protected constructor(); - protected emit(data: TData): void; - static create(): readonly [Event_2, (data: TData) => void]; - subscribe(listener: Listener_2): () => void; - batch({ minIdleTimeMs, maxBatchTimeMs, }: EventBatchingOpts): Event_2>; -} - -declare interface EventBatchingOpts { - minIdleTimeMs?: number; - maxBatchTimeMs?: number; -} - -/** - * Represents a file. Currently, the file can be either in the local file system or base64 encoded. - * - * @public - */ -export declare class FileHandle { - readonly filesNamespace: FilesNamespace; - readonly identifier: string; - readonly type: FileType; - readonly sizeBytes: number; - /** - * Original file name - */ - readonly name: string; - /** - * @deprecated Direct construction is not recommended. Please use the `prepareFile` API instead - */ - constructor(filesNamespace: FilesNamespace, identifier: string, type: FileType, sizeBytes: number, - /** - * Original file name - */ - name: string); - private readonly parsedIdentifier; - /** - * Gets the absolute file path of this file. - */ - getFilePath(): Promise; - isImage(): boolean; -} - -/** - * @public - * - * The namespace for file-related operations. - */ -export declare class FilesNamespace { - private readonly validator; - /** - * Adds a temporary image to LM Studio, and returns a FileHandle that can be used to reference - * this image. This image will be deleted when the client disconnects. - * - * This method can only be used in environments that have file system access (such as Node.js). - */ - prepareImage(path: string): Promise; - /** - * Adds a temporary image to LM Studio. The content of the file is specified using base64. If you - * are using Node.js and have a file laying around, consider using `prepareImage` instead. - */ - prepareImageBase64(fileName: string, contentBase64: string): Promise; - /** - * Adds a temporary file to LM Studio, and returns a FileHandle that can be used to reference this - * file. This file will be deleted when the client disconnects. - * - * This method can only be used in environments that have file system access (such as Node.js). - * - * @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for - * updates. - */ - prepareFile(path: string): Promise; - /** - * Adds a temporary file to LM Studio. The content of the file is specified using base64. If you - * are using Node.js and have a file laying around, consider using `prepareFile` instead. - * - * @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for - * updates. */ - prepareFileBase64(fileName: string, contentBase64: string): Promise; - /** - * @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for - * updates. */ - retrieve(query: string, files: Array, opts?: RetrievalOpts): Promise; - /** - * Parse a document - * - * @deprecated [DEP-DOC-PARSE] Document parsing API is still in active development. Stay tuned for - * updates. - */ - parseDocument(fileHandle: FileHandle, opts?: ParseDocumentOpts): Promise; - /** - * Get the parsing method for a document. - * - * @deprecated [DEP-DOC-PARSE] Document parsing API is still in active development. Stay tuned for - * updates. - */ - getDocumentParsingLibrary(fileHandle: FileHandle): Promise; -} - -/** - * @public - * - * TODO: Documentation - */ -export declare type FileType = "image" | "text/plain" | "application/pdf" | "application/word" | "text/other" | "unknown"; - -/** - * A tool that is a function. - * - * @public - */ -export declare interface FunctionTool extends ToolBase { - type: "function"; - parametersSchema: ZodSchema; - /** - * Checks the parameters. If not valid, throws an error. - */ - checkParameters: (params: any) => void; - implementation: (params: Record, ctx: ToolCallContext) => any | Promise; -} - -/** - * @public - */ -export declare interface FunctionToolCallRequest { - id?: string; - type: "function"; - arguments?: Record; - name: string; -} - -/** - * TODO: Documentation - * - * @public - */ -declare type Generator_2 = (ctl: GeneratorController, history: Chat) => Promise; -export { Generator_2 as Generator } - -/** - * Controller for a generator. - * - * @public - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ -export declare class GeneratorController extends BaseController { - private readonly toolDefinitions; - private readonly connector; - private readonly validator; - /** - * Get the definitions of the tools available for this generation. - */ - getToolDefinitions(): Array; - /** - * Use this function to report a text fragment has been generated. - * - * @param content - The content that has been generated. - * @param opts - Additional info about the generated content, such as how many tokens it contains. - * See {@link LLMPredictionFragmentInputOpts} for more info. All the fields are optional. - */ - fragmentGenerated(content: string, opts?: LLMPredictionFragmentInputOpts): void; - /** - * Use this function to report that a tool call generation has started. Each - * `toolCallGenerationStarted` must be paired up with a `toolCallGenerationEnded` call for - * successfully generated tool calls, or a `toolCallGenerationFailed` call for - * failed tool calls. - */ - toolCallGenerationStarted({ toolCallId, }?: { - /** - * The LLM specific call id of the tool call. - */ - toolCallId?: string; - }): void; - /** - * Use this function to report that the name of the tool call has been generated. This function - * should only be called once for each `toolCallGenerationStarted`. - * - * @param toolName - The name of the tool that has been generated. - */ - toolCallGenerationNameReceived(toolName: string): void; - /** - * Use this function to report that a new argument fragment has been generated for the tool call. - * This function can be called multiple times for each `toolCallGenerationStarted`. - * - * @param content - The new fragment that has been generated for the tool call. - */ - toolCallGenerationArgumentFragmentGenerated(content: string): void; - /** - * Use this function to report that a tool call generation has successfully ended. This function - * should only be called after a `toolCallGenerationStarted` call. - */ - toolCallGenerationEnded(toolCallRequest: ToolCallRequest): void; - /** - * Use this function to report that a tool call generation has failed. This function should only - * be called after a `toolCallGenerationStarted` call. - * - * @param error - The error that occurred during the tool call generation. - */ - toolCallGenerationFailed(error: Error): void; -} - -/** - * Represents the result of a prediction from a generator plugin. - * - * The most notably property is {@link GeneratorPredictionResult#content}, which contains the - * generated text. - * - * @public - * @experimental [EXP-GEN-PREDICT] Using generator plugins programmatically is still in development. - * This may change in the future without warning. - */ -export declare class GeneratorPredictionResult implements BasePredictionResult { - /** - * The newly generated text as generated by the generator plugin. - */ - readonly content: string; - /** - * Part of the generated text that is "reasoning" content. For example, text inside - * tags. The generator is responsible for determining what is considered reasoning content. - */ - readonly reasoningContent: string; - /** - * Part of the generated text that is not "reasoning" content. For example, text outside - * tags. The generator is responsible for determining what is considered reasoning - * content. - */ - readonly nonReasoningContent: string; - /** - * The identifier of the plugin that generated this result. - */ - readonly pluginIdentifier: string; - constructor( - /** - * The newly generated text as generated by the generator plugin. - */ - content: string, - /** - * Part of the generated text that is "reasoning" content. For example, text inside - * tags. The generator is responsible for determining what is considered reasoning content. - */ - reasoningContent: string, - /** - * Part of the generated text that is not "reasoning" content. For example, text outside - * tags. The generator is responsible for determining what is considered reasoning - * content. - */ - nonReasoningContent: string, - /** - * The identifier of the plugin that generated this result. - */ - pluginIdentifier: string); -} - -/** - * @public - */ -export declare type GlobalKVFieldValueTypeLibraryMap = GlobalKVValueTypesLibrary extends KVFieldValueTypeLibrary ? TKVFieldValueTypeLibraryMap : never; - -/** - * @public - */ -export declare type GlobalKVValueTypesLibrary = typeof kvValueTypesLibrary; - -/** - * Settings related to offloading work to the GPU. - * - * @public - * @deprecated We are currently working on an improved way to control split. You can use this for - * now. We will offer the alternative before this feature is removed. - */ -export declare type GPUSetting = { - /** - * A number between 0 to 1 representing the ratio of the work should be distributed to the GPU, - * where 0 means no work is distributed and 1 means all work is distributed. Can also specify the - * string "off" to mean 0 and the string "max" to mean 1. - */ - ratio?: LLMLlamaAccelerationOffloadRatio; - /** - * A number between 0 to 1 representing the ratio of the layers whose expert blocks will be - * forced into CPU memory, where 1 means all expert layers will be in CPU memory regardless of - * GPU offload configuration and 0 means the expert offload will be determined by GPU offload. - * Can also specify the string "off" to mean 0 and the string "max" to mean 1. - */ - numCpuExpertLayersRatio?: LLMLlamaAccelerationOffloadRatio; - /** - * The index of the GPU to use as the main GPU. - */ - mainGpu?: number; - /** - * How to split computation across multiple GPUs. - */ - splitStrategy?: LLMSplitStrategy; - /** - * Indices of GPUs to disable. - */ - disabledGpus?: number[]; -}; - -/** - * Controller object used to allow/modify/deny a tool call. - */ -declare class GuardToolCallController { - readonly toolCallRequest: ToolCallRequest; - readonly tool: Tool; - readonly resultContainer: [result: GuardToolCallResult | null]; - /** - * Don't construct this object yourself. - */ - constructor(toolCallRequest: ToolCallRequest, tool: Tool, resultContainer: [result: GuardToolCallResult | null]); - private assertNoResultYet; - /** - * Allows the tool call to proceed without any modifications. - */ - allow: () => void; - /** - * Allows the tool call to proceed, but overrides the parameters with the provided ones. - */ - allowAndOverrideParameters: (newParameters: Record) => void; - /** - * Denys the tool call with a specified reason. This will not interrupt the `.act` call. Instead, - * the reason you provide will be provided to the model as the tool call result. - * - * If `reason` is not provided, a generic default reason will be used. - * - * If you wish to immediately fail the `.act` call, you can throw an error instead. - */ - deny: (reason?: string) => void; -} - -declare type GuardToolCallResult = { - type: "allow"; -} | { - type: "allowAndOverrideParameters"; - parameters: Record; -} | { - type: "deny"; - reason?: string; -}; - -/** - * Represents a download source for a Hugging Face model. - * - * @public - */ -export declare type HuggingFaceModelDownloadSource = { - type: "huggingface"; - user: string; - repo: string; -}; - -declare type InferClientPort = TBackendInterfaceOrCreator extends BackendInterface ? ClientPort : TBackendInterfaceOrCreator extends (...ars: Array) => BackendInterface ? ClientPort : never; - -/** - * Given the type of a configSchematics, returns the type of the parsed config. Example usage: - * - * ```ts - * const config: InferParsedConfig = ctl.getPluginConfig(configSchematics); - * ``` - * - * @remarks - * - * You don't need this type in the above case because TypeScript has type inferencing. It is mainly - * useful when you want to pass the parsed config around and you need to type the parameter. - * - * @public - */ -export declare type InferParsedConfig> = TConfigSchematics extends ConfigSchematics ? ParsedConfig : never; - -/** - * Stringify options passed to actual implementations of stringify. - * - * @public - */ -export declare interface InnerFieldStringifyOpts { - /** - * Translate function. - */ - t: (key: string, fallback: string) => string; - /** - * If exists, a soft cap on how long the stringified value should be. - * - * This does not have to be followed. Mostly used for fields like promptFormatTemplate where it - * can grow very large. - */ - desiredLength?: number; -} - -/** - * Represents a single field value type definition. - * - * @public - */ -export declare interface KVConcreteFieldValueType { - paramType: ZodSchema; - schemaMaker: (param: any) => ZodSchema; - effectiveEquals: (a: any, b: any, typeParam: any) => boolean; - stringify: (value: any, typeParam: any, opts: InnerFieldStringifyOpts) => string; -} - -/** - * @public - */ -export declare type KVConcreteFieldValueTypesMap = Map; - -/** - * TODO: Documentation - * - * @public - */ -export declare interface KVConfig { - fields: Array; -} - -/** - * TODO: Documentation - * - * @public - */ -export declare interface KVConfigField { - key: string; - value?: any; -} - -/** - * @public - */ -export declare type KVConfigFieldDependency = { - key: string; - condition: { - type: "equals"; - value: any; - } | { - type: "notEquals"; - value: any; - }; -}; - -/** - * Represents a library of field value types. - * - * @public - */ -export declare class KVFieldValueTypeLibrary { - private readonly valueTypes; - constructor(valueTypes: KVConcreteFieldValueTypesMap); - /** - * Gets the schema for a specific field value type with the given key and parameters. - */ - getSchema(key: TKey, param: TKVFieldValueTypeLibraryMap[TKey]["param"]): ZodSchema; - parseParamTypes(key: TKey, param: any): TKVFieldValueTypeLibraryMap[TKey]["param"]; - effectiveEquals(key: TKey, typeParam: TKVFieldValueTypeLibraryMap[TKey]["param"], a: TKVFieldValueTypeLibraryMap[TKey]["value"], b: TKVFieldValueTypeLibraryMap[TKey]["value"]): boolean; - stringify(key: TKey, typeParam: TKVFieldValueTypeLibraryMap[TKey]["param"], opts: InnerFieldStringifyOpts, value: TKVFieldValueTypeLibraryMap[TKey]["value"]): string; -} - -/** - * The global key-value field value types library. This includes all the basic types and additional - * types that are used in the LM Studio application. - * - * @public - */ -export declare const kvValueTypesLibrary: KVFieldValueTypeLibrary<{ - numeric: { - value: number; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - min?: number | undefined; - max?: number | undefined; - step?: number | undefined; - int?: boolean | undefined; - precision?: number | undefined; - slider?: { - min: number; - max: number; - step: number; - } | undefined; - shortHand?: string | undefined; - }; - }; -} & { - string: { - value: string; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - minLength?: number | undefined; - maxLength?: number | undefined; - isParagraph?: boolean | undefined; - isProtected?: boolean | undefined; - isToken?: boolean | undefined; - placeholder?: string | undefined; - }; - }; -} & { - select: { - value: string; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: { - key: string; - condition: { - type: "equals"; - value: any; - } | { - type: "notEquals"; - value: any; - }; - }[] | undefined; - options: (string | { - value: string; - displayName: string; - })[]; - }; - }; -} & { - boolean: { - value: boolean; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - }; - }; -} & { - stringArray: { - value: string[]; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - maxNumItems?: number | undefined; - allowEmptyStrings?: boolean | undefined; - }; - }; -} & { - checkboxNumeric: { - value: { - value: number; - checked: boolean; - }; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - min?: number | undefined; - max?: number | undefined; - step?: number | undefined; - int?: boolean | undefined; - precision?: number | undefined; - slider?: { - min: number; - max: number; - step: number; - } | undefined; - uncheckedHint?: string | undefined; - }; - }; -} & { - numericArray: { - value: number[]; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - min?: number | undefined; - max?: number | undefined; - int?: boolean | undefined; - }; - }; -} & { - contextOverflowPolicy: { - value: "stopAtLimit" | "truncateMiddle" | "rollingWindow"; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - }; - }; -} & { - context: { - value: ({ - type: "jsonFile"; - absPath: string; - } | { - type: "yamlFile"; - absPath: string; - })[]; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - }; - }; -} & { - contextLength: { - value: number; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - max?: number | undefined; - }; - }; -} & { - modelIdentifier: { - value: string; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - domain?: ("llm" | "embedding" | "imageGen" | "transcription" | "tts")[] | undefined; - }; - }; -} & { - llmPromptTemplate: { - value: { - type: "manual" | "jinja"; - stopStrings: string[]; - manualPromptTemplate?: { - beforeSystem: string; - afterSystem: string; - beforeUser: string; - afterUser: string; - beforeAssistant: string; - afterAssistant: string; - } | undefined; - jinjaPromptTemplate?: { - template: string; - } | undefined; - }; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - }; - }; -} & { - llmReasoningParsing: { - value: { - enabled: boolean; - startString: string; - endString: string; - }; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - }; - }; -} & { - llamaStructuredOutput: { - value: { - type: "none" | "json" | "gbnf"; - jsonSchema?: any; - gbnfGrammar?: string | undefined; - }; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - }; - }; -} & { - speculativeDecodingDraftModel: { - value: string; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - }; - }; -} & { - toolUse: { - value: { - type: "none"; - } | { - type: "toolArray"; - tools?: { - function: { - name: string; - description?: string | undefined; - parameters?: { - type: "object"; - properties: Record; - required?: string[] | undefined; - additionalProperties?: boolean | undefined; - $defs?: Record | undefined; - } | undefined; - }; - type: "function"; - }[] | undefined; - force?: boolean | undefined; - }; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - }; - }; -} & { - toolNaming: { - value: "passThrough" | "removeSpecial" | "snakeCase" | "camelCase"; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - }; - }; -} & { - llamaAccelerationOffloadRatio: { - value: number | "max" | "off"; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - numLayers?: number | undefined; - }; - }; -} & { - llamaMirostatSampling: { - value: { - version: 0 | 1 | 2; - learningRate: number; - targetEntropy: number; - }; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - }; - }; -} & { - llamaLogitBias: { - value: [number, number | "-inf"][]; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - }; - }; -} & { - llamaCacheQuantizationType: { - value: { - value: "f32" | "f16" | "q8_0" | "q4_0" | "q4_1" | "iq4_nl" | "q5_0" | "q5_1"; - checked: boolean; - }; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - }; - }; -} & { - mlxKvCacheQuantizationType: { - value: { - enabled: boolean; - bits: 2 | 3 | 4 | 6 | 8; - groupSize: 32 | 64 | 128; - quantizedStart: number; - }; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - }; - }; -} & { - retrievalChunkingMethod: { - value: { - type: "recursive-v1"; - chunkSize: number; - chunkOverlap: number; - }; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - }; - }; -} & { - envVars: { - value: Partial>; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - }; - }; -} & { - gpuSplitConfig: { - value: { - disabledGpus: number[]; - strategy: "custom" | "evenly" | "priorityOrder"; - priority: number[]; - customRatio: number[]; - }; - param: { - displayName?: string | undefined; - hint?: string | undefined; - modelCentric?: boolean | undefined; - nonConfigurable?: boolean | undefined; - engineDoesNotSupport?: boolean | undefined; - machineDependent?: boolean | undefined; - warning?: string | undefined; - subtitle?: string | undefined; - isExperimental?: boolean | undefined; - dependencies?: KVConfigFieldDependency[] | undefined; - }; - }; -}>; - -/** - * Used internally by KVFieldValueTypesLibrary to keep track of a single field value type definition - * with the generics. - * - * @public - */ -export declare interface KVVirtualFieldValueType { - value: any; - param: any; -} - -/** - * Used internally by KVFieldValueTypesLibrary to keep track of all field value type definitions - * with the generics. - * - * @public - */ -export declare type KVVirtualFieldValueTypesMapping = { - [key: string]: KVVirtualFieldValueType; -}; - -/** - * A lazy signal is a signal that will only subscribe to the upstream when at least one subscriber - * is attached. It will unsubscribe from the upstream when the last subscriber is removed. - * - * A lazy signal can possess a special value "NOT_AVAILABLE", accessible from the static property - * {@link LazySignal.NOT_AVAILABLE}. This value is used to indicate that the value is not available - * yet. This can happen when the signal is created without an initial value and the upstream has not - * emitted a value yet. - */ -declare class LazySignal extends Subscribable implements SignalLike { - private readonly subscribeUpstream; - static readonly NOT_AVAILABLE: unique symbol; - private readonly signal; - private readonly setValue; - private dataIsStale; - private upstreamUnsubscribe; - private subscribersCount; - private isSubscribedToUpstream; - /** - * This event will be triggered even if the value did not change. This is for resolving .pull. - */ - private readonly updateReceivedEvent; - private readonly emitUpdateReceivedEvent; - private readonly updateReceivedSynchronousCallbacks; - static create(initialValue: TData, subscribeUpstream: SubscribeUpstream, equalsPredicate?: (a: TData, b: TData) => boolean): LazySignal; - static createWithoutInitialValue(subscribeUpstream: SubscribeUpstream, equalsPredicate?: (a: TData, b: TData) => boolean): LazySignal; - static deriveFrom, TData>(sourceSignals: { - [TKey in keyof TSource]: SignalLike; - }, deriver: (...sourceValues: { - [TKey in keyof TSource]: StripNotAvailable; - }) => TData, outputEqualsPredicate?: (a: TData, b: TData) => boolean): LazySignal ? RElement extends NotAvailable ? TData | NotAvailable : TData : never>; - static asyncDeriveFrom, TData>(strategy: AsyncDeriveFromStrategy, sourceSignals: { - [TKey in keyof TSource]: SignalLike; - }, deriver: (...sourceValues: { - [TKey in keyof TSource]: StripNotAvailable; - }) => Promise, outputEqualsPredicate?: (a: TData, b: TData) => boolean): LazySignal; - protected constructor(initialValue: TData, subscribeUpstream: SubscribeUpstream, equalsPredicate?: (a: TData, b: TData) => boolean); - /** - * Returns whether the value is currently stale. - * - * A value is stale whenever the upstream subscription is not active. This can happen in three - * cases: - * - * 1. When no subscriber is attached to this signal, the signal will not subscribe to the - * upstream. In this case, the value is always stale. - * 2. When a subscriber is attached, but the upstream has not yet emitted a single value, the - * value is also stale. - * 3. When the upstream has emitted an error. In this case, the subscription to the upstream is - * terminated and the value is stale. - * - * If you wish to get the current value and ensure that it is not stale, use the method - * {@link LazySignal#pull}. - */ - isStale(): boolean; - private subscribeToUpstream; - private unsubscribeFromUpstream; - /** - * Gets the current value of the signal. If the value is not available, it will return - * {@link LazySignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is created - * without an initial value and the upstream has not emitted a value yet.) - * - * In addition, the value returned by this method may be stale. Use {@link LazySignal#isStale} to - * check if the value is stale. - * - * If you wish to get the current value and ensure that it is not stale, use the method - * {@link LazySignal#pull}. - */ - get(): TData; - /** - * Pulls the current value of the signal. If the value is stale, it will subscribe and wait for - * the next value from the upstream and return it. - */ - pull(): Promise>; - /** - * If the data is not stale, the callback will be called synchronously with the current value. - * - * If the data is stale, it will pull the current value and call the callback with the value. - */ - runOnNextFreshData(callback: (value: StripNotAvailable) => void): void; - ensureAvailable(): Promise>>; - subscribe(subscriber: Subscriber): () => void; - subscribeFull(subscriber: SignalFullSubscriber): () => void; - /** - * Subscribes to the signal. Will not cause the signal to subscribe to the upstream. - */ - passiveSubscribe(subscriber: Subscriber): () => void; - passiveSubscribeFull(subscriber: SignalFullSubscriber): () => void; - until(predicate: (data: StripNotAvailable) => boolean): Promise>; -} - -declare type Listener = (data: TData) => void; - -declare type Listener_2 = (data: TData) => void; - -/** - * Represents a specific loaded LLM. Most LLM related operations are inherited from - * {@link LLMDynamicHandle}. - * - * @public - */ -export declare class LLM extends LLMDynamicHandle implements SpecificModel { - readonly identifier: string; - readonly path: string; - readonly modelKey: string; - readonly format: ModelCompatibilityType; - readonly displayName: string; - readonly sizeBytes: number; - readonly vision: boolean; - readonly trainedForToolUse: boolean; - unload(): Promise; - getModelInfo(): Promise; -} - -/** - * The base options for the `.act` method. - * - * @public - */ -export declare interface LLMActBaseOpts { - /** - * A callback that is called when the model has output the first token of a prediction. This - * callback is called with round index (the index of the prediction within `.act(...)`, - * 0-indexed). - */ - onFirstToken?: (roundIndex: number) => void; - /** - * A callback for each fragment that is output by the model. This callback is called with the - * fragment that is emitted. The fragment itself is augmented with the round index (the index of - * the prediction within `.act(...)`, 0-indexed). - * - * For example, for an `.act` invocation with 2 predictions, the callback may be called in the - * following sequence. - * - * - `{ roundIndex: 0, content: "f1", ... }` when the first prediction emits `f1`. - * - `{ roundIndex: 0, content: "f2", ... }` when the first prediction emits `f2`. - * - `{ roundIndex: 1, content: "f3", ... }` when the second prediction emits `f3`. - * - `{ roundIndex: 1, content: "f4", ... }` when the second prediction emits `f4`. - */ - onPredictionFragment?: (fragment: LLMPredictionFragmentWithRoundIndex) => void; - /** - * A callback that is called when a message is generated and should be added to the Chat. This is - * useful if you want to add the generated content to a chat so you can continue the conversation. - * - * Note that, during one `act` call, multiple messages may be generated, and this callback - * will be called multiple times. For example, if the model requests to use a tool during the - * first prediction and stops after the second prediction, three messages will be created (and - * thus this callback will be called three times): - * - * 1. The first prediction's generated message, which contains information about the tool request. - * 2. The result of running the tool. - * 3. The second prediction's generated message. - */ - onMessage?: (message: ChatMessage) => void; - /** - * A callback that will be called when a new round of prediction starts. - */ - onRoundStart?: (roundIndex: number) => void; - /** - * A callback that will be called when a round of prediction ends. - */ - onRoundEnd?: (roundIndex: number) => void; - /** - * A callback that will be called when a prediction in a round is completed. The callback is - * called with the result of the prediction. You can access the roundIndex via the `.roundIndex` - * property. (See {@link PredictionResult} for more info). - * - * Note: this is called immediately after the prediction is completed. The tools may still be - * running. - */ - onPredictionCompleted?: (predictionResult: TPredictionResult) => void; - /** - * A callback that is called when the model is processing the prompt. The callback is called with - * the round index (the index of the prediction within `.act(...)`, 0-indexed) and a number - * between 0 and 1, representing the progress of the prompt processing. - * - * For example, for an `.act` invocation with 2 prediction rounds, the callback may be called - * in the following sequence. - * - * - `(0, 0.3)` when the first prediction's prompt processing is 30% done. - * - `(0, 0.7)` when the first prediction's prompt processing is 70% done. - * - ... The model starts to stream the first prediction's output, during which, this callback is - * not called. - * - `(1, 0.3)` when the second prediction's prompt processing is 50% done. - * - `(1, 0.7)` when the second prediction's prompt processing is 70% done. - */ - onPromptProcessingProgress?: (roundIndex: number, progress: number) => void; - /** - * A callback that is called when the model starts generating a tool call request. - * - * This hook is intended for updating the UI, such as showing "XXX is planning to use a tool...". - * At this stage the tool call request has not been generated thus we don't know what tool will be - * called. It is guaranteed that each `invocation` of `onToolCallRequestStart` is paired - * with exactly one `onToolCallRequestEnd` or `onToolCallRequestFailure`. - * - * @experimental [EXP-GRANULAR-ACT] More granular .act status reporting is experimental and may - * change in the future - */ - onToolCallRequestStart?: (roundIndex: number, callId: number, info: { - /** - * The LLM-specific tool call ID that should go into the context. This will be the same as the - * `toolCallRequest.id`. Depending on the LLM, this may or may not exist, and the format of it - * may also vary. - * - * If you need to match up different stages of the tool call, please use the `callId`, which - * is provided by lmstudio.js and is guaranteed to behave consistently across all LLMs. - */ - toolCallId?: string; - }) => void; - /** - * A callback that is called when the model has received the name of the tool. - * - * This hook is intended for updating the UI to show the name of the tool that is being called. If - * the model being used does not support eager function name reporting, this callback will be - * called right before the `onToolCallRequestEnd` callback. - * - * @experimental [EXP-GRANULAR-ACT] More granular .act status reporting is experimental and may - * change in the future - */ - onToolCallRequestNameReceived?: (roundIndex: number, callId: number, name: string) => void; - /** - * A callback that is called when the model has generated a fragment of the arguments of the tool. - * - * This hook is intended for updating the UI to stream the arguments of the tool that is being - * called. If the model being used does not support function arguments streaming, this callback - * will be called right before the `onToolCallRequestEnd` callback, but after the - * `onToolCallRequestNameReceived`. - * - * Note, when piecing together all the argument fragments, there is no guarantee that the result - * will be valid JSON, as some models may not use JSON to represent tool calls. - * - * @experimental [EXP-GRANULAR-ACT] More granular .act status reporting is experimental and may - * change in the future - */ - onToolCallRequestArgumentFragmentGenerated?: (roundIndex: number, callId: number, content: string) => void; - /** - * A callback that is called when a tool call is requested by the model. - * - * You should not use this callback to call the tool - the SDK will automatically call the tools - * you provided in the tools array. - * - * Instead, you can use this callback to update the UI or maintain the context. If you are unsure - * what to do with this callback, you can ignore it. - * - * @experimental [EXP-GRANULAR-ACT] More granular .act status reporting is experimental and may - * change in the future - */ - onToolCallRequestEnd?: (roundIndex: number, callId: number, info: { - /** - * Whether this tool call is queued. This is true iff the tool will not be immediately - * executed due to a prior tool is currently executing and `allowParallelToolExecution` is set - * to `false` (the default). - * - * If `isQueued` is true for a specific call request, the `onToolCallRequestDequeued` callback - * will be called for the call before it is executed. - */ - isQueued: boolean; - /** - * The tool call request that was generated by the model. This field is especially unstable - * as we will likely replace it with a nicer type. - * - * Note, this is not guaranteed to be the actual parameters that will be passed to the tool - * as the `guardToolCall` handler may modify them. If you want to access the final parameters - * (i.e. to add to the history), you should use the `onToolCallRequestFinalized`. - */ - toolCallRequest: ToolCallRequest; - /** - * The raw output that represents this tool call. It is recommended to present this to - * the user as is, if desired. - * - * @remarks It is not guaranteed to be valid JSON as the model does not necessarily use - * JSON to represent tool calls. - */ - rawContent: string | undefined; - }) => void; - /** - * A callback that is called right before the tool call is executed. This is called after the - * `guardToolCall` handler (if provided) and will have the updated parameters if the - * `guardToolCall` updated them. - * - * @experimental [EXP-GRANULAR-ACT] More granular .act status reporting is experimental and may - * change in the future - */ - onToolCallRequestFinalized?: (roundIndex: number, callId: number, info: { - /** - * The tool call request that is about to be executed. - */ - toolCallRequest: ToolCallRequest; - /** - * The raw output that represents this tool call. It is recommended to present this to - * the user as is, if desired. - * - * @remarks It is not guaranteed to be valid JSON as the model does not necessarily use - * JSON to represent tool calls. In addition, it might not match up the `toolCallRequest` - * as the `guardToolCall` handler may modify the parameters. - */ - rawContent: string | undefined; - }) => void; - /** - * A callback that is called when a tool call has failed to generate. - * - * This hook is intended for updating the UI, such as showing "a tool call has failed to - * generate.". - * - * @experimental [EXP-GRANULAR-ACT] More granular .act status reporting is experimental and may - * change in the future - */ - onToolCallRequestFailure?: (roundIndex: number, callId: number, error: ToolCallRequestError) => void; - /** - * A callback that is called when a queued tool call request is dequeued and is about to be - * executed. - * - * This callback will only be called for tool call requests that are queued, i.e. when `isQueued` - * is `true` in the `onToolCallRequestEnd` callback. - * - * If `allowParallelToolExecution` is set to `true`, this callback will never be called as - * all tool call requests will be handled immediately as they are being generated. - * - * If the tool call themselves are very fast, this callback may never be called, because the - * the first tool call might finish before the second tool call request is generated. - * - * @experimental [EXP-GRANULAR-ACT] More granular .act status reporting is experimental and may - * change in the future - */ - onToolCallRequestDequeued?: (roundIndex: number, callId: number) => void; - /** - * A handler that is called right before a tool call is executed. - * - * You may allow/allowAndOverrideParameters/deny the tool call in this handler by calling the - * respective method on the controller object passed in as the third parameter. - * - * An example `guardToolCll` that denies all tool calls is given below: - * - * ```ts - * model.act(history, tools, { - * guardToolCall: (roundIndex, callId, { deny }) => { - * deny("Tool calls are not allowed :("); - * }, - * }); - * ``` - * - * A more sophisticated example that prompts the user to confirm the tool call in CLI is given - * below (needs to be run in a Node.js environment): - * - * ```ts - * import readline from "readline/promises"; - * - * // ... - * - * model.act(history, tools, { - * guardToolCall: async (roundIndex, callId, { toolCallRequest, allow, deny }) => { - * const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); - * const answer = await rl.question( - * `Allow tool ${toolCallRequest.name}(${JSON.stringify(toolCallRequest.arguments)})? (y/n): ` - * ); - * rl.close(); - * if (answer.trim().toLowerCase() === "y") { - * allow(); - * } else { - * deny("Tool call denied by user."); - * } - * }, - * }); - * ``` - * - * @experimental [EXP-GRANULAR-ACT] More granular .act status reporting is experimental and may - * change in the future - * - * @remarks - * - * You must call one of the methods on the controller object to allow or deny the tool call. If - * you do not call any of the methods, `.act` will fail. - */ - guardToolCall?: (roundIndex: number, callId: number, controller: GuardToolCallController) => any | Promise; - /** - * A handler that is called when a tool request is made by the model but is invalid. - * - * There are multiple ways for a tool request to be invalid. For example, the model can simply - * output a string that claims to be a tool request, but cannot at all be parsed as one. Or it may - * request to use a tool that doesn't exist, or the parameters provided are invalid. - * - * When this happens, LM Studio will provide why it failed in the error parameter. We will also - * try to parse the tool request and provide it as the second parameter. However, this is not - * guaranteed to success, and the second parameter may be `undefined`. - * - * If we successfully parsed the request (thus the request parameter is not undefined), anything - * returned in this callback will be used as the result of the tool call. This is useful for - * providing a error message to the model so it may try again. However, if nothing (undefined) is - * returned, LM Studio will not provide a result to the given tool call. - * - * If we failed to parsed the request (thus the request parameter is undefined), the return value - * of this callback will be ignored as LM Studio cannot provide results to a tool call that has - * failed to parse. - * - * If you decide the failure is too severe to continue, you can always throw an error in this - * callback, which will immediately fail the `.act` call with the same error you provided. - * - * By default, we use the following implementation: - * - * ```ts - * handleInvalidToolRequest: (error, request) => { - * if (request) { - * return error.message; - * } - * throw error; - * }, - * ``` - * - * The default handler will do the following: If the model requested a tool that can be parsed but - * is still invalid, we will return the error message as the result of the tool call. If the model - * requested a tool that cannot be parsed, we will throw an error, which will immediately fail the - * `.act` call. - * - * Note, when an invalid tool request occurs due to parameters type mismatch, we will never call - * the original tool automatically due to security considerations. If you do decide to call the - * original tool, you can do so manually within this callback. - * - * This callback can also be async. - */ - handleInvalidToolRequest?: (error: ToolCallRequestError, request: ToolCallRequest | undefined) => any | Promise; - /** - * Limit the number of prediction rounds that the model can perform. In the last prediction, the - * model will not be allowed to use more tools. - * - * Note, some models may requests multiple tool calls within a single prediction round. This - * option only limits the number of prediction rounds, not the total number of tool calls. - */ - maxPredictionRounds?: number; - /** - * An abort signal that can be used to cancel the prediction. - */ - signal?: AbortSignal; - /** - * Whether to allow parallel tool calls to be executed in parallel. Defaults to `false`. - * - * @remarks - * - * Note, disabling this does NOT prevent the model from making parallel tool requests - models can - * still output multiple tool requests in the same prediction round. However, if this is set to - * `false`, the SDK will only execute one tool call at a time, and will wait for the previous tool - * call to finish before executing the next one. - * - * Enabling this option can speed up the act process if the tools are expected to take some time - * to execute, such as when they make network requests. However, it can lead to problems when - * tools are stateful and have strict ordering requirements. - */ - allowParallelToolExecution?: boolean; -} - -/** - * Options for {@link LLMDynamicHandle#act}. - * - * @public - */ -export declare type LLMActionOpts = LLMPredictionConfigInput & LLMActBaseOpts & { - /** - * Which preset to use. - * - * @remarks - * - * This preset selection is "layered" between your overrides and the "server session" config. - * Which means, other fields you specify in this opts object will override the preset, while the - * preset content will override the "server session" config. - */ - preset?: string; -}; - -/** - * LLM specific information. - * - * @public - */ -export declare interface LLMAdditionalInfo { - /** - * Whether this model is vision-enabled (i.e. supports image input). - */ - vision: boolean; - /** - * Whether this model is trained natively for tool use. - */ - trainedForToolUse: boolean; - /** - * Maximum context length of the model. - */ - maxContextLength: number; -} - -/** - * Options for applying a prompt template. - * @public - */ -export declare interface LLMApplyPromptTemplateOpts { - /** - * Whether to omit the BOS token when formatting. - * - * Default: false - */ - omitBosToken?: boolean; - /** - * Whether to omit the EOS token when formatting. - * - * Default: false - */ - omitEosToken?: boolean; - /** - * Optional tool definitions to include in the prompt. - */ - toolDefinitions?: Array; -} - -/** - * Behavior for when the generated tokens length exceeds the context window size. Only the following - * values are allowed: - * - * - `stopAtLimit`: Stop the prediction when the generated tokens length exceeds the context window - * size. If the generation is stopped because of this limit, the `stopReason` in the prediction - * stats will be set to `contextLengthReached`. - * - `truncateMiddle`: Keep the system prompt and the first user message, truncate middle. - * - `rollingWindow`: Maintain a rolling window and truncate past messages. - * - * @public - */ -export declare type LLMContextOverflowPolicy = "stopAtLimit" | "truncateMiddle" | "rollingWindow"; - -/** - * This represents a set of requirements for a model. It is not tied to a specific model, but rather - * to a set of requirements that a model must satisfy. - * - * For example, if you got the model via `client.llm.model("my-identifier")`, you will get a - * `LLMDynamicHandle` for the model with the identifier `my-identifier`. If the model is unloaded, - * and another model is loaded with the same identifier, using the same `LLMDynamicHandle` will use - * the new model. - * - * @public - */ -export declare class LLMDynamicHandle extends DynamicHandle { - private predictionConfigInputToKVConfig; - private createZodParser; - /** - * Use the loaded model to predict text. - * - * This method returns an {@link OngoingPrediction} object. An ongoing prediction can be used as a - * promise (if you only care about the final result) or as an async iterable (if you want to - * stream the results as they are being generated). - * - * Example usage as a promise (Resolves to a {@link PredictionResult}): - * - * ```typescript - * const result = await model.complete("When will The Winds of Winter be released?"); - * console.log(result.content); - * ``` - * - * Or - * - * ```typescript - * model.complete("When will The Winds of Winter be released?") - * .then(result =\> console.log(result.content)) - * .catch(error =\> console.error(error)); - * ``` - * - * Example usage as an async iterable (streaming): - * - * ```typescript - * for await (const { content } of model.complete("When will The Winds of Winter be released?")) { - * process.stdout.write(content); - * } - * ``` - * - * If you wish to stream the result, but also getting the final prediction results (for example, - * you wish to get the prediction stats), you can use the following pattern: - * - * ```typescript - * const prediction = model.complete("When will The Winds of Winter be released?"); - * for await (const { content } of prediction) { - * process.stdout.write(content); - * } - * const result = await prediction.result(); - * console.log(result.stats); - * ``` - * - * @param prompt - The prompt to use for prediction. - * @param opts - Options for the prediction. - */ - complete(prompt: string, opts?: LLMPredictionOpts): OngoingPrediction; - private resolveCompletionContext; - /** - * Use the loaded model to generate a response based on the given history. - * - * This method returns an {@link OngoingPrediction} object. An ongoing prediction can be used as a - * promise (if you only care about the final result) or as an async iterable (if you want to - * stream the results as they are being generated). - * - * Example usage as a promise (Resolves to a {@link PredictionResult}): - * - * ```typescript - * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }]; - * const result = await model.respond(history); - * console.log(result.content); - * ``` - * - * Or - * - * ```typescript - * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }]; - * model.respond(history) - * .then(result => console.log(result.content)) - * .catch(error => console.error(error)); - * ``` - * - * Example usage as an async iterable (streaming): - * - * ```typescript - * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }]; - * for await (const { content } of model.respond(history)) { - * process.stdout.write(content); - * } - * ``` - * - * If you wish to stream the result, but also getting the final prediction results (for example, - * you wish to get the prediction stats), you can use the following pattern: - * - * ```typescript - * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }]; - * const prediction = model.respond(history); - * for await (const { content } of prediction) { - * process.stdout.write(content); - * } - * const result = await prediction; - * console.log(result.stats); - * ``` - * - * @param chat - The LLMChatHistory array to use for generating a response. - * @param opts - Options for the prediction. - */ - respond(chat: ChatLike, opts?: LLMRespondOpts): OngoingPrediction; - /** - * @param chat - The LLMChatHistory array to act from as the base - * @param tool - An array of tools that the model can use during the operation. You can create - * tools by using the `tool` function. - * @param opts - Additional options - * - * Example: - * - * ``` - * import { LMStudioClient, tool } from "@lmstudio/sdk"; - * import { z } from "zod"; - * - * const client = new LMStudioClient(); - * const model = await client.llm.model(); - * - * const additionTool = tool({ - * name: "add", - * description: "Add two numbers", - * parameters: { - * a: z.number(), - * b: z.number(), - * }, - * implementation: ({ a, b }) => a + b, - * }); - * - * await model.act("What is 1234 + 4321?", [additionTool], { - * onMessage: message => console.log(message.toString()), - * }); - * ``` - */ - act(chat: ChatLike, tools: Array, opts?: LLMActionOpts): Promise; - getContextLength(): Promise; - applyPromptTemplate(history: ChatLike, opts?: LLMApplyPromptTemplateOpts): Promise; - tokenize(inputString: string): Promise>; - tokenize(inputStrings: Array): Promise>>; - countTokens(inputString: string): Promise; - /** - * Starts to eagerly preload a draft model. This is useful when you want a draft model to be ready - * for speculative decoding. - * - * Preloading is done on a best-effort basis and may not always succeed. It is not guaranteed that - * the draft model is actually loaded when this method returns. Thus, this method should only be - * used as an optimization. The actual draft model used only depends on the parameter set when - * performing the prediction. - */ - unstable_preloadDraftModel(draftModelKey: string): Promise; -} - -/** - * Options for the LLM generator's act method. - * - * @public - * @experimental [EXP-GEN-PREDICT] Using generator plugins programmatically is still in development. - * This may change in the future without warning. - */ -export declare type LLMGeneratorActOpts = LLMActBaseOpts & { - /** - * Config provided to the plugin. - */ - pluginConfig?: KVConfig; - /** - * Working directory for the generator. - */ - workingDirectory?: string; -}; - -/** - * Represents a handle for a generator that can act as a LLM. - * - * @public - * @experimental [EXP-GEN-PREDICT] Using generator plugins programmatically is still in development. - * This may change in the future without warning. - */ -export declare class LLMGeneratorHandle { - /** - * The identifier of the plugin that this handle is associated with. - */ - readonly identifier: string; - private getPluginConfigSpecifier; - /** - * Use the generator to produce a response based on the given history. - */ - respond(chat: ChatLike, opts?: LLMGeneratorPredictionOpts): OngoingGeneratorPrediction; - act(chat: ChatLike, tools: Array, opts?: LLMGeneratorActOpts): Promise; -} - -/** - * Options for {@link LLMGeneratorHandle#respond}. - * - * @public - * @experimental [EXP-GEN-PREDICT] Using generator plugins programmatically is still in development. - * This may change in the future without warning. - */ -export declare interface LLMGeneratorPredictionOpts { - /** - * A callback that is called when the first token is generated. - */ - onFirstToken?: () => void; - /** - * A callback that is called when a prediction fragment is generated. - */ - onPredictionFragment?: (fragment: LLMPredictionFragment) => void; - /** - * A convenience callback that is called when the model finishes generation. The callback is - * called with a message that has the role set to "assistant" and the content set to the generated - * text. - * - * This callback is useful if you want to add the generated message to a chat. - * - * For example: - * - * ```ts - * const chat = Chat.empty(); - * chat.append("user", "When will The Winds of Winter be released?"); - * - * const generator = client.llm.createGeneratorHandle("lmstudio/some-plugin") - * const prediction = generator.respond(chat, { - * onMessage: message => chat.append(message), - * }); - * ``` - */ - onMessage?: (message: ChatMessage) => void; - /** - * An abort signal that - */ - signal?: AbortSignal; - /** - * Config provided to the plugin. - */ - pluginConfig?: KVConfig; - /** - * Working directory for the generator. - */ - workingDirectory?: string; -} - -/** - * @public - */ -export declare interface LLMGenInfo { - indexedModelIdentifier: string; - identifier: string; - loadModelConfig: KVConfig; - predictionConfig: KVConfig; - stats: LLMPredictionStats; -} - -/** - * Info of an LLM. It is a combination of {@link ModelInfoBase} and {@link LLMAdditionalInfo}. - * - * @public - */ -export declare type LLMInfo = { - type: "llm"; -} & ModelInfoBase & LLMAdditionalInfo; - -/** - * Additional information of an LLM instance. - * - * @public - */ -export declare interface LLMInstanceAdditionalInfo { - contextLength: number; -} - -/** - * Info of a loaded LLM instance. It is a combination of {@link ModelInstanceInfoBase}, - * {@link LLMAdditionalInfo} and {@link LLMInstanceAdditionalInfo}. - * - * @public - */ -export declare type LLMInstanceInfo = { - type: "llm"; -} & ModelInstanceInfoBase & LLMAdditionalInfo & LLMInstanceAdditionalInfo; - -/** - * @public - */ -export declare interface LLMJinjaPromptTemplate { - template: string; -} - -/** - * How much of the model's work should be offloaded to the GPU. The value should be between 0 and 1. - * A value of 0 means that no layers are offloaded to the GPU, while a value of 1 means that all - * layers (that can be offloaded) are offloaded to the GPU. - * - * @public - */ -export declare type LLMLlamaAccelerationOffloadRatio = number | "max" | "off"; - -/** - * TODO: Add documentation - * - * @public - */ -export declare type LLMLlamaCacheQuantizationType = "f32" | "f16" | "q8_0" | "q4_0" | "q4_1" | "iq4_nl" | "q5_0" | "q5_1"; - -/** @public */ -export declare interface LLMLoadModelConfig { - /** - * How to distribute the work to your GPUs. See {@link GPUSetting} for more information. - * - * @public - * @deprecated We are currently working on an improved way to control split. You can use this for - * now but expect breakage in the future. - */ - gpu?: GPUSetting; - /** - * If set to true, detected system limits for VRAM will be strictly enforced. If a model + gpu - * offload combination would exceed the detected available VRAM, model offload will be capped to - * not exceed the available VRAM. - * - * @public - */ - gpuStrictVramCap?: boolean; - /** - * If set to true, KV cache will be offloaded to GPU memory if available. If false, KV cache will - * be loaded to RAM. - * - * @public - */ - offloadKVCacheToGpu?: boolean; - /** - * The size of the context length in number of tokens. This will include both the prompts and the - * responses. Once the context length is exceeded, the value set in - * {@link LLMPredictionConfigBase#contextOverflowPolicy} is used to determine the behavior. - * - * See {@link LLMContextOverflowPolicy} for more information. - */ - contextLength?: number; - /** - * Custom base frequency for rotary positional embeddings (RoPE). - * - * This advanced parameter adjusts how positional information is embedded in the model's - * representations. Increasing this value may enable better performance at high context lengths by - * modifying how the model processes position-dependent information. - */ - ropeFrequencyBase?: number; - /** - * Scaling factor for RoPE (Rotary Positional Encoding) frequency. - * - * This factor scales the effective context window by modifying how positional information is - * encoded. Higher values allow the model to handle longer contexts by making positional encoding - * more granular, which can be particularly useful for extending a model beyond its original - * training context length. - */ - ropeFrequencyScale?: number; - /** - * Number of input tokens to process together in a single batch during evaluation. - * - * Increasing this value typically improves processing speed and throughput by leveraging - * parallelization, but requires more memory. Finding the optimal batch size often involves - * balancing between performance gains and available hardware resources. - */ - evalBatchSize?: number; - /** - * Enables Flash Attention for optimized attention computation. - * - * Flash Attention is an efficient implementation that reduces memory usage and speeds up - * generation by optimizing how attention mechanisms are computed. This can significantly - * improve performance on compatible hardware, especially for longer sequences. - */ - flashAttention?: boolean; - /** - * When enabled, prevents the model from being swapped out of system memory. - * - * This option reserves system memory for the model even when portions are offloaded to GPU, - * ensuring faster access times when the model needs to be used. Improves performance - * particularly for interactive applications, but increases overall RAM requirements. - */ - keepModelInMemory?: boolean; - /** - * Random seed value for model initialization to ensure reproducible outputs. - * - * Setting a specific seed ensures that random operations within the model (like sampling) - * produce the same results across different runs, which is important for reproducibility - * in testing and development scenarios. - */ - seed?: number; - /** - * When enabled, stores the key-value cache in half-precision (FP16) format. - * - * This option significantly reduces memory usage during inference by using 16-bit floating - * point numbers instead of 32-bit for the attention cache. While this may slightly reduce - * numerical precision, the impact on output quality is generally minimal for most applications. - */ - useFp16ForKVCache?: boolean; - /** - * Attempts to use memory-mapped (mmap) file access when loading the model. - * - * Memory mapping can improve initial load times by mapping model files directly from disk to - * memory, allowing the operating system to handle paging. This is particularly beneficial for - * quick startup, but may reduce performance if the model is larger than available system RAM, - * causing frequent disk access. - */ - tryMmap?: boolean; - /** - * Specifies the number of experts to use for models with Mixture of Experts (MoE) architecture. - * - * MoE models contain multiple "expert" networks that specialize in different aspects of the task. - * This parameter controls how many of these experts are active during inference, affecting both - * performance and quality of outputs. Only applicable for models designed with the MoE - * architecture. - */ - numExperts?: number; - /** - * Quantization type for the Llama model's key cache. - * - * This option determines the precision level used to store the key component of the attention - * mechanism's cache. Lower precision values (e.g., 4-bit or 8-bit quantization) significantly - * reduce memory usage during inference but may slightly impact output quality. The effect varies - * between different models, with some being more robust to quantization than others. - * - * Set to false to disable quantization and use full precision. - */ - llamaKCacheQuantizationType?: LLMLlamaCacheQuantizationType | false; - /** - * Quantization type for the Llama model's value cache. - * - * Similar to the key cache quantization, this option controls the precision used for the value - * component of the attention mechanism's cache. Reducing precision saves memory but may affect - * generation quality. This option requires Flash Attention to be enabled to function properly. - * - * Different models respond differently to value cache quantization, so experimentation may be - * needed to find the optimal setting for a specific use case. Set to false to disable - * quantization. - */ - llamaVCacheQuantizationType?: LLMLlamaCacheQuantizationType | false; -} - -/** - * @public - */ -export declare interface LLMManualPromptTemplate { - /** - * String to be prepended to the system prompt. - */ - beforeSystem: string; - /** - * String to be appended to the system prompt. - */ - afterSystem: string; - /** - * String to be prepended to a user message. - */ - beforeUser: string; - /** - * String to be appended to a user message. - */ - afterUser: string; - /** - * String to be prepended to an assistant message. - */ - beforeAssistant: string; - /** - * String to be appended to an assistant message. - */ - afterAssistant: string; -} - -/** @public */ -export declare class LLMNamespace extends ModelNamespace { -} - -/** - * @public - */ -export declare type LLMPredictionConfig = Omit, "structured"> & { - structured?: LLMStructuredPredictionSetting; -}; - -/** - * Shared config for running predictions on an LLM. - * - * @public - */ -export declare interface LLMPredictionConfigInput { - /** - * Number of tokens to predict at most. If set to false, the model will predict as many tokens as - * it wants. - * - * When the prediction is stopped because of this limit, the `stopReason` in the prediction stats - * will be set to `maxPredictedTokensReached`. - * - * See {@link LLMPredictionStopReason} for other reasons that a prediction might stop. - */ - maxTokens?: number | false; - /** - * The temperature parameter for the prediction model. A higher value makes the predictions more - * random, while a lower value makes the predictions more deterministic. The value should be - * between 0 and 1. - */ - temperature?: number; - /** - * An array of strings. If the model generates one of these strings, the prediction will stop. - * - * When the prediction is stopped because of this limit, the `stopReason` in the prediction stats - * will be set to `stopStringFound`. - * - * See {@link LLMPredictionStopReason} for other reasons that a prediction might stop. - */ - stopStrings?: Array; - /** - * An array of strings. If the model generates one of these strings, the prediction will stop with - * the `stopReason` `toolCalls`. - * - * See {@link LLMPredictionStopReason} for other reasons that a prediction might stop. - */ - toolCallStopStrings?: Array; - /** - * The behavior for when the generated tokens length exceeds the context window size. The allowed - * values are: - * - * - `stopAtLimit`: Stop the prediction when the generated tokens length exceeds the context - * window size. If the generation is stopped because of this limit, the `stopReason` in the - * prediction stats will be set to `contextLengthReached` - * - `truncateMiddle`: Keep the system prompt and the first user message, truncate middle. - * - `rollingWindow`: Maintain a rolling window and truncate past messages. - */ - contextOverflowPolicy?: LLMContextOverflowPolicy; - /** - * Configures the model to output structured JSON data that follows a specific schema defined - * using Zod. - * - * When you provide a Zod schema, the model will be instructed to generate JSON that conforms to - * that schema rather than free-form text. - * - * This is particularly useful for extracting specific data points from model responses or when - * you need the output in a format that can be directly used by your application. - */ - structured?: { - /** - * IMPORTANT - * - * When passing in a zod schema as the structured generation option, you must provide an - * actual zod schema object. (returned by z.something()). The type here only requires an - * object with a `parse` function. This is not enough! We need an actual zod schema because - * we will need to extract the JSON schema from it. If you don't want use zod, consider - * passing in a `LLMStructuredPredictionSetting` instead. - * - * The reason we only have a `parse` function here (as oppose to actually requiring - * ZodType is due to this zod bug causing TypeScript breakage, when - * multiple versions of zod exist. - * - * - https://github.com/colinhacks/zod/issues/577 - * - https://github.com/colinhacks/zod/issues/2697 - * - https://github.com/colinhacks/zod/issues/3435 - */ - parse: (input: any) => TStructuredOutputType; - } | LLMStructuredPredictionSetting; - /** - * @deprecated Raw tools are currently not well-supported. It may or may not work. If you want to - * use tools, use `model.act` instead. - */ - rawTools?: LLMToolUseSetting; - /** - * What transformations to apply to tool names before sending them to the model. See - * {@link ToolNaming} for more details. - */ - toolNaming?: ToolNaming; - /** - * Controls token sampling diversity by limiting consideration to the K most likely next tokens. - * - * For example, if set to 40, only the 40 tokens with the highest probabilities will be considered - * for the next token selection. A lower value (e.g., 20) will make the output more focused and - * conservative, while a higher value (e.g., 100) allows for more creative and diverse outputs. - * - * Typical values range from 20 to 100. - */ - topKSampling?: number; - /** - * Applies a penalty to repeated tokens to prevent the model from getting stuck in repetitive - * patterns. - * - * A value of 1.0 means no penalty. Values greater than 1.0 increase the penalty. For example, 1.2 - * would reduce the probability of previously used tokens by 20%. This is particularly useful for - * preventing the model from repeating phrases or getting stuck in loops. - * - * Set to false to disable the penalty completely. - */ - repeatPenalty?: number | false; - /** - * Sets a minimum probability threshold that a token must meet to be considered for generation. - * - * For example, if set to 0.05, any token with less than 5% probability will be excluded from - * consideration. This helps filter out unlikely or irrelevant tokens, potentially improving - * output quality. - * - * Value should be between 0 and 1. Set to false to disable this filter. - */ - minPSampling?: number | false; - /** - * Implements nucleus sampling by only considering tokens whose cumulative probabilities reach a - * specified threshold. - * - * For example, if set to 0.9, the model will consider only the most likely tokens that together - * add up to 90% of the probability mass. This helps balance between diversity and quality by - * dynamically adjusting the number of tokens considered based on their probability distribution. - * - * Value should be between 0 and 1. Set to false to disable nucleus sampling. - */ - topPSampling?: number | false; - /** - * Controls how often the XTC (Exclude Top Choices) sampling technique is applied during - * generation. - * - * XTC sampling can boost creativity and reduce clichés by occasionally filtering out common - * tokens. For example, if set to 0.3, there's a 30% chance that XTC sampling will be applied when - * generating each token. - * - * Value should be between 0 and 1. Set to false to disable XTC completely. - */ - xtcProbability?: number | false; - /** - * Defines the lower probability threshold for the XTC (Exclude Top Choices) sampling technique. - * - * When XTC sampling is activated (based on xtcProbability), the algorithm identifies tokens with - * probabilities between this threshold and 0.5, then removes all such tokens except the least - * probable one. This helps introduce more diverse and unexpected tokens into the generation. - * - * Only takes effect when xtcProbability is enabled. - */ - xtcThreshold?: number | false; - /** - * @deprecated We are still working on bringing logProbs to SDK. Stay tuned for updates. - */ - logProbs?: number | false; - /** - * Specifies the number of CPU threads to allocate for model inference. - * - * Higher values can improve performance on multi-core systems but may compete with other - * processes. For example, on an 8-core system, a value of 4-6 might provide good performance - * while leaving resources for other tasks. - * - * If not specified, the system will use a default value based on available hardware. - */ - cpuThreads?: number; - /** - * Defines a custom template for formatting prompts before sending them to the model. - * - * Prompt templates allow you to control exactly how conversations are formatted, including - * system messages, user inputs, and assistant responses. This is particularly useful when - * working with models that expect specific formatting conventions. - * - * Different models may have different optimal prompt templates, so this allows for - * model-specific customization. - * - * @deprecated The current type for promptTemplate is not yet finalized. We are working on a new - * type that will be more flexible and easier to use. Stay tuned for updates. - */ - promptTemplate?: LLMPromptTemplate; - /** - * The draft model to use for speculative decoding. Speculative decoding is a technique that can - * drastically increase the generation speed (up to 3x for larger models) by paring a main model - * with a smaller draft model. - * - * See here for more information: https://lmstudio.ai/docs/advanced/speculative-decoding - * - * You do not need to load the draft model yourself. Simply specifying its model key here is - * enough. - */ - draftModel?: string; - /** - * Warning: Experimental and subject to change. - * - * @alpha - * @deprecated This feature is experimental and may change or be removed in the future. - */ - speculativeDecodingNumDraftTokensExact?: number; - /** - * Warning: Experimental and subject to change. - * - * Minimum number of drafted tokens required to run draft through the main model. - * - * @alpha - * - */ - speculativeDecodingMinDraftLengthToConsider?: number; - /** - * Warning: Experimental and subject to change. - * - * @alpha - * @deprecated This feature is experimental and may change or be removed in the future. - */ - speculativeDecodingMinContinueDraftingProbability?: number; - /** - * How to parse the reasoning sections in the model output. Only need to specify the `startString` - * and the `endString`. - * - * For example, DeepSeek models use: - * - * ``` - * reasoningParsing: { - * enabled: true, - * startString: "", - * endString: "", - * } - * ``` - */ - reasoningParsing?: LLMReasoningParsing; - /** - * Raw KV Config. - * - * @experimental - * @deprecated Internal mechanism to carry arbitrary config that does not have a public API yet. - * May change at any time. Do not use. - */ - raw?: KVConfig; -} - -/** - * Represents a fragment of a prediction from an LLM. Note that a fragment may contain multiple - * tokens. - * - * @public - */ -export declare interface LLMPredictionFragment { - /** - * String content of the fragment. - */ - content: string; - /** - * Number of tokens contains in this fragment. Note this value is not always accurate as tokens - * may be split across fragments. However, over a period of time, the sum of token counts of - * multiple fragments will be close to the actual token count. As such, this value can be - * accumulated to provide a "live tokens count". - */ - tokensCount: number; - /** - * Whether this fragment contains tokens from the draft model. - */ - containsDrafted: boolean; - /** - * Type of reasoning for this fragment. See {@link LLMPredictionFragmentReasoningType} for more - * info. - */ - reasoningType: LLMPredictionFragmentReasoningType; - /** - * TODO: Documentation - * - * @experimental WIP - do not use yet. - */ - isStructural: boolean; -} - -/** - * Options for creating a prediction fragment. - * - * @public - */ -export declare interface LLMPredictionFragmentInputOpts { - /** - * How many tokens this fragment contains. Defaults to 1. - */ - tokenCount?: number; - /** - * Whether this fragment contains tokens from the draft model (when using speculative decoding). - * Defaults to `false`. - */ - containsDrafted?: boolean; - /** - * Type of reasoning for this fragment. Defaults to "none". - */ - reasoningType?: LLMPredictionFragmentReasoningType; - /** - * TODO: Documentation - * - * @experimental WIP - do not use yet. - */ - isStructural?: boolean; -} - -/** - * Represents the type of this fragment in terms of reasoning. - * - * - `none`: Content outside of a reasoning block. - * - `reasoning`: Content inside a reasoning block. - * - `reasoningStartTag`: Start tag of a reasoning block. - * - `reasoningEndTag`: End tag of a reasoning block. - * - * @public - */ -export declare type LLMPredictionFragmentReasoningType = "none" | "reasoning" | "reasoningStartTag" | "reasoningEndTag"; - -/** - * A {@link LLMPredictionFragment} with the index of the prediction within `.act(...)`. - * - * See {@link LLMPredictionFragment} for more fields. - * - * @public - */ -export declare type LLMPredictionFragmentWithRoundIndex = LLMPredictionFragment & { - roundIndex: number; -}; - -/** - * Options for {@link LLMDynamicHandle#complete}. - * - * Note, this interface extends {@link LLMPredictionConfigInput}. See its documentation for more - * fields. - * - * Alternatively, use your IDE/editor's intellisense to see the fields. - * - * @public - */ -export declare interface LLMPredictionOpts extends LLMPredictionConfigInput { - /** - * A callback that is called when the model is processing the prompt. The callback is called with - * a number between 0 and 1, representing the progress of the prompt processing. - * - * Prompt processing progress callbacks will only be called before the first token is emitted. - */ - onPromptProcessingProgress?: (progress: number) => void; - /** - * A callback that is called when the model has output the first token. - */ - onFirstToken?: () => void; - /** - * A callback for each fragment that is output by the model. - */ - onPredictionFragment?: (fragment: LLMPredictionFragment) => void; - /** - * A callback that is called when the model starts generating a tool call request. - * - * This hook is intended for updating the UI, such as showing "XXX is planning to use a tool...". - * At this stage the tool call request has not been generated thus we don't know what tool will be - * called. It is guaranteed that each `invocation` of `onToolCallRequestStart` is paired with - * exactly one `onToolCallRequestEnd` or `onToolCallRequestFailure`. - * - * @experimental [EXP-NON-ACT-TOOL-CALLBACKS] Tool call callbacks in .respond/.complete is in an - * experimental feature. This may change in the future without warning. - */ - onToolCallRequestStart?: (callId: number, info: { - /** - * The LLM-specific tool call ID that should go into the context. This will be the same as the - * `toolCallRequest.id`. Depending on the LLM, this may or may not exist, and the format of it - * may also vary. - * - * If you need to match up different stages of the tool call, please use the `callId`, which - * is provided by lmstudio.js and is guaranteed to behave consistently across all LLMs. - */ - toolCallId?: string; - }) => void; - /** - * A callback that is called when the model has received the name of the tool. - * - * This hook is intended for updating the UI to show the name of the tool that is being called. If - * the model being used does not support eager function name reporting, this callback will be - * called right before the `onToolCallRequestEnd` callback. - * - * @experimental [EXP-NON-ACT-TOOL-CALLBACKS] Tool call callbacks in .respond/.complete is in an - * experimental feature. This may change in the future without warning. - */ - onToolCallRequestNameReceived?: (callId: number, name: string) => void; - /** - * A callback that is called when the model has generated a fragment of the arguments of the tool. - * - * This hook is intended for updating the UI to stream the arguments of the tool that is being - * called. If the model being used does not support function arguments streaming, this callback - * will be called right before the `onToolCallRequestEnd` callback, but after the - * `onToolCallRequestNameReceived`. - * - * Note, when piecing together all the argument fragments, there is no guarantee that the result - * will be valid JSON, as some models may not use JSON to represent tool calls. - * - * @experimental [EXP-NON-ACT-TOOL-CALLBACKS] Tool call callbacks in .respond/.complete is in an - * experimental feature. This may change in the future without warning. - */ - onToolCallRequestArgumentFragmentGenerated?: (callId: number, content: string) => void; - /** - * A callback that is called when a tool call is requested by the model. - * - * @experimental [EXP-NON-ACT-TOOL-CALLBACKS] Tool call callbacks in .respond/.complete is in an - * experimental feature. This may change in the future without warning. - */ - onToolCallRequestEnd?: (callId: number, info: { - /** - * The tool call request that was generated by the model. This field is especially unstable - * as we will likely replace it with a nicer type. - */ - toolCallRequest: ToolCallRequest; - /** - * The raw output that represents this tool call. It is recommended to present this to - * the user as is, if desired. - * - * @remarks It is not guaranteed to be valid JSON as the model does not necessarily use - * JSON to represent tool calls. - */ - rawContent: string | undefined; - }) => void; - /** - * A callback that is called when a tool call has failed to generate. - * - * @experimental [EXP-NON-ACT-TOOL-CALLBACKS] Tool call callbacks in .respond/.complete is in an - * experimental feature. This may change in the future without warning. - */ - onToolCallRequestFailure?: (callId: number, error: ToolCallRequestError) => void; - /** - * An abort signal that can be used to cancel the prediction. - */ - signal?: AbortSignal; - /** - * Which preset to use. - * - * @remarks - * - * This preset selection is "layered" between your overrides and the "server session" config. - * Which means, other fields you specify in this opts object will override the preset, while the - * preset content will override the "server session" config. - */ - preset?: string; -} - -/** @public */ -export declare interface LLMPredictionStats { - /** - * The reason why the prediction stopped. - * - * This is a string enum with the following possible values: - * - * - `userStopped`: The user stopped the prediction. This includes calling the `cancel` method on - * the `OngoingPrediction` object. - * - `modelUnloaded`: The model was unloaded during the prediction. - * - `failed`: An error occurred during the prediction. - * - `eosFound`: The model predicted an end-of-sequence token, which is a way for the model to - * indicate that it "thinks" the sequence is complete. - * - `stopStringFound`: A stop string was found in the prediction. (Stop strings can be specified - * with the `stopStrings` config option. This stop reason will only occur if the `stopStrings` - * config option is set.) - * - `maxPredictedTokensReached`: The maximum number of tokens to predict was reached. (Length - * limit can be specified with the `maxPredictedTokens` config option. This stop reason will - * only occur if the `maxPredictedTokens` config option is set to a value other than -1.) - * - `contextLengthReached`: The context length was reached. This stop reason will only occur if - * the `contextOverflowPolicy` is set to `stopAtLimit`. - */ - stopReason: LLMPredictionStopReason; - /** - * The average number of tokens predicted per second. - * - * Note: This value can be undefined in the case of a very short prediction which results in a - * NaN or a Infinity value. - */ - tokensPerSecond?: number; - /** - * The number of GPU layers used in the prediction. (Currently not correct.) - */ - numGpuLayers?: number; - /** - * The time it took to predict the first token in seconds. - */ - timeToFirstTokenSec?: number; - /** - * The total time it took to predict the result in seconds. - */ - totalTimeSec?: number; - /** - * The number of tokens that were supplied. - */ - promptTokensCount?: number; - /** - * The number of tokens that were predicted. - */ - predictedTokensCount?: number; - /** - * The total number of tokens. This is the sum of the prompt tokens and the predicted tokens. - */ - totalTokensCount?: number; - /** - * If the prediction used speculative decoding, this is the model key of the draft model that was - * used. - */ - usedDraftModelKey?: string; - /** - * Total number of tokens generated by the draft model when using speculative decoding. Undefined - * if speculative decoding is not used. - * - * ``` - * totalDraftTokensCount = - * rejectedDraftTokensCount + acceptedDraftTokensCount + ignoredDraftTokensCount - * ``` - */ - totalDraftTokensCount?: number; - /** - * Number of drafted tokens that are accepted by the main model. The higher the better. Undefined - * if speculative decoding is not used. - * - * ``` - * totalDraftTokensCount = - * rejectedDraftTokensCount + acceptedDraftTokensCount + ignoredDraftTokensCount - * ``` - */ - acceptedDraftTokensCount?: number; - /** - * Number of draft tokens that are rejected by the main model. The lower the better. Undefined if - * speculative decoding is not used. - * - * ``` - * totalDraftTokensCount = - * rejectedDraftTokensCount + acceptedDraftTokensCount + ignoredDraftTokensCount - * ``` - */ - rejectedDraftTokensCount?: number; - /** - * Number of draft tokens that were not sent to the main model for decoding. Undefined if - * speculative decoding is not used. - * - * ``` - * totalDraftTokensCount = - * rejectedDraftTokensCount + acceptedDraftTokensCount + ignoredDraftTokensCount - * ``` - */ - ignoredDraftTokensCount?: number; -} - -/** - * Represents the reason why a prediction stopped. Only the following values are possible: - * - * - `userStopped`: The user stopped the prediction. This includes calling the `cancel` method on - * the `OngoingPrediction` object. - * - `modelUnloaded`: The model was unloaded during the prediction. - * - `failed`: An error occurred during the prediction. - * - `eosFound`: The model predicted an end-of-sequence token, which is a way for the model to - * indicate that it "thinks" the sequence is complete. - * - `stopStringFound`: A stop string was found in the prediction. (Stop strings can be specified - * with the `stopStrings` config option. This stop reason will only occur if the `stopStrings` - * config option is set to an array of strings.) - * - `maxPredictedTokensReached`: The maximum number of tokens to predict was reached. (Length limit - * can be specified with the `maxPredictedTokens` config option. This stop reason will only occur - * if the `maxPredictedTokens` config option is set to a value other than -1.) - * - `contextLengthReached`: The context length was reached. This stop reason will only occur if the - * `contextOverflowPolicy` is set to `stopAtLimit`. - * - * @public - */ -export declare type LLMPredictionStopReason = "userStopped" | "modelUnloaded" | "failed" | "eosFound" | "stopStringFound" | "toolCalls" | "maxPredictedTokensReached" | "contextLengthReached"; - -/** - * @public - */ -export declare interface LLMPromptTemplate { - type: LLMPromptTemplateType; - manualPromptTemplate?: LLMManualPromptTemplate; - jinjaPromptTemplate?: LLMJinjaPromptTemplate; - /** - * Additional stop strings to be used with this template. - */ - stopStrings: Array; -} - -/** @public */ -export declare type LLMPromptTemplateType = "manual" | "jinja"; - -/** - * How to parse reasoning sections in the model output. An easier to use type will be added in the - * future. - * - * @public - */ -export declare interface LLMReasoningParsing { - /** - * Whether to enable reasoning parsing. - */ - enabled: boolean; - startString: string; - endString: string; -} - -/** - * Options for {@link LLMDynamicHandle#respond}. - * - * Note, this interface extends {@link LLMPredictionOpts} and {@link LLMPredictionConfigInput}. See - * their documentation for more fields. - * - * Alternatively, use your IDE/editor's intellisense to see the fields. - * - * @public - */ -export declare interface LLMRespondOpts extends LLMPredictionOpts { - /** - * A convenience callback that is called when the model finishes generation. The callback is - * called with a message that has the role set to "assistant" and the content set to the generated - * text. - * - * This callback is useful if you want to add the generated message to a chat. - * - * For example: - * - * ```ts - * const chat = Chat.empty(); - * chat.append("user", "When will The Winds of Winter be released?"); - * - * const llm = client.llm.model(); - * const prediction = llm.respond(chat, { - * onMessage: message => chat.append(message), - * }); - * ``` - */ - onMessage?: (message: ChatMessage) => void; -} - -/** - * How to split the model across GPUs. - * - "evenly": Splits model evenly across GPUs - * - "favorMainGpu": Fill the main GPU first, then fill the rest of the GPUs evenly - * - * @public - * @deprecated We are currently working on an improved way to control split. You can use this for - * now. We will offer the alternative before this feature is removed. - */ -export declare type LLMSplitStrategy = "evenly" | "favorMainGpu"; - -/** - * Settings for structured prediction. Structured prediction is a way to force the model to generate - * predictions that conform to a specific structure. - * - * For example, you can use structured prediction to make the model only generate valid JSON, or - * event JSON that conforms to a specific schema (i.e. having strict types). - * - * Some examples: - * - * Only generate valid JSON: - * - * ```ts - * const prediction = model.complete("...", { - * maxTokens: 100, - * structured: { type: "json" }, - * }); - * ``` - * - * Only generate JSON that conforms to a specific schema (See https://json-schema.org/ for more - * information on authoring JSON schema): - * - * ```ts - * const schema = { - * type: "object", - * properties: { - * name: { type: "string" }, - * age: { type: "number" }, - * }, - * required: ["name", "age"], - * }; - * const prediction = model.complete("...", { - * maxTokens: 100, - * structured: { type: "json", jsonSchema: schema }, - * }); - * ``` - * - * By default, `{ type: "none" }` is used, which means no structured prediction is used. - * - * Caveats: - * - * - Although the model is forced to generate predictions that conform to the specified structure, - * the prediction may be interrupted (for example, if the user stops the prediction). When that - * happens, the partial result may not conform to the specified structure. Thus, always check the - * prediction result before using it, for example, by wrapping the `JSON.parse` inside a try-catch - * block. - * - In certain cases, the model may get stuck. For example, when forcing it to generate valid JSON, - * it may generate a opening brace `{` but never generate a closing brace `}`. In such cases, the - * prediction will go on forever until the context length is reached, which can take a long time. - * Therefore, it is recommended to always set a `maxTokens` limit. - * - * @public - */ -export declare type LLMStructuredPredictionSetting = { - type: LLMStructuredPredictionType; - jsonSchema?: any; - gbnfGrammar?: string; -}; - -/** - * @public - */ -export declare type LLMStructuredPredictionType = "none" | "json" | "gbnf"; - -/** - * TODO: Documentation - * - * @public - */ -export declare type LLMTool = { - type: "function"; - function: { - name: string; - description?: string; - parameters?: LLMToolParameters; - }; -}; - -/** - * TODO: Documentation - * - * @public - */ -export declare type LLMToolParameters = { - type: "object"; - properties: Record; - required?: string[]; - additionalProperties?: boolean; - $defs?: Record; -}; - -/** - * TODO: Documentation - * - * @public - */ -export declare type LLMToolUseSetting = { - type: "none"; -} | { - type: "toolArray"; - tools?: LLMTool[]; - force?: boolean; -}; - -/** @public */ -export declare class LMStudioClient { - readonly clientIdentifier: string; - readonly llm: LLMNamespace; - readonly embedding: EmbeddingNamespace; - readonly system: SystemNamespace; - readonly diagnostics: DiagnosticsNamespace; - readonly files: FilesNamespace; - readonly repository: RepositoryNamespace; - /** - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - readonly plugins: PluginsNamespace; - private isLocalhostWithGivenPortLMStudioServer; - /** - * Guess the base URL of the LM Studio server by visiting localhost on various default ports. - */ - private guessBaseUrl; - private createPort; - private resolvingBaseUrl; - private verboseErrorMessages; - constructor(opts?: LMStudioClientConstructorOpts); - [Symbol.asyncDispose](): Promise; -} - -/** @public */ -export declare interface LMStudioClientConstructorOpts { - /** - * Changes the logger that is used by LMStudioClient internally. The default logger is `console`. - * By default, LMStudioClient only logs warnings and errors that require user intervention. If the - * `verbose` option is enabled while calling supporting methods, those messages will also be - * directed to the specified logger. - */ - logger?: LoggerInterface; - /** - * The base URL of the LM Studio server. If not provided, LM Studio will attempt to connect to the - * localhost with various default ports. - * - * If you have set a custom port and/or are reverse-proxying, you should pass in the baseUrl. - * - * Since LM Studio uses WebSockets, the protocol must be "ws" or "wss". - * - * For example, if have changed the port to 8080, you should create the LMStudioClient like so: - * - * ```typescript - * const client = new LMStudioClient({ baseUrl: "ws://127.0.0.1:8080" }); - * ``` - */ - baseUrl?: string; - /** - * Whether to include stack traces in the errors caused by LM Studio. By default, this is set to - * `false`. If set to `true`, LM Studio SDK will include a stack trace in the error message. - */ - verboseErrorMessages?: boolean; - /** - * Changes the client identifier used to authenticate with LM Studio. By default, it uses a - * randomly generated string. - * - * If you wish to share resources across multiple LMStudioClient, you should set them to use the - * same `clientIdentifier` and `clientPasskey`. - */ - clientIdentifier?: string; - /** - * Changes the client passkey used to authenticate with LM Studio. By default, it uses a randomly - * generated string. - * - * If you wish to share resources across multiple LMStudioClient, you should set them to use the - * same `clientIdentifier` and `clientPasskey`. - */ - clientPasskey?: string; -} - -/** - * Represents a file entry in a local artifact. - * - * @public - */ -export declare interface LocalArtifactFileEntry { - relativePath: string; - sizeBytes: number; -} - -/** - * Represents a the list of files in a local artifact. - * - * @public - */ -export declare interface LocalArtifactFileList { - files: Array; - usedIgnoreFile: string | null; -} - -/** @public */ -export declare interface LoggerInterface { - info(...messages: Array): void; - error(...messages: Array): void; - warn(...messages: Array): void; - debug(...messages: Array): void; -} - -/** - * Options to use with {@link RepositoryNamespace#loginWithPreAuthenticatedKeys}. - * - * @public - */ -export declare interface LoginWithPreAuthenticatedKeysOpts { - keyId: string; - publicKey: string; - privateKey: string; -} - -/** - * Result of {@link RepositoryNamespace#loginWithPreAuthenticatedKeys}. - * - * @public - */ -export declare interface LoginWithPreAuthenticatedKeysResult { - userName: string; -} - -/** @public */ -export declare type LogLevel = "debug" | "info" | "warn" | "error"; - -/** - * Represents some underlying data that may or may not be mutable. - * - * @public - */ -export declare abstract class MaybeMutable { - protected readonly data: Data; - protected readonly mutable: boolean; - protected constructor(data: Data, mutable: boolean); - /** - * Gets the class name. This is used for printing errors. - */ - protected abstract getClassName(): string; - /** - * Creates a new instance of the class with the given data. - */ - protected abstract create(data: Data, mutable: boolean): this; - /** - * Clones the data. - */ - protected abstract cloneData(data: Data): Data; - asMutableCopy(): this; - asImmutableCopy(): this; - protected guardMutable(): void; -} - -/** - * @public - */ -export declare type ModelCompatibilityType = "gguf" | "safetensors" | "onnx" | "ggml" | "mlx_placeholder" | "torch_safetensors"; - -/** - * @public - */ -export declare type ModelDomainType = "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - -/** - * Represents a download source for a concrete model. - * - * @public - */ -export declare type ModelDownloadSource = HuggingFaceModelDownloadSource; - -/** - * Information about a model. - * - * @public - */ -export declare type ModelInfo = LLMInfo | EmbeddingModelInfo; - -/** - * Represents info of a model that is downloaded and sits on the disk. This is the base type shared - * by all models of different domains. - * - * @public - */ -export declare interface ModelInfoBase { - /** - * The key of the model. Use to load the model. - */ - modelKey: string; - /** - * The format of the model. - */ - format: ModelCompatibilityType; - /** - * Machine generated name of the model. - */ - displayName: string; - /** - * The relative path of the model. - */ - path: string; - /** - * The size of the model in bytes. - */ - sizeBytes: number; - /** - * A string that represents the number of params in the model. May not always be available. - */ - paramsString?: string; - /** - * The architecture of the model. May not always be available. - */ - architecture?: string; - /** - * The quantization of the model. May not always be available. - */ - quantization?: Quantization; -} - -/** - * Information about a model that is loaded. - * - * @public - */ -export declare type ModelInstanceInfo = LLMInstanceInfo | EmbeddingModelInstanceInfo; - -/** - * Represents info of a model that is already loaded. Contains all fields from - * {@link ModelInfoBase}. This is the base typed share by all model instances of different domains. - * - * @public - */ -export declare interface ModelInstanceInfoBase extends ModelInfoBase { - /** - * The identifier of the instance. - */ - identifier: string; - /** - * The internal immutable reference of the instance. - */ - instanceReference: string; -} - -/** - * Abstract namespace for namespaces that deal with models. - * - * @public - */ -export declare abstract class ModelNamespace, TSpecificModel> { - /** - * Load a model for inferencing. The first parameter is the model key. The second parameter is an - * optional object with additional options. - * - * To find out what models are available, you can use the `lms ls` command, or programmatically - * use the `client.system.listDownloadedModels` method. - * - * Here are some examples: - * - * Loading Llama 3.2: - * - * ```typescript - * const model = await client.llm.load("llama-3.2-3b-instruct"); - * ``` - * - * Once loaded, see {@link LLMDynamicHandle} or {@link EmbeddingDynamicHandle} for how to use the - * model for inferencing or other things you can do with the model. - * - * @param modelKey - The path of the model to load. - * @param opts - Options for loading the model. - * @returns A promise that resolves to the model that can be used for inferencing - */ - load(modelKey: string, opts?: BaseLoadModelOpts): Promise; - /** - * Unload a model. Once a model is unloaded, it can no longer be used. If you wish to use the - * model afterwards, you will need to load it with {@link LLMNamespace#loadModel} again. - * - * @param identifier - The identifier of the model to unload. - */ - unload(identifier: string): Promise; - /** - * List all the currently loaded models. - */ - listLoaded(): Promise>; - /** - * Get any loaded model of this domain. - */ - private getAny; - /** - * Get a dynamic model handle for any loaded model that satisfies the given query. - * - * For more information on the query, see {@link ModelQuery}. - * - * Note: The returned handle is not tied to any specific loaded model. Instead, it represents a - * "handle for a model that satisfies the given query". If the model that satisfies the query is - * unloaded, the handle will still be valid, but any method calls on it will fail. And later, if a - * new model is loaded that satisfies the query, the handle will be usable again. - * - * You can use {@link DynamicHandle#getModelInfo} to get information about the model that is - * currently associated with this handle. - * - * @example - * - * If you have loaded a model with the identifier "my-model", you can use it like this: - * - * ```ts - * const dh = client.llm.createDynamicHandle({ identifier: "my-model" }); - * const prediction = dh.complete("..."); - * ``` - * - * @example - * - * Use the Gemma 2B IT model (given it is already loaded elsewhere): - * - * ```ts - * const dh = client.llm.createDynamicHandle({ path: "lmstudio-community/Meta-Llama-3-8B-Instruct-GGUF" }); - * const prediction = dh.complete("..."); - * ``` - * - * @param query - The query to use to get the model. - */ - createDynamicHandle(query: ModelQuery): TDynamicHandle; - /** - * Get a dynamic model handle by its identifier. - * - * Note: The returned handle is not tied to any specific loaded model. Instead, it represents a - * "handle for a model with the given identifier". If the model with the given identifier is - * unloaded, the handle will still be valid, but any method calls on it will fail. And later, if a - * new model is loaded with the same identifier, the handle will be usable again. - * - * You can use {@link DynamicHandle#getModelInfo} to get information about the model that is - * currently associated with this handle. - * - * @example - * - * If you have loaded a model with the identifier "my-model", you can get use it like this: - * - * ```ts - * const dh = client.llm.createDynamicHandle("my-model"); - * const prediction = dh.complete("..."); - * ``` - * - * @param identifier - The identifier of the model to get. - */ - createDynamicHandle(identifier: string): TDynamicHandle; - /** - * Create a dynamic handle from the internal instance reference. - * - * @alpha - */ - createDynamicHandleFromInstanceReference(instanceReference: string): TDynamicHandle; - /** - * Get a model by its identifier. If no model is loaded with such identifier, load a model with - * the given key. This is the recommended way of getting a model to work with. - * - * For example, to use the DeepSeek r1 distill of Llama 8B: - * - * ```typescript - * const model = await client.llm.model("deepseek-r1-distill-llama-8b"); - * ``` - */ - model(modelKey: string, opts?: BaseLoadModelOpts): Promise; - /** - * Get any loaded model of this domain. If you want to use a specific model, pass in the model key - * as a parameter. - */ - model(): Promise; -} - -/** - * Represents a query for a loaded LLM. - * - * @public - */ -export declare interface ModelQuery { - /** - * The domain of the model. - */ - domain?: ModelDomainType; - /** - * If specified, the model must have exactly this identifier. - * - * Note: The identifier of a model is set when loading the model. It defaults to the filename of - * the model if not specified. However, this default behavior should not be relied upon. If you - * wish to query a model by its path, you should specify the path instead of the identifier: - * - * Instead of - * - * ```ts - * const model = client.llm.get({ identifier: "lmstudio-community/Meta-Llama-3-8B-Instruct-GGUF" }); - * // OR - * const model = client.llm.get("lmstudio-community/Meta-Llama-3-8B-Instruct-GGUF"); - * ``` - * - * Use - * - * ```ts - * const model = client.llm.get({ path: "lmstudio-community/Meta-Llama-3-8B-Instruct-GGUF" }); - * ``` - */ - identifier?: string; - /** - * If specified, the model must have this path. - * - * When specifying the model path, you can use the following format: - * - * `/[/model_file]` - * - * If `model_file` is not specified, any quantization of the model will match this query. - * - * Here are some examples: - * - * Query any loaded Llama 3 model: - * - * ```ts - * const model = client.llm.get({ - * path: "lmstudio-community/Meta-Llama-3-8B-Instruct-GGUF", - * }); - * ``` - * - * Query any loaded model with a specific quantization of the Llama 3 model: - * - * ```ts - * const model = client.llm.get({ - * path: "lmstudio-community/Meta-Llama-3-8B-Instruct-GGUF/Meta-Llama-3-8B-Instruct-Q4_K_M.gguf", - * }); - * ``` - */ - path?: string; - /** - * If true, the model must have vision capabilities. If false, the model must not have vision - * capabilities. - */ - vision?: boolean; -} - -/** @public */ -export declare interface ModelSearchOpts { - /** - * The search term to use when searching for models. If not provided, recommended models will - * be returned. - */ - searchTerm?: string; - /** - * How many results to return. If not provided, this value will be decided by LM Studio. - */ - limit?: number; - /** - * The model compatibility types to filter by. If not provided, only models that are supported - * by your current runtimes will be returned. - */ - compatibilityTypes?: Array; -} - -/** @public */ -export declare class ModelSearchResultDownloadOption { - private readonly logger; - private readonly data; - readonly quantization?: string; - readonly name: string; - readonly sizeBytes: number; - readonly fitEstimation?: ModelSearchResultDownloadOptionFitEstimation; - readonly indexedModelIdentifier: string; - isRecommended(): boolean; - /** - * Download the model. Returns the model key which can be used to load the model. - */ - download(opts?: DownloadOpts): Promise; -} - -/** - * @public - */ -export declare type ModelSearchResultDownloadOptionFitEstimation = "fullGPUOffload" | "partialGPUOffload" | "fitWithoutGPU" | "willNotFit"; - -/** @public */ -export declare class ModelSearchResultEntry { - private readonly logger; - private readonly data; - readonly name: string; - isExactMatch(): boolean; - isStaffPick(): boolean; - getDownloadOptions(): Promise>; -} - -declare type NotAvailable = typeof LazySignal.NOT_AVAILABLE; - -/** - * Represents an ongoing prediction from a generator. - * - * Note, this class is Promise-like, meaning you can use it as a promise. It resolves to a - * {@link GeneratorPredictionResult}, which contains the generated text in the `.content` property. Example - * usage: - * - * ```typescript - * const result = await generator.complete("When will The Winds of Winter be released?"); - * console.log(result.content); - * ``` - * - * Or you can use instances methods like `then` and `catch` to handle the result or error of the - * prediction. - * - * ```typescript - * generator.complete("When will The Winds of Winter be released?") - * .then(result =\> console.log(result.content)) - * .catch(error =\> console.error(error)); - * ``` - * - * Alternatively, you can also stream the result (process the results as more content is being - * generated). For example: - * - * ```typescript - * for await (const { content } of generator.complete("When will The Winds of Winter be released?")) { - * process.stdout.write(content); - * } - * ``` - * - * @public - * @experimental [EXP-GEN-PREDICT] Using generator plugins programmatically is still in development. - * This may change in the future without warning. - */ -export declare class OngoingGeneratorPrediction extends StreamablePromise { - private readonly pluginIdentifier; - private readonly onCancel; - protected collect(fragments: ReadonlyArray): Promise; - private constructor(); - /** - * Get the final prediction results. If you have been streaming the results, awaiting on this - * method will take no extra effort, as the results are already available in the internal buffer. - * - * Example: - * - * ```typescript - * const prediction = generator.complete("When will The Winds of Winter be released?"); - * for await (const { content } of prediction) { - * process.stdout.write(content); - * } - * const result = await prediction.result(); - * console.log(result.stats); - * ``` - * - * Technically, awaiting on this method is the same as awaiting on the instance itself: - * - * ```typescript - * await prediction.result(); - * - * // Is the same as: - * - * await prediction; - * ``` - */ - result(): Promise; - /** - * Cancels the prediction. - */ - cancel(): Promise; -} - -/** - * Represents an ongoing prediction. - * - * Note, this class is Promise-like, meaning you can use it as a promise. It resolves to a - * {@link PredictionResult}, which contains the generated text in the `.content` property. Example - * usage: - * - * ```typescript - * const result = await model.complete("When will The Winds of Winter be released?"); - * console.log(result.content); - * ``` - * - * Or you can use instances methods like `then` and `catch` to handle the result or error of the - * prediction. - * - * ```typescript - * model.complete("When will The Winds of Winter be released?") - * .then(result =\> console.log(result.content)) - * .catch(error =\> console.error(error)); - * ``` - * - * Alternatively, you can also stream the result (process the results as more content is being - * generated). For example: - * - * ```typescript - * for await (const { content } of model.complete("When will The Winds of Winter be released?")) { - * process.stdout.write(content); - * } - * ``` - * - * @public - */ -export declare class OngoingPrediction extends StreamablePromise> { - private readonly onCancel; - private readonly parser; - private stats; - private modelInfo; - private loadModelConfig; - private predictionConfig; - protected collect(fragments: ReadonlyArray): Promise; - private constructor(); - /** - * Get the final prediction results. If you have been streaming the results, awaiting on this - * method will take no extra effort, as the results are already available in the internal buffer. - * - * Example: - * - * ```typescript - * const prediction = model.complete("When will The Winds of Winter be released?"); - * for await (const { content } of prediction) { - * process.stdout.write(content); - * } - * const result = await prediction.result(); - * console.log(result.stats); - * ``` - * - * Technically, awaiting on this method is the same as awaiting on the instance itself: - * - * ```typescript - * await prediction.result(); - * - * // Is the same as: - * - * await prediction; - * ``` - */ - result(): Promise>; - /** - * Cancels the prediction. This will stop the prediction with stop reason `userStopped`. See - * {@link LLMPredictionStopReason} for other reasons that a prediction might stop. - */ - cancel(): Promise; -} - -/** - * OWLSignal - Optimistic Writable Lazy Signal - * - * - Signal: It is a signal, i.e. an observable that remembers its current value - * - Lazy: It is lazy, i.e. it does not subscribe to the upstream until a subscriber is attached - * - Writable: It is writable, i.e. it has a setter to update its value - * - Optimistic: It is optimistic, i.e. it updates its value optimistically and then waits for the - * upstream to confirm the update - * - Once the setter is called, the value is updated optimistically and all subscribers are - * notified synchronously - * - * Guarantees: - * - * - The OWLSignal is designed for single-writer multiple-reader scenarios, as the coordination of - * writes are tracked inside the OWLSignal. If there are multiple writers for the same data (i.e. - * multiple OWLSignal backed by the same upstream), there are no strong guarantees. For example, - * two updaters may read the same value, update it, and write it back to the upstream, causing one - * of the updates to be lost. The following guarantees are provided for single-writer scenarios: - * - The updates are applied in the order they are received, and each updater is guaranteed to see - * all updates that were applied before it. - * - If there are updaters [u_0, u_1, ..., u_n], for any read-only reader, there exists a time t - * where the reader will see the updates [u_0, u_1, ..., u_t] in the order they were applied. This - * also applies to the writer itself. - */ -declare class OWLSignal extends Subscribable implements SignalLike { - private readonly writeUpstream; - static readonly NOT_AVAILABLE: NotAvailable; - /** - * The inner signal used to subscribe to the upstream - */ - private readonly innerSignal; - /** - * The outer signal used to notify subscribers of the value (after applying optimistic updates) - */ - private readonly outerSignal; - /** - * The setter function to update the value of the signal. - */ - private readonly setOuterSignal; - private isWriteLoopRunning; - /** - * We have a passive subscription to the inner signal to update the optimistic value whenever the - * inner signal changes. - * - * However, if the content changes are caused by a write, we want to update the inner value, - * remove the optimistic update, and apply the remaining optimistic updates all at once. - * - * Therefore, when a write is ongoing, we set this flag to true to prevent the passive - * subscription from updating the optimistic value. We will handle the updates within the write - * loop. - */ - private isSubscriptionHandledByWriteLoop; - /** - * A queue of updates to apply optimistically. - */ - private queuedUpdates; - private writeErrorEvent; - private emitWriteErrorEvent; - private applyOptimisticUpdates; - private updateOptimisticValue; - private constructor(); - static create(initialValue: TData, subscribeUpstream: SubscribeUpstream, - /** - * Returns true if the update is sent to the upstream (thus should wait for the upstream to - * confirm. Returns false if the update is not sent and the update should be dropped. - */ - writeUpstream: (data: StripNotAvailable, patches: Array, tags: Array) => boolean, equalsPredicate?: (a: TData, b: TData) => boolean): readonly [OWLSignal, Setter>, (tags: Array, error: any) => void]; - static createWithoutInitialValue(subscribeUpstream: SubscribeUpstream, writeUpstream: (data: StripNotAvailable, patches: Array, tags: Array) => boolean, equalsPredicate?: (a: TData, b: TData) => boolean): readonly [OWLSignal, Setter>, (tags: Array, error: any) => void]; - private update; - /** - * Starts the write loop if it is not already running. - */ - private ensureWriteLoop; - /** - * The main write loop, it will keep running until there are no more updates to process. - */ - private writeLoop; - /** - * Returns whether the value is currently stale. - * - * A value is stale whenever the upstream subscription is not active. This can happen in three - * cases: - * - * 1. When no subscriber is attached to this signal, the signal will not subscribe to the - * upstream. In this case, the value is always stale. - * 2. When a subscriber is attached, but the upstream has not yet emitted a single value, the - * value is also stale. - * 3. When the upstream has emitted an error. In this case, the subscription to the upstream is - * terminated and the value is stale. - * - * If you wish to get the current value and ensure that it is not stale, use the method - * {@link OWLSignal#pull}. - */ - isStale(): boolean; - /** - * Gets the current value of the signal. If the value is not available, it will return - * {@link OWLSignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is created - * without an initial value and the upstream has not emitted a value yet.) - * - * In addition, the value returned by this method may be stale. Use {@link OWLSignal#isStale} to - * check if the value is stale. - * - * If you wish to get the current value and ensure that it is not stale, use the method - * {@link OWLSignal#pull}. - */ - get(): TData; - /** - * Gets the current value of the signal pessimistically. If the value is not available, it will - * return {@link OWLSignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is - * created without an initial value and the upstream has not emitted a value yet.) - */ - getPessimistic(): TData; - /** - * Pulls the current value of the signal. If the value is stale, it will subscribe and wait for - * the next value from the upstream and return it. - * - * You must also provide an `optimistic` flag. If `optimistic` is true, the pending optimistic - * updates will be applied to the value before returning it. - */ - pull({ optimistic }?: { - optimistic?: boolean; - }): Promise>; - private currentEnsureAvailablePromise; - ensureAvailable(): Promise>>; - subscribe(subscriber: Subscriber): () => void; - subscribeFull(subscriber: SignalFullSubscriber): () => void; -} - -/** - * @public - */ -export declare interface ParsedConfig { - [configSchematicsBrand]?: TVirtualConfigSchematics; - get(key: TKey): TVirtualConfigSchematics[TKey]["type"]; -} - -/** - * Options for parsing a document. - * - * @public - * @deprecated [DEP-DOC-PARSE] Document parsing API is still in active development. Stay tuned for - * updates. - */ -export declare type ParseDocumentOpts = DocumentParsingOpts & { - /** - * A callback function that is called when the parser is identified and loaded. - */ - onParserLoaded?: (parser: DocumentParsingLibraryIdentifier) => void; - /** - * A callback function that is called with the progress of the document parsing (0-1). - */ - onProgress?: (progress: number) => void; - /** - * An optional AbortSignal that can be used to abort the document parsing. - */ - signal?: AbortSignal; -}; - -/** - * The result of parsing a document. - * - * @public - * @deprecated [DEP-DOC-PARSE] Document parsing API is still in active development. Stay tuned for - * updates. - */ -export declare interface ParseDocumentResult { - /** - * String representation of the parsed document. - */ - content: string; - /** - * The parser used to parse the document. - */ - parser: DocumentParsingLibraryIdentifier; -} - -/** - * @public - */ -export declare interface PluginContext { - /** - * Sets the per-chat config schematics associated with this plugin context. Per-chat configs are - * stored per chat, useful for configurations that would affect context. Returns the same - * PluginContext for chaining. - */ - withConfigSchematics: (configSchematics: ConfigSchematics) => PluginContext; - /** - * Sets the global config schematics associated with this plugin context. Global configs are - * global across the entire application, useful for things like API keys or database - * configurations. Returns the same PluginContext for chaining. - */ - withGlobalConfigSchematics: (globalConfigSchematics: ConfigSchematics) => PluginContext; - /** - * Sets the prediction loop handler associated with this plugin context. Returns the same - * PluginContext for chaining. - */ - withPredictionLoopHandler(predictionLoopHandler: PredictionLoopHandler): PluginContext; - /** - * Sets the promptPreprocessor associated with this plugin context. Returns the same PluginContext for - * chaining. - */ - withPromptPreprocessor(preprocess: PromptPreprocessor): PluginContext; - /** - * Sets the tools provider associated with this plugin context. Returns the same PluginContext for - * chaining. - */ - withToolsProvider(toolsProvider: ToolsProvider): PluginContext; - /** - * Sets the generator associated with this plugin context. Returns the same PluginContext for - * chaining. - */ - withGenerator(generator: Generator_2): PluginContext; -} - -/** - * @public - */ -export declare interface PluginManifest extends ArtifactManifestBase { - type: "plugin"; - runner: PluginRunnerType; -} - -/** - * @public - */ -export declare type PluginRunnerType = "ecmascript" | "node" | "mcpBridge"; - -/** - * @deprecated This class is used internally by a plugin to register hooks. Do not use directly. - * @public - */ -declare class PluginSelfRegistrationHost { - private readonly port; - private readonly client; - private readonly rootLogger; - private readonly validator; - constructor(port: PluginsPort, client: LMStudioClient, rootLogger: LoggerInterface, validator: Validator); - /** - * Sets the promptPreprocessor to be used by the plugin represented by this client. - * - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - setPromptPreprocessor(promptPreprocessor: PromptPreprocessor): void; - /** - * Sets the prediction loop handler to be used by the plugin represented by this client. - * - * @deprecated [DEP-PLUGIN-PREDICTION-LOOP-HANDLER] Prediction loop handler support is still in - * development. Stay tuned for updates. - */ - setPredictionLoopHandler(predictionLoopHandler: PredictionLoopHandler): void; - /** - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - setConfigSchematics(configSchematics: ConfigSchematics): Promise; - /** - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - setGlobalConfigSchematics(globalConfigSchematics: ConfigSchematics): Promise; - /** - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - setToolsProvider(toolsProvider: ToolsProvider): void; - /** - * Sets the generator to be used by the plugin represented by this client. - * - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - setGenerator(generator: Generator_2): void; - /** - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - initCompleted(): Promise; -} - -/** - * @public - * - * The namespace for file-related operations. Currently no public-facing methods. - */ -export declare class PluginsNamespace { - private readonly client; - private readonly validator; - private readonly rootLogger; - /** - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - registerDevelopmentPlugin(opts: RegisterDevelopmentPluginOpts): Promise; - /** - * Requests LM Studio to reindex all the plugins. - * - * CAVEAT: Currently, we do not wait for the reindex to complete before returning. In the future, - * we will change this behavior and only return after the reindex is completed. - * - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - reindexPlugins(): Promise; - /** - * If this client is currently running as a plugin, get the self registration host which can be - * used to register hooks. - * - * @deprecated This method is used by plugins internally to register hooks. Do not use directly. - */ - getSelfRegistrationHost(): PluginSelfRegistrationHost; - /** - * Starts a tool use session use any config specifier. - */ - private internalStartToolUseSession; - /** - * Start a tool use session with a plugin. Note, this method must be used with "Explicit Resource - * Management". That is, you should use it like so: - * - * ```typescript - * using pluginTools = await client.plugins.pluginTools("owner/name", { ... }); - * // ^ Notice the `using` keyword here. - * ``` - * - * If you do not use `using`, you must call `pluginTools[Symbol.dispose]()` after you are done. - * Otherwise, there will be a memory leak and the plugins you requested tools from will be loaded - * indefinitely. - * - * @experimental [EXP-USE-USE-PLUGIN-TOOLS] Using tools from other applications is still in - * development. This may change in the future without warning. - */ - pluginTools(pluginIdentifier: string, opts?: PluginToolsOpts): Promise; - /** - * @experimental [EXP-GEN-PREDICT] Using generator plugins programmatically is still in - * development. This may change in the future without warning. - */ - createGeneratorHandle(pluginIdentifier: string): LLMGeneratorHandle; -} - -declare type PluginsPort = InferClientPort; - -/** - * Options to use with {@link PluginsNamespace#pluginTools}. - * - * @experimental [EXP-USE-USE-PLUGIN-TOOLS] Using tools from other applications is still in - * development. This may change in the future without warning. - * - * @public - */ -declare interface PluginToolsOpts { - /** - * @deprecated [DEP-PLUGIN-RAW-CONFIG] Plugin config access API is still in active development. - * Stay tuned for updates. - */ - pluginConfig?: KVConfig; - /** - * The working directory to use for the plugin tools. If not provided, the tools provider will not - * get a working directory. - */ - workingDirectory?: string; -} - -/** - * TODO: Documentation - * - * @public - */ -export declare type PredictionLoopHandler = (ctl: PredictionLoopHandlerController) => Promise; - -/** - * @public - */ -export declare type PredictionLoopHandlerController = Omit; - -/** - * Controller for a citation block in the prediction process. Currently cannot do anything. - * - * @public - */ -export declare class PredictionProcessCitationBlockController { - private readonly id; -} - -/** - * @public - * - * TODO: Documentation - */ -export declare class PredictionProcessContentBlockController { - private readonly id; - private readonly role; - appendText(text: string, { tokensCount, fromDraftModel, isStructural }?: ContentBlockAppendTextOpts): void; - appendToolRequest({ callId, toolCallRequestId, name, parameters, pluginIdentifier, }: ContentBlockAppendToolRequestOpts): void; - replaceToolRequest({ callId, toolCallRequestId, name, parameters, pluginIdentifier, }: ContentBlockReplaceToolRequestOpts): void; - appendToolResult({ callId, toolCallRequestId, content, }: ContentBlockAppendToolResultOpts): void; - replaceText(text: string): void; - setStyle(style: ContentBlockStyle): void; - setPrefix(prefix: string): void; - setSuffix(suffix: string): void; - attachGenInfo(genInfo: LLMGenInfo): void; - pipeFrom(prediction: OngoingPrediction): Promise; -} - -/** - * Controller for a debug info block in the prediction process. Currently cannot do anything. - * - * @public - */ -export declare class PredictionProcessDebugInfoBlockController { - private readonly id; -} - -/** - * Controller for a status block in the prediction process. - * - * @public - */ -export declare class PredictionProcessStatusController { - private readonly id; - private readonly indentation; - private lastSubStatus; - private lastState; - setText(text: string): void; - setState(state: StatusStepState): void; - remove(): void; - private getNestedLastSubStatusBlockId; - addSubStatus(initialState: StatusStepState): PredictionProcessStatusController; -} - -/** - * Controller for a tool status block in the prediction process. - * - * @public - */ -export declare class PredictionProcessToolStatusController { - private readonly id; - private status; - private customStatus; - private customWarnings; - private updateState; - setCustomStatusText(status: string): void; - addWarning(warning: string): void; - setStatus(status: ToolStatusStepStateStatus): void; - appendArgumentFragment(content: string): void; -} - -/** - * Represents the result of an LLM prediction. - * - * The most notably property is {@link PredictionResult#content}, which contains the generated text. - * Additionally, the {@link PredictionResult#stats} property contains statistics about the - * prediction. - * - * @public - */ -export declare class PredictionResult implements BasePredictionResult { - /** - * The newly generated text as predicted by the LLM. - */ - readonly content: string; - /** - * Part of the generated text that is "reasoning" content. For example, text inside - * tags. You can adjust what is considered reasoning content by changing the `reasoningParsing` - * field when performing the prediction. - */ - readonly reasoningContent: string; - /** - * Part of the generated that is not "reasoning" content. For example, text outside - * tags. You can adjust what is considered reasoning content by changing the `reasoningParsing` - * field when performing the prediction. - */ - readonly nonReasoningContent: string; - /** - * Statistics about the prediction. - */ - readonly stats: LLMPredictionStats; - /** - * Information about the model used for the prediction. - */ - readonly modelInfo: LLMInstanceInfo; - /** - * The 0-indexed round index of the prediction in multi-round scenario (for example, - * `.act`). Will always be 0 for single-round predictions such as `.respond` or `.complete`. - */ - readonly roundIndex: number; - /** - * The configuration used to load the model. Not stable, subject to change. - * - * @deprecated [DEP-RAW-CONFIG] Raw config access API is still in active development. Stay - * turned for updates. - */ - readonly loadConfig: KVConfig; - /** - * The configuration used for the prediction. Not stable, subject to change. - * - * @deprecated [DEP-RAW-CONFIG] Raw config access API is still in active development. Stay - * turned for updates. - */ - readonly predictionConfig: KVConfig; - constructor( - /** - * The newly generated text as predicted by the LLM. - */ - content: string, - /** - * Part of the generated text that is "reasoning" content. For example, text inside - * tags. You can adjust what is considered reasoning content by changing the `reasoningParsing` - * field when performing the prediction. - */ - reasoningContent: string, - /** - * Part of the generated that is not "reasoning" content. For example, text outside - * tags. You can adjust what is considered reasoning content by changing the `reasoningParsing` - * field when performing the prediction. - */ - nonReasoningContent: string, - /** - * Statistics about the prediction. - */ - stats: LLMPredictionStats, - /** - * Information about the model used for the prediction. - */ - modelInfo: LLMInstanceInfo, - /** - * The 0-indexed round index of the prediction in multi-round scenario (for example, - * `.act`). Will always be 0 for single-round predictions such as `.respond` or `.complete`. - */ - roundIndex: number, - /** - * The configuration used to load the model. Not stable, subject to change. - * - * @deprecated [DEP-RAW-CONFIG] Raw config access API is still in active development. Stay - * turned for updates. - */ - loadConfig: KVConfig, - /** - * The configuration used for the prediction. Not stable, subject to change. - * - * @deprecated [DEP-RAW-CONFIG] Raw config access API is still in active development. Stay - * turned for updates. - */ - predictionConfig: KVConfig); -} - -/** - * @public - */ -export declare class ProcessingController extends BaseController { - private readonly enabledPluginInfos; - private sendUpdate; - /** - * Gets a mutable copy of the current history. The returned history is a copy, so mutating it will - * not affect the actual history. It is mutable for convenience reasons. - * - * - If you are a promptPreprocessor, this will not include the user message you are currently - * preprocessing. - * - If you are a prediction loop handler, this will include the user message, and can be fed into - * the {@link LLMDynamicHandle#respond} method directly. - */ - pullHistory(): Promise; - createStatus(initialState: StatusStepState): PredictionProcessStatusController; - addCitations(retrievalResult: RetrievalResult): void; - addCitations(entries: Array): void; - createCitationBlock(citedText: string, source: CreateCitationBlockOpts): PredictionProcessCitationBlockController; - createContentBlock({ roleOverride, includeInContext, style, prefix, suffix, }?: CreateContentBlockOpts): PredictionProcessContentBlockController; - debug(...messages: Array): void; - /** - * Gets the token source associated with this prediction process (i.e. what the user has selected - * on the top navigation bar). - * - * The token source can either be a model or a generator plugin. In both cases, the returned - * object will contain a ".act" and a ".respond" method, which can be used to generate text. - * - * The token source is already pre-configured to use user's prediction config - you don't need to - * pass through any additional configuration. - */ - tokenSource(): Promise; - /** - * Sets the sender name for this message. The sender name shown above the message in the chat. - */ - setSenderName(name: string): Promise; - /** - * Throws an error if the prediction process has been aborted. Sprinkle this throughout your code - * to ensure that the prediction process is aborted as soon as possible. - */ - guardAbort(): void; - /** - * Whether this prediction process has had any status. - */ - hasStatus(): Promise; - /** - * Returns whether this conversation needs a name. - */ - needsNaming(): Promise; - /** - * Suggests a name for this conversation. - */ - suggestName(name: string): Promise; - requestConfirmToolCall({ callId, pluginIdentifier, name, parameters, }: RequestConfirmToolCallOpts): Promise; - createToolStatus(callId: number, initialStatus: ToolStatusStepStateStatus): PredictionProcessToolStatusController; - /** - * Starts a tool use session with tools available in the prediction process. Note, this method - * should be used with "Explicit Resource Management". That is, you should use it like so: - * - * ```typescript - * using toolUseSession = await ctl.startToolUseSession(); - * // ^ Notice the `using` keyword here. - * ``` - * - * If you do not `using`, you should call `toolUseSession[Symbol.dispose]()` after you are done. - * - * If you don't, lmstudio-js will close the session upon the end of the prediction step - * automatically. However, it is not recommended. - * - * @public - * @deprecated WIP - */ - startToolUseSession(): Promise; -} - -declare type ProcessingRequest = ProcessingRequestConfirmToolCall | ProcessingRequestTextInput; - -/** - * Represents a request to the user to confirm a tool call. - */ -declare type ProcessingRequestConfirmToolCall = { - type: "confirmToolCall"; - callId: number; - /** - * The plugin that provided the tool. - */ - pluginIdentifier?: string; - /** - * The name of the tool to call. - */ - name: string; - /** - * The parameters to pass to the tool. - */ - parameters: Record; -}; - -declare type ProcessingRequestResponse = ProcessingRequestResponseConfirmToolCall | ProcessingRequestResponseTextInput; - -declare type ProcessingRequestResponseConfirmToolCall = { - type: "confirmToolCall"; - result: { - type: "allow"; - toolArgsOverride?: Record; - } | { - type: "deny"; - denyReason?: string; - }; -}; - -/** - * @deprecated [DEP-PLUGIN-PREDICTION-LOOP-HANDLER] Prediction loop handler support is still in - * development. Stay tuned for updates. - */ -declare type ProcessingRequestResponseTextInput = { - type: "textInput"; - result: string; -}; - -/** - * @deprecated [DEP-PLUGIN-PREDICTION-LOOP-HANDLER] Prediction loop handler support is still in - * development. Stay tuned for updates. - */ -declare type ProcessingRequestTextInput = { - type: "textInput"; - prompt: string; -}; - -declare type ProcessingUpdate = ProcessingUpdateStatusCreate | ProcessingUpdateStatusUpdate | ProcessingUpdateStatusRemove | ProcessingUpdateCitationBlockCreate | ProcessingUpdateDebugInfoBlockCreate | ProcessingUpdateContentBlockCreate | ProcessingUpdateContentBlockAppendText | ProcessingUpdateContentBlockAppendToolRequest | ProcessingUpdateContentBlockReplaceToolRequest | ProcessingUpdateContentBlockAppendToolResult | ProcessingUpdateContentBlockReplaceText | ProcessingUpdateContentBlockSetPrefix | ProcessingUpdateContentBlockSetSuffix | ProcessingUpdateContentBlockAttachGenInfo | ProcessingUpdateContentBlockSetStyle | ProcessingUpdateToolStatusCreate | ProcessingUpdateToolStatusUpdate | ProcessingUpdateToolStatusArgumentFragment | ProcessingUpdateSetSenderName; - -declare type ProcessingUpdateCitationBlockCreate = { - type: "citationBlock.create"; - id: string; - citedText: string; - fileName: string; - fileIdentifier: string; - pageNumber?: number | [start: number, end: number]; - lineNumber?: number | [start: number, end: number]; -}; - -declare type ProcessingUpdateContentBlockAppendText = { - type: "contentBlock.appendText"; - id: string; - text: string; - tokensCount?: number; - fromDraftModel?: boolean; - isStructural?: boolean; -}; - -declare type ProcessingUpdateContentBlockAppendToolRequest = { - type: "contentBlock.appendToolRequest"; - /** - * ID of the content block. - */ - id: string; - /** - * Call ID created by LM Studio. Used to pair up requests and responses. - */ - callId: number; - /** - * Model specific optional tool call request ID (string). - */ - toolCallRequestId?: string; - /** - * Name of the tool called. - */ - name: string; - /** - * Arguments of the tool call. - */ - parameters: Record; - /** - * Optional identifier of the plugin that provided the tool. - */ - pluginIdentifier?: string; -}; - -declare type ProcessingUpdateContentBlockAppendToolResult = { - type: "contentBlock.appendToolResult"; - /** - * ID of the content block. - */ - id: string; - /** - * Call ID created by LM Studio. Used to pair up requests and responses. - */ - callId: number; - /** - * Model specific optional tool call request ID (string). - */ - toolCallRequestId?: string; - /** - * Result of the tool call. - */ - content: string; -}; - -declare type ProcessingUpdateContentBlockAttachGenInfo = { - type: "contentBlock.attachGenInfo"; - id: string; - genInfo: LLMGenInfo; -}; - -declare type ProcessingUpdateContentBlockCreate = { - type: "contentBlock.create"; - id: string; - includeInContext: boolean; - roleOverride?: "user" | "assistant" | "system" | "tool"; - style?: ContentBlockStyle; - prefix?: string; - suffix?: string; -}; - -declare type ProcessingUpdateContentBlockReplaceText = { - type: "contentBlock.replaceText"; - id: string; - text: string; -}; - -declare type ProcessingUpdateContentBlockReplaceToolRequest = { - type: "contentBlock.replaceToolRequest"; - id: string; - /** - * Call ID created by LM Studio. Used to pair up requests and responses. - */ - callId: number; - /** - * Model specific optional tool call request ID (string). - */ - toolCallRequestId?: string; - /** - * Name of the tool called. - */ - name: string; - /** - * Arguments of the tool call. - */ - parameters: Record; - /** - * Optional identifier of the plugin that provided the tool. - */ - pluginIdentifier?: string; -}; - -declare type ProcessingUpdateContentBlockSetPrefix = { - type: "contentBlock.setPrefix"; - id: string; - prefix: string; -}; - -declare type ProcessingUpdateContentBlockSetStyle = { - type: "contentBlock.setStyle"; - id: string; - style: ContentBlockStyle; -}; - -declare type ProcessingUpdateContentBlockSetSuffix = { - type: "contentBlock.setSuffix"; - id: string; - suffix: string; -}; - -declare type ProcessingUpdateDebugInfoBlockCreate = { - type: "debugInfoBlock.create"; - id: string; - debugInfo: string; -}; - -declare type ProcessingUpdateSetSenderName = { - type: "setSenderName"; - name: string; -}; - -declare type ProcessingUpdateStatusCreate = { - type: "status.create"; - id: string; - state: StatusStepState; - location?: BlockLocation; - indentation?: number; -}; - -declare type ProcessingUpdateStatusRemove = { - type: "status.remove"; - id: string; -}; - -declare type ProcessingUpdateStatusUpdate = { - type: "status.update"; - id: string; - state: StatusStepState; -}; - -declare type ProcessingUpdateToolStatusArgumentFragment = { - type: "toolStatus.argumentFragment"; - id: string; - content: string; -}; - -declare type ProcessingUpdateToolStatusCreate = { - type: "toolStatus.create"; - id: string; - callId: number; - state: ToolStatusStepState; -}; - -declare type ProcessingUpdateToolStatusUpdate = { - type: "toolStatus.update"; - id: string; - state: ToolStatusStepState; -}; - -/** - * TODO: Documentation - * - * @public - */ -export declare type PromptPreprocessor = (ctl: PromptPreprocessorController, userMessage: ChatMessage) => Promise; - -/** - * @public - */ -export declare type PromptPreprocessorController = Omit; - -/** - * Options to use with {@link RepositoryNamespace#pushArtifact}. - * - * @public - */ -export declare interface PushArtifactOpts { - path: string; - /** - * Change the description of the artifact. - */ - description?: string; - /** - * Request to make the artifact private. Only effective if the artifact did not exist before. Will - * not change the visibility of an existing artifact. - */ - makePrivate?: boolean; - /** - * If true, will write the revision number of the artifact after the push back to the artifact - * manifest.json. - */ - writeRevision?: boolean; - /** - * Internal overrides for updating artifact metadata. - */ - overrides?: any; - onMessage?: (message: string) => void; -} - -/** - * Represents the quantization of a model. - * - * @public - */ -declare type Quantization = { - /** - * Name of the quantization. - */ - name: string; - /** - * Roughly how many bits this quantization uses per value. This is not accurate and can vary from - * the actual BPW (bits per weight) of the quantization. Gives a rough idea of the - * quantization level. - */ - bits: number; -}; - -/** - * A tool that has a its parameters defined by a JSON schema. - * - * @public - * @experimental [EXP-RAW-FUNCTION] This is an experimental feature and may change in the future. - */ -export declare interface RawFunctionTool extends ToolBase { - type: "rawFunction"; - parametersJsonSchema: any; - /** - * Checks the parameters. If not valid, throws an error. - */ - checkParameters: (params: any) => void; - implementation: (params: Record, ctx: ToolCallContext) => any | Promise; -} - -/** - * A function that can be used to create a raw function `Tool` given a function definition and its - * implementation. - * - * @public - * @experimental Not stable, will likely change in the future. - */ -export declare function rawFunctionTool({ name, description, parametersJsonSchema, implementation, }: { - name: string; - description: string; - parametersJsonSchema: any; - implementation: (params: Record, ctx: ToolCallContext) => any | Promise; -}): Tool; - -/** - * Options to use with {@link PluginsNamespace#registerDevelopmentPlugin}. - * - * @public - */ -export declare interface RegisterDevelopmentPluginOpts { - manifest: PluginManifest; -} - -/** - * Result of {@link PluginsNamespace#registerDevelopmentPlugin}. - * - * @public - */ -export declare interface RegisterDevelopmentPluginResult { - clientIdentifier: string; - clientPasskey: string; - unregister: () => Promise; -} - -/** - * Represents a plugin that is currently available in LM Studio. - * - * @experimental [EXP-USE-PLUGINS-API] Using plugins API is still in development. This may change in - * the future without warning. - * - * @public - */ -declare interface RemotePluginInfo { - /** - * The identifier of the plugin. For non-dev plugins, this is the same as the artifact identifier - * when uploaded to LM Studio Hub. For example, `lmstudio/dice`. - * - * For dev plugins, this will be prefixed with `dev/` to indicate that it is a development - * version. For example, `dev/owner/plugin-name`. - * - * The exact format of this identifier may change in the future. You should not parse it. - */ - identifier: string; - /** - * Whether this plugin is in development mode, e.g. running externally using `lms dev`. - */ - isDev: boolean; - /** - * Whether this plugin is trusted. - */ - isTrusted: boolean; - /** - * Whether this plugin has a prompt preprocessor component. - */ - hasPromptPreprocessor: boolean; - /** - * Whether this plugin has a prediction loop handler component. - */ - hasPredictionLoopHandler: boolean; - /** - * Whether this plugin has a tools provider component. - */ - hasToolsProvider: boolean; - /** - * Whether this plugin has a generator component. - */ - hasGenerator: boolean; -} - -/** - * Represents a tool that is exposed by LMStudio plugins. - * - * @public - * @experimental [EXP-USE-USE-PLUGIN-TOOLS] Using tools from other plugins is still in development. - * This may change in the future without warning. - */ -declare interface RemoteTool extends ToolBase { - type: "remoteTool"; - /** - * Which plugin this tool belongs to. - */ - pluginIdentifier: string; - parametersJsonSchema: any; - checkParameters: (params: any) => void; - implementation: (params: Record, ctx: ToolCallContext) => any | Promise; -} - -/** - * Represents a session for using remote tools. - */ -declare interface RemoteToolUseSession extends Disposable { - tools: Array; - [Symbol.dispose](): void; -} - -/** @public */ -export declare class RepositoryNamespace { - private readonly repositoryPort; - private readonly validator; - searchModels(opts: ModelSearchOpts): Promise>; - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - installPluginDependencies(pluginFolder: string): Promise; - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - downloadArtifact(opts: DownloadArtifactOpts): Promise; - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - pushArtifact(opts: PushArtifactOpts): Promise; - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - getLocalArtifactFileList(path: string): Promise; - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - ensureAuthenticated(opts: EnsureAuthenticatedOpts): Promise; - loginWithPreAuthenticatedKeys(opts: LoginWithPreAuthenticatedKeysOpts): Promise; - private readonly downloadPlanFinalizationRegistry; - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - createArtifactDownloadPlanner(opts: CreateArtifactDownloadPlannerOpts): ArtifactDownloadPlanner; -} - -/** - * Options to use with {@link ProcessingController#requestConfirmToolCall}. - * - * @public - * @deprecated [DEP-PLUGIN-PREDICTION-LOOP-HANDLER] Prediction loop handler support is still in - * development. Stay tuned for updates. - */ -export declare interface RequestConfirmToolCallOpts { - callId: number; - pluginIdentifier?: string; - name: string; - parameters: Record; -} - -/** - * Return type of {@link ProcessingController#requestConfirmToolCall}. - * - * @public - * @deprecated [DEP-PLUGIN-PREDICTION-LOOP-HANDLER] Prediction loop handler support is still in - * development. Stay tuned for updates. - */ -export declare type RequestConfirmToolCallResult = { - type: "allow"; - toolArgsOverride?: Record; -} | { - type: "deny"; - denyReason?: string; -}; - -/** - * @public - */ -export declare interface RetrievalCallbacks { - /** - * Callback when the list of files to process is available. This list can be shorter than the list - * passed in because some files may already have cached embeddings. - * - * @param filePathsToProcess - The list of files that will be processed. - */ - onFileProcessList?: (filesToProcess: Array) => void; - /** - * Callback when starting to process a file. - * - * @param file - The file being processed. - * @param index - The index of the file in the list of files to process. - * @param filePathsToProcess - The list of files that will be processed. This will be the same as - * the list passed to `onFileProcessList`. - */ - onFileProcessingStart?: (file: FileHandle, index: number, filesToProcess: Array) => void; - /** - * Callback when processing a file has ended. - * - * @param file - The file that has been processed. - * @param index - The index of the file in the list of files to process. - * @param filePathsToProcess - The list of files that will be processed. This will be the same as - * the list passed to `onFileProcessList`. - */ - onFileProcessingEnd?: (file: FileHandle, index: number, filesToProcess: Array) => void; - /** - * Callback when starting a processing step for a file. LM Studio process files one at a time and - * processing each file involves multiple steps. This callback is called when starting a step. - * - * @param file - The file being processed. - * @param step - The step being started. - */ - onFileProcessingStepStart?: (file: FileHandle, step: RetrievalFileProcessingStep) => void; - /** - * Granular progress callback for a processing step. - * - * @param file - The file being processed. - * @param step - The step being started. - * @param progressInStep - The progress in the step for the step. This value is between 0 and 1. - */ - onFileProcessingStepProgress?: (file: FileHandle, step: RetrievalFileProcessingStep, progressInStep: number) => void; - /** - * Callback when a processing step has ended. - * - * @param file - The file being processed. - * @param step - The step that has ended. - */ - onFileProcessingStepEnd?: (file: FileHandle, step: RetrievalFileProcessingStep) => void; - /** - * Callback when we have embedded all the files and are starting to search in the vector database. - */ - onSearchingStart?: () => void; - /** - * Callback when we have finished searching in the vector database. The chunk usually will be - * returned immediately after this callback. - */ - onSearchingEnd?: () => void; - /** - * Controls the logging of retrieval progress. - * - * - If set to `true`, logs progress at the "info" level. - * - If set to `false`, no logs are emitted. This is the default. - * - If a specific logging level is desired, it can be provided as a string. Acceptable values are - * "debug", "info", "warn", and "error". - * - * Logs are directed to the logger specified during the `LMStudioClient` construction. - * - * Progress logs will be disabled if any of the callbacks are provided. - * - * Default value is "info", which logs progress at the "info" level. - */ - verbose?: boolean | LogLevel; -} - -/** - * @public - */ -export declare interface RetrievalChunk { - content: string; - score: number; - citation: CitationSource; -} - -/** - * @public - */ -export declare type RetrievalChunkingMethod = { - type: "recursive-v1"; - chunkSize: number; - chunkOverlap: number; -}; - -/** - * @public - */ -export declare type RetrievalFileProcessingStep = "loading" | "chunking" | "embedding"; - -/** - * @public - * N.B.: onProgress returns progress as a float taking values from 0 to 1, 1 being completed - */ -export declare type RetrievalOpts = RetrievalCallbacks & { - /** - * The chunking method to use. By default uses recursive-v1 with chunk size 512 and chunk overlap - * 100. - */ - chunkingMethod?: RetrievalChunkingMethod; - /** - * The number of results to return. - */ - limit?: number; - /** - * The embedding model to use. - */ - embeddingModel?: EmbeddingDynamicHandle; - /** - * The path to the database. - */ - databasePath?: string; - /** - * The signal to abort the retrieval - */ - signal?: AbortSignal; -}; - -/** @public */ -export declare interface RetrievalResult { - entries: Array; -} - -/** @public */ -export declare interface RetrievalResultEntry { - content: string; - score: number; - source: FileHandle; -} - -declare interface RpcEndpoint { - name: string; - parameter: z.ZodType; - returns: z.ZodType; - serialization: SerializationType; - handler: RpcEndpointHandler | null; -} - -declare type RpcEndpointHandler = (ctx: TContext, parameter: TParameter) => TReturns | Promise; - -declare interface RpcEndpointSpecBase { - parameter: any; - returns: any; -} - -declare type RpcEndpointsSpecBase = { - [endpointName: string]: RpcEndpointSpecBase; -}; - -/** - * Type of serialization: - * - * Raw: JSON.stringify and JSON.parse - * Superjson: SuperJSON.serialize and SuperJSON.deserialize - */ -declare type SerializationType = "raw" | "superjson"; - -/** - * @public - */ -declare interface SerializedKVConfigSchematics { - fields: Array; - extensionPrefixes?: Array; -} - -/** - * @public - */ -declare interface SerializedKVConfigSchematicsField { - shortKey: string; - fullKey: string; - typeKey: string; - typeParams: any; - defaultValue: any; -} - -declare type SerializedLMSExtendedError = z.infer; - -declare const serializedLMSExtendedErrorSchema: z.ZodObject<{ - title: z.ZodDefault>; - cause: z.ZodOptional>; - suggestion: z.ZodOptional>; - errorData: z.ZodOptional | undefined, z.ZodTypeDef, Record | undefined>>; - displayData: z.ZodOptional>; - stack: z.ZodOptional>; - rootTitle: z.ZodOptional>; -}, "strip", z.ZodTypeAny, { - title: string; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; -}, { - title?: string | undefined; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; -}>; - -/** - * Opaque type that represents a serialized value. The representation here is not accurate and is - * only used to prevent accidental reading/writing of the opaque value. - */ -declare type SerializedOpaque = { - [serializedOpaqueSymbol]: T; -}; - -declare const serializedOpaqueSymbol: unique symbol; - -declare type ServerToClientMessage = z.infer; - -declare const serverToClientMessageSchema: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{ - type: z.ZodLiteral<"communicationWarning">; - warning: z.ZodString; -}, "strip", z.ZodTypeAny, { - type: "communicationWarning"; - warning: string; -}, { - type: "communicationWarning"; - warning: string; -}>, z.ZodObject<{ - type: z.ZodLiteral<"keepAliveAck">; -}, "strip", z.ZodTypeAny, { - type: "keepAliveAck"; -}, { - type: "keepAliveAck"; -}>, z.ZodObject<{ - type: z.ZodLiteral<"channelSend">; - channelId: z.ZodNumber; - message: z.ZodType, z.ZodTypeDef, SerializedOpaque>; - ackId: z.ZodOptional; -}, "strip", z.ZodTypeAny, { - message: SerializedOpaque; - type: "channelSend"; - channelId: number; - ackId?: number | undefined; -}, { - message: SerializedOpaque; - type: "channelSend"; - channelId: number; - ackId?: number | undefined; -}>, z.ZodObject<{ - type: z.ZodLiteral<"channelAck">; - channelId: z.ZodNumber; - ackId: z.ZodNumber; -}, "strip", z.ZodTypeAny, { - type: "channelAck"; - channelId: number; - ackId: number; -}, { - type: "channelAck"; - channelId: number; - ackId: number; -}>, z.ZodObject<{ - type: z.ZodLiteral<"channelClose">; - channelId: z.ZodNumber; -}, "strip", z.ZodTypeAny, { - type: "channelClose"; - channelId: number; -}, { - type: "channelClose"; - channelId: number; -}>, z.ZodObject<{ - type: z.ZodLiteral<"channelError">; - channelId: z.ZodNumber; - error: z.ZodObject<{ - title: z.ZodDefault>; - cause: z.ZodOptional>; - suggestion: z.ZodOptional>; - errorData: z.ZodOptional | undefined, z.ZodTypeDef, Record | undefined>>; - displayData: z.ZodOptional>; - stack: z.ZodOptional>; - rootTitle: z.ZodOptional>; - }, "strip", z.ZodTypeAny, { - title: string; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }, { - title?: string | undefined; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }>; -}, "strip", z.ZodTypeAny, { - type: "channelError"; - channelId: number; - error: { - title: string; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }; -}, { - type: "channelError"; - channelId: number; - error: { - title?: string | undefined; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }; -}>, z.ZodObject<{ - type: z.ZodLiteral<"rpcResult">; - callId: z.ZodNumber; - result: z.ZodType, z.ZodTypeDef, SerializedOpaque>; -}, "strip", z.ZodTypeAny, { - type: "rpcResult"; - callId: number; - result: SerializedOpaque; -}, { - type: "rpcResult"; - callId: number; - result: SerializedOpaque; -}>, z.ZodObject<{ - type: z.ZodLiteral<"rpcError">; - callId: z.ZodNumber; - error: z.ZodObject<{ - title: z.ZodDefault>; - cause: z.ZodOptional>; - suggestion: z.ZodOptional>; - errorData: z.ZodOptional | undefined, z.ZodTypeDef, Record | undefined>>; - displayData: z.ZodOptional>; - stack: z.ZodOptional>; - rootTitle: z.ZodOptional>; - }, "strip", z.ZodTypeAny, { - title: string; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }, { - title?: string | undefined; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }>; -}, "strip", z.ZodTypeAny, { - type: "rpcError"; - callId: number; - error: { - title: string; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }; -}, { - type: "rpcError"; - callId: number; - error: { - title?: string | undefined; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }; -}>, z.ZodObject<{ - type: z.ZodLiteral<"signalUpdate">; - subscribeId: z.ZodNumber; - patches: z.ZodArray, z.ZodTypeDef, SerializedOpaque>, "many">; - tags: z.ZodArray; -}, "strip", z.ZodTypeAny, { - type: "signalUpdate"; - subscribeId: number; - patches: SerializedOpaque[]; - tags: string[]; -}, { - type: "signalUpdate"; - subscribeId: number; - patches: SerializedOpaque[]; - tags: string[]; -}>, z.ZodObject<{ - type: z.ZodLiteral<"signalError">; - subscribeId: z.ZodNumber; - error: z.ZodObject<{ - title: z.ZodDefault>; - cause: z.ZodOptional>; - suggestion: z.ZodOptional>; - errorData: z.ZodOptional | undefined, z.ZodTypeDef, Record | undefined>>; - displayData: z.ZodOptional>; - stack: z.ZodOptional>; - rootTitle: z.ZodOptional>; - }, "strip", z.ZodTypeAny, { - title: string; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }, { - title?: string | undefined; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }>; -}, "strip", z.ZodTypeAny, { - type: "signalError"; - subscribeId: number; - error: { - title: string; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }; -}, { - type: "signalError"; - subscribeId: number; - error: { - title?: string | undefined; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }; -}>, z.ZodObject<{ - type: z.ZodLiteral<"writableSignalUpdate">; - subscribeId: z.ZodNumber; - patches: z.ZodArray, z.ZodTypeDef, SerializedOpaque>, "many">; - tags: z.ZodArray; -}, "strip", z.ZodTypeAny, { - type: "writableSignalUpdate"; - subscribeId: number; - patches: SerializedOpaque[]; - tags: string[]; -}, { - type: "writableSignalUpdate"; - subscribeId: number; - patches: SerializedOpaque[]; - tags: string[]; -}>, z.ZodObject<{ - type: z.ZodLiteral<"writableSignalError">; - subscribeId: z.ZodNumber; - error: z.ZodObject<{ - title: z.ZodDefault>; - cause: z.ZodOptional>; - suggestion: z.ZodOptional>; - errorData: z.ZodOptional | undefined, z.ZodTypeDef, Record | undefined>>; - displayData: z.ZodOptional>; - stack: z.ZodOptional>; - rootTitle: z.ZodOptional>; - }, "strip", z.ZodTypeAny, { - title: string; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }, { - title?: string | undefined; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }>; -}, "strip", z.ZodTypeAny, { - type: "writableSignalError"; - subscribeId: number; - error: { - title: string; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }; -}, { - type: "writableSignalError"; - subscribeId: number; - error: { - title?: string | undefined; - cause?: string | undefined; - suggestion?: string | undefined; - errorData?: Record | undefined; - displayData?: { - code: "generic.specificModelUnloaded"; - } | { - code: "generic.noModelMatchingQuery"; - query: { - path?: string | undefined; - identifier?: string | undefined; - domain?: "llm" | "embedding" | "imageGen" | "transcription" | "tts" | undefined; - vision?: boolean | undefined; - }; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.pathNotFound"; - path: string; - availablePathsSample: string[]; - totalModels: number; - } | { - code: "generic.identifierNotFound"; - identifier: string; - loadedModelsSample: string[]; - totalLoadedModels: number; - } | { - code: "generic.domainMismatch"; - path: string; - actualDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - expectedDomain: "llm" | "embedding" | "imageGen" | "transcription" | "tts"; - } | { - code: "generic.engineDoesNotSupportFeature"; - feature: string; - engineName: string; - engineType: string; - installedVersion: string; - supportedVersion: string | null; - } | { - code: "generic.presetNotFound"; - specifiedFuzzyPresetIdentifier: string; - availablePresetsSample: { - name: string; - identifier: string; - }[]; - totalAvailablePresets: number; - } | undefined; - stack?: string | undefined; - rootTitle?: string | undefined; - }; -}>]>; - -/** - * A setter is a function that can be used to update a value. Different flavors of setters are - * available in properties: - * - `withProducer`: to update the value using Immer - * - `withUpdater`: to update the value using a function - * - `withPatches`: to update the value using a set of patches - */ -declare interface Setter { - /** - * Replaces the value entirely with the given value. If you want to update a substructure of the - * value, use `withProducer`. - */ - (value: StripNotAvailable, tags?: Array): void; - /** - * Updates the value using Immer. (Recommended) - */ - withProducer(producer: (draft: TData) => void, tags?: Array): void; - /** - * Updates the value using a function. Prefer using `withProducer` instead. - */ - withUpdater(updater: (oldValue: TData) => StripNotAvailable, tags?: Array): void; - /** - * Updates the value using a function that returns both the new value and the patches to apply. - */ - withPatchUpdater(updater: (oldValue: TData) => readonly [newValue: StripNotAvailable, patches: Array], tags?: Array): void; - /** - * Updates the value using a set of patches. - */ - withPatches(patches: Array, tags?: Array): void; - /** - * Similar to `withPatches`, but also accepts the new value. This is useful when the new value is - * already known. - */ - withValueAndPatches(newValue: StripNotAvailable, patches: Array, tags?: Array): void; -} - -/** - * A signal is a wrapper for a value. It can be used to notify subscribers when the value changes. - * For it to work properly, the value should be immutable. - * - * To create a signal, please use the `Signal.create` static method. It will return a signal - * along with a function to update its value. - */ -declare class Signal extends Subscribable implements SignalLike { - private value; - private equalsPredicate; - /** - * Creates a signal. - * - * @param value - The initial value of the signal. - * @param equalsPredicate - A function to compare two values. The subscribers will only be called - * if the value changes according to the `equalsPredicate`. By default, it uses the `===` - * operator. - * @returns This method returns a tuple with two elements: - * - The signal - * - A function to update the value - **/ - static create(value: TValue, equalsPredicate?: (a: TValue, b: TValue) => boolean): readonly [Signal, Setter]; - static createReadonly(value: TValue): Signal; - protected constructor(value: TValue, equalsPredicate: (a: TValue, b: TValue) => boolean); - private subscribers; - /** - * Returns the current value of the signal. - */ - get(): TValue; - pull(): StripNotAvailable; - private queuedUpdaters; - private isEmitting; - private notifyFull; - private notifyAll; - private notifyAndUpdateIfChanged; - private isReplaceRoot; - private update; - /** - * Subscribes to the signal. The callback will be called whenever the value changes. All callbacks - * are called synchronously upon updating. It will NOT be immediately called with the current - * value. (Use `get()` to get the current value.) Returns a function to unsubscribe. - * - * Edge cases involving manipulating the signal in the callback: - * - * - If the callback adds new subscribers, they will also be called within the same update. - * - If the callback causes removal of subscribers that have not been called yet, they will no - * longer be called. - * - If the callback causes an update of the value, the update will be queued. If multiple updates - * are queued, only the last one will be executed. - * - * Edge cases involving adding the same callback multiple times. - * - * - Callbacks are tracked with a set. Adding the same subscriber will not cause it to be called - * multiple times. - */ - subscribe(callback: Subscriber): () => void; - /** - * Subscribes to the signal with the callback and trigger the callback immediately with the - * current value. - */ - subscribeAndNow(callback: Subscriber): () => void; - subscribeFull(callback: SignalFullSubscriber): () => void; - /** - * Wait until the signal satisfies a predicate. If the predicate is already satisfied, it will - * return immediately. Otherwise, it will wait until the signal satisfies the predicate. - */ - until(predicate: (data: TValue) => boolean): Promise; -} - -declare interface SignalEndpoint { - name: string; - creationParameter: z.ZodType; - signalData: z.ZodType; - serialization: SerializationType; - handler: SignalEndpointHandler | null; -} - -declare type SignalEndpointHandler = (ctx: TContext, creationParameter: TCreationParameter) => SignalLike | Promise> | SignalLike | Promise>; - -declare interface SignalEndpointSpecBase { - creationParameter: any; - signalData: any; -} - -declare type SignalEndpointsSpecBase = { - [endpointName: string]: SignalEndpointSpecBase; -}; - -declare type SignalFullSubscriber = (value: TValue, patches: Array, tags: Array) => void; - -declare interface SignalLike extends Subscribable { - get(): TValue; - subscribe(subscriber: Subscriber): () => void; - subscribeFull(subscriber: SignalFullSubscriber): () => void; - pull(): Promise> | StripNotAvailable; -} - -/** - * @public - */ -export declare interface SpecificModel extends DynamicHandle { - readonly identifier: string; - readonly path: string; - unload(): Promise; -} - -declare type StartHttpServerOpts = z.infer; - -declare const startHttpServerOptsSchema: z.ZodObject<{ - port: z.ZodNumber; - cors: z.ZodBoolean; -}, "strip", z.ZodTypeAny, { - port: number; - cors: boolean; -}, { - port: number; - cors: boolean; -}>; - -/** - * @public - */ -export declare interface StatusStepState { - status: StatusStepStatus; - text: string; -} - -/** - * @public - */ -export declare type StatusStepStatus = "waiting" | "loading" | "done" | "error" | "canceled"; - -/** - * A StreamablePromise is a promise-like that is also async iterable. This means you can use it as a - * promise (awaiting it, using `.then`, `.catch`, etc.), and you can also use it as an async - * iterable (using `for await`). - * - * Notably, as much as it implements the async iterable interface, it is not a traditional iterable, - * as it internally maintains a buffer and new values are pushed into the buffer by the producer, as - * oppose to being pulled by the consumer. - * - * The async iterable interface is used instead of the Node.js object stream because streams are too - * clunky to use, and the `for await` syntax is much more ergonomic for most people. - * - * If any iterator is created for this instance, an empty rejection handler will be attached to the - * promise to prevent unhandled rejection warnings. - * - * This class is provided as an abstract class and is meant to be extended. Crucially, the `collect` - * method must be implemented, which will be called to convert an array of values into the final - * resolved value of the promise. - * - * In addition, the constructor of the subclass should be marked as private, and a static method - * that exposes the constructor, the `finished` method, and the `push` method should be provided. - * - * @typeParam TFragment - The type of the individual fragments that are pushed into the buffer. - * @typeParam TFinal - The type of the final resolved value of the promise. - * @public - */ -export declare abstract class StreamablePromise implements Promise, AsyncIterable { - protected abstract collect(fragments: ReadonlyArray): Promise; - private promiseFinal; - private resolveFinal; - private rejectFinal; - protected status: "pending" | "resolved" | "rejected"; - private buffer; - private nextFragmentPromiseBundle; - /** - * If there has ever been any iterators created for this instance. Once any iterator is created, - * a reject handler will be attached to the promise to prevent unhandled rejection warnings, as - * the errors will be handled by the iterator. - * - * The purpose of this variable is to prevent registering the reject handler more than once. - */ - private hasIterator; - /** - * Called by the producer when it has finished producing values. If an error is provided, the - * promise will be rejected with that error. If no error is provided, the promise will be resolved - * with the final value. - * - * This method should be exposed in the static constructor of the subclass. - * - * @param error - The error to reject the promise with, if any. - */ - protected finished(error?: any): void; - /** - * Called by the producer to push a new fragment into the buffer. This method should be exposed in - * the static constructor of the subclass. - * - * This method should be exposed in the static constructor of the subclass. - * - * @param fragment - The fragment to push into the buffer. - */ - protected push(fragment: TFragment): void; - protected constructor(); - then(onfulfilled?: ((value: TFinal) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined): Promise; - catch(onrejected?: ((reason: any) => TResult | PromiseLike) | null | undefined): Promise; - finally(onfinally?: (() => void) | null | undefined): Promise; - [Symbol.toStringTag]: string; - /** - * If nextFragmentPromiseBundle exists, it is returned. Otherwise, a new one is created and - * returned. - */ - private obtainNextFragmentPromiseBundle; - [Symbol.asyncIterator](): AsyncIterator; -} - -declare type StripNotAvailable = T extends NotAvailable ? never : T; - -/** - * Result of a typed structured prediction. In addition to a regular {@link PredictionResult}, there - * is one additional field: {@link StructuredPredictionResult#parsed}. - * - * To enable typed structured prediction, you should pass in a zod schema as the structured option - * when constructing the prediction config. - * - * @public - */ -export declare class StructuredPredictionResult extends PredictionResult { - /** - * Parsed result of the structured output. - */ - readonly parsed: TStructuredOutputType; - constructor(content: string, reasoningContent: string, nonReasoningContent: string, stats: LLMPredictionStats, modelInfo: LLMInstanceInfo, roundIndex: number, loadConfig: KVConfig, predictionConfig: KVConfig, - /** - * Parsed result of the structured output. - */ - parsed: TStructuredOutputType); -} - -/** - * Base class for objects that can be subscribed to. Provides common utility methods. - */ -declare abstract class Subscribable { - abstract subscribe(listener: (data: TData) => void): () => void; - subscribeWithCleaner(cleaner: Cleaner, listener: (data: TData) => void): void; - subscribeOnce(listener: (data: TData) => void): () => void; - subscribeOnceWithCleaner(cleaner: Cleaner, listener: (data: TData) => void): void; - derive(deriver: (data: StripNotAvailable) => StripNotAvailable, outputEqualsPredicate?: (a: TOutput, b: TOutput) => boolean): typeof Subscribable extends { - get(): TData; - } ? TOutput extends NotAvailable ? LazySignal : LazySignal : LazySignal; -} - -declare type Subscriber = (value: TValue) => void; - -declare type SubscribeUpstream = ( -/** - * The setter function that should be called whenever the upstream emits a new value. The setter - * function should be called with the new value. - */ -setDownstream: Setter, -/** - * The error listener should be called when the upstream subscription encounters an error. Once - * and error is encountered, the subscription to the upstream is assumed to be terminated, meaning - * the unsubscriber will NOT be called. - */ -errorListener: (error: any) => void) => () => void; - -/** @public */ -export declare class SystemNamespace { - private readonly systemPort; - private readonly validator; - /** - * List all downloaded models. - * @public - */ - listDownloadedModels(): Promise>; - listDownloadedModels(domain: "llm"): Promise>; - listDownloadedModels(domain: "embedding"): Promise>; - whenDisconnected(): Promise; - notify(notification: BackendNotification): Promise; - getLMStudioVersion(): Promise<{ - version: string; - build: number; - }>; - /** - * Sets an experiment flags for LM Studio. This is an unstable API and may change without notice. - * - * @experimental - */ - unstable_setExperimentFlag(flag: string, value: boolean): Promise; - /** - * Gets all experiment flags for LM Studio. This is an unstable API and may change without notice. - * - * @experimental - */ - unstable_getExperimentFlags(): Promise>; - /** - * Starts the API server on the specified port. - * - * @experimental - */ - startHttpServer(opts: StartHttpServerOpts): Promise; - /** - * Stops the API server if it is running. - * - * @experimental - */ - stopHttpServer(): Promise; -} - -/** - * A string literal tag function that does the following: - * - * - Removes leading new lines - * - Removes trailing new lines and whitespace - * - Removes common indentation from the start of each line (Empty lines are ignored) - * - Single newlines are replaced with a space + extra whitespace is removed - * - * Note: Only spaces are considered. - * - * @remarks - * - * The exact implementation of this function is not guaranteed to be the same, as we may add - * additional edge case handling in the future. However, the general behavior should remain the - * same. - * - * @public - */ -export declare function text(strings: TemplateStringsArray, ...values: ReadonlyArray): string; - -/** - * The allowed types for the values in the `text` tag function. - * - * @public - */ -export declare type TextAllowedTypes = string | number | object; - -declare type TokenSourceIdentifier = { - type: "model"; - identifier: string; -} | { - type: "generator"; - pluginIdentifier: string; -}; - -/** - * Represents a tool that can be given to an LLM with `.act`. - * - * @public - */ -export declare type Tool = FunctionTool | RawFunctionTool | UnimplementedRawFunctionTool | RemoteTool; - -/** - * A function that can be used to create a function `Tool` given a function definition and its - * implementation. - * - * @public - */ -export declare function tool>({ name, description, parameters, implementation, }: { - name: string; - description: string; - /** - * The parameters of the function. Must be an with values being zod schemas. - * - * IMPORTANT - * - * The type here only requires an object with a `parse` function. This is not enough! We need an - * actual zod schema because we will need to extract the JSON schema from it. - * - * The reason we only have a `parse` function here (as oppose to actually requiring ZodType is due - * to this zod bug causing TypeScript breakage, when multiple versions of zod exist. - * - * - https://github.com/colinhacks/zod/issues/577 - * - https://github.com/colinhacks/zod/issues/2697 - * - https://github.com/colinhacks/zod/issues/3435 - */ - parameters: TParameters; - implementation: (params: { - [K in keyof TParameters]: TParameters[K] extends { - parse: (input: any) => infer RReturnType; - } ? RReturnType : never; - }, ctx: ToolCallContext) => any | Promise; -}): Tool; - -/** - * Shared properties of all tools. - * - * @public - */ -export declare interface ToolBase { - name: string; - description: string; -} - -/** - * Use this context object to report status and/or getting information about whether the tool call - * should be aborted. - * - * This is passed to the tool implementation as the second argument. - * - * @public - */ -export declare interface ToolCallContext { - /** - * Report the current status of the tool call. The LLM will not be able to see this. - */ - status: (text: string) => void; - /** - * Report a recoverable error, i.e. something unexpected happened, but you have already handled - * it. The LLM will not be able to see this. - * - * Error handling best practices: - * - * - If the error is recoverable (really just a warning), use `warn` to report it. - * - If the error is not recoverable, but you think the LLM can try again, you should return the - * error as a string. For example, `return "Error: file already exists."`. - * - If the error is disastrous and something truly unexpected happened, you should just throw - * the error. This is useful for cases like failing to connect to the database. - */ - warn: (text: string) => void; - /** - * A signal that should be listened to in order to know when to abort the tool call. Not necessary - * for simple tools calls, however recommended for long running tools such as those that uses - * makes multiple network requests. - */ - signal: AbortSignal; - /** - * The internal ID of the tool call. This allows you to match up tool calls. Is guaranteed to be - * unique within one `.act` call. - * - * @remarks This field is not the same as the `toolCallId` inside the tool call request, as the - * existence and format of that ID is model dependent. - * - * @experimental [EXP-GRANULAR-ACT] More granular .act status reporting is experimental and may - * change in the future - */ - callId: number; -} - -/** - * @public - */ -export declare type ToolCallRequest = FunctionToolCallRequest; - -/** - * Represents an error that is caused by invalid tool call request. - * - * @public - * @experimental [EXP-GRANULAR-ACT] More granular .act status reporting is experimental and may - * change in the future - */ -export declare class ToolCallRequestError extends Error { - /** - * The raw output that was generated by the model before the tool call. The exact nature of this - * fields depends on the error. It sometimes include the entire tool calls section, or sometimes - * just the single tool call that failed. - * - * This field is not always available, and may be `undefined`. - * - * @experimental [EXP-GRANULAR-ACT] More granular .act status reporting is experimental and may - * change in the future - * @experimental [EXP-NON-ACT-TOOL-CALLBACKS] Tool call callbacks in .respond/.complete is in an - * experimental feature. This may change in the future without warning. - */ - readonly rawContent: string | undefined; - constructor(message: string, - /** - * The raw output that was generated by the model before the tool call. The exact nature of this - * fields depends on the error. It sometimes include the entire tool calls section, or sometimes - * just the single tool call that failed. - * - * This field is not always available, and may be `undefined`. - * - * @experimental [EXP-GRANULAR-ACT] More granular .act status reporting is experimental and may - * change in the future - * @experimental [EXP-NON-ACT-TOOL-CALLBACKS] Tool call callbacks in .respond/.complete is in an - * experimental feature. This may change in the future without warning. - */ - rawContent: string | undefined); -} - -/** - * Represents the result of a tool call. - * - * @public - */ -export declare interface ToolCallResult { - content: string; - toolCallId?: string; -} - -/** - * Determine how to apply name transformations to tools. - * - * - `passThrough`: The tool name is used as-is, without any transformations. This is generally not - * recommended as the tool name can contain weird characters that may confuse the model. - * - `removeSpecial`: The tool name is transformed to replace non-alphanumeric characters with - * underscores. - * - `snakeCase`: The tool name is transformed to snake_case. - * - `camelCase`: The tool name is transformed to camelCase. - */ -declare type ToolNaming = "passThrough" | "removeSpecial" | "snakeCase" | "camelCase"; - -/** - * Tools provider a function that when called, return a list of tools. - * - * @public - */ -export declare type ToolsProvider = (ctl: ToolsProviderController) => Promise>; - -/** - * Controller for tools provider. - * - * @public - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ -export declare class ToolsProviderController extends BaseController { -} - -declare type ToolStatusStepState = { - status: ToolStatusStepStateStatus; - customStatus: string; - customWarnings: Array; -}; - -/** - * Represents the state of a tool call. - * - * @public - */ -export declare type ToolStatusStepStateStatus = { - type: "generatingToolCall"; - /** - * The name of the tool to be called (if known). - */ - name?: string; - /** - * The identifier of the plugin that provided the tool, if known + applicable. - */ - pluginIdentifier?: string; - /** - * The string representation of the arguments (as being streamed). - */ - argumentsString?: string; -} | { - type: "toolCallGenerationFailed"; - error: string; - rawContent?: string; -} | { - type: "toolCallQueued"; -} | { - type: "confirmingToolCall"; -} | { - type: "toolCallDenied"; - denyReason?: string; -} | { - type: "callingTool"; -} | { - type: "toolCallFailed"; - error: string; -} | { - type: "toolCallSucceeded"; - timeMs: number; -}; - -declare abstract class Transport { - /** - * Implemented by ClientTransport / ServerTransport. Called by transport implementation to verify - * incoming message. - */ - protected abstract parseIncomingMessage(message: any): TIncoming; - /** - * Implemented by transport. At this point, message is already validated. - */ - protected abstract sendViaTransport(message: TOutgoing): void; - /** - * Implemented by ClientTransport / ServerTransport. Call by outside to send a message. - */ - abstract send(message: TOutgoing): void; - /** - * Whether this transport has been disposed. - */ - protected disposed: boolean; - [Symbol.asyncDispose](): Promise; -} - -declare interface UnimplementedRawFunctionTool extends ToolBase { - type: "unimplementedRawFunction"; - parametersJsonSchema: any; - checkParameters: (params: any) => void; - implementation: (params: Record, ctx: ToolCallContext) => never; -} - -/** - * A function that can be used to create a raw function `Tool` that is not implemented yet. When - * using `.act`, upon encountering an unimplemented tool, the `.act` will stop gracefully. - * - * @public - * @experimental Not stable, will likely change in the future. - */ -export declare function unimplementedRawFunctionTool({ name, description, parametersJsonSchema, }: { - name: string; - description: string; - parametersJsonSchema: any; -}): UnimplementedRawFunctionTool; - -declare class Validator { - private readonly attachStack; - constructor({ attachStack }?: ValidatorConstructorOpts); - /** - * Pretty-prints a Zod error. - * - * @param rootObjectName - The name of the object being validated (used for error messages) - * @param error - The Zod error to pretty-print - * - * @returns The pretty-printed error in a string - */ - static prettyPrintZod(rootObjectName: string, error: ZodError): string; - /** - * Validates a value against a schema and throws an error if it's invalid. - * - * @param lead - The start of the error message (used for error messages) - * @param rootObjectName - The name of the object being validated (used for error messages) - * @param schema - The schema to validate against - * @param value - The value to validate - * - * @returns The validated value - * @throws An error if the value is invalid - */ - validateOrThrow(lead: string, rootObjectName: string, schema: z.Schema, value: unknown, stack?: string): T; - /** - * Validates multiple values against multiple schemas and throws an error if any of them are - * invalid. All values are validated before any errors are thrown. This is useful when you want to - * validate multiple values at once and want to see all the errors at once. - * - * @param leadProducer - The function to produce the start of the error message (used for error). - * It is called with a set of indices of the invalid values. - * @param rootObjectNames - The names of the objects being validated (used for error messages) - * @param schemas - The schemas to validate against - * @param values - The values to validate - * - * @returns The validated values - * @throws An error if any of the values are invalid - */ - validateMultipleOrThrow>(leadProducer: (erroredValues: Set) => string, rootObjectNames: Array, schemas: Array>, values: T, stack?: string): T; - /** - * Validates a value against a schema and throws an error if it's invalid. This is a convenience - * function for validating one single method parameter. - * - * @param className - The name of the class containing the method (used for error messages) - * @param methodName - The name of the method (used for error messages) - * @param paramName - The name of the parameter being validated (used for error messages) - * @param schema - The schema to validate against - * @param value - The value to validate - * - * @returns The validated value - * @throws An error if the value is invalid - */ - validateMethodParamOrThrow(className: string, methodName: string, paramName: string, schema: z.Schema, value: unknown, stack?: string): T; - /** - * Validates multiple values against multiple schemas and throws an error if any of them are - * invalid. This is a convenience function for validating multiple method parameters. - * - * @param className - The name of the class containing the method (used for error messages) - * @param methodName - The name of the method (used for error messages) - * @param paramNames - The names of the parameters being validated (used for error messages) - * @param schemas - The schemas to validate against - * @param values - The values to validate - * - * @returns The validated values - * @throws An error if any of the values are invalid - */ - validateMethodParamsOrThrow>(className: string, methodName: string, paramNames: Array, schemas: Array>, values: T, stack?: string): T; - /** - * Validates a value against a schema and throws an error if it's invalid. This is a convenience - * function for validating one single constructor parameter. - * - * @param className - The name of the class (used for error messages) - * @param paramName - The name of the parameter being validated (used for error messages) - * @param schema - The schema to validate against - * @param value - The value to validate - * - * @returns The validated value - * @throws An error if the value is invalid - */ - validateConstructorParamOrThrow(className: string, paramName: string, schema: z.Schema, value: unknown, stack?: string): T; - /** - * Validates multiple values against multiple schemas and throws an error if any of them are - * invalid. This is a convenience function for validating multiple constructor parameters. - * - * @param className - The name of the class (used for error messages) - * @param paramNames - The names of the parameters being validated (used for error messages) - * - * @param schemas - The schemas to validate against - * @param values - The values to validate - */ - validateConstructorParamsOrThrow>(className: string, paramNames: Array, schemas: Array>, values: T, stack?: string): T; -} - -declare interface ValidatorConstructorOpts { - attachStack?: boolean; -} - -/** - * @public - */ -export declare type VirtualConfigSchematics = { - [key: string]: { - key: string; - type: any; - valueTypeKey: string; - }; -}; - -declare interface WritableSignalEndpoint { - name: string; - creationParameter: z.ZodType; - signalData: z.ZodType; - serialization: SerializationType; - handler: WritableSignalEndpointHandler | null; -} - -declare type WritableSignalEndpointHandler = (ctx: TContext, creationParameter: TCreationParameter) => readonly [signal: SignalLike, setter: Setter] | Promise, setter: Setter]> | readonly [signal: SignalLike, setter: Setter] | Promise, setter: Setter]>; - -declare interface WritableSignalEndpointSpecBase { - creationParameter: any; - signalData: any; -} - -declare type WritableSignalEndpointsSpecBase = { - [endpointName: string]: WritableSignalEndpointSpecBase; -}; - -/** - * A write tag is a tag that can be optionally passed to a setter to identify the update. - */ -declare type WriteTag = string; - -export { } diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/dist/index.mjs b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/dist/index.mjs deleted file mode 100644 index 7dedc3e10..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/dist/index.mjs +++ /dev/null @@ -1,20637 +0,0 @@ -import { z } from 'zod'; -import process$1 from 'process'; -import chalk from 'chalk'; -import { terminalSize, WebSocket, readFileAsBase64, generateRandomBase64 } from '@lmstudio/lms-isomorphic'; -import { zodToJsonSchema } from 'zod-to-json-schema'; - -function isSignalLike(value) { - return (typeof value === "object" && - value !== null && - typeof value.get === "function" && - typeof value.subscribe === "function"); -} -/** - * Base class for objects that can be subscribed to. Provides common utility methods. - */ -class Subscribable { - subscribeWithCleaner(cleaner, listener) { - const unsubscribe = this.subscribe(listener); - cleaner.register(unsubscribe); - } - subscribeOnce(listener) { - const unsubscribe = this.subscribe(data => { - unsubscribe(); - listener(data); - }); - return unsubscribe; - } - subscribeOnceWithCleaner(cleaner, listener) { - const unsubscribe = this.subscribeOnce(listener); - cleaner.register(unsubscribe); - } - derive(deriver, outputEqualsPredicate = (a, b) => a === b) { - if (isSignalLike(this)) { - return LazySignal.deriveFrom([this], deriver); - } - const thisWithGetter = this; - if (thisWithGetter.get !== undefined) { - const initialValue = thisWithGetter.get(); - if (initialValue === LazySignal.NOT_AVAILABLE) { - return LazySignal.createWithoutInitialValue(setDownstream => { - return thisWithGetter.subscribe(data => { - if (isAvailable(data)) { - setDownstream(deriver(data)); - } - }); - }); - } - const thisNarrowed = thisWithGetter; - return LazySignal.create(deriver(thisNarrowed.get()), setDownstream => { - return thisNarrowed.subscribe(data => { - setDownstream(deriver(data)); - }); - }, outputEqualsPredicate); - } - return LazySignal.createWithoutInitialValue(setDownstream => { - return this.subscribe(data => { - if (isAvailable(data)) { - setDownstream(deriver(data)); - } - }); - }, outputEqualsPredicate); - } -} - -/** - * Represents an event that can be subscribed to. Emitted events will trigger all subscribers in the - * next microtask. If multiple events are emitted, they will be triggered in the same microtask. - */ -class Event extends Subscribable { - /** - * Internal state that tracks whether the event has any subscribers. - */ - constructor() { - super(); - this.subscribers = new Set(); - /** - * Internal callback that is called when the number of subscribers goes from 0 to 1. - */ - this.onSubscribed = null; - /** - * Internal callback that is called when the number of subscribers goes from 1 to 0. - */ - this.onUnsubscribed = null; - } - emit(data) { - queueMicrotask(() => { - for (const subscriber of this.subscribers) { - subscriber(data); - } - }); - } - static create() { - const event = new Event(); - const emitter = data => { - event.emit(data); - }; - return [event, emitter]; - } - subscribe(listener) { - const previousSize = this.subscribers.size; - this.subscribers.add(listener); - if (previousSize === 0 && this.subscribers.size === 1) { - this.onSubscribed?.(); - } - return () => { - const previousSize = this.subscribers.size; - this.subscribers.delete(listener); - if (previousSize === 1 && this.subscribers.size === 0) { - this.onUnsubscribed?.(); - } - }; - } - batch({ minIdleTimeMs = 200, maxBatchTimeMs = 1000, }) { - const [batchedEvent, emitBatchedEvent] = Event.create(); - batchedEvent.onSubscribed = () => { - let batch = []; - let emitBatchTimeout = null; - let firstEventTime = 0; - const emitBatch = () => { - emitBatchTimeout = null; - emitBatchedEvent(batch); - batch = []; - }; - batchedEvent.onUnsubscribed = this.subscribe(data => { - batch.push(data); - if (emitBatchTimeout === null) { - // No scheduled batch - firstEventTime = Date.now(); - emitBatchTimeout = setTimeout(emitBatch, Math.min(minIdleTimeMs, maxBatchTimeMs)); - } - else { - // Reschedule emission - clearTimeout(emitBatchTimeout); - const timeSinceFirstEvent = Date.now() - firstEventTime; - emitBatchTimeout = setTimeout(emitBatch, Math.min(minIdleTimeMs, Math.max(0, maxBatchTimeMs - timeSinceFirstEvent))); - } - }); - }; - return batchedEvent; - } -} - -function makePromise() { - let resolve; - let reject; - const promise = new Promise((_resolve, _reject) => { - resolve = _resolve; - reject = _reject; - }); - return { promise, resolve: resolve, reject: reject }; -} - -// src/utils/env.ts -var NOTHING = Symbol.for("immer-nothing"); -var DRAFTABLE = Symbol.for("immer-draftable"); -var DRAFT_STATE = Symbol.for("immer-state"); - -// src/utils/errors.ts -var errors = process.env.NODE_ENV !== "production" ? [ - // All error codes, starting by 0: - function(plugin) { - return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`; - }, - function(thing) { - return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`; - }, - "This object has been frozen and should not be mutated", - function(data) { - return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data; - }, - "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.", - "Immer forbids circular references", - "The first or second argument to `produce` must be a function", - "The third argument to `produce` must be a function or undefined", - "First argument to `createDraft` must be a plain object, an array, or an immerable object", - "First argument to `finishDraft` must be a draft returned by `createDraft`", - function(thing) { - return `'current' expects a draft, got: ${thing}`; - }, - "Object.defineProperty() cannot be used on an Immer draft", - "Object.setPrototypeOf() cannot be used on an Immer draft", - "Immer only supports deleting array indices", - "Immer only supports setting array indices and the 'length' property", - function(thing) { - return `'original' expects a draft, got: ${thing}`; - } - // Note: if more errors are added, the errorOffset in Patches.ts should be increased - // See Patches.ts for additional errors -] : []; -function die(error, ...args) { - if (process.env.NODE_ENV !== "production") { - const e = errors[error]; - const msg = typeof e === "function" ? e.apply(null, args) : e; - throw new Error(`[Immer] ${msg}`); - } - throw new Error( - `[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf` - ); -} - -// src/utils/common.ts -var getPrototypeOf = Object.getPrototypeOf; -function isDraft(value) { - return !!value && !!value[DRAFT_STATE]; -} -function isDraftable(value) { - if (!value) - return false; - return isPlainObject$2(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor?.[DRAFTABLE] || isMap$1(value) || isSet$1(value); -} -var objectCtorString = Object.prototype.constructor.toString(); -function isPlainObject$2(value) { - if (!value || typeof value !== "object") - return false; - const proto = getPrototypeOf(value); - if (proto === null) { - return true; - } - const Ctor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor; - if (Ctor === Object) - return true; - return typeof Ctor == "function" && Function.toString.call(Ctor) === objectCtorString; -} -function each(obj, iter) { - if (getArchtype(obj) === 0 /* Object */) { - Reflect.ownKeys(obj).forEach((key) => { - iter(key, obj[key], obj); - }); - } else { - obj.forEach((entry, index) => iter(index, entry, obj)); - } -} -function getArchtype(thing) { - const state = thing[DRAFT_STATE]; - return state ? state.type_ : Array.isArray(thing) ? 1 /* Array */ : isMap$1(thing) ? 2 /* Map */ : isSet$1(thing) ? 3 /* Set */ : 0 /* Object */; -} -function has(thing, prop) { - return getArchtype(thing) === 2 /* Map */ ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop); -} -function get(thing, prop) { - return getArchtype(thing) === 2 /* Map */ ? thing.get(prop) : thing[prop]; -} -function set(thing, propOrOldValue, value) { - const t = getArchtype(thing); - if (t === 2 /* Map */) - thing.set(propOrOldValue, value); - else if (t === 3 /* Set */) { - thing.add(value); - } else - thing[propOrOldValue] = value; -} -function is(x, y) { - if (x === y) { - return x !== 0 || 1 / x === 1 / y; - } else { - return x !== x && y !== y; - } -} -function isMap$1(target) { - return target instanceof Map; -} -function isSet$1(target) { - return target instanceof Set; -} -function latest(state) { - return state.copy_ || state.base_; -} -function shallowCopy(base, strict) { - if (isMap$1(base)) { - return new Map(base); - } - if (isSet$1(base)) { - return new Set(base); - } - if (Array.isArray(base)) - return Array.prototype.slice.call(base); - const isPlain = isPlainObject$2(base); - if (strict === true || strict === "class_only" && !isPlain) { - const descriptors = Object.getOwnPropertyDescriptors(base); - delete descriptors[DRAFT_STATE]; - let keys = Reflect.ownKeys(descriptors); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - const desc = descriptors[key]; - if (desc.writable === false) { - desc.writable = true; - desc.configurable = true; - } - if (desc.get || desc.set) - descriptors[key] = { - configurable: true, - writable: true, - // could live with !!desc.set as well here... - enumerable: desc.enumerable, - value: base[key] - }; - } - return Object.create(getPrototypeOf(base), descriptors); - } else { - const proto = getPrototypeOf(base); - if (proto !== null && isPlain) { - return { ...base }; - } - const obj = Object.create(proto); - return Object.assign(obj, base); - } -} -function freeze(obj, deep = false) { - if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) - return obj; - if (getArchtype(obj) > 1) { - obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections; - } - Object.freeze(obj); - if (deep) - Object.values(obj).forEach((value) => freeze(value, true)); - return obj; -} -function dontMutateFrozenCollections() { - die(2); -} -function isFrozen(obj) { - return Object.isFrozen(obj); -} - -// src/utils/plugins.ts -var plugins = {}; -function getPlugin(pluginKey) { - const plugin = plugins[pluginKey]; - if (!plugin) { - die(0, pluginKey); - } - return plugin; -} -function loadPlugin(pluginKey, implementation) { - if (!plugins[pluginKey]) - plugins[pluginKey] = implementation; -} - -// src/core/scope.ts -var currentScope; -function getCurrentScope() { - return currentScope; -} -function createScope(parent_, immer_) { - return { - drafts_: [], - parent_, - immer_, - // Whenever the modified draft contains a draft from another scope, we - // need to prevent auto-freezing so the unowned draft can be finalized. - canAutoFreeze_: true, - unfinalizedDrafts_: 0 - }; -} -function usePatchesInScope(scope, patchListener) { - if (patchListener) { - getPlugin("Patches"); - scope.patches_ = []; - scope.inversePatches_ = []; - scope.patchListener_ = patchListener; - } -} -function revokeScope(scope) { - leaveScope(scope); - scope.drafts_.forEach(revokeDraft); - scope.drafts_ = null; -} -function leaveScope(scope) { - if (scope === currentScope) { - currentScope = scope.parent_; - } -} -function enterScope(immer2) { - return currentScope = createScope(currentScope, immer2); -} -function revokeDraft(draft) { - const state = draft[DRAFT_STATE]; - if (state.type_ === 0 /* Object */ || state.type_ === 1 /* Array */) - state.revoke_(); - else - state.revoked_ = true; -} - -// src/core/finalize.ts -function processResult(result, scope) { - scope.unfinalizedDrafts_ = scope.drafts_.length; - const baseDraft = scope.drafts_[0]; - const isReplaced = result !== void 0 && result !== baseDraft; - if (isReplaced) { - if (baseDraft[DRAFT_STATE].modified_) { - revokeScope(scope); - die(4); - } - if (isDraftable(result)) { - result = finalize(scope, result); - if (!scope.parent_) - maybeFreeze(scope, result); - } - if (scope.patches_) { - getPlugin("Patches").generateReplacementPatches_( - baseDraft[DRAFT_STATE].base_, - result, - scope.patches_, - scope.inversePatches_ - ); - } - } else { - result = finalize(scope, baseDraft, []); - } - revokeScope(scope); - if (scope.patches_) { - scope.patchListener_(scope.patches_, scope.inversePatches_); - } - return result !== NOTHING ? result : void 0; -} -function finalize(rootScope, value, path) { - if (isFrozen(value)) - return value; - const state = value[DRAFT_STATE]; - if (!state) { - each( - value, - (key, childValue) => finalizeProperty(rootScope, state, value, key, childValue, path) - ); - return value; - } - if (state.scope_ !== rootScope) - return value; - if (!state.modified_) { - maybeFreeze(rootScope, state.base_, true); - return state.base_; - } - if (!state.finalized_) { - state.finalized_ = true; - state.scope_.unfinalizedDrafts_--; - const result = state.copy_; - let resultEach = result; - let isSet2 = false; - if (state.type_ === 3 /* Set */) { - resultEach = new Set(result); - result.clear(); - isSet2 = true; - } - each( - resultEach, - (key, childValue) => finalizeProperty(rootScope, state, result, key, childValue, path, isSet2) - ); - maybeFreeze(rootScope, result, false); - if (path && rootScope.patches_) { - getPlugin("Patches").generatePatches_( - state, - path, - rootScope.patches_, - rootScope.inversePatches_ - ); - } - } - return state.copy_; -} -function finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath, targetIsSet) { - if (process.env.NODE_ENV !== "production" && childValue === targetObject) - die(5); - if (isDraft(childValue)) { - const path = rootPath && parentState && parentState.type_ !== 3 /* Set */ && // Set objects are atomic since they have no keys. - !has(parentState.assigned_, prop) ? rootPath.concat(prop) : void 0; - const res = finalize(rootScope, childValue, path); - set(targetObject, prop, res); - if (isDraft(res)) { - rootScope.canAutoFreeze_ = false; - } else - return; - } else if (targetIsSet) { - targetObject.add(childValue); - } - if (isDraftable(childValue) && !isFrozen(childValue)) { - if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) { - return; - } - finalize(rootScope, childValue); - if ((!parentState || !parentState.scope_.parent_) && typeof prop !== "symbol" && Object.prototype.propertyIsEnumerable.call(targetObject, prop)) - maybeFreeze(rootScope, childValue); - } -} -function maybeFreeze(scope, value, deep = false) { - if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) { - freeze(value, deep); - } -} - -// src/core/proxy.ts -function createProxyProxy(base, parent) { - const isArray = Array.isArray(base); - const state = { - type_: isArray ? 1 /* Array */ : 0 /* Object */, - // Track which produce call this is associated with. - scope_: parent ? parent.scope_ : getCurrentScope(), - // True for both shallow and deep changes. - modified_: false, - // Used during finalization. - finalized_: false, - // Track which properties have been assigned (true) or deleted (false). - assigned_: {}, - // The parent draft state. - parent_: parent, - // The base state. - base_: base, - // The base proxy. - draft_: null, - // set below - // The base copy with any updated values. - copy_: null, - // Called by the `produce` function. - revoke_: null, - isManual_: false - }; - let target = state; - let traps = objectTraps; - if (isArray) { - target = [state]; - traps = arrayTraps; - } - const { revoke, proxy } = Proxy.revocable(target, traps); - state.draft_ = proxy; - state.revoke_ = revoke; - return proxy; -} -var objectTraps = { - get(state, prop) { - if (prop === DRAFT_STATE) - return state; - const source = latest(state); - if (!has(source, prop)) { - return readPropFromProto(state, source, prop); - } - const value = source[prop]; - if (state.finalized_ || !isDraftable(value)) { - return value; - } - if (value === peek(state.base_, prop)) { - prepareCopy(state); - return state.copy_[prop] = createProxy(value, state); - } - return value; - }, - has(state, prop) { - return prop in latest(state); - }, - ownKeys(state) { - return Reflect.ownKeys(latest(state)); - }, - set(state, prop, value) { - const desc = getDescriptorFromProto(latest(state), prop); - if (desc?.set) { - desc.set.call(state.draft_, value); - return true; - } - if (!state.modified_) { - const current2 = peek(latest(state), prop); - const currentState = current2?.[DRAFT_STATE]; - if (currentState && currentState.base_ === value) { - state.copy_[prop] = value; - state.assigned_[prop] = false; - return true; - } - if (is(value, current2) && (value !== void 0 || has(state.base_, prop))) - return true; - prepareCopy(state); - markChanged(state); - } - if (state.copy_[prop] === value && // special case: handle new props with value 'undefined' - (value !== void 0 || prop in state.copy_) || // special case: NaN - Number.isNaN(value) && Number.isNaN(state.copy_[prop])) - return true; - state.copy_[prop] = value; - state.assigned_[prop] = true; - return true; - }, - deleteProperty(state, prop) { - if (peek(state.base_, prop) !== void 0 || prop in state.base_) { - state.assigned_[prop] = false; - prepareCopy(state); - markChanged(state); - } else { - delete state.assigned_[prop]; - } - if (state.copy_) { - delete state.copy_[prop]; - } - return true; - }, - // Note: We never coerce `desc.value` into an Immer draft, because we can't make - // the same guarantee in ES5 mode. - getOwnPropertyDescriptor(state, prop) { - const owner = latest(state); - const desc = Reflect.getOwnPropertyDescriptor(owner, prop); - if (!desc) - return desc; - return { - writable: true, - configurable: state.type_ !== 1 /* Array */ || prop !== "length", - enumerable: desc.enumerable, - value: owner[prop] - }; - }, - defineProperty() { - die(11); - }, - getPrototypeOf(state) { - return getPrototypeOf(state.base_); - }, - setPrototypeOf() { - die(12); - } -}; -var arrayTraps = {}; -each(objectTraps, (key, fn) => { - arrayTraps[key] = function() { - arguments[0] = arguments[0][0]; - return fn.apply(this, arguments); - }; -}); -arrayTraps.deleteProperty = function(state, prop) { - if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop))) - die(13); - return arrayTraps.set.call(this, state, prop, void 0); -}; -arrayTraps.set = function(state, prop, value) { - if (process.env.NODE_ENV !== "production" && prop !== "length" && isNaN(parseInt(prop))) - die(14); - return objectTraps.set.call(this, state[0], prop, value, state[0]); -}; -function peek(draft, prop) { - const state = draft[DRAFT_STATE]; - const source = state ? latest(state) : draft; - return source[prop]; -} -function readPropFromProto(state, source, prop) { - const desc = getDescriptorFromProto(source, prop); - return desc ? `value` in desc ? desc.value : ( - // This is a very special case, if the prop is a getter defined by the - // prototype, we should invoke it with the draft as context! - desc.get?.call(state.draft_) - ) : void 0; -} -function getDescriptorFromProto(source, prop) { - if (!(prop in source)) - return void 0; - let proto = getPrototypeOf(source); - while (proto) { - const desc = Object.getOwnPropertyDescriptor(proto, prop); - if (desc) - return desc; - proto = getPrototypeOf(proto); - } - return void 0; -} -function markChanged(state) { - if (!state.modified_) { - state.modified_ = true; - if (state.parent_) { - markChanged(state.parent_); - } - } -} -function prepareCopy(state) { - if (!state.copy_) { - state.copy_ = shallowCopy( - state.base_, - state.scope_.immer_.useStrictShallowCopy_ - ); - } -} - -// src/core/immerClass.ts -var Immer2 = class { - constructor(config) { - this.autoFreeze_ = true; - this.useStrictShallowCopy_ = false; - /** - * The `produce` function takes a value and a "recipe function" (whose - * return value often depends on the base state). The recipe function is - * free to mutate its first argument however it wants. All mutations are - * only ever applied to a __copy__ of the base state. - * - * Pass only a function to create a "curried producer" which relieves you - * from passing the recipe function every time. - * - * Only plain objects and arrays are made mutable. All other objects are - * considered uncopyable. - * - * Note: This function is __bound__ to its `Immer` instance. - * - * @param {any} base - the initial state - * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified - * @param {Function} patchListener - optional function that will be called with all the patches produced here - * @returns {any} a new state, or the initial state if nothing was modified - */ - this.produce = (base, recipe, patchListener) => { - if (typeof base === "function" && typeof recipe !== "function") { - const defaultBase = recipe; - recipe = base; - const self = this; - return function curriedProduce(base2 = defaultBase, ...args) { - return self.produce(base2, (draft) => recipe.call(this, draft, ...args)); - }; - } - if (typeof recipe !== "function") - die(6); - if (patchListener !== void 0 && typeof patchListener !== "function") - die(7); - let result; - if (isDraftable(base)) { - const scope = enterScope(this); - const proxy = createProxy(base, void 0); - let hasError = true; - try { - result = recipe(proxy); - hasError = false; - } finally { - if (hasError) - revokeScope(scope); - else - leaveScope(scope); - } - usePatchesInScope(scope, patchListener); - return processResult(result, scope); - } else if (!base || typeof base !== "object") { - result = recipe(base); - if (result === void 0) - result = base; - if (result === NOTHING) - result = void 0; - if (this.autoFreeze_) - freeze(result, true); - if (patchListener) { - const p = []; - const ip = []; - getPlugin("Patches").generateReplacementPatches_(base, result, p, ip); - patchListener(p, ip); - } - return result; - } else - die(1, base); - }; - this.produceWithPatches = (base, recipe) => { - if (typeof base === "function") { - return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args)); - } - let patches, inversePatches; - const result = this.produce(base, recipe, (p, ip) => { - patches = p; - inversePatches = ip; - }); - return [result, patches, inversePatches]; - }; - if (typeof config?.autoFreeze === "boolean") - this.setAutoFreeze(config.autoFreeze); - if (typeof config?.useStrictShallowCopy === "boolean") - this.setUseStrictShallowCopy(config.useStrictShallowCopy); - } - createDraft(base) { - if (!isDraftable(base)) - die(8); - if (isDraft(base)) - base = current(base); - const scope = enterScope(this); - const proxy = createProxy(base, void 0); - proxy[DRAFT_STATE].isManual_ = true; - leaveScope(scope); - return proxy; - } - finishDraft(draft, patchListener) { - const state = draft && draft[DRAFT_STATE]; - if (!state || !state.isManual_) - die(9); - const { scope_: scope } = state; - usePatchesInScope(scope, patchListener); - return processResult(void 0, scope); - } - /** - * Pass true to automatically freeze all copies created by Immer. - * - * By default, auto-freezing is enabled. - */ - setAutoFreeze(value) { - this.autoFreeze_ = value; - } - /** - * Pass true to enable strict shallow copy. - * - * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties. - */ - setUseStrictShallowCopy(value) { - this.useStrictShallowCopy_ = value; - } - applyPatches(base, patches) { - let i; - for (i = patches.length - 1; i >= 0; i--) { - const patch = patches[i]; - if (patch.path.length === 0 && patch.op === "replace") { - base = patch.value; - break; - } - } - if (i > -1) { - patches = patches.slice(i + 1); - } - const applyPatchesImpl = getPlugin("Patches").applyPatches_; - if (isDraft(base)) { - return applyPatchesImpl(base, patches); - } - return this.produce( - base, - (draft) => applyPatchesImpl(draft, patches) - ); - } -}; -function createProxy(value, parent) { - const draft = isMap$1(value) ? getPlugin("MapSet").proxyMap_(value, parent) : isSet$1(value) ? getPlugin("MapSet").proxySet_(value, parent) : createProxyProxy(value, parent); - const scope = parent ? parent.scope_ : getCurrentScope(); - scope.drafts_.push(draft); - return draft; -} - -// src/core/current.ts -function current(value) { - if (!isDraft(value)) - die(10, value); - return currentImpl(value); -} -function currentImpl(value) { - if (!isDraftable(value) || isFrozen(value)) - return value; - const state = value[DRAFT_STATE]; - let copy; - if (state) { - if (!state.modified_) - return state.base_; - state.finalized_ = true; - copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_); - } else { - copy = shallowCopy(value, true); - } - each(copy, (key, childValue) => { - set(copy, key, currentImpl(childValue)); - }); - if (state) { - state.finalized_ = false; - } - return copy; -} - -// src/plugins/mapset.ts -function enableMapSet() { - class DraftMap extends Map { - constructor(target, parent) { - super(); - this[DRAFT_STATE] = { - type_: 2 /* Map */, - parent_: parent, - scope_: parent ? parent.scope_ : getCurrentScope(), - modified_: false, - finalized_: false, - copy_: void 0, - assigned_: void 0, - base_: target, - draft_: this, - isManual_: false, - revoked_: false - }; - } - get size() { - return latest(this[DRAFT_STATE]).size; - } - has(key) { - return latest(this[DRAFT_STATE]).has(key); - } - set(key, value) { - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - if (!latest(state).has(key) || latest(state).get(key) !== value) { - prepareMapCopy(state); - markChanged(state); - state.assigned_.set(key, true); - state.copy_.set(key, value); - state.assigned_.set(key, true); - } - return this; - } - delete(key) { - if (!this.has(key)) { - return false; - } - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - prepareMapCopy(state); - markChanged(state); - if (state.base_.has(key)) { - state.assigned_.set(key, false); - } else { - state.assigned_.delete(key); - } - state.copy_.delete(key); - return true; - } - clear() { - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - if (latest(state).size) { - prepareMapCopy(state); - markChanged(state); - state.assigned_ = /* @__PURE__ */ new Map(); - each(state.base_, (key) => { - state.assigned_.set(key, false); - }); - state.copy_.clear(); - } - } - forEach(cb, thisArg) { - const state = this[DRAFT_STATE]; - latest(state).forEach((_value, key, _map) => { - cb.call(thisArg, this.get(key), key, this); - }); - } - get(key) { - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - const value = latest(state).get(key); - if (state.finalized_ || !isDraftable(value)) { - return value; - } - if (value !== state.base_.get(key)) { - return value; - } - const draft = createProxy(value, state); - prepareMapCopy(state); - state.copy_.set(key, draft); - return draft; - } - keys() { - return latest(this[DRAFT_STATE]).keys(); - } - values() { - const iterator = this.keys(); - return { - [Symbol.iterator]: () => this.values(), - next: () => { - const r = iterator.next(); - if (r.done) - return r; - const value = this.get(r.value); - return { - done: false, - value - }; - } - }; - } - entries() { - const iterator = this.keys(); - return { - [Symbol.iterator]: () => this.entries(), - next: () => { - const r = iterator.next(); - if (r.done) - return r; - const value = this.get(r.value); - return { - done: false, - value: [r.value, value] - }; - } - }; - } - [(Symbol.iterator)]() { - return this.entries(); - } - } - function proxyMap_(target, parent) { - return new DraftMap(target, parent); - } - function prepareMapCopy(state) { - if (!state.copy_) { - state.assigned_ = /* @__PURE__ */ new Map(); - state.copy_ = new Map(state.base_); - } - } - class DraftSet extends Set { - constructor(target, parent) { - super(); - this[DRAFT_STATE] = { - type_: 3 /* Set */, - parent_: parent, - scope_: parent ? parent.scope_ : getCurrentScope(), - modified_: false, - finalized_: false, - copy_: void 0, - base_: target, - draft_: this, - drafts_: /* @__PURE__ */ new Map(), - revoked_: false, - isManual_: false - }; - } - get size() { - return latest(this[DRAFT_STATE]).size; - } - has(value) { - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - if (!state.copy_) { - return state.base_.has(value); - } - if (state.copy_.has(value)) - return true; - if (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value))) - return true; - return false; - } - add(value) { - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - if (!this.has(value)) { - prepareSetCopy(state); - markChanged(state); - state.copy_.add(value); - } - return this; - } - delete(value) { - if (!this.has(value)) { - return false; - } - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - prepareSetCopy(state); - markChanged(state); - return state.copy_.delete(value) || (state.drafts_.has(value) ? state.copy_.delete(state.drafts_.get(value)) : ( - /* istanbul ignore next */ - false - )); - } - clear() { - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - if (latest(state).size) { - prepareSetCopy(state); - markChanged(state); - state.copy_.clear(); - } - } - values() { - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - prepareSetCopy(state); - return state.copy_.values(); - } - entries() { - const state = this[DRAFT_STATE]; - assertUnrevoked(state); - prepareSetCopy(state); - return state.copy_.entries(); - } - keys() { - return this.values(); - } - [(Symbol.iterator)]() { - return this.values(); - } - forEach(cb, thisArg) { - const iterator = this.values(); - let result = iterator.next(); - while (!result.done) { - cb.call(thisArg, result.value, result.value, this); - result = iterator.next(); - } - } - } - function proxySet_(target, parent) { - return new DraftSet(target, parent); - } - function prepareSetCopy(state) { - if (!state.copy_) { - state.copy_ = /* @__PURE__ */ new Set(); - state.base_.forEach((value) => { - if (isDraftable(value)) { - const draft = createProxy(value, state); - state.drafts_.set(value, draft); - state.copy_.add(draft); - } else { - state.copy_.add(value); - } - }); - } - } - function assertUnrevoked(state) { - if (state.revoked_) - die(3, JSON.stringify(latest(state))); - } - loadPlugin("MapSet", { proxyMap_, proxySet_ }); -} - -// src/plugins/patches.ts -function enablePatches() { - const errorOffset = 16; - if (process.env.NODE_ENV !== "production") { - errors.push( - 'Sets cannot have "replace" patches.', - function(op) { - return "Unsupported patch operation: " + op; - }, - function(path) { - return "Cannot apply patch, path doesn't resolve: " + path; - }, - "Patching reserved attributes like __proto__, prototype and constructor is not allowed" - ); - } - const REPLACE = "replace"; - const ADD = "add"; - const REMOVE = "remove"; - function generatePatches_(state, basePath, patches, inversePatches) { - switch (state.type_) { - case 0 /* Object */: - case 2 /* Map */: - return generatePatchesFromAssigned( - state, - basePath, - patches, - inversePatches - ); - case 1 /* Array */: - return generateArrayPatches(state, basePath, patches, inversePatches); - case 3 /* Set */: - return generateSetPatches( - state, - basePath, - patches, - inversePatches - ); - } - } - function generateArrayPatches(state, basePath, patches, inversePatches) { - let { base_, assigned_ } = state; - let copy_ = state.copy_; - if (copy_.length < base_.length) { - [base_, copy_] = [copy_, base_]; - [patches, inversePatches] = [inversePatches, patches]; - } - for (let i = 0; i < base_.length; i++) { - if (assigned_[i] && copy_[i] !== base_[i]) { - const path = basePath.concat([i]); - patches.push({ - op: REPLACE, - path, - // Need to maybe clone it, as it can in fact be the original value - // due to the base/copy inversion at the start of this function - value: clonePatchValueIfNeeded(copy_[i]) - }); - inversePatches.push({ - op: REPLACE, - path, - value: clonePatchValueIfNeeded(base_[i]) - }); - } - } - for (let i = base_.length; i < copy_.length; i++) { - const path = basePath.concat([i]); - patches.push({ - op: ADD, - path, - // Need to maybe clone it, as it can in fact be the original value - // due to the base/copy inversion at the start of this function - value: clonePatchValueIfNeeded(copy_[i]) - }); - } - for (let i = copy_.length - 1; base_.length <= i; --i) { - const path = basePath.concat([i]); - inversePatches.push({ - op: REMOVE, - path - }); - } - } - function generatePatchesFromAssigned(state, basePath, patches, inversePatches) { - const { base_, copy_ } = state; - each(state.assigned_, (key, assignedValue) => { - const origValue = get(base_, key); - const value = get(copy_, key); - const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD; - if (origValue === value && op === REPLACE) - return; - const path = basePath.concat(key); - patches.push(op === REMOVE ? { op, path } : { op, path, value }); - inversePatches.push( - op === ADD ? { op: REMOVE, path } : op === REMOVE ? { op: ADD, path, value: clonePatchValueIfNeeded(origValue) } : { op: REPLACE, path, value: clonePatchValueIfNeeded(origValue) } - ); - }); - } - function generateSetPatches(state, basePath, patches, inversePatches) { - let { base_, copy_ } = state; - let i = 0; - base_.forEach((value) => { - if (!copy_.has(value)) { - const path = basePath.concat([i]); - patches.push({ - op: REMOVE, - path, - value - }); - inversePatches.unshift({ - op: ADD, - path, - value - }); - } - i++; - }); - i = 0; - copy_.forEach((value) => { - if (!base_.has(value)) { - const path = basePath.concat([i]); - patches.push({ - op: ADD, - path, - value - }); - inversePatches.unshift({ - op: REMOVE, - path, - value - }); - } - i++; - }); - } - function generateReplacementPatches_(baseValue, replacement, patches, inversePatches) { - patches.push({ - op: REPLACE, - path: [], - value: replacement === NOTHING ? void 0 : replacement - }); - inversePatches.push({ - op: REPLACE, - path: [], - value: baseValue - }); - } - function applyPatches_(draft, patches) { - patches.forEach((patch) => { - const { path, op } = patch; - let base = draft; - for (let i = 0; i < path.length - 1; i++) { - const parentType = getArchtype(base); - let p = path[i]; - if (typeof p !== "string" && typeof p !== "number") { - p = "" + p; - } - if ((parentType === 0 /* Object */ || parentType === 1 /* Array */) && (p === "__proto__" || p === "constructor")) - die(errorOffset + 3); - if (typeof base === "function" && p === "prototype") - die(errorOffset + 3); - base = get(base, p); - if (typeof base !== "object") - die(errorOffset + 2, path.join("/")); - } - const type = getArchtype(base); - const value = deepClonePatchValue(patch.value); - const key = path[path.length - 1]; - switch (op) { - case REPLACE: - switch (type) { - case 2 /* Map */: - return base.set(key, value); - case 3 /* Set */: - die(errorOffset); - default: - return base[key] = value; - } - case ADD: - switch (type) { - case 1 /* Array */: - return key === "-" ? base.push(value) : base.splice(key, 0, value); - case 2 /* Map */: - return base.set(key, value); - case 3 /* Set */: - return base.add(value); - default: - return base[key] = value; - } - case REMOVE: - switch (type) { - case 1 /* Array */: - return base.splice(key, 1); - case 2 /* Map */: - return base.delete(key); - case 3 /* Set */: - return base.delete(patch.value); - default: - return delete base[key]; - } - default: - die(errorOffset + 1, op); - } - }); - return draft; - } - function deepClonePatchValue(obj) { - if (!isDraftable(obj)) - return obj; - if (Array.isArray(obj)) - return obj.map(deepClonePatchValue); - if (isMap$1(obj)) - return new Map( - Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)]) - ); - if (isSet$1(obj)) - return new Set(Array.from(obj).map(deepClonePatchValue)); - const cloned = Object.create(getPrototypeOf(obj)); - for (const key in obj) - cloned[key] = deepClonePatchValue(obj[key]); - if (has(obj, DRAFTABLE)) - cloned[DRAFTABLE] = obj[DRAFTABLE]; - return cloned; - } - function clonePatchValueIfNeeded(obj) { - if (isDraft(obj)) { - return deepClonePatchValue(obj); - } else - return obj; - } - loadPlugin("Patches", { - applyPatches_, - generatePatches_, - generateReplacementPatches_ - }); -} - -// src/immer.ts -var immer = new Immer2(); -immer.produce; -var produceWithPatches = immer.produceWithPatches.bind( - immer -); -immer.setAutoFreeze.bind(immer); -immer.setUseStrictShallowCopy.bind(immer); -var applyPatches = immer.applyPatches.bind(immer); -immer.createDraft.bind(immer); -immer.finishDraft.bind(immer); -enableMapSet(); -enablePatches(); - -/** - * Concatenate Writable Tags - */ -function cwt(...allTags) { - return allTags - .filter(tags => tags !== undefined) - .reduce((acc, tags) => acc.concat(tags), []); -} -function makeRootReplacingPatches(value) { - return [ - { - op: "replace", - path: [], - value, - }, - ]; -} -/** - * Creates a setter function that can be used to update a value. This setter will also return the - * patches that were applied to the value. - */ -function makeSetterWithPatches(update, prependTagsFn) { - const setter = (value, tags) => { - update(() => [value, makeRootReplacingPatches(value)], cwt(prependTagsFn?.(), tags)); - }; - setter.withProducer = (producer, tags) => { - update(oldData => { - const [newData, patches] = produceWithPatches(oldData, producer); - if (isAvailable(newData)) { - return [newData, patches]; - } - throw new Error("Cannot update value to NOT_AVAILABLE"); - }, cwt(prependTagsFn?.(), tags)); - }; - setter.withUpdater = (updater, tags) => { - update(oldData => { - const newData = updater(oldData); - return [newData, makeRootReplacingPatches(newData)]; - }, cwt(prependTagsFn?.(), tags)); - }; - setter.withPatchUpdater = (updater, tags) => { - update(updater, cwt(prependTagsFn?.(), tags)); - }; - setter.withPatches = (patches, tags) => { - update(oldData => { - return [applyPatches(oldData, patches), patches]; - }, cwt(prependTagsFn?.(), tags)); - }; - setter.withValueAndPatches = (newValue, patches, tags) => { - update(() => [newValue, patches], cwt(prependTagsFn?.(), tags)); - }; - return setter; -} - -const equals = (a, b) => a === b; -/** - * A signal is a wrapper for a value. It can be used to notify subscribers when the value changes. - * For it to work properly, the value should be immutable. - * - * To create a signal, please use the `Signal.create` static method. It will return a signal - * along with a function to update its value. - */ -class Signal extends Subscribable { - /** - * Creates a signal. - * - * @param value - The initial value of the signal. - * @param equalsPredicate - A function to compare two values. The subscribers will only be called - * if the value changes according to the `equalsPredicate`. By default, it uses the `===` - * operator. - * @returns This method returns a tuple with two elements: - * - The signal - * - A function to update the value - **/ - static create(value, equalsPredicate = equals) { - const signal = new Signal(value, equalsPredicate); - const update = (updater, tags) => { - signal.update(updater, tags); - }; - const setter = makeSetterWithPatches(update); - return [signal, setter]; - } - static createReadonly(value) { - return Signal.create(value)[0]; - } - constructor(value, equalsPredicate) { - super(); - this.value = value; - this.equalsPredicate = equalsPredicate; - this.subscribers = new Set(); - this.queuedUpdaters = []; - this.isEmitting = false; - } - /** - * Returns the current value of the signal. - */ - get() { - return this.value; - } - pull() { - return this.value; - } - notifyFull(value, patches, tags) { - for (const { type, callback } of this.subscribers) { - if (type === "full") { - callback(value, patches, tags); - } - } - } - notifyAll(value, patches, tags) { - for (const { type, callback } of this.subscribers) { - if (type === "regular") { - callback(value); - } - else { - callback(value, patches, tags); - } - } - } - notifyAndUpdateIfChanged(value, patches, tags) { - // If the value has changed, or if there are any tags that need to be flushed, notify - if (!this.equalsPredicate(this.value, value)) { - this.value = value; - // If the values have changed, notify everyone - this.notifyAll(value, patches, tags); - } - else if (tags.length > 0) { - // If values not changed, but there is a tag to be flushed, notify only full subscribers - this.notifyFull(value, patches, tags); - } - } - isReplaceRoot(patch) { - return patch.path.length === 0 && patch.op === "replace"; - } - update(updater, tags) { - this.queuedUpdaters.push([updater, tags]); - // Only one concurrent update may emit - if (this.isEmitting) { - return; - } - this.isEmitting = true; - try { - // Outer while is for handling new updates caused by the notify - while (this.queuedUpdaters.length > 0) { - let value = this.value; - let patches = []; - const tags = []; - // Inner while is for handling multiple updates - while (this.queuedUpdaters.length > 0) { - const [updater, newTags] = this.queuedUpdaters.shift(); - const [newValue, newPatches] = updater(value); - value = newValue; - // Extremely rudimentary patch merging - const rootReplacerIndex = newPatches.findIndex(this.isReplaceRoot); - if (rootReplacerIndex !== -1) { - patches = newPatches.slice(rootReplacerIndex); - } - else { - patches.push(...newPatches); - } - if (newTags !== undefined) { - tags.push(...newTags); - } - } - this.notifyAndUpdateIfChanged(value, patches, tags); - } - } - finally { - this.isEmitting = false; - } - } - /** - * Subscribes to the signal. The callback will be called whenever the value changes. All callbacks - * are called synchronously upon updating. It will NOT be immediately called with the current - * value. (Use `get()` to get the current value.) Returns a function to unsubscribe. - * - * Edge cases involving manipulating the signal in the callback: - * - * - If the callback adds new subscribers, they will also be called within the same update. - * - If the callback causes removal of subscribers that have not been called yet, they will no - * longer be called. - * - If the callback causes an update of the value, the update will be queued. If multiple updates - * are queued, only the last one will be executed. - * - * Edge cases involving adding the same callback multiple times. - * - * - Callbacks are tracked with a set. Adding the same subscriber will not cause it to be called - * multiple times. - */ - subscribe(callback) { - const subscriber = { - type: "regular", - callback, - }; - this.subscribers.add(subscriber); - return () => { - this.subscribers.delete(subscriber); - }; - } - /** - * Subscribes to the signal with the callback and trigger the callback immediately with the - * current value. - */ - subscribeAndNow(callback) { - const unsubscribe = this.subscribe(callback); - callback(this.value); - return unsubscribe; - } - subscribeFull(callback) { - const subscriber = { - type: "full", - callback, - }; - this.subscribers.add(subscriber); - return () => { - this.subscribers.delete(subscriber); - }; - } - /** - * Wait until the signal satisfies a predicate. If the predicate is already satisfied, it will - * return immediately. Otherwise, it will wait until the signal satisfies the predicate. - */ - async until(predicate) { - const current = this.get(); - if (predicate(current)) { - return current; - } - const { promise, resolve } = makePromise(); - const unsubscribe = this.subscribe(data => { - if (predicate(data)) { - resolve(data); - unsubscribe(); - } - }); - return await promise; - } -} - -function isAvailable(data) { - return data !== LazySignal.NOT_AVAILABLE; -} -/** - * A lazy signal is a signal that will only subscribe to the upstream when at least one subscriber - * is attached. It will unsubscribe from the upstream when the last subscriber is removed. - * - * A lazy signal can possess a special value "NOT_AVAILABLE", accessible from the static property - * {@link LazySignal.NOT_AVAILABLE}. This value is used to indicate that the value is not available - * yet. This can happen when the signal is created without an initial value and the upstream has not - * emitted a value yet. - */ -class LazySignal extends Subscribable { - static { this.NOT_AVAILABLE = Symbol("notAvailable"); } - static create(initialValue, subscribeUpstream, equalsPredicate = (a, b) => a === b) { - return new LazySignal(initialValue, subscribeUpstream, equalsPredicate); - } - static createWithoutInitialValue(subscribeUpstream, equalsPredicate = (a, b) => a === b) { - const fullEqualsPredicate = (a, b) => { - if (a === LazySignal.NOT_AVAILABLE || b === LazySignal.NOT_AVAILABLE) { - return a === b; - } - return equalsPredicate(a, b); - }; - return new LazySignal(LazySignal.NOT_AVAILABLE, subscribeUpstream, fullEqualsPredicate); - } - static deriveFrom(sourceSignals, deriver, outputEqualsPredicate) { - let fullEqualsPredicate = undefined; - if (outputEqualsPredicate !== undefined) { - fullEqualsPredicate = (a, b) => { - if (a === LazySignal.NOT_AVAILABLE || b === LazySignal.NOT_AVAILABLE) { - return a === b; - } - return outputEqualsPredicate(a, b); - }; - } - const derive = () => { - const sourceValues = sourceSignals.map(signal => signal.get()); - if (sourceValues.some(value => value === LazySignal.NOT_AVAILABLE)) { - return LazySignal.NOT_AVAILABLE; - } - return deriver(...sourceValues); - }; - return new LazySignal(derive(), setDownstream => { - const unsubscriber = sourceSignals.map(signal => signal.subscribe(() => { - const value = derive(); - if (isAvailable(value)) { - setDownstream(value); - } - })); - const newValue = derive(); - if (isAvailable(newValue)) { - setDownstream(newValue); - } - return () => { - unsubscriber.forEach(unsub => unsub()); - }; - }, fullEqualsPredicate); - } - static asyncDeriveFrom(strategy, sourceSignals, deriver, outputEqualsPredicate) { - let fullEqualsPredicate = undefined; - if (outputEqualsPredicate !== undefined) { - fullEqualsPredicate = (a, b) => { - if (a === LazySignal.NOT_AVAILABLE || b === LazySignal.NOT_AVAILABLE) { - return a === b; - } - return outputEqualsPredicate(a, b); - }; - } - let lastAppliedUpdateId = -1; - let lastIssuedUpdateId = -1; - return new LazySignal(LazySignal.NOT_AVAILABLE, setDownstream => { - const deriveAndUpdate = () => { - lastIssuedUpdateId++; - const updateId = lastIssuedUpdateId; - const sourceValues = sourceSignals.map(signal => signal.get()); - if (sourceValues.some(value => value === LazySignal.NOT_AVAILABLE)) { - return; - } - deriver(...sourceValues).then(result => { - if (!isAvailable(result)) { - return; - } - switch (strategy) { - case "eager": { - if (updateId > lastAppliedUpdateId) { - lastAppliedUpdateId = updateId; - setDownstream(result); - } - break; - } - default: { - const exhaustiveCheck = strategy; - throw new Error(`Unknown strategy: ${exhaustiveCheck}`); - } - } - }); - }; - const unsubscriber = sourceSignals.map(signal => signal.subscribe(() => { - deriveAndUpdate(); - })); - deriveAndUpdate(); - return () => { - unsubscriber.forEach(unsub => unsub()); - }; - }, fullEqualsPredicate); - } - constructor(initialValue, subscribeUpstream, equalsPredicate = (a, b) => a === b) { - super(); - this.subscribeUpstream = subscribeUpstream; - this.dataIsStale = true; - this.upstreamUnsubscribe = null; - this.subscribersCount = 0; - this.isSubscribedToUpstream = false; - this.updateReceivedSynchronousCallbacks = new Set(); - [this.signal, this.setValue] = Signal.create(initialValue, equalsPredicate); - [this.updateReceivedEvent, this.emitUpdateReceivedEvent] = Event.create(); - } - /** - * Returns whether the value is currently stale. - * - * A value is stale whenever the upstream subscription is not active. This can happen in three - * cases: - * - * 1. When no subscriber is attached to this signal, the signal will not subscribe to the - * upstream. In this case, the value is always stale. - * 2. When a subscriber is attached, but the upstream has not yet emitted a single value, the - * value is also stale. - * 3. When the upstream has emitted an error. In this case, the subscription to the upstream is - * terminated and the value is stale. - * - * If you wish to get the current value and ensure that it is not stale, use the method - * {@link LazySignal#pull}. - */ - isStale() { - return this.dataIsStale; - } - subscribeToUpstream() { - this.isSubscribedToUpstream = true; - let subscribed = true; - let becameStale = false; - const unsubscribeFromUpstream = this.subscribeUpstream(makeSetterWithPatches((updater, tags) => { - if (!subscribed) { - return; - } - this.setValue.withPatchUpdater(updater, tags); - this.dataIsStale = becameStale; - this.emitUpdateReceivedEvent(); - for (const callback of this.updateReceivedSynchronousCallbacks) { - callback(); - } - }), error => { - if (!subscribed) { - return; - } - Promise.reject(error); // Prints a global error for now - this.dataIsStale = true; - this.isSubscribedToUpstream = false; - this.upstreamUnsubscribe = null; - subscribed = false; - }); - this.upstreamUnsubscribe = () => { - if (subscribed) { - subscribed = false; - becameStale = true; - unsubscribeFromUpstream(); - } - }; - } - unsubscribeFromUpstream() { - this.isSubscribedToUpstream = false; - if (this.upstreamUnsubscribe !== null) { - this.upstreamUnsubscribe(); - this.upstreamUnsubscribe = null; - this.dataIsStale = true; - } - } - /** - * Gets the current value of the signal. If the value is not available, it will return - * {@link LazySignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is created - * without an initial value and the upstream has not emitted a value yet.) - * - * In addition, the value returned by this method may be stale. Use {@link LazySignal#isStale} to - * check if the value is stale. - * - * If you wish to get the current value and ensure that it is not stale, use the method - * {@link LazySignal#pull}. - */ - get() { - return this.signal.get(); - } - /** - * Pulls the current value of the signal. If the value is stale, it will subscribe and wait for - * the next value from the upstream and return it. - */ - async pull() { - const { promise, resolve } = makePromise(); - if (!this.isStale()) { - // If not stale, definitely not "NOT_AVAILABLE" - resolve(this.get()); - } - else { - const unsubscribe = this.subscribe(() => { }); - this.updateReceivedEvent.subscribeOnce(() => { - resolve(this.get()); - }); - promise.then(unsubscribe); - } - return promise; - } - /** - * If the data is not stale, the callback will be called synchronously with the current value. - * - * If the data is stale, it will pull the current value and call the callback with the value. - */ - runOnNextFreshData(callback) { - if (!this.isStale()) { - callback(this.get()); - } - else { - let unsubscribe = null; - const updateCallback = () => { - this.updateReceivedSynchronousCallbacks.delete(updateCallback); - callback(this.get()); - unsubscribe?.(); - }; - this.updateReceivedSynchronousCallbacks.add(updateCallback); - unsubscribe = this.subscribe(() => { }); - } - } - async ensureAvailable() { - await this.pull(); - return this; - } - subscribe(subscriber) { - if (!this.isSubscribedToUpstream) { - this.subscribeToUpstream(); - } - this.subscribersCount++; - const unsubscribe = this.signal.subscribe(subscriber); - let unsubscribeCalled = false; - return () => { - if (unsubscribeCalled) { - return; - } - unsubscribe(); - unsubscribeCalled = true; - this.subscribersCount--; - if (this.subscribersCount === 0 && this.isSubscribedToUpstream) { - this.unsubscribeFromUpstream(); - } - }; - } - subscribeFull(subscriber) { - if (!this.isSubscribedToUpstream) { - this.subscribeToUpstream(); - } - this.subscribersCount++; - const unsubscribe = this.signal.subscribeFull(subscriber); - let unsubscribeCalled = false; - return () => { - if (unsubscribeCalled) { - return; - } - unsubscribe(); - unsubscribeCalled = true; - this.subscribersCount--; - if (this.subscribersCount === 0 && this.isSubscribedToUpstream) { - this.unsubscribeFromUpstream(); - } - }; - } - /** - * Subscribes to the signal. Will not cause the signal to subscribe to the upstream. - */ - passiveSubscribe(subscriber) { - return this.signal.subscribe(subscriber); - } - passiveSubscribeFull(subscriber) { - return this.signal.subscribeFull(subscriber); - } - async until(predicate) { - const current = this.get(); - if (isAvailable(current) && predicate(current)) { - return current; - } - const { promise, resolve } = makePromise(); - const unsubscribe = this.subscribe(data => { - if (isAvailable(data) && predicate(data)) { - resolve(data); - unsubscribe(); - } - }); - return await promise; - } -} - -const apiServerPorts = [41343, 52993, 16141, 39414, 22931]; - -const waitForNextMicroTask = Symbol(); -/** - * A buffered event will buffer events in a queue if no subscribers are present. When a subscriber - * is added, all buffered events will trigger sequentially in the next microtask. - * - * Similar to Event, events are always emitted during the next microtask. - * - * Attempting to add more than one subscriber will resulting in an error. - */ -class BufferedEvent extends Subscribable { - static create() { - const event = new BufferedEvent(); - const emitter = data => { - event.emit(data); - }; - return [event, emitter]; - } - constructor() { - super(); - this.subscriber = null; - this.queued = []; - this.isNotifying = false; - } - emit(data) { - if (this.queued.length === 0 && this.queued.at(-1) !== waitForNextMicroTask) { - this.queued.push(waitForNextMicroTask); - } - this.queued.push(data); - if (!this.isNotifying) { - this.notifier(); - } - } - async notifier() { - this.isNotifying = true; - while (this.subscriber !== null && this.queued.length > 0) { - const data = this.queued.shift(); - if (data === waitForNextMicroTask) { - await Promise.resolve(); - } - else { - this.subscriber(data); - } - } - this.isNotifying = false; - } - subscribe(listener) { - if (this.subscriber !== null) { - throw new Error("Cannot have more than one subscriber"); - } - this.subscriber = listener; - if (!this.isNotifying && this.queued.length > 0) { - this.queued = [ - waitForNextMicroTask, - ...this.queued.filter(data => data !== waitForNextMicroTask), - ]; - this.notifier(); - } - return () => { - this.subscriber = null; - }; - } - /** - * Convert this buffered event to an event by stop buffering and triggering events on the new - * returned event. - */ - flow() { - const [event, emit] = Event.create(); - this.subscribe(emit); - return event; - } -} - -class CancelEvent extends Subscribable { - constructor() { - super(...arguments); - this.canceled = false; - this.listeners = new Set(); - } - subscribe(listener) { - if (this.canceled) { - let callbackCanceled = false; - Promise.resolve().then(() => { - if (!callbackCanceled) { - listener(); - } - }); - return () => { - callbackCanceled = true; - }; - } - this.listeners.add(listener); - return () => { - this.listeners.delete(listener); - }; - } - cancel() { - if (this.canceled) { - throw new Error("Already canceled"); - } - this.canceled = true; - for (const listener of this.listeners) { - listener(); - } - } - isCanceled() { - return this.canceled; - } -} - -class Cleaner { - constructor() { - this.eagerCleaned = false; - this.disposed = false; - this.cleanups = []; - } - register(fn) { - if (this.eagerCleaned) { - throw new Error("Cannot register a cleanup after eagerClean() was called."); - } - if (this.disposed) { - throw new Error("Cannot register a cleanup after the Cleaner was disposed."); - } - this.cleanups.push(fn); - } - runCleanersInternal() { - for (const cleanup of this.cleanups) { - cleanup(); - } - // Just to free some memory because why not - this.cleanups.length = 0; - } - [Symbol.dispose]() { - if (this.eagerCleaned) { - // Already eagerly cleaned. Nothing to do. - return; - } - if (this.disposed) { - throw new Error("Cannot dispose a Cleaner that was already disposed."); - } - this.runCleanersInternal(); - } - eagerClean() { - if (this.eagerCleaned) { - throw new Error("Cannot call eagerClean() twice."); - } - if (this.disposed) { - throw new Error("Cannot call eagerClean() after the Cleaner was disposed."); - } - this.eagerCleaned = true; - this.runCleanersInternal(); - } -} - -// Error stack manipulation related functions -function getCurrentStack(goAbove = 0) { - const stack = new Error().stack; - if (!stack) { - return ""; - } - const lines = stack.split("\n"); - return lines.slice(2 + goAbove).join("\n"); -} -function changeErrorStackInPlace(error, newStack) { - if (process$1.env.LMS_KEEP_INTERNAL_STACK) { - return; - } - const stackContent = error.stack ?? ""; - error.stack = (stackContent.substring(0, stackContent.indexOf("\n at ")).trimEnd() + - "\n" + - newStack).trimEnd(); -} - -class IdGiver { - constructor(firstId = 0) { - this.nextId = firstId; - } - next() { - const id = this.nextId; - this.nextId++; - return id; - } -} - -function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; -} - -var boxen$1 = {exports: {}}; - -var stringWidth = {exports: {}}; - -var ansiRegex; -var hasRequiredAnsiRegex; - -function requireAnsiRegex () { - if (hasRequiredAnsiRegex) return ansiRegex; - hasRequiredAnsiRegex = 1; - - ansiRegex = ({onlyFirst = false} = {}) => { - const pattern = [ - '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', - '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' - ].join('|'); - - return new RegExp(pattern, onlyFirst ? undefined : 'g'); - }; - return ansiRegex; -} - -var stripAnsi; -var hasRequiredStripAnsi; - -function requireStripAnsi () { - if (hasRequiredStripAnsi) return stripAnsi; - hasRequiredStripAnsi = 1; - const ansiRegex = requireAnsiRegex(); - - stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; - return stripAnsi; -} - -var isFullwidthCodePoint = {exports: {}}; - -/* eslint-disable yoda */ - -var hasRequiredIsFullwidthCodePoint; - -function requireIsFullwidthCodePoint () { - if (hasRequiredIsFullwidthCodePoint) return isFullwidthCodePoint.exports; - hasRequiredIsFullwidthCodePoint = 1; - - const isFullwidthCodePoint$1 = codePoint => { - if (Number.isNaN(codePoint)) { - return false; - } - - // Code points are derived from: - // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt - if ( - codePoint >= 0x1100 && ( - codePoint <= 0x115F || // Hangul Jamo - codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET - codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET - // CJK Radicals Supplement .. Enclosed CJK Letters and Months - (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || - // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A - (0x3250 <= codePoint && codePoint <= 0x4DBF) || - // CJK Unified Ideographs .. Yi Radicals - (0x4E00 <= codePoint && codePoint <= 0xA4C6) || - // Hangul Jamo Extended-A - (0xA960 <= codePoint && codePoint <= 0xA97C) || - // Hangul Syllables - (0xAC00 <= codePoint && codePoint <= 0xD7A3) || - // CJK Compatibility Ideographs - (0xF900 <= codePoint && codePoint <= 0xFAFF) || - // Vertical Forms - (0xFE10 <= codePoint && codePoint <= 0xFE19) || - // CJK Compatibility Forms .. Small Form Variants - (0xFE30 <= codePoint && codePoint <= 0xFE6B) || - // Halfwidth and Fullwidth Forms - (0xFF01 <= codePoint && codePoint <= 0xFF60) || - (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || - // Kana Supplement - (0x1B000 <= codePoint && codePoint <= 0x1B001) || - // Enclosed Ideographic Supplement - (0x1F200 <= codePoint && codePoint <= 0x1F251) || - // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane - (0x20000 <= codePoint && codePoint <= 0x3FFFD) - ) - ) { - return true; - } - - return false; - }; - - isFullwidthCodePoint.exports = isFullwidthCodePoint$1; - isFullwidthCodePoint.exports.default = isFullwidthCodePoint$1; - return isFullwidthCodePoint.exports; -} - -var emojiRegex; -var hasRequiredEmojiRegex; - -function requireEmojiRegex () { - if (hasRequiredEmojiRegex) return emojiRegex; - hasRequiredEmojiRegex = 1; - - emojiRegex = function () { - // https://mths.be/emoji - return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\u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4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; - }; - return emojiRegex; -} - -var hasRequiredStringWidth; - -function requireStringWidth () { - if (hasRequiredStringWidth) return stringWidth.exports; - hasRequiredStringWidth = 1; - const stripAnsi = requireStripAnsi(); - const isFullwidthCodePoint = requireIsFullwidthCodePoint(); - const emojiRegex = requireEmojiRegex(); - - const stringWidth$1 = string => { - if (typeof string !== 'string' || string.length === 0) { - return 0; - } - - string = stripAnsi(string); - - if (string.length === 0) { - return 0; - } - - string = string.replace(emojiRegex(), ' '); - - let width = 0; - - for (let i = 0; i < string.length; i++) { - const code = string.codePointAt(i); - - // Ignore control characters - if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { - continue; - } - - // Ignore combining characters - if (code >= 0x300 && code <= 0x36F) { - continue; - } - - // Surrogates - if (code > 0xFFFF) { - i++; - } - - width += isFullwidthCodePoint(code) ? 2 : 1; - } - - return width; - }; - - stringWidth.exports = stringWidth$1; - // TODO: remove this in the next major version - stringWidth.exports.default = stringWidth$1; - return stringWidth.exports; -} - -var widestLine = {exports: {}}; - -var hasRequiredWidestLine; - -function requireWidestLine () { - if (hasRequiredWidestLine) return widestLine.exports; - hasRequiredWidestLine = 1; - const stringWidth = requireStringWidth(); - - const widestLine$1 = input => { - let max = 0; - - for (const line of input.split('\n')) { - max = Math.max(max, stringWidth(line)); - } - - return max; - }; - - widestLine.exports = widestLine$1; - // TODO: remove this in the next major version - widestLine.exports.default = widestLine$1; - return widestLine.exports; -} - -var cliBoxes = {exports: {}}; - -var single = { - topLeft: "┌", - topRight: "┐", - bottomRight: "┘", - bottomLeft: "└", - vertical: "│", - horizontal: "─" -}; -var double = { - topLeft: "╔", - topRight: "╗", - bottomRight: "╝", - bottomLeft: "╚", - vertical: "║", - horizontal: "═" -}; -var round = { - topLeft: "╭", - topRight: "╮", - bottomRight: "╯", - bottomLeft: "╰", - vertical: "│", - horizontal: "─" -}; -var bold = { - topLeft: "┏", - topRight: "┓", - bottomRight: "┛", - bottomLeft: "┗", - vertical: "┃", - horizontal: "━" -}; -var singleDouble = { - topLeft: "╓", - topRight: "╖", - bottomRight: "╜", - bottomLeft: "╙", - vertical: "║", - horizontal: "─" -}; -var doubleSingle = { - topLeft: "╒", - topRight: "╕", - bottomRight: "╛", - bottomLeft: "╘", - vertical: "│", - horizontal: "═" -}; -var classic = { - topLeft: "+", - topRight: "+", - bottomRight: "+", - bottomLeft: "+", - vertical: "|", - horizontal: "-" -}; -var require$$0 = { - single: single, - double: double, - round: round, - bold: bold, - singleDouble: singleDouble, - doubleSingle: doubleSingle, - classic: classic -}; - -var hasRequiredCliBoxes; - -function requireCliBoxes () { - if (hasRequiredCliBoxes) return cliBoxes.exports; - hasRequiredCliBoxes = 1; - const cliBoxes$1 = require$$0; - - cliBoxes.exports = cliBoxes$1; - // TODO: Remove this for the next major release - cliBoxes.exports.default = cliBoxes$1; - return cliBoxes.exports; -} - -var camelcase = {exports: {}}; - -var hasRequiredCamelcase; - -function requireCamelcase () { - if (hasRequiredCamelcase) return camelcase.exports; - hasRequiredCamelcase = 1; - - const UPPERCASE = /[\p{Lu}]/u; - const LOWERCASE = /[\p{Ll}]/u; - const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu; - const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u; - const SEPARATORS = /[_.\- ]+/; - - const LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source); - const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu'); - const NUMBERS_AND_IDENTIFIER = new RegExp('\\d+' + IDENTIFIER.source, 'gu'); - - const preserveCamelCase = (string, toLowerCase, toUpperCase) => { - let isLastCharLower = false; - let isLastCharUpper = false; - let isLastLastCharUpper = false; - - for (let i = 0; i < string.length; i++) { - const character = string[i]; - - if (isLastCharLower && UPPERCASE.test(character)) { - string = string.slice(0, i) + '-' + string.slice(i); - isLastCharLower = false; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = true; - i++; - } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) { - string = string.slice(0, i - 1) + '-' + string.slice(i - 1); - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = false; - isLastCharLower = true; - } else { - isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character; - } - } - - return string; - }; - - const preserveConsecutiveUppercase = (input, toLowerCase) => { - LEADING_CAPITAL.lastIndex = 0; - - return input.replace(LEADING_CAPITAL, m1 => toLowerCase(m1)); - }; - - const postProcess = (input, toUpperCase) => { - SEPARATORS_AND_IDENTIFIER.lastIndex = 0; - NUMBERS_AND_IDENTIFIER.lastIndex = 0; - - return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier)) - .replace(NUMBERS_AND_IDENTIFIER, m => toUpperCase(m)); - }; - - const camelCase = (input, options) => { - if (!(typeof input === 'string' || Array.isArray(input))) { - throw new TypeError('Expected the input to be `string | string[]`'); - } - - options = { - pascalCase: false, - preserveConsecutiveUppercase: false, - ...options - }; - - if (Array.isArray(input)) { - input = input.map(x => x.trim()) - .filter(x => x.length) - .join('-'); - } else { - input = input.trim(); - } - - if (input.length === 0) { - return ''; - } - - const toLowerCase = options.locale === false ? - string => string.toLowerCase() : - string => string.toLocaleLowerCase(options.locale); - const toUpperCase = options.locale === false ? - string => string.toUpperCase() : - string => string.toLocaleUpperCase(options.locale); - - if (input.length === 1) { - return options.pascalCase ? toUpperCase(input) : toLowerCase(input); - } - - const hasUpperCase = input !== toLowerCase(input); - - if (hasUpperCase) { - input = preserveCamelCase(input, toLowerCase, toUpperCase); - } - - input = input.replace(LEADING_SEPARATORS, ''); - - if (options.preserveConsecutiveUppercase) { - input = preserveConsecutiveUppercase(input, toLowerCase); - } else { - input = toLowerCase(input); - } - - if (options.pascalCase) { - input = toUpperCase(input.charAt(0)) + input.slice(1); - } - - return postProcess(input, toUpperCase); - }; - - camelcase.exports = camelCase; - // TODO: Remove this for the next major release - camelcase.exports.default = camelCase; - return camelcase.exports; -} - -var ansiAlign_1; -var hasRequiredAnsiAlign; - -function requireAnsiAlign () { - if (hasRequiredAnsiAlign) return ansiAlign_1; - hasRequiredAnsiAlign = 1; - - const stringWidth = requireStringWidth(); - - function ansiAlign (text, opts) { - if (!text) return text - - opts = opts || {}; - const align = opts.align || 'center'; - - // short-circuit `align: 'left'` as no-op - if (align === 'left') return text - - const split = opts.split || '\n'; - const pad = opts.pad || ' '; - const widthDiffFn = align !== 'right' ? halfDiff : fullDiff; - - let returnString = false; - if (!Array.isArray(text)) { - returnString = true; - text = String(text).split(split); - } - - let width; - let maxWidth = 0; - text = text.map(function (str) { - str = String(str); - width = stringWidth(str); - maxWidth = Math.max(width, maxWidth); - return { - str, - width - } - }).map(function (obj) { - return new Array(widthDiffFn(maxWidth, obj.width) + 1).join(pad) + obj.str - }); - - return returnString ? text.join(split) : text - } - - ansiAlign.left = function left (text) { - return ansiAlign(text, { align: 'left' }) - }; - - ansiAlign.center = function center (text) { - return ansiAlign(text, { align: 'center' }) - }; - - ansiAlign.right = function right (text) { - return ansiAlign(text, { align: 'right' }) - }; - - ansiAlign_1 = ansiAlign; - - function halfDiff (maxWidth, curWidth) { - return Math.floor((maxWidth - curWidth) / 2) - } - - function fullDiff (maxWidth, curWidth) { - return maxWidth - curWidth - } - return ansiAlign_1; -} - -var ansiStyles = {exports: {}}; - -var colorName; -var hasRequiredColorName; - -function requireColorName () { - if (hasRequiredColorName) return colorName; - hasRequiredColorName = 1; - - colorName = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aqua": [0, 255, 255], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 219], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [219, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "rebeccapurple": [102, 51, 153], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] - }; - return colorName; -} - -/* MIT license */ - -var conversions; -var hasRequiredConversions; - -function requireConversions () { - if (hasRequiredConversions) return conversions; - hasRequiredConversions = 1; - /* eslint-disable no-mixed-operators */ - const cssKeywords = requireColorName(); - - // NOTE: conversions should only return primitive values (i.e. arrays, or - // values that give correct `typeof` results). - // do not use box values types (i.e. Number(), String(), etc.) - - const reverseKeywords = {}; - for (const key of Object.keys(cssKeywords)) { - reverseKeywords[cssKeywords[key]] = key; - } - - const convert = { - rgb: {channels: 3, labels: 'rgb'}, - hsl: {channels: 3, labels: 'hsl'}, - hsv: {channels: 3, labels: 'hsv'}, - hwb: {channels: 3, labels: 'hwb'}, - cmyk: {channels: 4, labels: 'cmyk'}, - xyz: {channels: 3, labels: 'xyz'}, - lab: {channels: 3, labels: 'lab'}, - lch: {channels: 3, labels: 'lch'}, - hex: {channels: 1, labels: ['hex']}, - keyword: {channels: 1, labels: ['keyword']}, - ansi16: {channels: 1, labels: ['ansi16']}, - ansi256: {channels: 1, labels: ['ansi256']}, - hcg: {channels: 3, labels: ['h', 'c', 'g']}, - apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, - gray: {channels: 1, labels: ['gray']} - }; - - conversions = convert; - - // Hide .channels and .labels properties - for (const model of Object.keys(convert)) { - if (!('channels' in convert[model])) { - throw new Error('missing channels property: ' + model); - } - - if (!('labels' in convert[model])) { - throw new Error('missing channel labels property: ' + model); - } - - if (convert[model].labels.length !== convert[model].channels) { - throw new Error('channel and label counts mismatch: ' + model); - } - - const {channels, labels} = convert[model]; - delete convert[model].channels; - delete convert[model].labels; - Object.defineProperty(convert[model], 'channels', {value: channels}); - Object.defineProperty(convert[model], 'labels', {value: labels}); - } - - convert.rgb.hsl = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const min = Math.min(r, g, b); - const max = Math.max(r, g, b); - const delta = max - min; - let h; - let s; - - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta; - } else if (g === max) { - h = 2 + (b - r) / delta; - } else if (b === max) { - h = 4 + (r - g) / delta; - } - - h = Math.min(h * 60, 360); - - if (h < 0) { - h += 360; - } - - const l = (min + max) / 2; - - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta / (max + min); - } else { - s = delta / (2 - max - min); - } - - return [h, s * 100, l * 100]; - }; - - convert.rgb.hsv = function (rgb) { - let rdif; - let gdif; - let bdif; - let h; - let s; - - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const v = Math.max(r, g, b); - const diff = v - Math.min(r, g, b); - const diffc = function (c) { - return (v - c) / 6 / diff + 1 / 2; - }; - - if (diff === 0) { - h = 0; - s = 0; - } else { - s = diff / v; - rdif = diffc(r); - gdif = diffc(g); - bdif = diffc(b); - - if (r === v) { - h = bdif - gdif; - } else if (g === v) { - h = (1 / 3) + rdif - bdif; - } else if (b === v) { - h = (2 / 3) + gdif - rdif; - } - - if (h < 0) { - h += 1; - } else if (h > 1) { - h -= 1; - } - } - - return [ - h * 360, - s * 100, - v * 100 - ]; - }; - - convert.rgb.hwb = function (rgb) { - const r = rgb[0]; - const g = rgb[1]; - let b = rgb[2]; - const h = convert.rgb.hsl(rgb)[0]; - const w = 1 / 255 * Math.min(r, Math.min(g, b)); - - b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); - - return [h, w * 100, b * 100]; - }; - - convert.rgb.cmyk = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - - const k = Math.min(1 - r, 1 - g, 1 - b); - const c = (1 - r - k) / (1 - k) || 0; - const m = (1 - g - k) / (1 - k) || 0; - const y = (1 - b - k) / (1 - k) || 0; - - return [c * 100, m * 100, y * 100, k * 100]; - }; - - function comparativeDistance(x, y) { - /* - See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance - */ - return ( - ((x[0] - y[0]) ** 2) + - ((x[1] - y[1]) ** 2) + - ((x[2] - y[2]) ** 2) - ); - } - - convert.rgb.keyword = function (rgb) { - const reversed = reverseKeywords[rgb]; - if (reversed) { - return reversed; - } - - let currentClosestDistance = Infinity; - let currentClosestKeyword; - - for (const keyword of Object.keys(cssKeywords)) { - const value = cssKeywords[keyword]; - - // Compute comparative distance - const distance = comparativeDistance(rgb, value); - - // Check if its less, if so set as closest - if (distance < currentClosestDistance) { - currentClosestDistance = distance; - currentClosestKeyword = keyword; - } - } - - return currentClosestKeyword; - }; - - convert.keyword.rgb = function (keyword) { - return cssKeywords[keyword]; - }; - - convert.rgb.xyz = function (rgb) { - let r = rgb[0] / 255; - let g = rgb[1] / 255; - let b = rgb[2] / 255; - - // Assume sRGB - r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); - g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); - b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); - - const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); - const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); - const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); - - return [x * 100, y * 100, z * 100]; - }; - - convert.rgb.lab = function (rgb) { - const xyz = convert.rgb.xyz(rgb); - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; - - x /= 95.047; - y /= 100; - z /= 108.883; - - x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); - - const l = (116 * y) - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); - - return [l, a, b]; - }; - - convert.hsl.rgb = function (hsl) { - const h = hsl[0] / 360; - const s = hsl[1] / 100; - const l = hsl[2] / 100; - let t2; - let t3; - let val; - - if (s === 0) { - val = l * 255; - return [val, val, val]; - } - - if (l < 0.5) { - t2 = l * (1 + s); - } else { - t2 = l + s - l * s; - } - - const t1 = 2 * l - t2; - - const rgb = [0, 0, 0]; - for (let i = 0; i < 3; i++) { - t3 = h + 1 / 3 * -(i - 1); - if (t3 < 0) { - t3++; - } - - if (t3 > 1) { - t3--; - } - - if (6 * t3 < 1) { - val = t1 + (t2 - t1) * 6 * t3; - } else if (2 * t3 < 1) { - val = t2; - } else if (3 * t3 < 2) { - val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; - } else { - val = t1; - } - - rgb[i] = val * 255; - } - - return rgb; - }; - - convert.hsl.hsv = function (hsl) { - const h = hsl[0]; - let s = hsl[1] / 100; - let l = hsl[2] / 100; - let smin = s; - const lmin = Math.max(l, 0.01); - - l *= 2; - s *= (l <= 1) ? l : 2 - l; - smin *= lmin <= 1 ? lmin : 2 - lmin; - const v = (l + s) / 2; - const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); - - return [h, sv * 100, v * 100]; - }; - - convert.hsv.rgb = function (hsv) { - const h = hsv[0] / 60; - const s = hsv[1] / 100; - let v = hsv[2] / 100; - const hi = Math.floor(h) % 6; - - const f = h - Math.floor(h); - const p = 255 * v * (1 - s); - const q = 255 * v * (1 - (s * f)); - const t = 255 * v * (1 - (s * (1 - f))); - v *= 255; - - switch (hi) { - case 0: - return [v, t, p]; - case 1: - return [q, v, p]; - case 2: - return [p, v, t]; - case 3: - return [p, q, v]; - case 4: - return [t, p, v]; - case 5: - return [v, p, q]; - } - }; - - convert.hsv.hsl = function (hsv) { - const h = hsv[0]; - const s = hsv[1] / 100; - const v = hsv[2] / 100; - const vmin = Math.max(v, 0.01); - let sl; - let l; - - l = (2 - s) * v; - const lmin = (2 - s) * vmin; - sl = s * vmin; - sl /= (lmin <= 1) ? lmin : 2 - lmin; - sl = sl || 0; - l /= 2; - - return [h, sl * 100, l * 100]; - }; - - // http://dev.w3.org/csswg/css-color/#hwb-to-rgb - convert.hwb.rgb = function (hwb) { - const h = hwb[0] / 360; - let wh = hwb[1] / 100; - let bl = hwb[2] / 100; - const ratio = wh + bl; - let f; - - // Wh + bl cant be > 1 - if (ratio > 1) { - wh /= ratio; - bl /= ratio; - } - - const i = Math.floor(6 * h); - const v = 1 - bl; - f = 6 * h - i; - - if ((i & 0x01) !== 0) { - f = 1 - f; - } - - const n = wh + f * (v - wh); // Linear interpolation - - let r; - let g; - let b; - /* eslint-disable max-statements-per-line,no-multi-spaces */ - switch (i) { - default: - case 6: - case 0: r = v; g = n; b = wh; break; - case 1: r = n; g = v; b = wh; break; - case 2: r = wh; g = v; b = n; break; - case 3: r = wh; g = n; b = v; break; - case 4: r = n; g = wh; b = v; break; - case 5: r = v; g = wh; b = n; break; - } - /* eslint-enable max-statements-per-line,no-multi-spaces */ - - return [r * 255, g * 255, b * 255]; - }; - - convert.cmyk.rgb = function (cmyk) { - const c = cmyk[0] / 100; - const m = cmyk[1] / 100; - const y = cmyk[2] / 100; - const k = cmyk[3] / 100; - - const r = 1 - Math.min(1, c * (1 - k) + k); - const g = 1 - Math.min(1, m * (1 - k) + k); - const b = 1 - Math.min(1, y * (1 - k) + k); - - return [r * 255, g * 255, b * 255]; - }; - - convert.xyz.rgb = function (xyz) { - const x = xyz[0] / 100; - const y = xyz[1] / 100; - const z = xyz[2] / 100; - let r; - let g; - let b; - - r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); - g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); - b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); - - // Assume sRGB - r = r > 0.0031308 - ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) - : r * 12.92; - - g = g > 0.0031308 - ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) - : g * 12.92; - - b = b > 0.0031308 - ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) - : b * 12.92; - - r = Math.min(Math.max(0, r), 1); - g = Math.min(Math.max(0, g), 1); - b = Math.min(Math.max(0, b), 1); - - return [r * 255, g * 255, b * 255]; - }; - - convert.xyz.lab = function (xyz) { - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; - - x /= 95.047; - y /= 100; - z /= 108.883; - - x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); - - const l = (116 * y) - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); - - return [l, a, b]; - }; - - convert.lab.xyz = function (lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let x; - let y; - let z; - - y = (l + 16) / 116; - x = a / 500 + y; - z = y - b / 200; - - const y2 = y ** 3; - const x2 = x ** 3; - const z2 = z ** 3; - y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; - x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; - z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; - - x *= 95.047; - y *= 100; - z *= 108.883; - - return [x, y, z]; - }; - - convert.lab.lch = function (lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let h; - - const hr = Math.atan2(b, a); - h = hr * 360 / 2 / Math.PI; - - if (h < 0) { - h += 360; - } - - const c = Math.sqrt(a * a + b * b); - - return [l, c, h]; - }; - - convert.lch.lab = function (lch) { - const l = lch[0]; - const c = lch[1]; - const h = lch[2]; - - const hr = h / 360 * 2 * Math.PI; - const a = c * Math.cos(hr); - const b = c * Math.sin(hr); - - return [l, a, b]; - }; - - convert.rgb.ansi16 = function (args, saturation = null) { - const [r, g, b] = args; - let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization - - value = Math.round(value / 50); - - if (value === 0) { - return 30; - } - - let ansi = 30 - + ((Math.round(b / 255) << 2) - | (Math.round(g / 255) << 1) - | Math.round(r / 255)); - - if (value === 2) { - ansi += 60; - } - - return ansi; - }; - - convert.hsv.ansi16 = function (args) { - // Optimization here; we already know the value and don't need to get - // it converted for us. - return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); - }; - - convert.rgb.ansi256 = function (args) { - const r = args[0]; - const g = args[1]; - const b = args[2]; - - // We use the extended greyscale palette here, with the exception of - // black and white. normal palette only has 4 greyscale shades. - if (r === g && g === b) { - if (r < 8) { - return 16; - } - - if (r > 248) { - return 231; - } - - return Math.round(((r - 8) / 247) * 24) + 232; - } - - const ansi = 16 - + (36 * Math.round(r / 255 * 5)) - + (6 * Math.round(g / 255 * 5)) - + Math.round(b / 255 * 5); - - return ansi; - }; - - convert.ansi16.rgb = function (args) { - let color = args % 10; - - // Handle greyscale - if (color === 0 || color === 7) { - if (args > 50) { - color += 3.5; - } - - color = color / 10.5 * 255; - - return [color, color, color]; - } - - const mult = (~~(args > 50) + 1) * 0.5; - const r = ((color & 1) * mult) * 255; - const g = (((color >> 1) & 1) * mult) * 255; - const b = (((color >> 2) & 1) * mult) * 255; - - return [r, g, b]; - }; - - convert.ansi256.rgb = function (args) { - // Handle greyscale - if (args >= 232) { - const c = (args - 232) * 10 + 8; - return [c, c, c]; - } - - args -= 16; - - let rem; - const r = Math.floor(args / 36) / 5 * 255; - const g = Math.floor((rem = args % 36) / 6) / 5 * 255; - const b = (rem % 6) / 5 * 255; - - return [r, g, b]; - }; - - convert.rgb.hex = function (args) { - const integer = ((Math.round(args[0]) & 0xFF) << 16) - + ((Math.round(args[1]) & 0xFF) << 8) - + (Math.round(args[2]) & 0xFF); - - const string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; - }; - - convert.hex.rgb = function (args) { - const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); - if (!match) { - return [0, 0, 0]; - } - - let colorString = match[0]; - - if (match[0].length === 3) { - colorString = colorString.split('').map(char => { - return char + char; - }).join(''); - } - - const integer = parseInt(colorString, 16); - const r = (integer >> 16) & 0xFF; - const g = (integer >> 8) & 0xFF; - const b = integer & 0xFF; - - return [r, g, b]; - }; - - convert.rgb.hcg = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const max = Math.max(Math.max(r, g), b); - const min = Math.min(Math.min(r, g), b); - const chroma = (max - min); - let grayscale; - let hue; - - if (chroma < 1) { - grayscale = min / (1 - chroma); - } else { - grayscale = 0; - } - - if (chroma <= 0) { - hue = 0; - } else - if (max === r) { - hue = ((g - b) / chroma) % 6; - } else - if (max === g) { - hue = 2 + (b - r) / chroma; - } else { - hue = 4 + (r - g) / chroma; - } - - hue /= 6; - hue %= 1; - - return [hue * 360, chroma * 100, grayscale * 100]; - }; - - convert.hsl.hcg = function (hsl) { - const s = hsl[1] / 100; - const l = hsl[2] / 100; - - const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); - - let f = 0; - if (c < 1.0) { - f = (l - 0.5 * c) / (1.0 - c); - } - - return [hsl[0], c * 100, f * 100]; - }; - - convert.hsv.hcg = function (hsv) { - const s = hsv[1] / 100; - const v = hsv[2] / 100; - - const c = s * v; - let f = 0; - - if (c < 1.0) { - f = (v - c) / (1 - c); - } - - return [hsv[0], c * 100, f * 100]; - }; - - convert.hcg.rgb = function (hcg) { - const h = hcg[0] / 360; - const c = hcg[1] / 100; - const g = hcg[2] / 100; - - if (c === 0.0) { - return [g * 255, g * 255, g * 255]; - } - - const pure = [0, 0, 0]; - const hi = (h % 1) * 6; - const v = hi % 1; - const w = 1 - v; - let mg = 0; - - /* eslint-disable max-statements-per-line */ - switch (Math.floor(hi)) { - case 0: - pure[0] = 1; pure[1] = v; pure[2] = 0; break; - case 1: - pure[0] = w; pure[1] = 1; pure[2] = 0; break; - case 2: - pure[0] = 0; pure[1] = 1; pure[2] = v; break; - case 3: - pure[0] = 0; pure[1] = w; pure[2] = 1; break; - case 4: - pure[0] = v; pure[1] = 0; pure[2] = 1; break; - default: - pure[0] = 1; pure[1] = 0; pure[2] = w; - } - /* eslint-enable max-statements-per-line */ - - mg = (1.0 - c) * g; - - return [ - (c * pure[0] + mg) * 255, - (c * pure[1] + mg) * 255, - (c * pure[2] + mg) * 255 - ]; - }; - - convert.hcg.hsv = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - - const v = c + g * (1.0 - c); - let f = 0; - - if (v > 0.0) { - f = c / v; - } - - return [hcg[0], f * 100, v * 100]; - }; - - convert.hcg.hsl = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - - const l = g * (1.0 - c) + 0.5 * c; - let s = 0; - - if (l > 0.0 && l < 0.5) { - s = c / (2 * l); - } else - if (l >= 0.5 && l < 1.0) { - s = c / (2 * (1 - l)); - } - - return [hcg[0], s * 100, l * 100]; - }; - - convert.hcg.hwb = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - const v = c + g * (1.0 - c); - return [hcg[0], (v - c) * 100, (1 - v) * 100]; - }; - - convert.hwb.hcg = function (hwb) { - const w = hwb[1] / 100; - const b = hwb[2] / 100; - const v = 1 - b; - const c = v - w; - let g = 0; - - if (c < 1) { - g = (v - c) / (1 - c); - } - - return [hwb[0], c * 100, g * 100]; - }; - - convert.apple.rgb = function (apple) { - return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; - }; - - convert.rgb.apple = function (rgb) { - return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; - }; - - convert.gray.rgb = function (args) { - return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; - }; - - convert.gray.hsl = function (args) { - return [0, 0, args[0]]; - }; - - convert.gray.hsv = convert.gray.hsl; - - convert.gray.hwb = function (gray) { - return [0, 100, gray[0]]; - }; - - convert.gray.cmyk = function (gray) { - return [0, 0, 0, gray[0]]; - }; - - convert.gray.lab = function (gray) { - return [gray[0], 0, 0]; - }; - - convert.gray.hex = function (gray) { - const val = Math.round(gray[0] / 100 * 255) & 0xFF; - const integer = (val << 16) + (val << 8) + val; - - const string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; - }; - - convert.rgb.gray = function (rgb) { - const val = (rgb[0] + rgb[1] + rgb[2]) / 3; - return [val / 255 * 100]; - }; - return conversions; -} - -var route; -var hasRequiredRoute; - -function requireRoute () { - if (hasRequiredRoute) return route; - hasRequiredRoute = 1; - const conversions = requireConversions(); - - /* - This function routes a model to all other models. - - all functions that are routed have a property `.conversion` attached - to the returned synthetic function. This property is an array - of strings, each with the steps in between the 'from' and 'to' - color models (inclusive). - - conversions that are not possible simply are not included. - */ - - function buildGraph() { - const graph = {}; - // https://jsperf.com/object-keys-vs-for-in-with-closure/3 - const models = Object.keys(conversions); - - for (let len = models.length, i = 0; i < len; i++) { - graph[models[i]] = { - // http://jsperf.com/1-vs-infinity - // micro-opt, but this is simple. - distance: -1, - parent: null - }; - } - - return graph; - } - - // https://en.wikipedia.org/wiki/Breadth-first_search - function deriveBFS(fromModel) { - const graph = buildGraph(); - const queue = [fromModel]; // Unshift -> queue -> pop - - graph[fromModel].distance = 0; - - while (queue.length) { - const current = queue.pop(); - const adjacents = Object.keys(conversions[current]); - - for (let len = adjacents.length, i = 0; i < len; i++) { - const adjacent = adjacents[i]; - const node = graph[adjacent]; - - if (node.distance === -1) { - node.distance = graph[current].distance + 1; - node.parent = current; - queue.unshift(adjacent); - } - } - } - - return graph; - } - - function link(from, to) { - return function (args) { - return to(from(args)); - }; - } - - function wrapConversion(toModel, graph) { - const path = [graph[toModel].parent, toModel]; - let fn = conversions[graph[toModel].parent][toModel]; - - let cur = graph[toModel].parent; - while (graph[cur].parent) { - path.unshift(graph[cur].parent); - fn = link(conversions[graph[cur].parent][cur], fn); - cur = graph[cur].parent; - } - - fn.conversion = path; - return fn; - } - - route = function (fromModel) { - const graph = deriveBFS(fromModel); - const conversion = {}; - - const models = Object.keys(graph); - for (let len = models.length, i = 0; i < len; i++) { - const toModel = models[i]; - const node = graph[toModel]; - - if (node.parent === null) { - // No possible conversion, or this node is the source model. - continue; - } - - conversion[toModel] = wrapConversion(toModel, graph); - } - - return conversion; - }; - return route; -} - -var colorConvert; -var hasRequiredColorConvert; - -function requireColorConvert () { - if (hasRequiredColorConvert) return colorConvert; - hasRequiredColorConvert = 1; - const conversions = requireConversions(); - const route = requireRoute(); - - const convert = {}; - - const models = Object.keys(conversions); - - function wrapRaw(fn) { - const wrappedFn = function (...args) { - const arg0 = args[0]; - if (arg0 === undefined || arg0 === null) { - return arg0; - } - - if (arg0.length > 1) { - args = arg0; - } - - return fn(args); - }; - - // Preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; - } - - function wrapRounded(fn) { - const wrappedFn = function (...args) { - const arg0 = args[0]; - - if (arg0 === undefined || arg0 === null) { - return arg0; - } - - if (arg0.length > 1) { - args = arg0; - } - - const result = fn(args); - - // We're assuming the result is an array here. - // see notice in conversions.js; don't use box types - // in conversion functions. - if (typeof result === 'object') { - for (let len = result.length, i = 0; i < len; i++) { - result[i] = Math.round(result[i]); - } - } - - return result; - }; - - // Preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; - } - - models.forEach(fromModel => { - convert[fromModel] = {}; - - Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); - Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); - - const routes = route(fromModel); - const routeModels = Object.keys(routes); - - routeModels.forEach(toModel => { - const fn = routes[toModel]; - - convert[fromModel][toModel] = wrapRounded(fn); - convert[fromModel][toModel].raw = wrapRaw(fn); - }); - }); - - colorConvert = convert; - return colorConvert; -} - -ansiStyles.exports; - -var hasRequiredAnsiStyles; - -function requireAnsiStyles () { - if (hasRequiredAnsiStyles) return ansiStyles.exports; - hasRequiredAnsiStyles = 1; - (function (module) { - - const wrapAnsi16 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${code + offset}m`; - }; - - const wrapAnsi256 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${38 + offset};5;${code}m`; - }; - - const wrapAnsi16m = (fn, offset) => (...args) => { - const rgb = fn(...args); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; - }; - - const ansi2ansi = n => n; - const rgb2rgb = (r, g, b) => [r, g, b]; - - const setLazyProperty = (object, property, get) => { - Object.defineProperty(object, property, { - get: () => { - const value = get(); - - Object.defineProperty(object, property, { - value, - enumerable: true, - configurable: true - }); - - return value; - }, - enumerable: true, - configurable: true - }); - }; - - /** @type {typeof import('color-convert')} */ - let colorConvert; - const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { - if (colorConvert === undefined) { - colorConvert = requireColorConvert(); - } - - const offset = isBackground ? 10 : 0; - const styles = {}; - - for (const [sourceSpace, suite] of Object.entries(colorConvert)) { - const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; - if (sourceSpace === targetSpace) { - styles[name] = wrap(identity, offset); - } else if (typeof suite === 'object') { - styles[name] = wrap(suite[targetSpace], offset); - } - } - - return styles; - }; - - function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - - // Bright color - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - - // Alias bright black as gray (and grey) - styles.color.gray = styles.color.blackBright; - styles.bgColor.bgGray = styles.bgColor.bgBlackBright; - styles.color.grey = styles.color.blackBright; - styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; - - for (const [groupName, group] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group)) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; - - group[styleName] = styles[styleName]; - - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - } - - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; - - setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); - setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); - - return styles; - } - - // Make the export immutable - Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles - }); - } (ansiStyles)); - return ansiStyles.exports; -} - -var wrapAnsi_1; -var hasRequiredWrapAnsi; - -function requireWrapAnsi () { - if (hasRequiredWrapAnsi) return wrapAnsi_1; - hasRequiredWrapAnsi = 1; - const stringWidth = requireStringWidth(); - const stripAnsi = requireStripAnsi(); - const ansiStyles = requireAnsiStyles(); - - const ESCAPES = new Set([ - '\u001B', - '\u009B' - ]); - - const END_CODE = 39; - - const ANSI_ESCAPE_BELL = '\u0007'; - const ANSI_CSI = '['; - const ANSI_OSC = ']'; - const ANSI_SGR_TERMINATOR = 'm'; - const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`; - - const wrapAnsi = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`; - const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`; - - // Calculate the length of words split on ' ', ignoring - // the extra characters added by ansi escape codes - const wordLengths = string => string.split(' ').map(character => stringWidth(character)); - - // Wrap a long word across multiple rows - // Ansi escape codes do not count towards length - const wrapWord = (rows, word, columns) => { - const characters = [...word]; - - let isInsideEscape = false; - let isInsideLinkEscape = false; - let visible = stringWidth(stripAnsi(rows[rows.length - 1])); - - for (const [index, character] of characters.entries()) { - const characterLength = stringWidth(character); - - if (visible + characterLength <= columns) { - rows[rows.length - 1] += character; - } else { - rows.push(character); - visible = 0; - } - - if (ESCAPES.has(character)) { - isInsideEscape = true; - isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK); - } - - if (isInsideEscape) { - if (isInsideLinkEscape) { - if (character === ANSI_ESCAPE_BELL) { - isInsideEscape = false; - isInsideLinkEscape = false; - } - } else if (character === ANSI_SGR_TERMINATOR) { - isInsideEscape = false; - } - - continue; - } - - visible += characterLength; - - if (visible === columns && index < characters.length - 1) { - rows.push(''); - visible = 0; - } - } - - // It's possible that the last row we copy over is only - // ansi escape characters, handle this edge-case - if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { - rows[rows.length - 2] += rows.pop(); - } - }; - - // Trims spaces from a string ignoring invisible sequences - const stringVisibleTrimSpacesRight = string => { - const words = string.split(' '); - let last = words.length; - - while (last > 0) { - if (stringWidth(words[last - 1]) > 0) { - break; - } - - last--; - } - - if (last === words.length) { - return string; - } - - return words.slice(0, last).join(' ') + words.slice(last).join(''); - }; - - // The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode - // - // 'hard' will never allow a string to take up more than columns characters - // - // 'soft' allows long words to expand past the column length - const exec = (string, columns, options = {}) => { - if (options.trim !== false && string.trim() === '') { - return ''; - } - - let returnValue = ''; - let escapeCode; - let escapeUrl; - - const lengths = wordLengths(string); - let rows = ['']; - - for (const [index, word] of string.split(' ').entries()) { - if (options.trim !== false) { - rows[rows.length - 1] = rows[rows.length - 1].trimStart(); - } - - let rowLength = stringWidth(rows[rows.length - 1]); - - if (index !== 0) { - if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { - // If we start with a new word but the current row length equals the length of the columns, add a new row - rows.push(''); - rowLength = 0; - } - - if (rowLength > 0 || options.trim === false) { - rows[rows.length - 1] += ' '; - rowLength++; - } - } - - // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' - if (options.hard && lengths[index] > columns) { - const remainingColumns = (columns - rowLength); - const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); - const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); - if (breaksStartingNextLine < breaksStartingThisLine) { - rows.push(''); - } - - wrapWord(rows, word, columns); - continue; - } - - if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { - if (options.wordWrap === false && rowLength < columns) { - wrapWord(rows, word, columns); - continue; - } - - rows.push(''); - } - - if (rowLength + lengths[index] > columns && options.wordWrap === false) { - wrapWord(rows, word, columns); - continue; - } - - rows[rows.length - 1] += word; - } - - if (options.trim !== false) { - rows = rows.map(stringVisibleTrimSpacesRight); - } - - const pre = [...rows.join('\n')]; - - for (const [index, character] of pre.entries()) { - returnValue += character; - - if (ESCAPES.has(character)) { - const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}}; - if (groups.code !== undefined) { - const code = Number.parseFloat(groups.code); - escapeCode = code === END_CODE ? undefined : code; - } else if (groups.uri !== undefined) { - escapeUrl = groups.uri.length === 0 ? undefined : groups.uri; - } - } - - const code = ansiStyles.codes.get(Number(escapeCode)); - - if (pre[index + 1] === '\n') { - if (escapeUrl) { - returnValue += wrapAnsiHyperlink(''); - } - - if (escapeCode && code) { - returnValue += wrapAnsi(code); - } - } else if (character === '\n') { - if (escapeCode && code) { - returnValue += wrapAnsi(escapeCode); - } - - if (escapeUrl) { - returnValue += wrapAnsiHyperlink(escapeUrl); - } - } - } - - return returnValue; - }; - - // For each newline, invoke the method separately - wrapAnsi_1 = (string, columns, options) => { - return String(string) - .normalize() - .replace(/\r\n/g, '\n') - .split('\n') - .map(line => exec(line, columns, options)) - .join('\n'); - }; - return wrapAnsi_1; -} - -var hasRequiredBoxen; - -function requireBoxen () { - if (hasRequiredBoxen) return boxen$1.exports; - hasRequiredBoxen = 1; - const stringWidth = requireStringWidth(); - const chalk$1 = chalk; - const widestLine = requireWidestLine(); - const cliBoxes = requireCliBoxes(); - const camelCase = requireCamelcase(); - const ansiAlign = requireAnsiAlign(); - const wrapAnsi = requireWrapAnsi(); - - const NL = '\n'; - const PAD = ' '; - - const terminalColumns = () => { - const {env, stdout, stderr} = process; - - if (stdout && stdout.columns) { - return stdout.columns; - } - - if (stderr && stderr.columns) { - return stderr.columns; - } - - if (env.COLUMNS) { - return Number.parseInt(env.COLUMNS, 10); - } - - return 80; - }; - - const getObject = detail => { - return typeof detail === 'number' ? { - top: detail, - right: detail * 3, - bottom: detail, - left: detail * 3 - } : { - top: 0, - right: 0, - bottom: 0, - left: 0, - ...detail - }; - }; - - const getBorderChars = borderStyle => { - const sides = [ - 'topLeft', - 'topRight', - 'bottomRight', - 'bottomLeft', - 'vertical', - 'horizontal' - ]; - - let chararacters; - - if (typeof borderStyle === 'string') { - chararacters = cliBoxes[borderStyle]; - - if (!chararacters) { - throw new TypeError(`Invalid border style: ${borderStyle}`); - } - } else { - for (const side of sides) { - if (!borderStyle[side] || typeof borderStyle[side] !== 'string') { - throw new TypeError(`Invalid border style: ${side}`); - } - } - - chararacters = borderStyle; - } - - return chararacters; - }; - - const makeTitle = (text, horizontal, alignement) => { - let title = ''; - - const textWidth = stringWidth(text); - - switch (alignement) { - case 'left': - title = text + horizontal.slice(textWidth); - break; - case 'right': - title = horizontal.slice(textWidth) + text; - break; - default: - horizontal = horizontal.slice(textWidth); - - if (horizontal.length % 2 === 1) { // This is needed in case the length is odd - horizontal = horizontal.slice(Math.floor(horizontal.length / 2)); - title = horizontal.slice(1) + text + horizontal; // We reduce the left part of one character to avoid the bar to go beyond its limit - } else { - horizontal = horizontal.slice(horizontal.length / 2); - title = horizontal + text + horizontal; - } - - break; - } - - return title; - }; - - const makeContentText = (text, padding, columns, align) => { - text = ansiAlign(text, {align}); - let lines = text.split(NL); - const textWidth = widestLine(text); - - const max = columns - padding.left - padding.right; - - if (textWidth > max) { - const newLines = []; - for (const line of lines) { - const createdLines = wrapAnsi(line, max, {hard: true}); - const alignedLines = ansiAlign(createdLines, {align}); - const alignedLinesArray = alignedLines.split('\n'); - const longestLength = Math.max(...alignedLinesArray.map(s => stringWidth(s))); - - for (const alignedLine of alignedLinesArray) { - let paddedLine; - switch (align) { - case 'center': - paddedLine = PAD.repeat((max - longestLength) / 2) + alignedLine; - break; - case 'right': - paddedLine = PAD.repeat(max - longestLength) + alignedLine; - break; - default: - paddedLine = alignedLine; - break; - } - - newLines.push(paddedLine); - } - } - - lines = newLines; - } - - if (align === 'center' && textWidth < max) { - lines = lines.map(line => PAD.repeat((max - textWidth) / 2) + line); - } else if (align === 'right' && textWidth < max) { - lines = lines.map(line => PAD.repeat(max - textWidth) + line); - } - - const paddingLeft = PAD.repeat(padding.left); - const paddingRight = PAD.repeat(padding.right); - - lines = lines.map(line => paddingLeft + line + paddingRight); - - lines = lines.map(line => { - if (columns - stringWidth(line) > 0) { - switch (align) { - case 'center': - return line + PAD.repeat(columns - stringWidth(line)); - case 'right': - return line + PAD.repeat(columns - stringWidth(line)); - default: - return line + PAD.repeat(columns - stringWidth(line)); - } - } - - return line; - }); - - if (padding.top > 0) { - lines = new Array(padding.top).fill(PAD.repeat(columns)).concat(lines); - } - - if (padding.bottom > 0) { - lines = lines.concat(new Array(padding.bottom).fill(PAD.repeat(columns))); - } - - return lines.join(NL); - }; - - const isHex = color => color.match(/^#(?:[0-f]{3}){1,2}$/i); - const isColorValid = color => typeof color === 'string' && ((chalk$1[color]) || isHex(color)); - const getColorFn = color => isHex(color) ? chalk$1.hex(color) : chalk$1[color]; - const getBGColorFn = color => isHex(color) ? chalk$1.bgHex(color) : chalk$1[camelCase(['bg', color])]; - - boxen$1.exports = (text, options) => { - options = { - padding: 0, - borderStyle: 'single', - dimBorder: false, - textAlignment: 'left', - float: 'left', - titleAlignment: 'left', - ...options - }; - - // This option is deprecated - if (options.align) { - options.textAlignment = options.align; - } - - const BORDERS_WIDTH = 2; - - if (options.borderColor && !isColorValid(options.borderColor)) { - throw new Error(`${options.borderColor} is not a valid borderColor`); - } - - if (options.backgroundColor && !isColorValid(options.backgroundColor)) { - throw new Error(`${options.backgroundColor} is not a valid backgroundColor`); - } - - const chars = getBorderChars(options.borderStyle); - const padding = getObject(options.padding); - const margin = getObject(options.margin); - - const colorizeBorder = border => { - const newBorder = options.borderColor ? getColorFn(options.borderColor)(border) : border; - return options.dimBorder ? chalk$1.dim(newBorder) : newBorder; - }; - - const colorizeContent = content => options.backgroundColor ? getBGColorFn(options.backgroundColor)(content) : content; - - const columns = terminalColumns() - 1; - - let contentWidth = widestLine(wrapAnsi(text, columns - BORDERS_WIDTH, {hard: true, trim: false})) + padding.left + padding.right; - - // This prevents the title bar to exceed the console's width - let title = options.title && options.title.slice(0, columns - 4 - margin.left - margin.right); - - if (title) { - title = ` ${title} `; - // Make the box larger to fit a larger title - if (stringWidth(title) > contentWidth) { - contentWidth = stringWidth(title); - } - } - - if ((margin.left && margin.right) && contentWidth + BORDERS_WIDTH + margin.left + margin.right > columns) { - // Let's assume we have margins: left = 3, right = 5, in total = 8 - const spaceForMargins = columns - contentWidth - BORDERS_WIDTH; - // Let's assume we have space = 4 - const multiplier = spaceForMargins / (margin.left + margin.right); - // Here: multiplier = 4/8 = 0.5 - margin.left = Math.max(0, Math.floor(margin.left * multiplier)); - margin.right = Math.max(0, Math.floor(margin.right * multiplier)); - // Left: 3 * 0.5 = 1.5 -> 1 - // Right: 6 * 0.5 = 3 - } - - // Prevent content from exceeding the console's width - contentWidth = Math.min(contentWidth, columns - BORDERS_WIDTH - margin.left - margin.right); - - text = makeContentText(text, padding, contentWidth, options.textAlignment); - - let marginLeft = PAD.repeat(margin.left); - - if (options.float === 'center') { - const marginWidth = Math.max((columns - contentWidth - BORDERS_WIDTH) / 2, 0); - marginLeft = PAD.repeat(marginWidth); - } else if (options.float === 'right') { - const marginWidth = Math.max(columns - contentWidth - margin.right - BORDERS_WIDTH, 0); - marginLeft = PAD.repeat(marginWidth); - } - - const horizontal = chars.horizontal.repeat(contentWidth); - const top = colorizeBorder(NL.repeat(margin.top) + marginLeft + chars.topLeft + (title ? makeTitle(title, horizontal, options.titleAlignment) : horizontal) + chars.topRight); - const bottom = colorizeBorder(marginLeft + chars.bottomLeft + horizontal + chars.bottomRight + NL.repeat(margin.bottom)); - const side = colorizeBorder(chars.vertical); - - const LINE_SEPARATOR = NL; - - const lines = text.split(NL); - - const middle = lines.map(line => { - return marginLeft + side + colorizeContent(line) + side; - }).join(LINE_SEPARATOR); - - return top + LINE_SEPARATOR + middle + LINE_SEPARATOR + bottom; - }; - - boxen$1.exports._borderStyles = cliBoxes; - return boxen$1.exports; -} - -var boxenExports = requireBoxen(); -var boxen = /*@__PURE__*/getDefaultExportFromCjs(boxenExports); - -function makeTitledPrettyError(title, content, stack) { - return makePrettyError(chalk.redBright(title) + "\n\n" + content, stack); -} -function makePrettyError(content, stack) { - if (process$1.browser || process$1.env.LMS_NO_FANCY_ERRORS || terminalSize().columns < 80) { - const error = new Error(content); - if (stack === undefined) { - changeErrorStackInPlace(error, ""); - } - else { - changeErrorStackInPlace(error, stack); - } - return error; - } - else { - if (stack !== undefined) { - content += - "\n\n\n " + chalk.bgWhite.black(" STACK TRACE ") + "\n\n" + chalk.gray(stack); - } - const error = new Error("\n" + boxen(content, { padding: 1, margin: 1, borderColor: "redBright", title: "Error" })); - Object.defineProperty(error, "lmstudioRawError", { value: content, enumerable: false }); - changeErrorStackInPlace(error, ""); - return error; - } -} - -/** - * A cache for avoiding recompiling the same template strings. - * - * The cached value is a string with 2N + 1 elements, where N is the number of variables in the - * template. - */ -const compiledTemplatesCache = new WeakMap(); -/** - * A string literal tag function that does the following: - * - * - Removes leading new lines - * - Removes trailing new lines and whitespace - * - Removes common indentation from the start of each line (Empty lines are ignored) - * - Single newlines are replaced with a space + extra whitespace is removed - * - * Note: Only spaces are considered. - * - * @remarks - * - * The exact implementation of this function is not guaranteed to be the same, as we may add - * additional edge case handling in the future. However, the general behavior should remain the - * same. - * - * @public - */ -function text(strings, ...values) { - if (values.length + 1 !== strings.length) { - throw new Error("text called with the wrong number of arguments."); - } - let compiled = compiledTemplatesCache.get(strings); - if (compiled === undefined) { - compiled = compile(strings); - compiledTemplatesCache.set(strings, compiled); - } - // We can modify the array in place because JavaScript is single-threaded and the array is not - // being accessed by any other code. - for (let i = 0; i < values.length; i++) { - if (typeof values[i] === "object") { - if (typeof values[i].stack === "string") { - compiled[i * 2 + 1] = values[i].stack; - } - else { - try { - compiled[i * 2 + 1] = JSON.stringify(values[i]); - } - catch (error) { - compiled[i * 2 + 1] = "[Object failed to stringify]"; - } - } - } - else { - compiled[i * 2 + 1] = String(values[i]); - } - } - return compiled.join(""); -} -function removeLeadingNewlines(input) { - return input.replace(/^\n+/, ""); -} -function removeTrailingNewlinesAndWhitespace(input) { - return input.replace(/[\n ]+$/, ""); -} -function removeLeadingWhitespace(input) { - return input.replace(/^ +/, ""); -} -function removeTrailingWhitespace(input) { - return input.replace(/ +$/, ""); -} -function breakIntoLines(strings) { - const lines = []; - let currentLine = []; - for (const string of strings) { - let prevNewlineIndex = -1; - let nextNewlineIndex; - while ((nextNewlineIndex = string.indexOf("\n", prevNewlineIndex + 1)) !== -1) { - currentLine.push(string.substring(prevNewlineIndex + 1, nextNewlineIndex)); - lines.push(currentLine); - currentLine = []; - prevNewlineIndex = nextNewlineIndex; - } - currentLine.push(string.substring(prevNewlineIndex + 1)); - } - lines.push(currentLine); - return lines; -} -/** - * Returns the number of spaces at the start of the string. If the string only contains spaces, - * returns infinity. - */ -function countStringIndentations(string) { - let count = 0; - for (const char of string) { - if (char === " ") { - count++; - } - else { - return count; - } - } - return Infinity; -} -function countLineIndentations(line) { - const firstPart = line[0]; - const firstPartIndentation = countStringIndentations(firstPart); - if (firstPartIndentation === Infinity) { - if (line.length === 1) { - return Infinity; - } - else { - // If there is a variable after it, the length of indentation is the same as the length of the - // first part. - return firstPart.length; - } - } - return firstPartIndentation; -} -function findMaxCommonIndentation(lines) { - let minIndentation = Infinity; - for (const line of lines) { - minIndentation = Math.min(minIndentation, countLineIndentations(line)); - } - return minIndentation; -} -function removeIndentation(line, indentation) { - if (line.length < indentation) { - return ""; - } - return line.slice(indentation); -} -function removeAllIndentation(lines, indentation) { - for (const line of lines) { - line[0] = removeIndentation(line[0], indentation); - } -} -function isEmptyLine(line) { - if (line.length !== 1) { - return false; - } - for (const char of line[0]) { - if (char !== " ") { - return false; - } - } - return true; -} -function mergeLines(lines) { - const linesAreEmpty = lines.map(isEmptyLine); - const paragraphs = []; - let currentParagraph = []; - for (let i = 0; i < lines.length; i++) { - if (linesAreEmpty[i]) { - if (currentParagraph.length !== 0) { - paragraphs.push(currentParagraph); - currentParagraph = []; - } - continue; - } - if (currentParagraph.length !== 0) { - const last = removeTrailingWhitespace(currentParagraph[currentParagraph.length - 1]); - const next = removeLeadingWhitespace(lines[i][0]); - currentParagraph[currentParagraph.length - 1] = last + " " + next; - currentParagraph.push(...lines[i].slice(1)); - } - else { - currentParagraph.push(...lines[i]); - } - } - if (currentParagraph.length !== 0) { - paragraphs.push(currentParagraph); - } - return paragraphs; -} -function mergeParagraphs(paragraphs) { - const result = []; - if (paragraphs.length === 0) { - return [""]; - } - result.push(...paragraphs[0]); - for (let i = 1; i < paragraphs.length; i++) { - result[result.length - 1] += "\n\n" + paragraphs[i][0]; - result.push(...paragraphs[i].slice(1)); - } - return result; -} -function addHolesForVariables(strings) { - const result = []; - for (let i = 0; i < strings.length; i++) { - result.push(strings[i]); - if (i < strings.length - 1) { - result.push(""); - } - } - return result; -} -function compile(readonlyStrings) { - const strings = [...readonlyStrings]; - strings[0] = removeLeadingNewlines(strings[0]); - strings[strings.length - 1] = removeTrailingNewlinesAndWhitespace(strings[strings.length - 1]); - const lines = breakIntoLines(strings); - const commonIndentation = findMaxCommonIndentation(lines); - removeAllIndentation(lines, commonIndentation); - const paragraphs = mergeLines(lines); - return addHolesForVariables(mergeParagraphs(paragraphs)); -} - -/** - * Represents some underlying data that may or may not be mutable. - * - * @public - */ -class MaybeMutable { - constructor(data, mutable) { - this.data = data; - this.mutable = mutable; - } - /** - * Gets the underlying data without any access control. Only used internally. - * - * @internal - */ - _internalGetData() { - return this.data; - } - /** - * If this instance is mutable, return as is. - * - * If this instance is immutable, return a mutable copy. - * - * Very easy to misuse, thus internal only for now. - * - * @internal - */ - _internalToMutable() { - if (this.mutable) { - return this; - } - return this.asMutableCopy(); - } - asMutableCopy() { - return this.create(this.cloneData(this.data), true); - } - asImmutableCopy() { - if (this.mutable) { - return this.create(this.cloneData(this.data), false); - } - return this; - } - guardMutable() { - if (!this.mutable) { - throw new Error(text ` - Cannot modify immutable ${this.getClassName()} instance. Use asMutableCopy() to get a - mutable copy. - `); - } - } -} -function accessMaybeMutableInternals(maybeMutable) { - return maybeMutable; -} - -/** - * OWLSignal - Optimistic Writable Lazy Signal - * - * - Signal: It is a signal, i.e. an observable that remembers its current value - * - Lazy: It is lazy, i.e. it does not subscribe to the upstream until a subscriber is attached - * - Writable: It is writable, i.e. it has a setter to update its value - * - Optimistic: It is optimistic, i.e. it updates its value optimistically and then waits for the - * upstream to confirm the update - * - Once the setter is called, the value is updated optimistically and all subscribers are - * notified synchronously - * - * Guarantees: - * - * - The OWLSignal is designed for single-writer multiple-reader scenarios, as the coordination of - * writes are tracked inside the OWLSignal. If there are multiple writers for the same data (i.e. - * multiple OWLSignal backed by the same upstream), there are no strong guarantees. For example, - * two updaters may read the same value, update it, and write it back to the upstream, causing one - * of the updates to be lost. The following guarantees are provided for single-writer scenarios: - * - The updates are applied in the order they are received, and each updater is guaranteed to see - * all updates that were applied before it. - * - If there are updaters [u_0, u_1, ..., u_n], for any read-only reader, there exists a time t - * where the reader will see the updates [u_0, u_1, ..., u_t] in the order they were applied. This - * also applies to the writer itself. - */ -class OWLSignal extends Subscribable { - static { this.NOT_AVAILABLE = LazySignal.NOT_AVAILABLE; } - applyOptimisticUpdates(data) { - for (const update of this.queuedUpdates) { - [data] = update.updater(data); - } - return data; - } - updateOptimisticValue(tags) { - const innerValue = this.innerSignal.get(); - if (!isAvailable(innerValue)) { - return; - } - this.setOuterSignal(this.applyOptimisticUpdates(innerValue), tags); - } - constructor(initialValue, subscribeUpstream, writeUpstream, equalsPredicate) { - super(); - this.writeUpstream = writeUpstream; - this.isWriteLoopRunning = false; - /** - * We have a passive subscription to the inner signal to update the optimistic value whenever the - * inner signal changes. - * - * However, if the content changes are caused by a write, we want to update the inner value, - * remove the optimistic update, and apply the remaining optimistic updates all at once. - * - * Therefore, when a write is ongoing, we set this flag to true to prevent the passive - * subscription from updating the optimistic value. We will handle the updates within the write - * loop. - */ - this.isSubscriptionHandledByWriteLoop = false; - /** - * A queue of updates to apply optimistically. - */ - this.queuedUpdates = []; - this.currentEnsureAvailablePromise = null; - [this.writeErrorEvent, this.emitWriteErrorEvent] = Event.create(); - [this.outerSignal, this.setOuterSignal] = Signal.create(initialValue, equalsPredicate); - this.innerSignal = LazySignal.create(initialValue, subscribeUpstream, equalsPredicate); - this.innerSignal.passiveSubscribeFull((_data, _patches, tags) => { - if (this.isSubscriptionHandledByWriteLoop) { - return; - } - this.updateOptimisticValue(tags); - }); - } - static create(initialValue, subscribeUpstream, - /** - * Returns true if the update is sent to the upstream (thus should wait for the upstream to - * confirm. Returns false if the update is not sent and the update should be dropped. - */ - writeUpstream, equalsPredicate = (a, b) => a === b) { - const signal = new OWLSignal(initialValue, subscribeUpstream, writeUpstream, equalsPredicate); - const setSignal = makeSetterWithPatches(signal.update.bind(signal)); - const emitError = (tags, error) => signal.emitWriteErrorEvent({ tags, error }); - return [signal, setSignal, emitError]; - } - static createWithoutInitialValue(subscribeUpstream, writeUpstream, equalsPredicate = (a, b) => a === b) { - const fullEqualsPredicate = (a, b) => { - if (a === OWLSignal.NOT_AVAILABLE || b === OWLSignal.NOT_AVAILABLE) { - return a === b; - } - return equalsPredicate(a, b); - }; - return OWLSignal.create(OWLSignal.NOT_AVAILABLE, subscribeUpstream, writeUpstream, fullEqualsPredicate); - } - async update(updater, tags) { - const { promise, reject, resolve } = makePromise(); - this.queuedUpdates.push({ - updater, - tags: tags ?? [], - resolve, - reject, - }); - this.updateOptimisticValue(); - this.ensureWriteLoop(); - return promise; - } - /** - * Starts the write loop if it is not already running. - */ - ensureWriteLoop() { - if (!this.isWriteLoopRunning) { - this.writeLoop(); // This is not expected to error, if it does, just default behavior - } - } - /** - * The main write loop, it will keep running until there are no more updates to process. - */ - async writeLoop() { - const unsubscribe = this.innerSignal.subscribe(() => { }); - this.isWriteLoopRunning = true; - if (this.isStale()) { - await this.innerSignal.pull(); - } - while (this.queuedUpdates.length > 0) { - const numQueuedUpdatesToHandle = this.queuedUpdates.length; - const updater = (data) => { - const patches = []; - for (let i = 0; i < numQueuedUpdatesToHandle; i++) { - const [newData, newPatches] = this.queuedUpdates[i].updater(data); - data = newData; - patches.push(...newPatches); - } - return [data, patches]; - }; - const resolve = () => { - for (let i = 0; i < numQueuedUpdatesToHandle; i++) { - this.queuedUpdates[i].resolve(); - } - }; - const reject = (error) => { - for (let i = 0; i < numQueuedUpdatesToHandle; i++) { - this.queuedUpdates[i].reject(error); - } - }; - const queuedUpdateTags = this.queuedUpdates.flatMap(update => update.tags); - const tag = Date.now() + "-" + Math.random(); - await new Promise(nextStep => { - this.isSubscriptionHandledByWriteLoop = true; - const unsubscribeArray = []; - const settle = () => { - this.isSubscriptionHandledByWriteLoop = false; - unsubscribeArray.forEach(unsubscribe => unsubscribe()); - nextStep(); - }; - unsubscribeArray.push(this.innerSignal.subscribeFull((_data, _patches, tags) => { - if (!this.isSubscriptionHandledByWriteLoop) { - return; - } - if (tags?.includes(tag)) { - settle(); - resolve(); - // If this update is caused by the write, we need to remove the optimistic update - // and apply the remaining optimistic updates - this.queuedUpdates.splice(0, numQueuedUpdatesToHandle); - this.updateOptimisticValue(tags.filter(t => t !== tag)); - } - else { - // This update is not caused by the write, simply update the optimistic value - // as normal - this.updateOptimisticValue(tags); - } - })); - unsubscribeArray.push(this.writeErrorEvent.subscribe(({ tags, error }) => { - if (!this.isSubscriptionHandledByWriteLoop) { - return; - } - if (tags.includes(tag)) { - settle(); - reject(error); - this.queuedUpdates.splice(0, numQueuedUpdatesToHandle); - } - })); - // At this point, we know the data is available, because upon entering the write loop, we - // ensure that the data is available by pulling. Hence, we can safely cast the data to - // StripNotAvailable. - const sent = this.writeUpstream(...updater(this.innerSignal.get()), [tag, ...queuedUpdateTags]); - if (!sent) { - settle(); - resolve(); - this.queuedUpdates.splice(0, numQueuedUpdatesToHandle); - this.updateOptimisticValue(queuedUpdateTags.filter(t => t !== tag)); - } - }); - } - this.isWriteLoopRunning = false; - unsubscribe(); - } - /** - * Returns whether the value is currently stale. - * - * A value is stale whenever the upstream subscription is not active. This can happen in three - * cases: - * - * 1. When no subscriber is attached to this signal, the signal will not subscribe to the - * upstream. In this case, the value is always stale. - * 2. When a subscriber is attached, but the upstream has not yet emitted a single value, the - * value is also stale. - * 3. When the upstream has emitted an error. In this case, the subscription to the upstream is - * terminated and the value is stale. - * - * If you wish to get the current value and ensure that it is not stale, use the method - * {@link OWLSignal#pull}. - */ - isStale() { - return this.innerSignal.isStale(); - } - /** - * Gets the current value of the signal. If the value is not available, it will return - * {@link OWLSignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is created - * without an initial value and the upstream has not emitted a value yet.) - * - * In addition, the value returned by this method may be stale. Use {@link OWLSignal#isStale} to - * check if the value is stale. - * - * If you wish to get the current value and ensure that it is not stale, use the method - * {@link OWLSignal#pull}. - */ - get() { - return this.outerSignal.get(); - } - /** - * Gets the current value of the signal pessimistically. If the value is not available, it will - * return {@link OWLSignal.NOT_AVAILABLE}. (A value will only be unavailable if the signal is - * created without an initial value and the upstream has not emitted a value yet.) - */ - getPessimistic() { - return this.innerSignal.get(); - } - /** - * Pulls the current value of the signal. If the value is stale, it will subscribe and wait for - * the next value from the upstream and return it. - * - * You must also provide an `optimistic` flag. If `optimistic` is true, the pending optimistic - * updates will be applied to the value before returning it. - */ - async pull({ optimistic = true } = {}) { - if (optimistic) { - return this.applyOptimisticUpdates(await this.innerSignal.pull()); - } - else { - return this.innerSignal.pull(); - } - } - async ensureAvailable() { - if (this.currentEnsureAvailablePromise === null) { - this.currentEnsureAvailablePromise = (async () => { - await this.innerSignal.pull(); - return this; - })(); - } - return this.currentEnsureAvailablePromise; - } - subscribe(subscriber) { - const unsubscribeOuter = this.outerSignal.subscribe(subscriber); - const unsubscribeInner = this.innerSignal.subscribe(() => { }); - return () => { - unsubscribeOuter(); - unsubscribeInner(); - }; - } - subscribeFull(subscriber) { - const unsubscribeOuter = this.outerSignal.subscribeFull(subscriber); - const unsubscribeInner = this.innerSignal.subscribeFull(() => { }); - return () => { - unsubscribeOuter(); - unsubscribeInner(); - }; - } -} - -function parseFileIdentifier(fileIdentifier) { - if (!fileIdentifier.includes(":")) { - fileIdentifier = `local:${fileIdentifier}`; - } - const colonIndex = fileIdentifier.indexOf(":"); - const namespace = fileIdentifier.slice(0, colonIndex); - const content = fileIdentifier.slice(colonIndex + 1); - switch (namespace) { - case "local": { - if (content.includes("/") || content.includes("\\") || content.length === 0) { - throw new Error(`Invalid local file name: ${content}.`); - } - return { - type: "local", - fileName: content, - }; - } - case "base64": { - return { - type: "base64", - base64Data: content, - }; - } - default: { - throw new Error(`Unknown file identifier namespace: ${namespace}.`); - } - } -} - -function promisifyAbortSignal(abortSignal) { - return new Promise((_resolve, reject) => { - if (abortSignal.aborted) { - reject(abortSignal.reason); - return; - } - abortSignal.addEventListener("abort", () => { - reject(abortSignal.reason); - }, { once: true }); - }); -} -function raceWithAbortSignal(promise, abortSignal) { - return Promise.race([promise, promisifyAbortSignal(abortSignal)]); -} - -const allowableEnvVarKeys = ["HSA_OVERRIDE_GFX_VERSION"]; -const allowableEnvVarKeysSchema = z.enum(allowableEnvVarKeys); -const allowableEnvVarsSchema = z.record(allowableEnvVarKeysSchema, z.string()); - -const kebabCaseRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; -const kebabCaseSchema = z.string().regex(kebabCaseRegex); -const kebabCaseWithDotsRegex = /^[a-z0-9]+(?:[-.][a-z0-9]+)*$/; -const kebabCaseWithDotsSchema = z.string().regex(kebabCaseWithDotsRegex); - -/** - * Matches valid file names - */ -const fileNameRegex = /^[\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~`][\p{L}\p{N}!@#$%^&()\-_+=,.;'[\]{}~` ]*(? { - try { - // Needs a more performant way to do this. - return JSON.parse(JSON.stringify(val)); - } - catch (e) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: "Not JSON serializable: " + e.message, - }); - return val; - } -}); - -const chatMessagePartTextDataSchema = z.object({ - type: z.literal("text"), - text: z.string(), -}); -const chatMessagePartFileDataSchema = z.object({ - type: z.literal("file"), - name: z.string(), - identifier: z.string(), - sizeBytes: z.number().int(), - fileType: fileTypeSchema, -}); -const functionToolCallRequestSchema = z.object({ - id: z.string().optional(), - type: z.literal("function"), - arguments: z.record(jsonSerializableSchema).optional(), - name: z.string(), -}); -const toolCallRequestSchema = z.discriminatedUnion("type", [ - functionToolCallRequestSchema, -]); -const chatMessagePartToolCallRequestDataSchema = z.object({ - type: z.literal("toolCallRequest"), - toolCallRequest: toolCallRequestSchema, -}); -z.object({ - content: z.string(), - toolCallId: z.string().optional(), -}); -const chatMessagePartToolCallResultDataSchema = z.object({ - type: z.literal("toolCallResult"), - content: z.string(), - toolCallId: z.string().optional(), -}); -z.discriminatedUnion("type", [ - chatMessagePartTextDataSchema, - chatMessagePartFileDataSchema, - chatMessagePartToolCallRequestDataSchema, - chatMessagePartToolCallResultDataSchema, -]); -z.enum(["assistant", "user", "system", "tool"]); -const chatMessageDataSchema = z.discriminatedUnion("role", [ - z.object({ - role: z.literal("assistant"), - content: z.array(z.discriminatedUnion("type", [ - chatMessagePartTextDataSchema, - chatMessagePartFileDataSchema, - chatMessagePartToolCallRequestDataSchema, - ])), - }), - z.object({ - role: z.literal("user"), - content: z.array(z.discriminatedUnion("type", [chatMessagePartTextDataSchema, chatMessagePartFileDataSchema])), - }), - z.object({ - role: z.literal("system"), - content: z.array(z.discriminatedUnion("type", [chatMessagePartTextDataSchema, chatMessagePartFileDataSchema])), - }), - z.object({ - role: z.literal("tool"), - content: z.array(chatMessagePartToolCallResultDataSchema), - }), -]); -const chatHistoryDataSchema = z.object({ - messages: z.array(chatMessageDataSchema), -}); - -const citationSourceSchema = z.object({ - fileName: z.string(), - absoluteFilePath: z.string().optional(), - pageNumber: z.union([z.number().int(), z.tuple([z.number().int(), z.number().int()])]).optional(), - lineNumber: z.union([z.number().int(), z.tuple([z.number().int(), z.number().int()])]).optional(), -}); - -/** - * @deprecated Use colorPaletteSchema instead. - */ -const colorPalette = z.enum([ - "red", - "green", - "blue", - "yellow", - "orange", - "purple", - "default", -]); -const colorPaletteSchema = colorPalette; - -const diagnosticsLogEventDataSchema = z.discriminatedUnion("type", [ - z.object({ - type: z.literal("llm.prediction.input"), - modelPath: z.string(), - modelIdentifier: z.string(), - input: z.string(), - }), -]); -const diagnosticsLogEventSchema = z.object({ - timestamp: z.number(), - data: diagnosticsLogEventDataSchema, -}); - -const llmLlamaAccelerationOffloadRatioSchema = z.union([ - z.number().min(0).max(1), - z.literal("max"), - z.literal("off"), -]); -const llmSplitStrategySchema = z.enum(["evenly", "favorMainGpu"]); -const gpuSettingSchema = z.object({ - ratio: llmLlamaAccelerationOffloadRatioSchema.optional(), - mainGpu: z.number().int().optional(), - splitStrategy: llmSplitStrategySchema.optional(), - disabledGpus: z.array(z.number().int()).optional(), -}); -const llmLlamaCacheQuantizationTypes = [ - "f32", - "f16", - "q8_0", - "q4_0", - "q4_1", - "iq4_nl", - "q5_0", - "q5_1", -]; -const llmLlamaCacheQuantizationTypeSchema = z.enum(llmLlamaCacheQuantizationTypes); -const llmMlxKvCacheBitsTypeSchema = z.union([ - z.literal(8), - z.literal(6), - z.literal(4), - z.literal(3), - z.literal(2), -]); -const llmMlxKvCacheGroupSizeTypesSchema = z.union([ - z.literal(32), - z.literal(64), - z.literal(128), -]); -const llmMlxKvCacheQuantizationSchema = z.object({ - enabled: z.boolean(), - bits: llmMlxKvCacheBitsTypeSchema, - groupSize: llmMlxKvCacheGroupSizeTypesSchema, - quantizedStart: z.number().int().nonnegative(), -}); -const llmLoadModelConfigSchema = z.object({ - gpu: gpuSettingSchema.optional(), - gpuStrictVramCap: z.boolean().optional(), - offloadKVCacheToGpu: z.boolean().optional(), - contextLength: z.number().int().min(1).optional(), - ropeFrequencyBase: z.number().optional(), - ropeFrequencyScale: z.number().optional(), - evalBatchSize: z.number().int().min(1).optional(), - flashAttention: z.boolean().optional(), - keepModelInMemory: z.boolean().optional(), - seed: z.number().int().optional(), - useFp16ForKVCache: z.boolean().optional(), - tryMmap: z.boolean().optional(), - numExperts: z.number().int().optional(), - llamaKCacheQuantizationType: z - .enum(llmLlamaCacheQuantizationTypes) - .or(z.literal(false)) - .optional(), - llamaVCacheQuantizationType: z - .enum(llmLlamaCacheQuantizationTypes) - .or(z.literal(false)) - .optional(), -}); - -const embeddingLoadModelConfigSchema = z.object({ - gpu: gpuSettingSchema.optional(), - contextLength: z.number().int().min(1).optional(), - ropeFrequencyBase: z.number().optional(), - ropeFrequencyScale: z.number().optional(), - keepModelInMemory: z.boolean().optional(), - tryMmap: z.boolean().optional(), -}); - -const modelCompatibilityTypeSchema = z.enum([ - "gguf", - "safetensors", - "onnx", - "ggml", - "mlx_placeholder", - "torch_safetensors", -]); - -const quantizationSchema = z.object({ - name: z.string(), - bits: z.number().int(), -}); - -const modelInfoBaseSchema = z.object({ - modelKey: z.string(), - format: modelCompatibilityTypeSchema, - displayName: z.string(), - path: z.string(), - sizeBytes: z.number().int(), - paramsString: z.string().optional(), - architecture: z.string().optional(), - quantization: quantizationSchema.optional(), -}); -const modelInstanceInfoBaseSchema = modelInfoBaseSchema.extend({ - identifier: z.string(), - instanceReference: z.string(), -}); - -const embeddingModelAdditionalInfoSchema = z.object({ - maxContextLength: z.number().int(), -}); -const embeddingModelInstanceAdditionalInfoSchema = z.object({ - contextLength: z.number().int(), -}); -const embeddingModelInfoSchema = z - .object({ - type: z.literal("embedding"), -}) - .extend(modelInfoBaseSchema.shape) - .extend(embeddingModelAdditionalInfoSchema.shape); -const embeddingModelInstanceInfoSchema = z - .object({ type: z.literal("embedding") }) - .extend(modelInstanceInfoBaseSchema.shape) - .extend(embeddingModelAdditionalInfoSchema.shape) - .extend(embeddingModelInstanceAdditionalInfoSchema.shape); - -const modelDomainTypeSchema = z.enum([ - "llm", - "embedding", - "imageGen", - "transcription", - "tts", -]); - -/** - * A string that is reasonable to use as a key. For example, as preset name, model path, or model - * identifier. - */ -const reasonableKeyStringSchema = z - .string() - .min(1) - .max(1024) - .refine(value => value !== "__proto__", { - message: 'For security reasons, "__proto__" is not allowed', -}) - .refine(value => /\p{C}/u.test(value) === false, { - message: "Control characters are not allowed", -}); - -const modelQuerySchema = z.object({ - domain: modelDomainTypeSchema.optional(), - identifier: reasonableKeyStringSchema.optional(), - path: reasonableKeyStringSchema.optional(), - vision: z.boolean().optional(), -}); -const modelSpecifierSchema = z.discriminatedUnion("type", [ - z.object({ - type: z.literal("query"), - query: modelQuerySchema, - }), - z.object({ - type: z.literal("instanceReference"), - instanceReference: z.string(), - }), -]); - -const genericErrorDisplayDataSchema = [ - z.object({ - code: z.literal("generic.specificModelUnloaded"), - }), - z.object({ - code: z.literal("generic.noModelMatchingQuery"), - query: modelQuerySchema, - loadedModelsSample: z.array(z.string()), - totalLoadedModels: z.number().int(), - }), - z.object({ - code: z.literal("generic.pathNotFound"), - path: z.string(), - availablePathsSample: z.array(z.string()), - totalModels: z.number().int(), - }), - z.object({ - code: z.literal("generic.identifierNotFound"), - identifier: z.string(), - loadedModelsSample: z.array(z.string()), - totalLoadedModels: z.number().int(), - }), - z.object({ - code: z.literal("generic.domainMismatch"), - path: z.string(), - actualDomain: modelDomainTypeSchema, - expectedDomain: modelDomainTypeSchema, - }), - z.object({ - code: z.literal("generic.engineDoesNotSupportFeature"), - feature: z.string(), - engineName: z.string(), - engineType: z.string(), - installedVersion: z.string(), - supportedVersion: z.string().nullable(), - }), - z.object({ - code: z.literal("generic.presetNotFound"), - specifiedFuzzyPresetIdentifier: z.string(), - availablePresetsSample: z.array(z.object({ - identifier: z.string(), - name: z.string(), - })), - totalAvailablePresets: z.number().int(), - }), -]; - -const llmErrorDisplayDataSchema = []; - -const errorDisplayDataSchema = z.discriminatedUnion("code", [ - ...llmErrorDisplayDataSchema, - ...genericErrorDisplayDataSchema, -]); -/** - * Makes a Zod schema that turns a failed parse into an `undefined`. - */ -function failOk(schema) { - return z.any().transform(val => (schema.safeParse(val).success ? val : undefined)); -} -const serializedLMSExtendedErrorSchema = z.object({ - title: failOk(z.string()).default("Unknown error"), - cause: failOk(z.string()).optional(), - suggestion: failOk(z.string()).optional(), - errorData: failOk(z.record(z.string(), z.unknown())).optional(), - displayData: failOk(errorDisplayDataSchema).optional(), - stack: failOk(z.string()).optional(), - rootTitle: failOk(z.string()).optional(), -}); -function serializeError(error) { - if (typeof error === "object") { - const title = error.title ?? error.lmstudioRawError ?? error.message ?? "Unknown error"; - return serializedLMSExtendedErrorSchema.parse({ - title, - cause: error.cause, - suggestion: error.suggestion, - errorData: error.errorData, - displayData: error.displayData, - stack: error.stack, - rootTitle: title, - }); - } - else { - const title = String(error); - return { - title, - rootTitle: title, - }; - } -} -/** - * Attaches the additional error data from a serialized error to an error object. - */ -function attachSerializedErrorData(error, serialized) { - const untypedError = error; - untypedError.title = serialized.title; - if (serialized.cause !== undefined) { - untypedError.cause = serialized.cause; - } - if (serialized.suggestion !== undefined) { - untypedError.suggestion = serialized.suggestion; - } - if (serialized.errorData !== undefined) { - untypedError.errorData = serialized.errorData; - } -} -function fromSerializedError(error, message = "Rehydrated error", replacementStack) { - const result = new Error(error.rootTitle); - attachSerializedErrorData(result, error); - if (error.displayData !== undefined) { - result.displayData = error.displayData; - } - if (replacementStack !== undefined) { - if (error.stack !== undefined) { - result.stack = `Error: ${message}\n${replacementStack}\n- Caused By: ${error.stack}`; - } - else { - result.stack = `Error: ${message}\n${replacementStack}`; - } - } - else { - if (error.stack !== undefined) { - result.stack = - `Error: ${message}\n${result.stack.substring(error.stack.indexOf("\n") + 1)}\n- Caused By: ` + - error.stack; - } - else { - result.message += ` - caused by error without stack (${error.title})`; - } - } - return result; -} - -const documentParsingLibraryIdentifierSchema = z.object({ - library: z.string(), - version: z.string(), -}); -const documentParsingOptsSchema = z.object({ - parserId: documentParsingLibraryIdentifierSchema.optional(), -}); - -z.enum(["local", "base64"]); -z.discriminatedUnion("type", [ - z.object({ - type: z.literal("local"), - fileName: z.string(), - }), - z.object({ - type: z.literal("base64"), - base64Data: z.string(), - }), -]); - -const gpuSplitStrategies = ["evenly", "priorityOrder", "custom"]; -const gpuSplitStrategySchema = z.enum(gpuSplitStrategies); -const defaultGPUSplitConfig = { - strategy: "evenly", - disabledGpus: [], - priority: [], - customRatio: [], -}; -const gpuSplitConfigSchema = z.object({ - strategy: gpuSplitStrategySchema, - disabledGpus: z.array(z.number().int().min(0)), - priority: z.array(z.number().int().min(0)), - customRatio: z.array(z.number().min(0)), -}); -function convertGPUSettingToGPUSplitConfig(gpuSetting) { - return { - strategy: gpuSetting?.splitStrategy == "favorMainGpu" - ? "priorityOrder" - : gpuSetting?.splitStrategy ?? "evenly", - disabledGpus: gpuSetting?.disabledGpus ?? [], - priority: gpuSetting?.mainGpu ? [gpuSetting.mainGpu] : [], - customRatio: [], - }; -} - -const kvConfigFieldSchema = z.object({ - key: z.string(), - value: z.any(), -}); -const kvConfigSchema = z.object({ - fields: z.array(kvConfigFieldSchema), -}); -const kvConfigLayerNameSchema = z.enum([ - "currentlyEditing", - "currentlyLoaded", - "apiOverride", - "conversationSpecific", - "conversationGlobal", - "preset", - "serverSession", - "httpServerRequestOverride", - "completeModeFormatting", - "instance", - "userModelDefault", - "virtualModel", - "modelDefault", - "hardware", -]); -const kvConfigStackLayerSchema = z.object({ - layerName: kvConfigLayerNameSchema, - config: kvConfigSchema, -}); -const kvConfigStackSchema = z.object({ - layers: z.array(kvConfigStackLayerSchema), -}); -const kvConfigFieldDependencySchema = z.object({ - key: z.string(), - condition: z.discriminatedUnion("type", [ - z.object({ type: z.literal("equals"), value: z.any() }), - z.object({ type: z.literal("notEquals"), value: z.any() }), - ]), -}); - -const contentBlockStyleSchema = z.discriminatedUnion("type", [ - z.object({ - type: z.literal("default"), - }), - z.object({ - type: z.literal("customLabel"), - label: z.string(), - color: z.optional(colorPaletteSchema), - }), - z.object({ - type: z.literal("thinking"), - ended: z.boolean().optional(), - title: z.string().optional(), - }), -]); - -const llmToolParametersSchema = z.discriminatedUnion("type", [ - z.object({ - type: z.literal("object"), - properties: z.record(jsonSerializableSchema), - required: z.array(z.string()).optional(), - additionalProperties: z.boolean().optional(), - $defs: z.record(jsonSerializableSchema).optional(), - }), - // add more parameter types here - // ... -]); -const llmToolSchema = z.discriminatedUnion("type", [ - z.object({ - type: z.literal("function"), - function: z.object({ - name: z.string(), - description: z.string().optional(), - parameters: llmToolParametersSchema.optional(), - }), - }), - // add more tool types here - // ... -]); -/** - * For convenience - */ -z.array(llmToolSchema); -const llmToolUseSettingSchema = z.discriminatedUnion("type", [ - z.object({ - type: z.literal("none"), - }), - z.object({ - type: z.literal("toolArray"), - tools: z.array(llmToolSchema).optional(), - force: z.boolean().optional(), - }), -]); - -const llmApplyPromptTemplateOptsSchema = z.object({ - omitBosToken: z.boolean().optional(), - omitEosToken: z.boolean().optional(), - toolDefinitions: z.array(llmToolSchema).optional(), -}); - -const llmContextReferenceSchema = z.discriminatedUnion("type", [ - z.object({ - type: z.literal("jsonFile"), - absPath: z.string(), - }), - z.object({ - type: z.literal("yamlFile"), - absPath: z.string(), - }), -]); -z.array(z.object({ - role: z.enum(["user", "assistant", "system"]), - content: z.string(), -})); -z.array(z.union([ - z.object({ - system: z.string(), - }), - z.object({ - user: z.string(), - }), - z.object({ - assistant: z.string(), - }), -])); - -const llmAdditionalInfoSchema = z.object({ - vision: z.boolean(), - trainedForToolUse: z.boolean(), - maxContextLength: z.number().int(), -}); -const llmInstanceAdditionalInfoSchema = z.object({ - contextLength: z.number().int(), -}); -const llmInfoSchema = z - .object({ - type: z.literal("llm"), -}) - .extend(modelInfoBaseSchema.shape) - .extend(llmAdditionalInfoSchema.shape); -const llmInstanceInfoSchema = z - .object({ - type: z.literal("llm"), -}) - .extend(modelInstanceInfoBaseSchema.shape) - .extend(llmAdditionalInfoSchema.shape) - .extend(llmInstanceAdditionalInfoSchema.shape); - -const toolNamingSchema = z.enum(["passThrough", "removeSpecial", "snakeCase", "camelCase"]); - -/** - * Check if has a parse method. If not, output error message asking for it to be a zod schema. - */ -const zodSchemaSchema = z.custom(value => { - if (typeof value?.parse !== "function") { - return false; - } - return true; -}, "Expected a zod schema"); - -const llmManualPromptTemplateSchema = z.object({ - beforeSystem: z.string(), - afterSystem: z.string(), - beforeUser: z.string(), - afterUser: z.string(), - beforeAssistant: z.string(), - afterAssistant: z.string(), -}); -const llmJinjaPromptTemplateSchema = z.object({ - template: z.string(), -}); -const llmPromptTemplateTypeSchema = z.enum(["manual", "jinja"]); -const llmPromptTemplateSchema = z.object({ - type: llmPromptTemplateTypeSchema, - manualPromptTemplate: llmManualPromptTemplateSchema.optional(), - jinjaPromptTemplate: llmJinjaPromptTemplateSchema.optional(), - stopStrings: z.array(z.string()), -}); - -const llmStructuredPredictionTypeSchema = z.enum(["none", "json", "gbnf"]); -const llmStructuredPredictionSettingSchema = z.object({ - type: llmStructuredPredictionTypeSchema, - jsonSchema: jsonSerializableSchema.optional(), - gbnfGrammar: z.string().optional(), -}); - -const llmContextOverflowPolicySchema = z.enum([ - "stopAtLimit", - "truncateMiddle", - "rollingWindow", -]); -const llmReasoningParsingSchema = z.object({ - enabled: z.boolean(), - startString: z.string(), - endString: z.string(), -}); -const llmPredictionConfigInputSchema = z.object({ - maxTokens: z.number().int().min(-1).optional().or(z.literal(false)), - temperature: z.number().min(0).optional(), - stopStrings: z.array(z.string()).optional(), - toolCallStopStrings: z.array(z.string()).optional(), - contextOverflowPolicy: llmContextOverflowPolicySchema.optional(), - structured: z.union([zodSchemaSchema, llmStructuredPredictionSettingSchema]).optional(), - rawTools: llmToolUseSettingSchema.optional(), - toolNaming: toolNamingSchema.optional(), - topKSampling: z.number().optional(), - repeatPenalty: z.number().optional().or(z.literal(false)), - minPSampling: z.number().optional().or(z.literal(false)), - topPSampling: z.number().optional().or(z.literal(false)), - cpuThreads: z.number().int().optional(), - promptTemplate: llmPromptTemplateSchema.optional(), - draftModel: z.string().optional(), - speculativeDecodingNumDraftTokensExact: z.number().int().min(1).optional(), - speculativeDecodingMinDraftLengthToConsider: z.number().int().min(0).optional(), - speculativeDecodingMinContinueDraftingProbability: z.number().optional(), - reasoningParsing: llmReasoningParsingSchema.optional(), - raw: kvConfigSchema.optional(), -}); -z.object({ - ...llmPredictionConfigInputSchema.shape, - structured: llmStructuredPredictionSettingSchema.optional(), -}); -const llmLlamaMirostatSamplingConfigSchema = z.object({ - version: z.union([z.literal(0), z.literal(1), z.literal(2)]), - learningRate: z.number(), - targetEntropy: z.number(), -}); -const llmLlamaSingleLogitBiasModificationSchema = z.union([z.number(), z.literal("-inf")]); -const llmLlamaLogitBiasConfigSchema = z.array(z.tuple([z.number(), llmLlamaSingleLogitBiasModificationSchema])); - -const llmPredictionFragmentReasoningTypeSchema = z.enum([ - "none", - "reasoning", - "reasoningStartTag", - "reasoningEndTag", -]); -const llmPredictionFragmentSchema = z.object({ - content: z.string(), - tokensCount: z.number().int(), - containsDrafted: z.boolean(), - reasoningType: llmPredictionFragmentReasoningTypeSchema, - isStructural: z.boolean(), -}); -const llmPredictionFragmentInputOptsSchema = z.object({ - tokenCount: z.number().int().optional(), - containsDrafted: z.boolean().optional(), - reasoningType: llmPredictionFragmentReasoningTypeSchema.optional(), - isStructural: z.boolean().optional(), -}); - -const llmPredictionStopReasonSchema = z.enum([ - "userStopped", - "modelUnloaded", - "failed", - "eosFound", - "stopStringFound", - "toolCalls", - "maxPredictedTokensReached", - "contextLengthReached", -]); -const llmPredictionStatsSchema = z.object({ - stopReason: llmPredictionStopReasonSchema, - tokensPerSecond: z.number().optional(), - numGpuLayers: z.number().optional(), - timeToFirstTokenSec: z.number().optional(), - totalTimeSec: z.number().optional(), - promptTokensCount: z.number().int().optional(), - predictedTokensCount: z.number().int().optional(), - totalTokensCount: z.number().int().optional(), - usedDraftModelKey: z.string().optional(), - totalDraftTokensCount: z.number().int().optional(), - acceptedDraftTokensCount: z.number().int().optional(), - rejectedDraftTokensCount: z.number().int().optional(), - ignoredDraftTokensCount: z.number().int().optional(), -}); -const llmGenInfoSchema = z.object({ - indexedModelIdentifier: z.string(), - identifier: z.string(), - loadModelConfig: kvConfigSchema, - predictionConfig: kvConfigSchema, - stats: llmPredictionStatsSchema, -}); - -const blockLocationSchema = z.discriminatedUnion("type", [ - z.object({ - type: z.literal("beforeId"), - id: z.string(), - }), - z.object({ - type: z.literal("afterId"), - id: z.string(), - }), -]); -const statusStepStatusSchema = z.enum([ - "waiting", - "loading", - "done", - "error", - "canceled", -]); -const statusStepStateSchema = z.object({ - status: statusStepStatusSchema, - text: z.string(), -}); -const processingUpdateStatusCreateSchema = z.object({ - type: z.literal("status.create"), - id: z.string(), - state: statusStepStateSchema, - location: blockLocationSchema.optional(), - indentation: z.number().int().optional(), -}); -const processingUpdateStatusUpdateSchema = z.object({ - type: z.literal("status.update"), - id: z.string(), - state: statusStepStateSchema, -}); -const processingUpdateStatusRemoveSchema = z.object({ - type: z.literal("status.remove"), - id: z.string(), -}); -const processingUpdateCitationBlockCreateSchema = z.object({ - type: z.literal("citationBlock.create"), - id: z.string(), - citedText: z.string(), - fileName: z.string(), - fileIdentifier: z.string(), - pageNumber: z.union([z.number().int(), z.tuple([z.number().int(), z.number().int()])]).optional(), - lineNumber: z.union([z.number().int(), z.tuple([z.number().int(), z.number().int()])]).optional(), -}); -const processingUpdateDebugInfoBlockCreateSchema = z.object({ - type: z.literal("debugInfoBlock.create"), - id: z.string(), - debugInfo: z.string(), -}); -const processingUpdateContentBlockCreateSchema = z.object({ - type: z.literal("contentBlock.create"), - id: z.string(), - includeInContext: z.boolean(), - roleOverride: z.enum(["user", "assistant", "system", "tool"]).optional(), - style: contentBlockStyleSchema.optional(), - prefix: z.string().optional(), - suffix: z.string().optional(), -}); -const processingUpdateContentBlockAppendTextSchema = z.object({ - type: z.literal("contentBlock.appendText"), - id: z.string(), - text: z.string(), - tokensCount: z.number().int().optional(), - fromDraftModel: z.boolean().optional(), - isStructural: z.boolean().optional(), -}); -const processingUpdateContentBlockAppendToolResultSchema = z.object({ - type: z.literal("contentBlock.appendToolResult"), - id: z.string(), - callId: z.number().int(), - toolCallRequestId: z.string().optional(), - content: z.string(), -}); -const processingUpdateContentBlockAppendToolRequestSchema = z.object({ - type: z.literal("contentBlock.appendToolRequest"), - id: z.string(), - callId: z.number().int(), - toolCallRequestId: z.string().optional(), - name: z.string(), - parameters: z.record(z.unknown()), - pluginIdentifier: z.string().optional(), -}); -const processingUpdateContentBlockReplaceToolRequestSchema = z.object({ - type: z.literal("contentBlock.replaceToolRequest"), - id: z.string(), - callId: z.number().int(), - toolCallRequestId: z.string().optional(), - name: z.string(), - parameters: z.record(z.unknown()), - pluginIdentifier: z.string().optional(), -}); -const processingUpdateContentBlockReplaceTextSchema = z.object({ - type: z.literal("contentBlock.replaceText"), - id: z.string(), - text: z.string(), -}); -const processingUpdateContentBlockSetPrefixSchema = z.object({ - type: z.literal("contentBlock.setPrefix"), - id: z.string(), - prefix: z.string(), -}); -const processingUpdateContentBlockSetSuffixSchema = z.object({ - type: z.literal("contentBlock.setSuffix"), - id: z.string(), - suffix: z.string(), -}); -const processingUpdateContentBlockAttachGenInfoSchema = z.object({ - type: z.literal("contentBlock.attachGenInfo"), - id: z.string(), - genInfo: llmGenInfoSchema, -}); -const processingUpdateContentBlockSetStyleSchema = z.object({ - type: z.literal("contentBlock.setStyle"), - id: z.string(), - style: contentBlockStyleSchema, -}); -const toolStatusStepStateStatusSchema = z.discriminatedUnion("type", [ - z.object({ - type: z.literal("generatingToolCall"), - name: z.string().optional(), - pluginIdentifier: z.string().optional(), - argumentsString: z.string().optional(), - }), - z.object({ - type: z.literal("toolCallGenerationFailed"), - error: z.string(), - rawContent: z.string().optional(), - }), - z.object({ - type: z.literal("toolCallQueued"), - }), - z.object({ - type: z.literal("confirmingToolCall"), - }), - z.object({ - type: z.literal("toolCallDenied"), - denyReason: z.string().optional(), - }), - z.object({ - type: z.literal("callingTool"), - }), - z.object({ - type: z.literal("toolCallFailed"), - error: z.string(), - }), - z.object({ - type: z.literal("toolCallSucceeded"), - timeMs: z.number().int(), - }), -]); -const toolStatusStepStateSchema = z.object({ - status: toolStatusStepStateStatusSchema, - customStatus: z.string(), - customWarnings: z.array(z.string()), -}); -const processingUpdateToolStatusCreateSchema = z.object({ - type: z.literal("toolStatus.create"), - id: z.string(), - callId: z.number().int(), - state: toolStatusStepStateSchema, -}); -const processingUpdateToolStatusUpdateSchema = z.object({ - type: z.literal("toolStatus.update"), - id: z.string(), - state: toolStatusStepStateSchema, -}); -const processingUpdateToolStatusArgumentFragmentSchema = z.object({ - type: z.literal("toolStatus.argumentFragment"), - id: z.string(), - content: z.string(), -}); -const processingUpdateSetSenderNameSchema = z.object({ - type: z.literal("setSenderName"), - name: z.string(), -}); -const processingUpdateSchema = z.discriminatedUnion("type", [ - processingUpdateStatusCreateSchema, - processingUpdateStatusUpdateSchema, - processingUpdateStatusRemoveSchema, - processingUpdateCitationBlockCreateSchema, - processingUpdateDebugInfoBlockCreateSchema, - processingUpdateContentBlockCreateSchema, - processingUpdateContentBlockAppendTextSchema, - processingUpdateContentBlockAppendToolRequestSchema, - processingUpdateContentBlockReplaceToolRequestSchema, - processingUpdateContentBlockAppendToolResultSchema, - processingUpdateContentBlockReplaceTextSchema, - processingUpdateContentBlockSetPrefixSchema, - processingUpdateContentBlockSetSuffixSchema, - processingUpdateContentBlockAttachGenInfoSchema, - processingUpdateContentBlockSetStyleSchema, - processingUpdateToolStatusCreateSchema, - processingUpdateToolStatusUpdateSchema, - processingUpdateToolStatusArgumentFragmentSchema, - processingUpdateSetSenderNameSchema, -]); - -z.discriminatedUnion("type", [ - processingUpdateStatusCreateSchema, - processingUpdateStatusUpdateSchema, - processingUpdateStatusRemoveSchema, - processingUpdateCitationBlockCreateSchema, - processingUpdateDebugInfoBlockCreateSchema, - processingUpdateContentBlockCreateSchema, - processingUpdateContentBlockAppendTextSchema, - processingUpdateContentBlockReplaceTextSchema, - processingUpdateContentBlockAppendToolRequestSchema, - processingUpdateContentBlockReplaceToolRequestSchema, - processingUpdateContentBlockAppendToolResultSchema, - processingUpdateContentBlockAttachGenInfoSchema, - processingUpdateContentBlockSetStyleSchema, - processingUpdateToolStatusCreateSchema, - processingUpdateToolStatusUpdateSchema, - processingUpdateToolStatusArgumentFragmentSchema, - processingUpdateSetSenderNameSchema, -]); - -const processingRequestConfirmToolCallSchema = z.object({ - type: z.literal("confirmToolCall"), - callId: z.number().int(), - pluginIdentifier: z.string().optional(), - name: z.string(), - parameters: z.record(z.any()), -}); -const processingRequestTextInputSchema = z.object({ - type: z.literal("textInput"), - prompt: z.string(), -}); -const processingRequestSchema = z.discriminatedUnion("type", [ - processingRequestConfirmToolCallSchema, - processingRequestTextInputSchema, -]); -const processingRequestResponseConfirmToolCallSchema = z.object({ - type: z.literal("confirmToolCall"), - result: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("allow"), - toolArgsOverride: z.record(z.any()).optional(), - }), - z.object({ - type: z.literal("deny"), - denyReason: z.string().optional(), - }), - ]), -}); -const processingRequestResponseTextInputSchema = z.object({ - type: z.literal("textInput"), - result: z.string(), -}); -const processingRequestResponseSchema = z.discriminatedUnion("type", [ - processingRequestResponseConfirmToolCallSchema, - processingRequestResponseTextInputSchema, -]); - -z.object({ - modelTag: z.string().optional(), - ignoreUserConfig: z.boolean().optional(), -}); - -z.discriminatedUnion("type", [ - processingUpdateStatusCreateSchema, - processingUpdateStatusUpdateSchema, - processingUpdateStatusRemoveSchema, - processingUpdateCitationBlockCreateSchema, - processingUpdateDebugInfoBlockCreateSchema, -]); - -const tokenSourceIdentifierSchema = z.discriminatedUnion("type", [ - z.object({ - type: z.literal("model"), - identifier: z.string(), - }), - z.object({ - type: z.literal("generator"), - pluginIdentifier: z.string(), - }), -]); - -const modelInfoSchema = z.discriminatedUnion("type", [ - llmInfoSchema, - embeddingModelInfoSchema, -]); -const modelInstanceInfoSchema = z.discriminatedUnion("type", [ - llmInstanceInfoSchema, - embeddingModelInstanceInfoSchema, -]); - -const pluginConfigSpecifierSchema = z.discriminatedUnion("type", [ - z.object({ - type: z.literal("direct"), - config: kvConfigSchema, - workingDirectoryPath: z.string().optional(), - }), - z.object({ - type: z.literal("predictionProcess"), - pci: z.string(), - token: z.string(), - }), -]); - -const remotePluginInfoSchema = z.object({ - identifier: z.string(), - isDev: z.boolean(), - isTrusted: z.boolean(), - hasPromptPreprocessor: z.boolean(), - hasPredictionLoopHandler: z.boolean(), - hasToolsProvider: z.boolean(), - hasGenerator: z.boolean(), -}); - -const artifactDownloadPlanModelInfoSchema = z.object({ - displayName: z.string(), - sizeBytes: z.number(), - quantName: z.string().optional(), - compatibilityType: modelCompatibilityTypeSchema, -}); -const artifactDownloadPlanNodeStateSchema = z.enum(["pending", "fetching", "satisfied", "completed"]); -const artifactDownloadPlanNodeSchema = z.discriminatedUnion("type", [ - z.object({ - type: z.literal("artifact"), - owner: kebabCaseSchema, - name: kebabCaseWithDotsSchema, - state: artifactDownloadPlanNodeStateSchema, - artifactType: artifactTypeSchema.optional(), - sizeBytes: z.number().int().optional(), - dependencyNodes: z.array(z.number().int()), - }), - z.object({ - type: z.literal("model"), - state: artifactDownloadPlanNodeStateSchema, - resolvedSources: z.number().int().optional(), - totalSources: z.number().int().optional(), - alreadyOwned: artifactDownloadPlanModelInfoSchema.optional(), - selected: artifactDownloadPlanModelInfoSchema.optional(), - }), -]); -const artifactDownloadPlanSchema = z.object({ - nodes: z.array(artifactDownloadPlanNodeSchema), - downloadSizeBytes: z.number().int(), -}); - -const localArtifactFileEntrySchema = z.object({ - relativePath: z.string(), - sizeBytes: z.number().int(), -}); -const localArtifactFileListSchema = z.object({ - files: z.array(localArtifactFileEntrySchema), - usedIgnoreFile: z.string().nullable(), -}); - -const downloadProgressUpdateSchema = z.object({ - downloadedBytes: z.number().int(), - totalBytes: z.number().int(), - speedBytesPerSecond: z.number(), -}); - -const modelSearchResultDownloadOptionFitEstimationSchema = z.enum([ - "fullGPUOffload", - "partialGPUOffload", - "fitWithoutGPU", - "willNotFit", -]); -const modelSearchResultDownloadOptionDataSchema = z.object({ - quantization: z.string().optional(), - name: z.string(), - sizeBytes: z.number().int(), - fitEstimation: modelSearchResultDownloadOptionFitEstimationSchema, - recommended: z.boolean().optional(), - downloadIdentifier: z.string(), - indexedModelIdentifier: z.string(), -}); -const modelSearchResultIdentifierSchema = z.discriminatedUnion("type", [ - z.object({ - type: z.literal("catalog"), - identifier: z.string(), - }), - z.object({ - type: z.literal("hf"), - identifier: z.string(), - }), -]); -const modelSearchResultEntryDataSchema = z.object({ - name: z.string(), - identifier: modelSearchResultIdentifierSchema, - exact: z.boolean().optional(), - staffPick: z.boolean().optional(), -}); -const modelSearchOptsSchema = z.object({ - searchTerm: z.string().optional(), - limit: z.number().int().positive().max(25).optional(), - compatibilityTypes: z.array(modelCompatibilityTypeSchema).optional(), -}); - -const internalRetrievalResultEntrySchema = z.object({ - content: z.string(), - score: z.number(), - sourceIndex: z.number().int(), - pageNumber: z.union([z.number().int(), z.tuple([z.number().int(), z.number().int()])]).optional(), - lineNumber: z.union([z.number().int(), z.tuple([z.number().int(), z.number().int()])]).optional(), -}); -const internalRetrievalResultSchema = z.object({ - entries: z.array(internalRetrievalResultEntrySchema), -}); - -z.object({ - content: z.string(), - score: z.number(), - citation: citationSourceSchema, -}); - -const retrievalChunkingMethodSchema = z.discriminatedUnion("type", [ - z.object({ - type: z.literal("recursive-v1"), - chunkSize: z.number().int(), - chunkOverlap: z.number().int(), - }), -]); - -const retrievalFileProcessingStepSchema = z.enum(["loading", "chunking", "embedding"]); - -const acceleratorTypeSchema = z.enum(["unknown", "integratedGpu", "dedicatedGpu"]); -const acceleratorSchema = z.object({ - name: z.string(), - deviceId: z.number().int(), - totalMemoryBytes: z.number().int(), - type: acceleratorTypeSchema, -}); -z.object({ - key: z.string(), - name: z.string(), - accelerators: z.array(acceleratorSchema), -}); - -const serializedKVConfigSchematicsFieldSchema = z.object({ - shortKey: z.string(), - fullKey: z.string(), - typeKey: z.string(), - typeParams: jsonSerializableSchema, - defaultValue: jsonSerializableSchema, -}); -const serializedKVConfigSchematicsSchema = z.object({ - fields: z.array(serializedKVConfigSchematicsFieldSchema), - extensionPrefixes: z.array(z.string()).optional(), -}); -z.object({ - fullKey: z.string(), - error: jsonSerializableSchema, -}); - -const booleanOrMixedSchema = z.union([ - z.literal(true), - z.literal(false), - z.literal("mixed"), -]); -const virtualModelDefinitionMetadataOverridesSchema = z.object({ - domain: modelDomainTypeSchema.optional(), - architectures: z.array(z.string()).optional(), - compatibilityTypes: z.array(modelCompatibilityTypeSchema).optional(), - paramsStrings: z.array(z.string()).optional(), - minMemoryUsageBytes: z.number().optional(), - contextLengths: z.array(z.number()).optional(), - trainedForToolUse: booleanOrMixedSchema.optional(), - vision: booleanOrMixedSchema.optional(), - reasoning: booleanOrMixedSchema.optional(), - fim: booleanOrMixedSchema.optional(), -}); -const virtualModelDefinitionConcreteModelBaseSchema = z.object({ - key: z.string(), - sources: z.array(modelDownloadSourceSchema), -}); -const virtualModelCustomFieldSetJinjaVariableEffectSchema = z.object({ - type: z.literal("setJinjaVariable"), - variable: z.string(), -}); -const virtualModelCustomFieldPrependSystemPromptEffectSchema = z.object({ - type: z.literal("prependSystemPrompt"), - content: z.string(), -}); -const virtualModelCustomFieldAppendSystemPromptEffectSchema = z.object({ - type: z.literal("appendSystemPrompt"), - content: z.string(), -}); -const virtualModelCustomFieldDefinitionBaseSchema = z.object({ - key: z.string(), - displayName: z.string(), - description: z.string(), -}); -const virtualModelBooleanCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({ - type: z.literal("boolean"), - defaultValue: z.boolean(), - effects: z.array(z.discriminatedUnion("type", [ - virtualModelCustomFieldSetJinjaVariableEffectSchema, - virtualModelCustomFieldPrependSystemPromptEffectSchema, - virtualModelCustomFieldAppendSystemPromptEffectSchema, - ])), -}); -const virtualModelStringCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({ - type: z.literal("string"), - defaultValue: z.string(), - effects: z.array(z.discriminatedUnion("type", [virtualModelCustomFieldSetJinjaVariableEffectSchema])), -}); -const virtualModelSelectCustomFieldDefinitionSchema = virtualModelCustomFieldDefinitionBaseSchema.extend({ - type: z.literal("select"), - options: z.array(z.object({ - label: z.string(), - value: z.string(), - })), - defaultValue: z.string(), - effects: z.array(z.discriminatedUnion("type", [virtualModelCustomFieldSetJinjaVariableEffectSchema])), -}); -const virtualModelCustomFieldDefinitionSchema = z.discriminatedUnion("type", [ - virtualModelBooleanCustomFieldDefinitionSchema, - virtualModelStringCustomFieldDefinitionSchema, - virtualModelSelectCustomFieldDefinitionSchema, -]); -const virtualModelConditionEqualsSchema = z.object({ - type: z.literal("equals"), - key: z.string(), - value: jsonSerializableSchema, -}); -const virtualModelConditionSchema = z.discriminatedUnion("type", [ - virtualModelConditionEqualsSchema, -]); -const virtualModelSuggestionSchema = z.object({ - message: z.string(), - conditions: z.array(virtualModelConditionSchema), - fields: z.array(kvConfigFieldSchema).optional(), -}); -z.object({ - model: z.string().regex(/^[^/]+\/[^/]+$/), - base: z.union([z.string(), z.array(virtualModelDefinitionConcreteModelBaseSchema)]), - tags: z.array(z.string().max(100)).optional(), - config: z - .object({ - load: kvConfigSchema.optional(), - operation: kvConfigSchema.optional(), - }) - .optional(), - metadataOverrides: virtualModelDefinitionMetadataOverridesSchema.optional(), - customFields: z.array(virtualModelCustomFieldDefinitionSchema).optional(), - suggestions: z.array(virtualModelSuggestionSchema).optional(), -}); - -const logLevelSchema = z.enum(["debug", "info", "warn", "error"]); - -/** - * Call a user provided callback and log any errors that occur. This prevents the error from - * crashing the application. - */ -function safeCallCallback(logger, name, callback, args) { - if (callback === undefined) { - return; - } - try { - const maybePromise = callback(...args); - if (typeof maybePromise === "object" && typeof maybePromise.catch === "function") { - maybePromise.catch((error) => { - logger.error(`Error in the ${name} callback (triggered asynchronously):`, error); - }); - } - } - catch (error) { - logger.error(`Error in the ${name} callback:`, error); - } -} - -function isSimpleLogger(logger) { - return logger?.isSimpleLogger === true; -} -const defaultInfoPrefix = chalk.greenBright("I"); -const defaultWarnPrefix = chalk.yellowBright("W"); -const defaultErrorPrefix = chalk.redBright("E"); -const defaultDebugPrefix = chalk.blueBright("D"); -class SimpleLogger { - constructor(prefixText = "", parentLogger = console, { useLogLevelPrefixes, infoPrefix, warnPrefix, errorPrefix, debugPrefix, } = {}) { - this.isSimpleLogger = true; - this.infoPrefix = []; - this.warnPrefix = []; - this.errorPrefix = []; - this.debugPrefix = []; - if (isSimpleLogger(parentLogger)) { - useLogLevelPrefixes = useLogLevelPrefixes ?? parentLogger.opts.useLogLevelPrefixes; - infoPrefix = infoPrefix === undefined ? parentLogger.opts.infoPrefix : infoPrefix; - warnPrefix = warnPrefix === undefined ? parentLogger.opts.warnPrefix : warnPrefix; - errorPrefix = errorPrefix === undefined ? parentLogger.opts.errorPrefix : errorPrefix; - debugPrefix = debugPrefix === undefined ? parentLogger.opts.debugPrefix : debugPrefix; - if (prefixText === "") { - this.innerPrefix = parentLogger.innerPrefix; - this.fullPrefix = parentLogger.fullPrefix; - } - else { - if (parentLogger.fullPrefix === "") { - this.innerPrefix = prefixText; - } - else { - this.innerPrefix = `${parentLogger.innerPrefix}][${prefixText}`; - } - this.fullPrefix = chalk.whiteBright(`[${this.innerPrefix}]`); - } - this.parentLogger = parentLogger.parentLogger; - } - else { - useLogLevelPrefixes = useLogLevelPrefixes ?? false; - infoPrefix = infoPrefix === undefined ? defaultInfoPrefix : infoPrefix; - warnPrefix = warnPrefix === undefined ? defaultWarnPrefix : warnPrefix; - errorPrefix = errorPrefix === undefined ? defaultErrorPrefix : errorPrefix; - debugPrefix = debugPrefix === undefined ? defaultDebugPrefix : debugPrefix; - if (prefixText === "") { - this.innerPrefix = ""; - this.fullPrefix = ""; - } - else { - this.innerPrefix = prefixText; - this.fullPrefix = chalk.whiteBright(`[${this.innerPrefix}]`); - } - this.parentLogger = parentLogger; - } - if (useLogLevelPrefixes) { - if (infoPrefix !== null) { - this.infoPrefix.push(infoPrefix); - } - if (warnPrefix !== null) { - this.warnPrefix.push(warnPrefix); - } - if (errorPrefix !== null) { - this.errorPrefix.push(errorPrefix); - } - if (debugPrefix !== null) { - this.debugPrefix.push(debugPrefix); - } - } - if (this.fullPrefix !== "") { - this.infoPrefix.push(this.fullPrefix); - this.warnPrefix.push(this.fullPrefix); - this.errorPrefix.push(this.fullPrefix); - this.debugPrefix.push(this.fullPrefix); - } - this.opts = { - useLogLevelPrefixes, - infoPrefix, - warnPrefix, - errorPrefix, - debugPrefix, - }; - } - subclass(prefixText) { - return new SimpleLogger(`${this.innerPrefix}:${prefixText}`, this.parentLogger); - } - info(...messages) { - this.parentLogger.info(...this.infoPrefix, ...messages); - } - infoText(strings, ...values) { - this.info(text(strings, ...values)); - } - infoWithoutPrefix(...messages) { - this.parentLogger.info(...messages); - } - error(...messages) { - this.parentLogger.error(...this.errorPrefix, ...messages); - } - errorText(strings, ...values) { - this.error(text(strings, ...values)); - } - errorWithoutPrefix(...messages) { - this.parentLogger.error(...messages); - } - warn(...messages) { - this.parentLogger.warn(...this.warnPrefix, ...messages); - } - warnText(strings, ...values) { - this.warn(text(strings, ...values)); - } - warnWithoutPrefix(...messages) { - this.parentLogger.warn(...messages); - } - debug(...messages) { - this.parentLogger.debug(...this.debugPrefix, ...messages); - } - debugText(strings, ...values) { - this.debug(text(strings, ...values)); - } - debugWithoutPrefix(...messages) { - this.parentLogger.debug(...messages); - } - throw(message) { - throw new Error(`${this.fullPrefix} ${message}`); - } - logAtLevel(level, ...messages) { - switch (level) { - case "debug": - this.debug(...messages); - break; - case "info": - this.info(...messages); - break; - case "warn": - this.warn(...messages); - break; - case "error": - this.error(...messages); - break; - } - } - static fromMultiple(loggers, opts) { - return new SimpleLogger("", { - debug: (...messages) => { - for (const logger of loggers) { - logger.debug(...messages); - } - }, - info: (...messages) => { - for (const logger of loggers) { - logger.info(...messages); - } - }, - warn: (...messages) => { - for (const logger of loggers) { - logger.warn(...messages); - } - }, - error: (...messages) => { - for (const logger of loggers) { - logger.error(...messages); - } - }, - }, { - ...opts, - useLogLevelPrefixes: false, - }); - } -} - -var _a; -const finished = Symbol("finished"); -/** - * A StreamablePromise is a promise-like that is also async iterable. This means you can use it as a - * promise (awaiting it, using `.then`, `.catch`, etc.), and you can also use it as an async - * iterable (using `for await`). - * - * Notably, as much as it implements the async iterable interface, it is not a traditional iterable, - * as it internally maintains a buffer and new values are pushed into the buffer by the producer, as - * oppose to being pulled by the consumer. - * - * The async iterable interface is used instead of the Node.js object stream because streams are too - * clunky to use, and the `for await` syntax is much more ergonomic for most people. - * - * If any iterator is created for this instance, an empty rejection handler will be attached to the - * promise to prevent unhandled rejection warnings. - * - * This class is provided as an abstract class and is meant to be extended. Crucially, the `collect` - * method must be implemented, which will be called to convert an array of values into the final - * resolved value of the promise. - * - * In addition, the constructor of the subclass should be marked as private, and a static method - * that exposes the constructor, the `finished` method, and the `push` method should be provided. - * - * @typeParam TFragment - The type of the individual fragments that are pushed into the buffer. - * @typeParam TFinal - The type of the final resolved value of the promise. - * @public - */ -class StreamablePromise { - /** - * Called by the producer when it has finished producing values. If an error is provided, the - * promise will be rejected with that error. If no error is provided, the promise will be resolved - * with the final value. - * - * This method should be exposed in the static constructor of the subclass. - * - * @param error - The error to reject the promise with, if any. - */ - finished(error) { - if (this.status !== "pending") { - throw new Error("`finished` called while not pending"); - } - if (error === undefined) { - this.status = "resolved"; - this.nextFragmentPromiseBundle?.resolve(finished); - this.resolveFinal(this.collect(this.buffer)); - } - else { - this.status = "rejected"; - this.nextFragmentPromiseBundle?.reject(error); - this.rejectFinal(error); - } - } - /** - * Called by the producer to push a new fragment into the buffer. This method should be exposed in - * the static constructor of the subclass. - * - * This method should be exposed in the static constructor of the subclass. - * - * @param fragment - The fragment to push into the buffer. - */ - push(fragment) { - if (this.status !== "pending") { - throw new Error("`push` called while not pending"); - } - this.buffer.push(fragment); - this.nextFragmentPromiseBundle?.resolve(fragment); - this.nextFragmentPromiseBundle = null; - } - constructor() { - this.status = "pending"; - this.buffer = []; - this.nextFragmentPromiseBundle = null; - /** - * If there has ever been any iterators created for this instance. Once any iterator is created, - * a reject handler will be attached to the promise to prevent unhandled rejection warnings, as - * the errors will be handled by the iterator. - * - * The purpose of this variable is to prevent registering the reject handler more than once. - */ - this.hasIterator = false; - this[_a] = "StreamablePromise"; - const { promise, resolve, reject } = makePromise(); - this.promiseFinal = promise; - this.resolveFinal = resolve; - this.rejectFinal = reject; - } - then(onfulfilled, onrejected) { - return this.promiseFinal.then(onfulfilled, onrejected); - } - catch(onrejected) { - return this.promiseFinal.catch(onrejected); - } - finally(onfinally) { - return this.promiseFinal.finally(onfinally); - } - /** - * If nextFragmentPromiseBundle exists, it is returned. Otherwise, a new one is created and - * returned. - */ - obtainNextFragmentPromiseBundle() { - if (this.nextFragmentPromiseBundle === null) { - this.nextFragmentPromiseBundle = makePromise(); - } - return this.nextFragmentPromiseBundle; - } - async *[(_a = Symbol.toStringTag, Symbol.asyncIterator)]() { - if (!this.hasIterator) { - this.promiseFinal.catch(() => { }); // Prevent unhandled rejection warning - this.hasIterator = true; - } - let i = 0; - while (i < this.buffer.length || this.status === "pending") { - if (i < this.buffer.length) { - yield this.buffer[i]; - i++; - } - else { - const nextFragmentPromiseBundle = this.obtainNextFragmentPromiseBundle(); - const nextFragment = await nextFragmentPromiseBundle.promise; - if (nextFragment === finished) { - // Make sure the promise is resolved before breaking the loop. - break; - } - yield nextFragment; - i++; - } - } - await this.promiseFinal; - // Wait for one more microtask to ensure that the promise is resolved before terminating the - // loop. This ensures that the by the time async loop is terminated, the onMessage handler is - // already triggered. - await Promise.resolve(); - } -} - -class Validator { - constructor({ attachStack } = {}) { - this.attachStack = attachStack ?? true; - } - /** - * Pretty-prints a Zod error. - * - * @param rootObjectName - The name of the object being validated (used for error messages) - * @param error - The Zod error to pretty-print - * - * @returns The pretty-printed error in a string - */ - static prettyPrintZod(rootObjectName, error) { - return error.errors - .map(e => { - if (e.path.length === 0) { - return `- ${chalk.redBright(rootObjectName)}: ${e.message}`; - } - const path = chalk.red(`.${e.path.join(".")}`); - return `- ${chalk.redBright(rootObjectName)}${path}: ${e.message}`; - }) - .join("\n"); - } - /** - * Validates a value against a schema and throws an error if it's invalid. - * - * @param lead - The start of the error message (used for error messages) - * @param rootObjectName - The name of the object being validated (used for error messages) - * @param schema - The schema to validate against - * @param value - The value to validate - * - * @returns The validated value - * @throws An error if the value is invalid - */ - validateOrThrow(lead, rootObjectName, schema, value, stack) { - const result = schema.safeParse(value); - if (result.success) { - return result.data; - } - else { - throw makePrettyError(`${lead}\n\n${Validator.prettyPrintZod(rootObjectName, result.error)}`, this.attachStack ? stack : undefined); - } - } - /** - * Validates multiple values against multiple schemas and throws an error if any of them are - * invalid. All values are validated before any errors are thrown. This is useful when you want to - * validate multiple values at once and want to see all the errors at once. - * - * @param leadProducer - The function to produce the start of the error message (used for error). - * It is called with a set of indices of the invalid values. - * @param rootObjectNames - The names of the objects being validated (used for error messages) - * @param schemas - The schemas to validate against - * @param values - The values to validate - * - * @returns The validated values - * @throws An error if any of the values are invalid - */ - validateMultipleOrThrow(leadProducer, rootObjectNames, schemas, values, stack) { - const results = schemas.map((schema, index) => schema.safeParse(values[index])); - const errors = results - .map((result, index) => ({ result, index, rootObjectName: rootObjectNames[index] })) - .filter(({ result }) => !result.success) - .map(({ result, rootObjectName, index }) => ({ - error: result.error, - rootObjectName, - index, - })); - if (errors.length === 0) { - return results.map(result => result.data); - } - else { - const erroredValues = new Set(errors.map(({ index }) => index)); - const lead = leadProducer(erroredValues); - throw makePrettyError(`${lead}\n\n${errors - .map(({ error, rootObjectName }) => Validator.prettyPrintZod(rootObjectName, error)) - .join("\n")}`, this.attachStack ? stack : undefined); - } - } - /** - * Validates a value against a schema and throws an error if it's invalid. This is a convenience - * function for validating one single method parameter. - * - * @param className - The name of the class containing the method (used for error messages) - * @param methodName - The name of the method (used for error messages) - * @param paramName - The name of the parameter being validated (used for error messages) - * @param schema - The schema to validate against - * @param value - The value to validate - * - * @returns The validated value - * @throws An error if the value is invalid - */ - validateMethodParamOrThrow(className, methodName, paramName, schema, value, stack) { - const functionCall = chalk.yellowBright(text ` - ${className}.${methodName}(${chalk.redBright(paramName)}) - `); - return this.validateOrThrow(`Invalid parameter(s) for ${functionCall}:`, paramName, schema, value, stack); - } - /** - * Validates multiple values against multiple schemas and throws an error if any of them are - * invalid. This is a convenience function for validating multiple method parameters. - * - * @param className - The name of the class containing the method (used for error messages) - * @param methodName - The name of the method (used for error messages) - * @param paramNames - The names of the parameters being validated (used for error messages) - * @param schemas - The schemas to validate against - * @param values - The values to validate - * - * @returns The validated values - * @throws An error if any of the values are invalid - */ - validateMethodParamsOrThrow(className, methodName, paramNames, schemas, values, stack) { - return this.validateMultipleOrThrow(erroredValues => { - const coloredParamNames = paramNames.map((name, index) => erroredValues.has(index) ? chalk.redBright(name) : name); - const functionCall = chalk.yellowBright(text ` - ${className}.${methodName}(${coloredParamNames.join(", ")}) - `); - return `Invalid parameter(s) for ${functionCall}:`; - }, paramNames, schemas, values, stack); - } - /** - * Validates a value against a schema and throws an error if it's invalid. This is a convenience - * function for validating one single constructor parameter. - * - * @param className - The name of the class (used for error messages) - * @param paramName - The name of the parameter being validated (used for error messages) - * @param schema - The schema to validate against - * @param value - The value to validate - * - * @returns The validated value - * @throws An error if the value is invalid - */ - validateConstructorParamOrThrow(className, paramName, schema, value, stack) { - const functionCall = chalk.yellowBright(text ` - ${className}(${chalk.redBright(paramName)}) - `); - return this.validateOrThrow(`Invalid parameter(s) when constructing ${functionCall}`, paramName, schema, value, stack); - } - /** - * Validates multiple values against multiple schemas and throws an error if any of them are - * invalid. This is a convenience function for validating multiple constructor parameters. - * - * @param className - The name of the class (used for error messages) - * @param paramNames - The names of the parameters being validated (used for error messages) - * - * @param schemas - The schemas to validate against - * @param values - The values to validate - */ - validateConstructorParamsOrThrow(className, paramNames, schemas, values, stack) { - return this.validateMultipleOrThrow(erroredValues => { - const coloredParamNames = paramNames.map((name, index) => erroredValues.has(index) ? chalk.redBright(name) : name); - const functionCall = chalk.yellowBright(text ` - ${className}(${coloredParamNames.join(", ")}) - `); - return `Invalid parameter(s) when constructing ${functionCall}:`; - }, paramNames, schemas, values, stack); - } -} -const sharedValidator = new Validator(); - -/** - * Represents a file. Currently, the file can be either in the local file system or base64 encoded. - * - * @public - */ -class FileHandle { - /** - * @deprecated Direct construction is not recommended. Please use the `prepareFile` API instead - */ - constructor(filesNamespace, identifier, type, sizeBytes, - /** - * Original file name - */ - name) { - this.filesNamespace = filesNamespace; - this.identifier = identifier; - this.type = type; - this.sizeBytes = sizeBytes; - this.name = name; - this.parsedIdentifier = parseFileIdentifier(identifier); - } - /** - * Gets the absolute file path of this file. - */ - async getFilePath() { - switch (this.parsedIdentifier.type) { - case "local": { - return (await this.filesNamespace.getLocalFileAbsolutePath(this.parsedIdentifier.fileName)) - .path; - } - case "base64": { - throw new Error("Not implemented. Please open an issue on GitHub if you encountered this error."); - } - default: { - const _exhaustiveCheck = this.parsedIdentifier; - throw new Error(`Unexpected file identifier type: ${JSON.stringify(_exhaustiveCheck)}`); - } - } - } - isImage() { - return this.type === "image"; - } -} - -const chatMessageInputSchema = z.object({ - role: z.enum(["user", "assistant", "system"]).optional(), - content: z.string().optional(), - images: z.array(z.instanceof(FileHandle)).optional(), -}); -const chatHistoryInputSchema = z.array(chatMessageInputSchema); -/** - * Given a `ChatMessageInput` or `ChatMessageData`, returns true if the input is a - * `ChatMessageInput`. - */ -function isChatMessageInputAsOpposeToChatMessageData(chatMessageInput) { - return !Array.isArray(chatMessageInput.content); -} -function isChatMessageInputAsOpposeToChatHistoryData(chatMessageInput) { - return !("messages" in chatMessageInput); -} -function chatMessageInputToChatMessageData(chatMessageInput) { - const { role, content, images } = chatMessageInput; - const parts = []; - if (images === undefined || images.length === 0) { - if (content === undefined) { - // If both content and file are undefined, let's just create an empty part. - parts.push({ - type: "text", - text: "", - }); - } - } - else { - for (const file of images) { - parts.push({ - type: "file", - identifier: file.identifier, - name: file.name, - fileType: file.type, - sizeBytes: file.sizeBytes, - }); - } - } - if (content !== undefined) { - parts.push({ - type: "text", - text: content, - }); - } - return { - role: role ?? "user", - content: parts, - }; -} - -/** - * Represents a chat history. - * - * @public - */ -class Chat extends MaybeMutable { - getClassName() { - return "Chat"; - } - create(data, mutable) { - return new Chat(data, mutable); - } - cloneData(data) { - return chatHistoryDataSchema.parse(data); // Using zod to clone the data - } - /** - * Don't use this constructor directly. - * - * - To create an empty chat history, use `Chat.empty()`. - * - To create a chat history with existing data, use `Chat.from()`. - */ - constructor(data, mutable) { - super(data, mutable); - } - /** - * Creates an empty mutable chat history. - */ - static empty() { - return new Chat({ messages: [] }, true); - } - /** - * Quickly create a mutable chat history with something that can be converted to a chat history. - * - * The created chat history will be a mutable copy of the input. - * - * @example - * ```ts - * const history = Chat.from([ - * { role: "user", content: "Hello" }, - * { role: "assistant", content: "Hi!" }, - * { role: "user", content: "What is your name?" }, - * ]); - * ``` - */ - static from(initializer) { - const stack = getCurrentStack(1); - sharedValidator.validateMethodParamOrThrow("Chat", "from", "initializer", chatHistoryLikeSchema, initializer, stack); - if (initializer instanceof Chat) { - // Chat - return initializer.asMutableCopy(); - } - if (typeof initializer === "string") { - const chatHistory = Chat.empty(); - chatHistory.append("user", initializer); - return chatHistory; - } - if (Array.isArray(initializer)) { - // ChatInput - return new Chat({ messages: initializer.map(chatMessageInputToChatMessageData) }, true); - } - if (isChatMessageInputAsOpposeToChatHistoryData(initializer)) { - // ChatMessageInput - return new Chat({ messages: [chatMessageInputToChatMessageData(initializer)] }, true); - } - else { - // ChatHistoryData - return new Chat(initializer, false).asMutableCopy(); - } - } - /** - * Creates a chat history with raw data. This method is intended for internal use only. - * - * If mutable is set to false, you MUST ensure that the data is not mutated. - * - * @internal - */ - static createRaw(data, mutable) { - return new Chat(data, mutable); - } - /** - * Gets the raw data of this message. This method is intended for internal use only. - * - * If mutable is set to false, you MUST ensure that the data is not mutated. - * - * @internal - */ - getRaw() { - return this.data; - } - append(...args) { - this.guardMutable(); - if (args.length === 1) { - const [chatMessageLike] = args; - const chatMessage = ChatMessage.from(chatMessageLike); - const messageMutable = accessMaybeMutableInternals(chatMessage)._internalToMutable(); - this.data.messages.push(accessMaybeMutableInternals(messageMutable)._internalGetData()); - } - else { - const [role, content, opts = {}] = args; - if (role === "user" || role === "system" || role === "assistant") { - const parts = [ - { type: "text", text: content }, - ]; - if (opts.images !== undefined) { - for (const image of opts.images) { - parts.push({ - type: "file", - name: image.name, - identifier: image.identifier, - sizeBytes: image.sizeBytes, - fileType: image.type, - }); - } - } - this.data.messages.push({ role, content: parts }); - } - else { - throw new Error(text ` - Unsupported role for append() API with [role, content] parameters: ${role}. - Supported roles are 'user', 'system', and 'assistant'. - `); - } - } - } - withAppended(...args) { - const copy = this.asMutableCopy(); - copy.append(...args); - return copy; - } - /** - * Get the number of messages in the history. - */ - getLength() { - return this.data.messages.length; - } - /** - * Get the number of messages in the history. - */ - get length() { - return this.getLength(); - } - /** - * Remove the last message from the history. If the history is empty, this method will throw. - */ - pop() { - this.guardMutable(); - if (this.data.messages.length === 0) { - throw new Error("Tried to pop from an empty history."); - } - const popped = this.data.messages.pop(); - return ChatMessage.createRaw(popped, true); - } - /** - * Gets all files contained in this history. - * - * @param client - LMStudio client - */ - getAllFiles(client) { - return this.data.messages - .flatMap(message => message.content.filter(part => part.type === "file")) - .map(part => new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name)); - } - /** - * Allows iterating over the files in the history. - */ - *files(client) { - for (const message of this.data.messages) { - for (const part of message.content) { - if (part.type === "file") { - yield new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name); - } - } - } - } - /** - * Returns true if this history contains any files. - */ - hasFiles() { - return this.data.messages.some(message => message.content.some(part => part.type === "file")); - } - /** - * Gets the message at the given index. If the index is negative, it will be counted from the end. - * - * If the index is out of bounds, this method will throw as oppose to returning undefined. This is - * to help catch bugs early. - */ - at(index) { - let actualIndex = index; - if (index < 0) { - actualIndex = this.data.messages.length + index; - } - if (actualIndex < 0 || actualIndex >= this.data.messages.length) { - throw new Error(text ` - Tried to access the message at index ${index}, but the history only has - ${this.data.messages.length} messages. - `); - } - return ChatMessage.createRaw(this.data.messages[actualIndex], this.mutable); - } - /** - * Get all the messages in the history as an array of ChatMessage objects. - */ - getMessagesArray() { - return this.data.messages.map(message => ChatMessage.createRaw(message, this.mutable)); - } - /** - * Maps over the messages in the history and returns an array of the results. - */ - map(mapper) { - return this.getMessagesArray().map(mapper); - } - /** - * Maps over the messages in the history and returns a flattened array of the results. - * - * This is similar to `Array.prototype.flatMap`, but it works with ChatMessage objects. - */ - flatMap(mapper) { - return this.getMessagesArray().flatMap(mapper); - } - /** - * Allows iterating over the messages in the history. - */ - *[Symbol.iterator]() { - for (const message of this.data.messages) { - yield ChatMessage.createRaw(message, this.mutable); - } - } - /** - * Given a predicate, the predicate is called for each file in the history. - * - * - If the predicate returns true, the file is removed from the history and is collected into the - * returned array. - * - If the predicate returns false, the file is kept in the history. - * - * This method is useful if you are implementing a promptPreprocessor that needs to convert certain - * types of files. - * - * If the predicate needs to be async, use the {@link Chat#consumeFilesAsync} method. - * - * @param client - LMStudio client - * @param predicate - The predicate to call for each file. - * @returns The files that were consumed. - */ - consumeFiles(client, predicate) { - this.guardMutable(); - const consumedFiles = []; - for (const message of this.data.messages) { - consumedFiles.push(...ChatMessage.createRaw(message, true).consumeFiles(client, predicate)); - } - return consumedFiles; - } - /** - * Given an async predicate, the predicate is called for each file in the history. - * - * - If the predicate returns true, the file is removed from the history and is collected into the - * returned array. - * - If the predicate returns false, the file is kept in the history. - * - * This method is useful if you are implementing a promptPreprocessor that needs to convert certain - * types of files. - * - * If you need a synchronous version, use the {@link Chat#consumeFiles} method. - * - * @param client - LMStudio client - * @param predicate - The predicate to call for each file. - * @returns The files that were consumed. - */ - async consumeFilesAsync(client, predicate) { - this.guardMutable(); - const consumedFiles = []; - for (const message of this.data.messages) { - consumedFiles.push(...(await ChatMessage.createRaw(message, true).consumeFilesAsync(client, predicate))); - } - return consumedFiles; - } - getSystemPrompt() { - return this.data.messages - .filter(message => message.role === "system") - .map(message => message.content - .filter(part => part.type === "text") - .map(part => part.text) - .join(" ")) - .join("\n\n"); - } - replaceSystemPrompt(content) { - this.guardMutable(); - this.data.messages = this.data.messages.filter(message => message.role !== "system"); - this.data.messages.unshift({ role: "system", content: [{ type: "text", text: content }] }); - } - filterInPlace(predicate) { - this.guardMutable(); - this.data.messages = this.data.messages.filter(message => predicate(ChatMessage.createRaw(message, true))); - } - toString() { - return ("Chat {\n" + - this.data.messages - .map(message => { - const messageString = ChatMessage.createRaw(message, false).toString(); - return messageString - .split("\n") - .map(line => " " + line) - .join("\n"); - }) - .join("\n") + - "\n}"); - } -} -const chatHistoryLikeSchema = z.union([ - z.instanceof(Chat), - chatHistoryDataSchema, - z.string(), - chatHistoryInputSchema, - chatMessageInputSchema, -]); -/** - * Represents a single message in the history. - * - * @public - */ -class ChatMessage extends MaybeMutable { - getClassName() { - return "ChatMessage"; - } - create(data, mutable) { - return new ChatMessage(data, mutable); - } - cloneData(data) { - return chatMessageDataSchema.parse(data); // Using zod to clone the data - } - constructor(data, mutable) { - super(data, mutable); - } - /** - * Create a mutable text only message. - */ - static create(role, content) { - return new ChatMessage(chatMessageDataSchema.parse({ - role, - content: [{ type: "text", text: content }], - }), true); - } - /** - * Quickly create a mutable message with something that can be converted to a message. - */ - static from(initializer) { - const stack = getCurrentStack(1); - sharedValidator.validateMethodParamOrThrow("ChatMessage", "from", "initializer", chatMessageLikeSchema, initializer, stack); - if (initializer instanceof ChatMessage) { - // ChatMessage - return initializer.asMutableCopy(); - } - if (typeof initializer === "string") { - return new ChatMessage(chatMessageDataSchema.parse({ - role: "user", - content: [{ type: "text", text: initializer }], - }), true); - } - if (isChatMessageInputAsOpposeToChatMessageData(initializer)) { - // ChatMessageData - return new ChatMessage(chatMessageInputToChatMessageData(initializer), true); - } - else { - // ChatMessageInput - return new ChatMessage(initializer, true); - } - } - /** - * Creates a chat history with raw data. This method is intended for internal use only. - * - * If mutable is set to false, you MUST ensure that the data is not mutated. - * - * @internal - */ - static createRaw(data, mutable) { - return new ChatMessage(data, mutable); - } - /** - * Gets the raw data of this message. This method is intended for internal use only. - * - * If mutable is set to false, you MUST ensure that the data is not mutated. - * - * @internal - */ - getRaw() { - return this.data; - } - getRole() { - return this.data.role; - } - setRole(role) { - this.guardMutable(); - this.data.role = role; - } - getFileParts() { - return this.data.content.filter(part => part.type === "file"); - } - /** - * Gets all text contained in this message. - */ - getText() { - return this.data.content - .filter(part => part.type === "text") - .map(part => part.text) - .join(" "); - } - /** - * Get all tool call results within this message. - */ - getToolCallResults() { - return this.data.content - .filter(part => part.type === "toolCallResult") - .map(part => ({ - content: part.content, - toolCallId: part.toolCallId, - })); - } - /** - * Gets all file parts contained in this message. - */ - getToolCallRequests() { - return this.data.content - .filter(part => part.type === "toolCallRequest") - .map(part => part.toolCallRequest); - } - /** - * Gets all files contained in this message. - * - * @param client - LMStudio client - */ - getFiles(client) { - return this.getFileParts().map(part => new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name)); - } - /** - * Allows iterating over the files in the message. - */ - *files(client) { - for (const part of this.getFileParts()) { - yield new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name); - } - } - /** - * Given a predicate, the predicate is called for each file in the message. - * - * - If the predicate returns true, the file is removed from the message and is collected into the - * returned array. - * - If the predicate returns false, the file is kept in the message. - * - * This method is useful if you are implementing a promptPreprocessor that needs to convert certain - * types of files. - * - * If the predicate needs to be async, use the {@link ChatMessage#consumeFilesAsync} method. - * - * @param client - LMStudio client - * @param predicate - The predicate to call for each file. - * @returns The files that were consumed. - */ - consumeFiles(client, predicate) { - this.guardMutable(); - const consumedFiles = []; - const partIndexesToRemove = new Set(); - for (const [index, part] of this.data.content.entries()) { - if (part.type !== "file") { - continue; - } - const file = new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name); - if (predicate(file)) { - consumedFiles.push(file); - partIndexesToRemove.add(index); - } - } - this.data.content = this.data.content.filter((_, index) => !partIndexesToRemove.has(index)); - return consumedFiles; - } - /** - * Given an async predicate, the predicate is called for each file in the message. - * - * - If the predicate returns true, the file is removed from the message and is collected into the - * returned array. - * - If the predicate returns false, the file is kept in the message. - * - * This method is useful if you are implementing a promptPreprocessor that needs to convert certain - * types of files. - * - * If you need a synchronous version, use the {@link ChatMessage#consumeFiles} method. - * - * @param client - LMStudio client - * @param predicate - The predicate to call for each file. - * @returns The files that were consumed. - */ - async consumeFilesAsync(client, predicate) { - this.guardMutable(); - const consumedFiles = []; - const partIndexesToRemove = new Set(); - for (const [index, part] of this.data.content.entries()) { - if (part.type !== "file") { - continue; - } - const file = new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name); - if (await predicate(file)) { - consumedFiles.push(file); - partIndexesToRemove.add(index); - } - } - this.data.content = this.data.content.filter((_, index) => !partIndexesToRemove.has(index)); - return consumedFiles; - } - /** - * Returns true if this message contains any files. - */ - hasFiles() { - return this.data.content.some(part => part.type === "file"); - } - /** - * Append text to the message. - */ - appendText(text) { - this.guardMutable(); - switch (this.data.role) { - case "assistant": - case "user": - case "system": - this.data.content.push({ - type: "text", - text, - }); - break; - case "tool": - throw new Error(`Cannot append text to a message with role "${this.data.role}"`); - default: { - const exhaustiveCheck = this.data; - throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`); - } - } - } - /** - * Append a file to the message. Takes in a FileHandle. You can obtain a FileHandle from - * `client.files.prepareImage`. - */ - appendFile(file) { - this.guardMutable(); - switch (this.data.role) { - case "assistant": - case "user": - case "system": - this.data.content.push({ - type: "file", - name: file.name, - identifier: file.identifier, - sizeBytes: file.sizeBytes, - fileType: file.type, - }); - break; - case "tool": - throw new Error(`Cannot append text to a message with role "${this.data.role}"`); - default: { - const exhaustiveCheck = this.data; - throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`); - } - } - } - /** - * Replaces all text in the messages. - * - * If the message contains other components (such as files), they will kept. The replaced text - * will be inserted to the beginning of the message. - */ - replaceText(text) { - this.guardMutable(); - switch (this.data.role) { - case "assistant": - case "user": - case "system": - this.data.content = [ - { type: "text", text }, - ...this.data.content.filter(part => part.type !== "text"), - ]; - break; - case "tool": - throw new Error(`Cannot replace text in a message with role "${this.data.role}"`); - default: { - const exhaustiveCheck = this.data; - throw new Error(`Unhandled role in switch statement: ${exhaustiveCheck.role}`); - } - } - } - isSystemPrompt() { - return this.data.role === "system"; - } - isUserMessage() { - return this.data.role === "user"; - } - isAssistantMessage() { - return this.data.role === "assistant"; - } - toString() { - const text = this.data.content - .map(part => { - switch (part.type) { - case "text": - return part.text; - case "file": - return ``; - case "toolCallRequest": - return (part.toolCallRequest.name + `(${JSON.stringify(part.toolCallRequest.arguments)})`); - case "toolCallResult": - return part.content; - default: { - const exhaustiveCheck = part; - throw new Error(`Unknown part type: ${exhaustiveCheck.type}`); - } - } - }) - .join(" "); - if (text.includes("\n")) { - return (this.data.role + - ":\n" + - text - .split("\n") - .map(line => " " + line) - .join("\n")); - } - else { - return this.data.role + ": " + text; - } - } -} -const chatMessageLikeSchema = z.union([ - z.instanceof(ChatMessage), - chatMessageInputSchema, - z.string(), - chatMessageDataSchema, -]); - -/** - * A builder for building a KVFieldValueTypeLibrary. - * - * The reason why a builder is used is to enable much better type inference when defining the value - * types. - */ -class KVFieldValueTypesLibraryBuilder { - constructor(baseSchema) { - this.baseSchema = baseSchema; - this.valueTypes = new Map(); - } - /** - * Define a new field value type. - */ - valueType(key, param) { - if (this.valueTypes.has(key)) { - throw new Error(`ValueType with key ${key} already exists`); - } - this.valueTypes.set(key, { - paramType: z.object({ - ...this.baseSchema, - ...param.paramType, - }), - schemaMaker: param.schemaMaker, - effectiveEquals: param.effectiveEquals, - stringify: param.stringify, - }); - return this; - } - build() { - return new KVFieldValueTypeLibrary(new Map(this.valueTypes)); - } -} -/** - * Represents a library of field value types. - * - * @public - */ -class KVFieldValueTypeLibrary { - constructor(valueTypes) { - this.valueTypes = valueTypes; - } - /** - * Gets the schema for a specific field value type with the given key and parameters. - */ - getSchema(key, param) { - const valueType = this.valueTypes.get(key); - if (valueType === undefined) { - throw new Error(`Cannot find value type ${key}`); - } - return valueType.schemaMaker(valueType.paramType.parse(param)); - } - parseParamTypes(key, param) { - return this.valueTypes.get(key).paramType.parse(param); - } - effectiveEquals(key, typeParam, a, b) { - return this.valueTypes.get(key).effectiveEquals(a, b, typeParam); - } - stringify(key, typeParam, opts, value) { - return this.valueTypes.get(key).stringify(value, typeParam, opts); - } -} -class KVConfigSchematicsBuilder { - constructor(valueTypeLibrary) { - this.valueTypeLibrary = valueTypeLibrary; - this.fields = new Map(); - /** - * Prefixes for extensions. Does not affect parsing (i.e. extension fields will still not be - * visible). However, if a key starts with a prefix that is specified here, it will not be removed - * when going through the lenient zod schema. - */ - this.extensionPrefixes = []; - } - /** - * Adds a field - */ - field(key, valueTypeKey, valueTypeParams, defaultValue) { - const schema = this.valueTypeLibrary.getSchema(valueTypeKey, valueTypeParams); - const defaultValueParseResult = schema.safeParse(defaultValue); - if (!defaultValueParseResult.success) { - throw new Error(`Invalid default value for field ${key}: ${defaultValueParseResult.error.message}`); - } - defaultValue = defaultValueParseResult.data; - if (this.fields.has(key)) { - throw new Error(`Cannot add field with key ${key}. Key already exists in the schematics.`); - } - this.fields.set(key, { - valueTypeKey, - valueTypeParams, - schema: this.valueTypeLibrary.getSchema(valueTypeKey, valueTypeParams), - fullKey: key, - defaultValue, - }); - return this; - } - /** - * Adds an extension point. For example, if called with .extension("hello.world"), then any keys - * that match "hello.world.*" will be allowed when going through lenient zod schema. However, - * any extension fields will still not be accessible via this schematics. - */ - extension(prefix) { - this.extensionPrefixes.push(`${prefix}.`); - return this; - } - /** - * Convenience method for grouping a set of fields under a shared namespace. - * - * For example, if we want to create two fields: `some:namespace:a` and `some:namespace:b`. - * Instead of doing: - * - * ```ts - * builder - * .field("some:namespace:a", ...) - * .field("some:namespace:b", ...) - * ``` - * - * We can do: - * - * ```ts - * builder.scope("some:namespace", builder => - * builder - * .field("a", ...) - * .field("b", ...) - * ) - * ``` - * - * This method does support nesting. Whether to nest or not is up to the user. - */ - scope(scopeKey, fn) { - const innerBuilder = fn(new KVConfigSchematicsBuilder(this.valueTypeLibrary)); - for (const [key, { valueTypeKey, valueTypeParams, schema, defaultValue },] of innerBuilder.fields.entries()) { - const fullKey = `${scopeKey}.${key}`; - if (this.fields.has(fullKey)) { - throw new Error(`Cannot add field with key ${fullKey}. Key already exists in the schematics.`); - } - this.fields.set(fullKey, { - valueTypeKey, - valueTypeParams, - schema, - fullKey, - defaultValue, - }); - } - this.extensionPrefixes.push(...innerBuilder.extensionPrefixes.map(prefix => `${scopeKey}.${prefix}`)); - return this; - } - build() { - return new KVConfigSchematics(this.valueTypeLibrary, this.fields, this.extensionPrefixes); - } -} -const createParsedKVConfig = Symbol("createParsedKVConfig"); -class KVConfigSchematics { - constructor(valueTypeLibrary, fields, extensionPrefixes) { - this.valueTypeLibrary = valueTypeLibrary; - this.fields = fields; - this.extensionPrefixes = extensionPrefixes; - /** - * Cached full key map - */ - this.fullKepMap = undefined; - /** - * Cached lenient zod schema - */ - this.lenientZodSchema = undefined; - } - getFieldsMap() { - return new Map([...this.fields.values()].map(field => [field.fullKey, field])); - } - obtainField(key) { - const field = this.fields.get(key); - if (field === undefined) { - const fieldKeys = [...this.fields.keys()]; - let availableList = fieldKeys - .slice(0, 10) - .map(key => `- ${key}`) - .join("\n"); - if (fieldKeys.length > 10) { - availableList += `\n... and ${fieldKeys.length - 10} more`; - } - throw new Error(`Cannot access key ${key}. Key does not exist in the schematics. Available keys:\n\n` + - availableList); - } - return field; - } - obtainFieldByFullKey(fullKey) { - const field = this.getFullKeyMap().get(fullKey); - if (field === undefined) { - const fieldKeys = [...this.getFullKeyMap().keys()]; - let availableList = fieldKeys - .slice(0, 10) - .map(key => `- ${key}`) - .join("\n"); - if (fieldKeys.length > 10) { - availableList += `\n... and ${fieldKeys.length - 10} more`; - } - throw new Error(`Cannot access full key ${fullKey}. Full key does not exist in the schematics. Available` + - `keys:\n\n` + - availableList); - } - return field; - } - getSchemaForKey(key) { - const field = this.obtainField(key); - return field.schema; - } - parseField(fieldSchema, value) { - if (value === undefined) { - if (fieldSchema.defaultValue === undefined) { - throw new Error(`Field with key ${fieldSchema.fullKey} is missing and has no default value`); - } - return fieldSchema.defaultValue; - } - const parseResult = fieldSchema.schema.safeParse(value); - if (!parseResult.success) { - throw new Error(`Field with key ${fieldSchema.fullKey} does not satisfy the schema:` + - parseResult.error.message); - } - return parseResult.data; - } - parseFieldWithoutDefault(field, value) { - if (value === undefined) { - return undefined; - } - const parseResult = field.schema.safeParse(value); - if (!parseResult.success) { - throw new Error(`Field with key ${field.fullKey} does not satisfy the schema:` + parseResult.error.message); - } - return parseResult.data; - } - /** - * Parse and access a field in the config. - */ - access(config, key) { - const field = this.obtainField(key); - return this.parseField(field, config.fields.find(f => f.key === field.fullKey)?.value); - } - accessByFullKey(config, fullKey) { - const field = this.obtainFieldByFullKey(fullKey); - return this.parseField(field, config.fields.find(f => f.key === field.fullKey)?.value); - } - /** - * Parse and access a field in the config. Returns undefined if the field is missing. - */ - accessPartial(config, key) { - const field = this.obtainField(key); - return this.parseFieldWithoutDefault(field, config.fields.find(f => f.key === field.fullKey)?.value); - } - /** - * Gets a slice of the config schema with the given key patterns. Support syntax: - * - * - `some.namespace.key`: Matches exactly `some.namespace.key` - * - `some.namespace.*`: Matches anything that starts with `some.namespace.` - */ - sliced(...patterns) { - const parsedPatterns = patterns.map(p => { - if (p.endsWith("*")) { - return { type: "prefix", value: p.substring(0, p.length - 1) }; - } - return { type: "exact", value: p }; - }); - const newFields = new Map(); - for (const [key, field] of this.fields.entries()) { - for (const pattern of parsedPatterns) { - if ((pattern.type === "exact" && key === pattern.value) || - (pattern.type === "prefix" && key.startsWith(pattern.value))) { - newFields.set(key, field); - } - } - } - return new KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes); - } - /** - * Get a subset of the config schema with a specific scope. - */ - scoped(scopeKey) { - const newFields = new Map(); - for (const [key, field] of this.fields.entries()) { - if (key.startsWith(`${scopeKey}.`)) { - newFields.set(key.substring(scopeKey.length + 1), field); - } - } - return new KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes); - } - union(other) { - const newFields = new Map(); - for (const [key, field] of this.fields.entries()) { - newFields.set(key, field); - } - for (const [key, field] of other.fields.entries()) { - if (newFields.has(key)) { - throw new Error("Cannot union two KVConfigSchematics. The following key is duplicated: " + key); - } - newFields.set(key, field); - } - return new KVConfigSchematics(this.valueTypeLibrary, newFields, [ - ...this.extensionPrefixes, - ...other.extensionPrefixes, - ]); - } - /** - * Combine baseKey into the fields. Effectively removes the baseKey. - */ - flattenBaseKey() { - const newFields = new Map(); - for (const field of this.fields.values()) { - newFields.set(field.fullKey, field); - } - return new KVConfigSchematics(this.valueTypeLibrary, newFields, this.extensionPrefixes); - } - parseToMap(config) { - const rawConfigMap = kvConfigToMap(config); - const parsedConfigMap = new Map(); - for (const [key, field] of this.fields.entries()) { - const value = rawConfigMap.get(field.fullKey); - const parsedValue = this.parseField(field, value); - parsedConfigMap.set(key, parsedValue); - } - return parsedConfigMap; - } - parseToMapWithFullKey(config) { - const rawConfigMap = kvConfigToMap(config); - const parsedConfigMap = new Map(); - for (const field of this.fields.values()) { - const value = rawConfigMap.get(field.fullKey); - const parsedValue = this.parseField(field, value); - parsedConfigMap.set(field.fullKey, parsedValue); - } - return parsedConfigMap; - } - parseToMapPartial(config) { - const rawConfigMap = kvConfigToMap(config); - const parsedConfigMap = new Map(); - for (const [key, field] of this.fields.entries()) { - const value = rawConfigMap.get(field.fullKey); - const parsedValue = this.parseFieldWithoutDefault(field, value); - if (parsedValue !== undefined) { - parsedConfigMap.set(key, parsedValue); - } - } - return parsedConfigMap; - } - /** - * Parse the given config to a ParsedKVConfig. **Will throw** if the config does not satisfy the - * schema. - */ - parse(config) { - return ParsedKVConfig[createParsedKVConfig](this.parseToMap(config)); - } - parsePartial(config) { - return PartialParsedKVConfig[createParsedKVConfig](this.parseToMapPartial(config)); - } - /** - * Builds a full KV config from the given values record. **Will throw** if any of the values are - * missing or do not satisfy the schema. - */ - buildFullConfig(valuesRecord) { - return { - fields: Array.from(this.fields.entries()).map(([key, field]) => { - const value = this.parseField(field, valuesRecord[key]); - return { key: field.fullKey, value }; - }), - }; - } - /** - * Builds a partial KV config from the given values record. Will leave holes in the config if the - * values are missing. **Will throw** if any of the values do not satisfy the schema. - */ - buildPartialConfig(valuesRecord) { - return { - fields: Object.entries(valuesRecord) - .filter(([_key, value]) => value !== undefined) - .map(([key, value]) => { - const field = this.obtainField(key); - return { key: field.fullKey, value: this.parseField(field, value) }; - }), - }; - } - createBuildPartialConfigInput() { - return {}; - } - configBuilder() { - return new KVConfigBuilder(this.fields); - } - clone() { - return new KVConfigSchematics(this.valueTypeLibrary, new Map(this.fields), this.extensionPrefixes); - } - withTypeParamOverride(key, paramMapper) { - const field = this.obtainField(key); - const clone = this.clone(); - clone.fields.set(key, { - ...field, - valueTypeParams: paramMapper(field.valueTypeParams), - schema: this.valueTypeLibrary.getSchema(field.valueTypeKey, paramMapper(field.valueTypeParams)), - }); - return clone; - } - getFullKeyMap() { - if (this.fullKepMap !== undefined) { - return this.fullKepMap; - } - this.fullKepMap = new Map([...this.fields.values()].map(field => [field.fullKey, field])); - return this.fullKepMap; - } - makeLenientZodSchema() { - const fullKeyMap = this.getFullKeyMap(); - return kvConfigSchema.transform(value => { - const seenKeys = new Set(); - return { - fields: value.fields.filter(field => { - if (this.extensionPrefixes.some(prefix => field.key.startsWith(prefix))) { - // If we matched an extension prefix, we don't care about the key or value type. Just - // allow it. - return true; - } - if (seenKeys.has(field.key)) { - return false; - } - const fieldDef = fullKeyMap.get(field.key); - if (fieldDef === undefined) { - return false; - } - const parsed = fieldDef.schema.safeParse(field.value); - if (!parsed.success) { - return false; - } - seenKeys.add(field.key); - return true; - }), - }; - }); - } - /** - * Makes a zod schema that parses a KVConfig which only allows fields with correct keys and types - * through. - * - * Will filter out any fields that are not in the schema. - */ - getLenientZodSchema() { - if (this.lenientZodSchema !== undefined) { - return this.lenientZodSchema; - } - this.lenientZodSchema = this.makeLenientZodSchema(); - return this.lenientZodSchema; - } - getValueType(key) { - const field = this.fields.get(key); - if (field === undefined) { - return null; - } - return field.valueTypeKey; - } - getValueTypeParam(key) { - const field = this.fields.get(key); - if (field === undefined) { - return null; - } - return field.valueTypeParams; - } - getValueTypeParamByFullKey(key) { - const field = this.getFullKeyMap().get(key); - if (field === undefined) { - throw new Error(`Field with key ${key} does not exist in the schematics`); - } - return field.valueTypeParams; - } - hasFullKey(key) { - const field = this.getFullKeyMap().get(key); - return field !== undefined; - } - /** - * Given a KVConfig, filter it to only include fields that are in the schematics. - */ - filterConfig(config, additionalFilter) { - const fullKeyMap = this.getFullKeyMap(); - return { - fields: config.fields.filter(configField => { - const field = fullKeyMap.get(configField.key); - if (field === undefined) { - return false; - } - if (additionalFilter !== undefined) { - return additionalFilter(field.fullKey, { - type: field.valueTypeKey, - param: field.valueTypeParams, - }); - } - return true; - }), - }; - } - /** - * Given a KVConfigStack, filter it to only include fields that are in the schematics. - */ - filterStack(stack) { - return { - layers: stack.layers.map(layer => ({ - layerName: layer.layerName, - config: this.filterConfig(layer.config), - })), - }; - } - twoWayFilterConfig(config, additionalFilter) { - const includedFields = []; - const excludedFields = []; - const fullKeyMap = this.getFullKeyMap(); - for (const configField of config.fields) { - const field = fullKeyMap.get(configField.key); - let include = field !== undefined; - if (field !== undefined && additionalFilter !== undefined) { - include = additionalFilter(field.fullKey, { - type: field.valueTypeKey, - param: field.valueTypeParams, - }); - } - if (include) { - includedFields.push(configField); - } - else { - excludedFields.push(configField); - } - } - return [{ fields: includedFields }, { fields: excludedFields }]; - } - /** - * Given a list of keys, filter it to only include keys that are in the schematics. - */ - filterFullKeys(keys) { - const fullKeyMap = this.getFullKeyMap(); - return keys.filter(key => fullKeyMap.has(key)); - } - /** - * Compares two KV config. Compare with "effective equals". Only compare fields in the schematics. - * Does not apply defaults. - */ - configEffectiveEquals(a, b) { - const aMap = kvConfigToMap(a); - const bMap = kvConfigToMap(b); - for (const field of this.fields.values()) { - const aValue = aMap.get(field.fullKey); - const bValue = bMap.get(field.fullKey); - if (aValue === undefined) { - if (bValue === undefined) { - // Both are missing, continue - continue; - } - else { - return false; - } - } - this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, aValue, bValue); - } - return true; - } - /** - * Compares two KV config field. Compare with "effective equals". Can only compare fields in the - * schematics. - */ - fieldEffectiveEquals(key, a, b) { - const field = this.obtainField(key); - return this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, field.schema.parse(a), field.schema.parse(b)); - } - fieldEffectiveEqualsWithFullKey(fullKey, a, b) { - const fullKeyMap = this.getFullKeyMap(); - const field = fullKeyMap.get(fullKey); - if (field === undefined) { - throw new Error(`Field with key ${fullKey} does not exist in the schematics`); - } - return this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, field.schema.parse(a), field.schema.parse(b)); - } - makeInternalFieldStringifyOpts(opts) { - return { - t: opts.t ?? ((_key, fallback) => fallback), - desiredLength: opts.desiredLength, - }; - } - stringifyField(key, value, opts = {}) { - const field = this.obtainField(key); - return this.valueTypeLibrary.stringify(field.valueTypeKey, field.valueTypeParams, this.makeInternalFieldStringifyOpts(opts), value); - } - tryStringifyFieldWithFullKey(key, value, opts) { - const fullKeyMap = this.getFullKeyMap(); - const field = fullKeyMap.get(key); - if (field === undefined) { - return null; - } - return this.valueTypeLibrary.stringify(field.valueTypeKey, field.valueTypeParams, this.makeInternalFieldStringifyOpts(opts), value); - } - /** - * Apply config in patch to target. Only apply fields that are in the schematics. - */ - apply(target, patch) { - const filteredPatch = this.filterConfig(patch); - return collapseKVStackRaw([target, filteredPatch]); - } - /** - * Tries to un-apply the patch from the target. Will only un-apply fields that are in the - * schematics. - * - * If the value in the target is not effective equal to the value in the patch, it will not be - * removed. - */ - unApply(target, patch) { - const filteredPatch = this.filterConfig(patch); - const patchMap = kvConfigToMap(filteredPatch); - const newMap = new Map(kvConfigToMap(target)); - const fullKeyMap = this.getFullKeyMap(); - for (const [key, value] of patchMap.entries()) { - const field = fullKeyMap.get(key); - if (field === undefined) { - continue; - } - const targetValue = newMap.get(key); - if (targetValue !== undefined) { - if (!this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, value, targetValue)) { - continue; - } - newMap.delete(key); - } - } - return mapToKVConfig(newMap); - } - /** - * Given a KVConfig, iterate through all the fields that are in the schematics. Keys will be full - * keys. - */ - *iterateFieldsOfConfig(config) { - const fullKeyMap = this.getFullKeyMap(); - for (const { key, value } of config.fields) { - const field = fullKeyMap.get(key); - if (field !== undefined) { - yield [key, value]; - } - } - } - /** - * Given a KVConfig, iterate through all the fields that are in the schematics. - */ - *fullKeys() { - const fullKeyMap = this.getFullKeyMap(); - for (const key of fullKeyMap.keys()) { - yield key; - } - } - /** - * Effectively compare two KV config, and return full keys of fields that are different. - */ - effectiveCompareConfig(a, b, opts = {}) { - const { fieldFilter } = opts; - const aMap = kvConfigToMap(a); - const bMap = kvConfigToMap(b); - const onlyInA = []; - const onlyInB = []; - const inBothButDifferent = []; - for (const field of this.fields.values()) { - if (fieldFilter !== undefined) { - if (!fieldFilter(field.fullKey, { - type: field.valueTypeKey, - param: field.valueTypeParams, - })) { - continue; - } - } - const aValue = aMap.get(field.fullKey); - const bValue = bMap.get(field.fullKey); - if (aValue === undefined) { - if (bValue === undefined) { - continue; - } - else { - onlyInB.push(field.fullKey); - } - } - else { - if (bValue === undefined) { - onlyInA.push(field.fullKey); - } - else { - if (!this.valueTypeLibrary.effectiveEquals(field.valueTypeKey, field.valueTypeParams, aValue, bValue)) { - inBothButDifferent.push(field.fullKey); - } - } - } - } - return { onlyInA, onlyInB, inBothButDifferent }; - } - serialize() { - return { - fields: [...this.fields.entries()].map(([key, field]) => ({ - shortKey: key, - fullKey: field.fullKey, - typeKey: field.valueTypeKey, - typeParams: field.valueTypeParams, - defaultValue: field.defaultValue, - })), - extensionPrefixes: this.extensionPrefixes, - }; - } - /** - * Check if any of the fields in the schematics has a full key that starts with the given prefix. - */ - hasFieldsWithPrefix(prefix) { - for (const field of this.fields.values()) { - if (field.fullKey.startsWith(prefix)) { - return true; - } - } - return false; - } - static deserialize(valueTypeLibrary, serialized) { - const fields = new Map(serialized.fields.map(field => { - const typeParams = valueTypeLibrary.parseParamTypes(field.typeKey, field.typeParams); - const valueSchema = valueTypeLibrary.getSchema(field.typeKey, typeParams); - return [ - field.shortKey, - { - valueTypeKey: field.typeKey, - valueTypeParams: typeParams, - schema: valueSchema, - fullKey: field.fullKey, - defaultValue: valueSchema.parse(field.defaultValue), - }, - ]; - })); - return new KVConfigSchematics(valueTypeLibrary, fields, serialized.extensionPrefixes ?? []); - } - static tryDeserialize(valueTypeLibrary, serialized) { - const fields = new Map(); - const errors = []; - for (const field of serialized.fields) { - try { - const typeParams = valueTypeLibrary.parseParamTypes(field.typeKey, field.typeParams); - const valueSchema = valueTypeLibrary.getSchema(field.typeKey, typeParams); - fields.set(field.shortKey, { - valueTypeKey: field.typeKey, - valueTypeParams: typeParams, - schema: valueSchema, - fullKey: field.fullKey, - defaultValue: valueSchema.parse(field.defaultValue), - }); - } - catch (error) { - errors.push({ - fullKey: field.fullKey, - error: serializeError(error), - }); - } - } - return { - schematics: new KVConfigSchematics(valueTypeLibrary, fields, serialized.extensionPrefixes ?? []), - errors, - }; - } -} -class KVConfigBuilder { - constructor(fieldDefs) { - this.fieldDefs = fieldDefs; - this.fields = new Map(); - } - with(key, value) { - const field = this.fieldDefs.get(key); - if (field === undefined) { - throw new Error(`Field with key ${key} does not exist in the schematics.`); - } - this.fields.set(field.fullKey, value); - return this; - } - build() { - return mapToKVConfig(this.fields); - } -} -/** - * This class can be only constructed via the `parse` method on `KVConfigSchema`. It is guaranteed - * to satisfy the schema. - * - * All fields that exist on the schematics is guaranteed to exist here. - */ -class ParsedKVConfig { - constructor( - /** - * Guaranteed to satisfy the schema. - */ - configMap) { - this.configMap = configMap; - } - /** - * @internal - */ - static [createParsedKVConfig](configMap) { - return new ParsedKVConfig(configMap); - } - get(key) { - return this.configMap.get(key); - } -} -/** - * This class can be constructed via the `parsePartial` method on `KVConfigSchema`. All existing - * fields are guaranteed to satisfy the schema. However, there may be missing fields. - */ -class PartialParsedKVConfig { - constructor( - /** - * Guaranteed to satisfy the schema. - */ - configMap) { - this.configMap = configMap; - } - static [createParsedKVConfig](configMap) { - return new PartialParsedKVConfig(configMap); - } - get(key) { - return this.configMap.get(key); - } - has(key) { - return this.configMap.has(key); - } -} -function kvConfigToMap(config) { - return new Map(config.fields.map(f => [f.key, f.value])); -} -function mapToKVConfig(map) { - return { - fields: Array.from(map.entries()).map(([key, value]) => ({ key, value })), - }; -} -function collapseKVStackRaw(configs) { - const map = new Map(); - for (const config of configs) { - for (const { key, value } of config.fields) { - map.set(key, value); - } - } - return mapToKVConfig(map); -} -const emptyKVConfig = { - fields: [], -}; -function singleLayerKVConfigStackOf(name, config) { - return { - layers: [ - { - layerName: name, - config, - }, - ], - }; -} -/** - * Given a KVConfigStack, add a new layer to the top of the stack. Does not mutate the original - * stack. - */ -function addKVConfigToStack(stack, newLayerName, newLayerConfig) { - return { - layers: [ - ...stack.layers, - { - layerName: newLayerName, - config: newLayerConfig, - }, - ], - }; -} -function deepEquals(a, b) { - if (a === b) { - return true; - } - if (typeof a !== "object" || typeof b !== "object") { - return false; - } - if (a === null || b === null) { - return false; - } - if (Array.isArray(a) !== Array.isArray(b)) { - return false; - } - if (Array.isArray(a)) { - if (a.length !== b?.length) { - return false; - } - for (let i = 0; i < a.length; i++) { - if (!deepEquals(a[i], b[i])) { - return false; - } - } - return true; - } - const aKeys = new Set(Object.keys(a)); - const bKeys = new Set(Object.keys(b)); - if (aKeys.size !== bKeys.size) { - return false; - } - for (const key of aKeys) { - if (!bKeys.has(key)) { - return false; - } - if (!deepEquals(a[key], b[key])) { - return false; - } - } - return true; -} - -/** - * Quote a string. - */ -function quoteString(str, empty) { - if (str === undefined || str === "") { - return empty ?? '""'; - } - return JSON.stringify(str); -} -/** - * Quote a string that may include manual escape. (i.e. newlines represented with "\\n") - */ -function quoteStringWithManualEscape(str, empty) { - return quoteString(str?.replace(/\\n/g, "\n"), empty); -} -/** - * Builder for all the basic KV types. - * - * @public - */ -const baseKVValueTypesLibraryBuilder = new KVFieldValueTypesLibraryBuilder({ - /** - * Display name of the field. - */ - displayName: z.string().optional(), - /** - * Hint about the field. Shown when hovering over the field. - */ - hint: z.string().optional(), - /** - * A field can be marked as model centric when it loses its meaning when there is no model to - * reference. - * - * An example would be prompt template. There is no point to configure prompt template when there - * isn't a specific model. - * - * @experimental This field is experimental and may change in the future. - */ - modelCentric: z.boolean().optional(), - /** - * A field can be marked as non-configurable when it is only used as a means to carry information. - * As a result, it will not be shown in the UI. - * - * An example would be context length for MLX, as you cannot change it. - * - * @experimental This field is experimental and may change in the future. - */ - nonConfigurable: z.boolean().optional(), - /** - * A field can be marked as engineDoesNotSupport when when the engine running the model does not - * support the field. - * - * @experimental This field is experimental and may change in the future. - */ - engineDoesNotSupport: z.boolean().optional(), - /** - * A field can be marked as machine dependent when its value is highly dependent on the machine - * that is being used. When exporting the config, one may decide to not include machine dependent - * fields by default. - * - * An example would be GPU offload settings. - * - * @experimental This field is experimental and may change in the future. - */ - machineDependent: z.boolean().optional(), - warning: z.string().optional(), - subtitle: z.string().optional(), - isExperimental: z.boolean().optional(), - dependencies: z.array(kvConfigFieldDependencySchema).optional(), -}) - .valueType("numeric", { - paramType: { - min: z.number().optional(), - max: z.number().optional(), - step: z.number().optional(), - int: z.boolean().optional(), - precision: z.number().int().nonnegative().optional(), - slider: z - .object({ - min: z.number(), - max: z.number(), - step: z.number(), - }) - .optional(), - shortHand: z.string().optional(), - }, - schemaMaker: ({ min, max, int, precision }) => { - let schema = z.number(); - if (min !== undefined) { - schema = schema.min(min); - } - if (max !== undefined) { - schema = schema.max(max); - } - if (int) { - if (precision !== undefined) { - throw new Error("Cannot specify both int and precision."); - } - schema = schema.int(); - } - return schema; - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: (value, { int, precision }) => { - if (int) { - return String(Math.round(value)); - } - return value.toFixed(precision ?? 2); - }, -}) - .valueType("string", { - paramType: { - minLength: z.number().optional(), - maxLength: z.number().optional(), - isParagraph: z.boolean().optional(), - isProtected: z.boolean().optional(), - /** - * If true, the string should match to a single token. - */ - isToken: z.boolean().optional(), - placeholder: z.string().optional(), - }, - schemaMaker: ({ minLength, maxLength }) => { - let schema = z.string(); - if (minLength !== undefined) { - schema = schema.min(minLength); - } - if (maxLength !== undefined) { - schema = schema.max(maxLength); - } - return schema; - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: (value, { isParagraph, isProtected }, { t, desiredLength }) => { - if (isProtected) { - return "********"; - } - if (isParagraph) { - if (value === "") { - return t("config:customInputs.string.emptyParagraph", ""); - } - else { - if (desiredLength === undefined || value.length <= desiredLength) { - return value; - } - else { - return (value.slice(0, Math.floor(desiredLength / 2)) + - " ... " + - value.slice(-Math.ceil(desiredLength / 2))); - } - } - } - else { - const quoted = quoteString(value); - if (desiredLength === undefined || quoted.length <= desiredLength) { - return quoted; - } - else { - return (quoted.slice(0, Math.floor(desiredLength / 2)) + - "..." + - quoted.slice(-Math.ceil(desiredLength / 2))); - } - } - }, -}) - .valueType("select", { - paramType: { - options: z - .array(z.object({ value: z.string().nonempty(), displayName: z.string() }).or(z.string())) - .refine(options => { - // See if there are any duplicate values. - const values = new Set(); - for (const option of options) { - const value = typeof option === "string" ? option : option.value; - if (values.has(value)) { - return false; - } - values.add(value); - } - return true; - }, { - message: "Duplicate values in options.", - }), - }, - schemaMaker: ({ options }) => { - const allowedValues = new Set(options.map(option => (typeof option === "string" ? option : option.value))); - return z.string().refine(value => allowedValues.has(value)); - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: value => { - return value; - }, -}) - .valueType("boolean", { - paramType: {}, - schemaMaker: () => { - return z.boolean(); - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: value => { - return value ? "ON" : "OFF"; - }, -}) - .valueType("stringArray", { - paramType: { - maxNumItems: z.number().optional(), - /** - * Whether to allow empty strings in the array. Default is false. - */ - allowEmptyStrings: z.boolean().optional(), - }, - schemaMaker: ({ maxNumItems, allowEmptyStrings }) => { - let stringSchema = z.string(); - if (!allowEmptyStrings) { - stringSchema = stringSchema.min(1); - } - let schema = z.array(stringSchema); - if (maxNumItems !== undefined) { - schema = schema.max(maxNumItems); - } - return schema; - }, - effectiveEquals: (a, b) => { - return a.length === b.length && a.every((v, i) => v === b[i]); - }, - stringify: (value, _typeParam, { t, desiredLength }) => { - const quoted = value.map(v => quoteString(v)); - if (quoted.length === 0) { - return t("config:customInputs.stringArray.empty", ""); - } - if (quoted.length <= 2 || desiredLength === undefined) { - return quoted.join(", "); - } - // Desired length does not need to be followed strictly. It is just a hint. - let currentLength = quoted[0].length + quoted[1].length + 6; - for (let i = 1; i < quoted.length - 1; i++) { - currentLength += quoted[i].length + 2; - if (currentLength >= desiredLength) { - return quoted.slice(0, i).join(", ") + ", ..." + quoted[quoted.length - 1]; - } - } - return quoted.join(", "); - }, -}); -/** - * Basic key-value field value types library. These are the types that are exposed to plugins. - * - * @public - */ -baseKVValueTypesLibraryBuilder.build(); -/** - * The global key-value field value types library. This includes all the basic types and additional - * types that are used in the LM Studio application. - * - * @public - */ -const kvValueTypesLibrary = baseKVValueTypesLibraryBuilder - .valueType("checkboxNumeric", { - paramType: { - min: z.number().optional(), - max: z.number().optional(), - step: z.number().optional(), - int: z.boolean().optional(), - uncheckedHint: z.string().optional(), - precision: z.number().int().nonnegative().optional(), - slider: z - .object({ - min: z.number(), - max: z.number(), - step: z.number(), - }) - .optional(), - }, - schemaMaker: ({ min, max, int, precision }) => { - let numberSchema = z.number(); - if (min !== undefined) { - numberSchema = numberSchema.min(min); - } - if (max !== undefined) { - numberSchema = numberSchema.max(max); - } - if (int) { - if (precision !== undefined) { - throw new Error("Cannot specify both int and precision."); - } - numberSchema = numberSchema.int(); - } - return z.object({ - checked: z.boolean(), - value: numberSchema, - }); - }, - effectiveEquals: (a, b) => { - if (a.checked !== b.checked) { - return false; - } - if (!a.checked) { - return true; - } - return a.value === b.value; - }, - stringify: (value, { int, precision }, { t }) => { - if (!value.checked) { - return t("config:customInputs.checkboxNumeric.off", "OFF"); - } - if (int) { - return String(Math.round(value.value)); - } - return value.value.toFixed(precision ?? 2); - }, -}) - .valueType("numericArray", { - paramType: { - min: z.number().optional(), - max: z.number().optional(), - int: z.boolean().optional(), - }, - schemaMaker: ({ min, max, int }) => { - let numberSchema = z.number(); - if (min !== undefined) { - numberSchema = numberSchema.min(min); - } - if (max !== undefined) { - numberSchema = numberSchema.max(max); - } - if (int) { - numberSchema = numberSchema.int(); - } - return z.array(numberSchema); - }, - effectiveEquals: (a, b) => { - return a.length === b.length && a.every((v, i) => v === b[i]); - }, - stringify: (value, { int }) => { - return value.map(v => (int ? String(Math.round(v)) : String(v))).join(", "); - }, -}) - .valueType("contextOverflowPolicy", { - paramType: {}, - schemaMaker: () => { - return llmContextOverflowPolicySchema; - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: (value, _typeParam, { t }) => { - switch (value) { - case "stopAtLimit": - return t("config:customInputs.contextOverflowPolicy.stopAtLimit", "Stop At Limit"); - case "truncateMiddle": - return t("config:customInputs.contextOverflowPolicy.truncateMiddle", "Truncate Middle"); - case "rollingWindow": - return t("config:customInputs.contextOverflowPolicy.rollingWindow", "Rolling Window"); - } - }, -}) - .valueType("context", { - paramType: {}, - schemaMaker: () => { - return z.array(llmContextReferenceSchema); - }, - effectiveEquals: (a, b) => { - return deepEquals(a, b); - }, - stringify: value => { - return JSON.stringify(value, null, 2); // TODO: pretty print - }, -}) - .valueType("contextLength", { - paramType: { - max: z.number().optional(), - }, - schemaMaker: () => { - return z.number().int().positive(); - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: (value, { max }) => { - if (max === undefined) { - return String(value); - } - return `${value}/${max}`; - }, -}) - .valueType("modelIdentifier", { - paramType: { - domain: z.array(modelDomainTypeSchema).optional(), - }, - schemaMaker: () => { - return z.string(); - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: value => { - return value; - }, -}) - .valueType("llmPromptTemplate", { - paramType: {}, - schemaMaker: () => { - return llmPromptTemplateSchema; - }, - effectiveEquals: (a, b) => { - if (a.type !== b.type) { - return false; - } - if (a.stopStrings.length !== b.stopStrings.length) { - return false; - } - if (!a.stopStrings.every((v, i) => v === b.stopStrings[i])) { - return false; - } - switch (a.type) { - case "jinja": - return a.jinjaPromptTemplate?.template === b.jinjaPromptTemplate?.template; - case "manual": - return (a.manualPromptTemplate?.beforeSystem === b.manualPromptTemplate?.beforeSystem && - a.manualPromptTemplate?.afterSystem === b.manualPromptTemplate?.afterSystem && - a.manualPromptTemplate?.beforeUser === b.manualPromptTemplate?.beforeUser && - a.manualPromptTemplate?.afterUser === b.manualPromptTemplate?.afterUser && - a.manualPromptTemplate?.beforeAssistant === b.manualPromptTemplate?.beforeAssistant && - a.manualPromptTemplate?.afterAssistant === b.manualPromptTemplate?.afterAssistant); - default: { - const exhaustiveCheck = a.type; - throw new Error("Unknown template type: " + exhaustiveCheck); - } - } - }, - stringify: (value, _typeParam, { t, desiredLength }) => { - switch (value.type) { - case "jinja": { - const lead = `${t("config:customInputs.llmPromptTemplate.type", "Type")}: ` + - `${t("config:customInputs.llmPromptTemplate.types.jinja/label", "Jinja")}\n` + - `${t("config:customInputs.llmPromptTemplate.jinja.template/label", "Template")}: `; - if (desiredLength === undefined) { - return lead + value.jinjaPromptTemplate?.template; - } - const currentLength = lead.length; - const remainingLength = Math.min(100, desiredLength - currentLength); - const template = value.jinjaPromptTemplate?.template ?? ""; - if (template.length <= remainingLength) { - return lead + template; - } - return (lead + - template.slice(0, Math.floor(remainingLength / 2)) + - "..." + - template.slice(-Math.ceil(remainingLength / 2))); - } - case "manual": { - return (`${t("config:customInputs.llmPromptTemplate.type", "Type")}: ` + - `${t("config:customInputs.llmPromptTemplate.types.manual/label", "Manual")}\n` + - `${t("config:customInputs.llmPromptTemplate.manual.subfield.beforeSystem/label", "Before System")}: ` + - `${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeSystem)}\n` + - `${t("config:customInputs.llmPromptTemplate.manual.subfield.afterSystem/label", "After System")}: ` + - `${quoteStringWithManualEscape(value.manualPromptTemplate?.afterSystem)}\n` + - `${t("config:customInputs.llmPromptTemplate.manual.subfield.beforeUser/label", "Before User")}: ` + - `${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeUser)}\n` + - `${t("config:customInputs.llmPromptTemplate.manual.subfield.afterUser/label", "After User")}: ` + - `${quoteStringWithManualEscape(value.manualPromptTemplate?.afterUser)}\n` + - `${t("config:customInputs.llmPromptTemplate.manual.subfield.beforeAssistant/label", "Before Assistant")}: ` + - `${quoteStringWithManualEscape(value.manualPromptTemplate?.beforeAssistant)}\n` + - `${t("config:customInputs.llmPromptTemplate.manual.subfield.afterAssistant/label", "After Assistant")}: ` + - `${quoteStringWithManualEscape(value.manualPromptTemplate?.afterAssistant)}`); - } - default: { - const exhaustiveCheck = value.type; - throw new Error("Unknown template type: " + exhaustiveCheck); - } - } - }, -}) - .valueType("llmReasoningParsing", { - paramType: {}, - schemaMaker: () => { - return llmReasoningParsingSchema; - }, - effectiveEquals: (a, b) => { - return a.startString === b.startString && a.endString === b.endString; - }, - stringify: value => { - return JSON.stringify(value, null, 2); // TODO: pretty print - }, -}) - .valueType("llamaStructuredOutput", { - paramType: {}, - schemaMaker: () => { - return llmStructuredPredictionSettingSchema; - }, - effectiveEquals: (a, b) => { - if (a.type === "json" && b.type === "json") { - return deepEquals(a, b); - } - else if (a.type === "none" && b.type === "none") { - return true; - } - else { - return false; - } - }, - stringify: value => { - return JSON.stringify(value, null, 2); // TODO: pretty print - }, -}) - .valueType("speculativeDecodingDraftModel", { - paramType: {}, - schemaMaker: () => { - // Empty string means no speculative decoding. - return z.string(); - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: (value, _typeParam, { t }) => { - if (value === "") { - return t("config:customInputs.speculativeDecodingDraftModel.off", "OFF"); - } - return value; - }, -}) - .valueType("toolUse", { - paramType: {}, - schemaMaker: () => { - return llmToolUseSettingSchema; - }, - effectiveEquals: (a, b) => { - return deepEquals(a, b); // TODO: more performant comparison - }, - stringify: value => { - return JSON.stringify(value, null, 2); // TODO: pretty print - }, -}) - .valueType("toolNaming", { - paramType: {}, - schemaMaker: () => { - return toolNamingSchema; - }, - effectiveEquals: (a, b) => { - return a === b; - }, - stringify: value => { - return value; - }, -}) - .valueType("llamaAccelerationOffloadRatio", { - paramType: { - numLayers: z.number().optional(), - }, - schemaMaker: () => { - return llmLlamaAccelerationOffloadRatioSchema; - }, - effectiveEquals: (a, b) => { - const ratioA = a === "max" ? 1 : a === "off" ? 0 : a; - const ratioB = b === "max" ? 1 : b === "off" ? 0 : b; - return ratioA === ratioB; - }, - stringify: (value, { numLayers }, { t }) => { - if (value === "max" || value === 1) { - const label = t("config:customInputs.llamaAccelerationOffloadRatio.max", "MAX"); - if (numLayers !== 0) { - return `${label} (${numLayers})`; - } - return label; - } - if (value === "off" || value === 0) { - return t("config:customInputs.llamaAccelerationOffloadRatio.off", "OFF"); - } - if (numLayers !== undefined) { - return String(Math.round(numLayers * value)); - } - return (value * 100).toFixed(0) + "%"; - }, -}) - .valueType("llamaMirostatSampling", { - paramType: {}, - schemaMaker: () => { - return llmLlamaMirostatSamplingConfigSchema; - }, - effectiveEquals: (a, b) => { - return deepEquals(a, b); // TODO: more performant comparison - }, - stringify: value => { - return JSON.stringify(value, null, 2); // TODO: pretty print - }, -}) - .valueType("llamaLogitBias", { - paramType: {}, - schemaMaker: () => { - return llmLlamaLogitBiasConfigSchema; - }, - effectiveEquals: (a, b) => { - return deepEquals(a, b); // TODO: more performant comparison - }, - stringify: value => { - return JSON.stringify(value, null, 2); // TODO: pretty print - }, -}) - .valueType("llamaCacheQuantizationType", { - paramType: {}, - schemaMaker: () => { - return z.object({ - checked: z.boolean(), - value: llmLlamaCacheQuantizationTypeSchema, - }); - }, - effectiveEquals: (a, b) => { - if (a.checked !== b.checked) { - return false; - } - if (!a.checked) { - return true; - } - return a.value === b.value; - }, - stringify: (value, _typeParam, { t }) => { - if (!value.checked) { - return t("config:customInputs.llamaCacheQuantizationType.off", "OFF"); - } - return value.value; - }, -}) - .valueType("mlxKvCacheQuantizationType", { - paramType: {}, - schemaMaker: () => { - return llmMlxKvCacheQuantizationSchema; - }, - effectiveEquals: (a, b) => { - if (a.enabled !== b.enabled) { - return false; - } - if (!a.enabled) { - return true; - } - return (a.bits === b.bits && a.groupSize === b.groupSize && a.quantizedStart === b.quantizedStart); - }, - stringify: value => { - return JSON.stringify(value, null, 2); // TODO: pretty print - }, -}) - .valueType("retrievalChunkingMethod", { - paramType: {}, - schemaMaker: () => { - return retrievalChunkingMethodSchema; - }, - effectiveEquals: (a, b) => { - return deepEquals(a, b); // TODO: more performant comparison - }, - stringify: value => { - return JSON.stringify(value, null, 2); // TODO: pretty print - }, -}) - .valueType("envVars", { - paramType: {}, - schemaMaker: () => { - return allowableEnvVarsSchema; - }, - effectiveEquals: (a, b) => { - return deepEquals(a, b); - }, - stringify: value => { - return JSON.stringify(value, null, 2); - }, -}) - .valueType("gpuSplitConfig", { - paramType: {}, - schemaMaker: () => { - return gpuSplitConfigSchema; - }, - effectiveEquals: (a, b) => { - return deepEquals(a, b); - }, - stringify: value => { - return JSON.stringify(value, null, 2); - }, -}) - .build(); - -/** - * This file is divided into 4 sections: - * - * 1. globalConfigSchematics: The pool for all config keys and their types - * 2. Functionality scope definitions: i.e. what config keys are available in what functionality - * scope. An example functionality scope is llmPrediction. - * 3. Utility types that can be used to work with types of schema. - */ -// --------------------------- -// 1. globalConfigSchematics -// --------------------------- -const globalConfigSchematics = new KVConfigSchematicsBuilder(kvValueTypesLibrary) - .extension("ext.virtualModel.customField") - .field("envVars", "envVars", {}, {}) - .scope("llm.prediction", builder => builder - .field("temperature", "numeric", { - min: 0, - step: 0.01, - slider: { min: 0, max: 1, step: 0.01 }, - precision: 2, - shortHand: "temp", -}, 0.8) - .field("contextOverflowPolicy", "contextOverflowPolicy", {}, "truncateMiddle") - .field("maxPredictedTokens", "checkboxNumeric", { min: 1, int: true }, { checked: false, value: 1000 }) - .field("stopStrings", "stringArray", {}, []) - .field("toolCallStopStrings", "stringArray", {}, []) - .field("structured", "llamaStructuredOutput", {}, { type: "none" }) - .scope("speculativeDecoding", builder => builder - .field("draftModel", "speculativeDecodingDraftModel", { - modelCentric: true, -}, "") - .field("minDraftLengthToConsider", "numeric", { - modelCentric: true, - min: 0, - int: true, - slider: { min: 0, max: 10, step: 1 }, -}, 0) - .field("numReuseTokens", "numeric", { modelCentric: true, min: 1, int: true }, 256) - .field("minContinueDraftingProbability", "numeric", { - modelCentric: true, - min: 0, - max: 1, - step: 0.01, - precision: 2, - slider: { min: 0, max: 1, step: 0.01 }, -}, 0.75) - .field("maxTokensToDraft", "numeric", { modelCentric: true, min: 1, int: true, slider: { min: 10, max: 30, step: 1 } }, 16) - .field("numDraftTokensExact", "numeric", { - modelCentric: true, - min: 1, - int: true, - slider: { min: 1, max: 10, step: 1 }, -}, 2)) - .field("tools", "toolUse", {}, { type: "none" }) - .field("toolNaming", "toolNaming", {}, "removeSpecial") - .field("promptTemplate", "llmPromptTemplate", { modelCentric: true }, { - type: "manual", - manualPromptTemplate: { - beforeSystem: "Instruct: ", - afterSystem: "\n", - beforeAssistant: "AI: ", - afterAssistant: "\n", - beforeUser: "Human: ", - afterUser: "\n", - }, - stopStrings: [], -}) - .field("systemPrompt", "string", { isParagraph: true }, "") - .field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }) - .field("contextPrefill", "context", {}, []) - .field("topKSampling", "numeric", { min: -1, max: 500, int: true }, 40) - .field("repeatPenalty", "checkboxNumeric", { min: -1, step: 0.01 }, { checked: true, value: 1.1 }) - .field("minPSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: true, value: 0.05 }) - .field("topPSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: true, value: 0.95 }) - .field("logProbs", "checkboxNumeric", { min: 0, max: 100, int: true }, { checked: false, value: 0 }) - .scope("reasoning", builder => builder.field("parsing", "llmReasoningParsing", {}, { - enabled: true, - startString: "", - endString: "", -})) - .scope("llama", builder => builder - .field("cpuThreads", "numeric", { min: 1, int: true }, 4) - .field("frequencyPenalty", "checkboxNumeric", { precision: 2 }, { checked: false, value: 0.0 }) - .field("xtcProbability", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.5 }) - .field("xtcThreshold", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 0.5, step: 0.01 } }, { checked: false, value: 0.1 }) - .field("presencePenalty", "checkboxNumeric", { precision: 2 }, { checked: false, value: 0.0 }) - .field("mirostatSampling", "llamaMirostatSampling", {}, { - // Disabled by default - version: 0, - learningRate: 0.1, - targetEntropy: 5, -}) - .field("tailFreeSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.95 }) - .field("locallyTypicalSampling", "checkboxNumeric", { min: 0, max: 1, step: 0.01, precision: 2, slider: { min: 0, max: 1, step: 0.01 } }, { checked: false, value: 0.9 }) - .field("logitBias", "llamaLogitBias", {}, []))) - .scope("llm.load", builder => builder - .field("contextLength", "contextLength", { - machineDependent: true, -}, 2048) - .field("numExperts", "numeric", { min: 0, int: true }, 0) - .field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }) - .field("offloadKVCacheToGpu", "boolean", {}, true) - .field("numCpuExpertLayersRatio", "llamaAccelerationOffloadRatio", { machineDependent: true, isExperimental: true, }, "off") - .scope("llama", builder => builder - .scope("acceleration", builder => builder.field("offloadRatio", "llamaAccelerationOffloadRatio", { machineDependent: true }, "max")) - .field("cpuThreadPoolSize", "numeric", { min: 1, machineDependent: true }, 4) - .field("evalBatchSize", "numeric", { min: 1, int: true }, 512) - .field("flashAttention", "boolean", { isExperimental: true, warning: "config:flashAttentionWarning" }, false) - .field("ropeFrequencyBase", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyBaseUncheckedHint" }, { checked: false, value: 0 }) - .field("ropeFrequencyScale", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyScaleUncheckedHint" }, { checked: false, value: 0 }) - .field("keepModelInMemory", "boolean", {}, true) - .field("useFp16ForKVCache", "boolean", {}, true) - .field("tryMmap", "boolean", {}, true) - .field("kCacheQuantizationType", "llamaCacheQuantizationType", { isExperimental: true }, { checked: false, value: "f16" }) - .field("vCacheQuantizationType", "llamaCacheQuantizationType", { isExperimental: true, warning: "config:llamaKvCacheQuantizationWarning" }, { checked: false, value: "f16" })) - .scope("mlx", builder => builder.field("kvCacheQuantization", "mlxKvCacheQuantizationType", { isExperimental: true }, { enabled: false, bits: 8, groupSize: 64, quantizedStart: 5000 }))) - .scope("load", builder => builder - .field("gpuSplitConfig", "gpuSplitConfig", {}, defaultGPUSplitConfig) - .field("gpuStrictVramCap", "boolean", {}, false)) - .scope("embedding.load", builder => builder - .field("contextLength", "contextLength", { machineDependent: true }, 2048) - .field("seed", "checkboxNumeric", { int: true, min: -1, uncheckedHint: "config:seedUncheckedHint" }, { checked: false, value: -1 }) - .scope("llama", builder => builder - .scope("acceleration", builder => builder.field("offloadRatio", "llamaAccelerationOffloadRatio", { machineDependent: true }, "max")) - .field("evalBatchSize", "numeric", { min: 1, int: true }, 512) - .field("ropeFrequencyBase", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyBaseUncheckedHint" }, { checked: false, value: 0 }) - .field("ropeFrequencyScale", "checkboxNumeric", { min: 0, uncheckedHint: "config:ropeFrequencyScaleUncheckedHint" }, { checked: false, value: 0 }) - .field("keepModelInMemory", "boolean", {}, true) - .field("tryMmap", "boolean", {}, true))) - .scope("retrieval", builder => builder - .field("databaseFile", "string", { machineDependent: true }, "") - .field("chunkingMethod", "retrievalChunkingMethod", {}, { - type: "recursive-v1", - chunkSize: 512, - chunkOverlap: 100, -}) - .field("limit", "numeric", { min: 1, int: true }, 5) - .field("embeddingModel", "modelIdentifier", { domain: ["embedding"] }, "")) - .build(); -// ------------------------------------ -// 2. Functionality scope definitions -// ------------------------------------ -const llmPredictionConfigSchematics = globalConfigSchematics.scoped("llm.prediction"); -const llmSharedPredictionConfigSchematics = llmPredictionConfigSchematics.sliced("temperature", "maxPredictedTokens", "promptTemplate", "systemPrompt", "seed", "contextPrefill", "tools", "toolNaming", "reasoning.*"); -llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("llama.*", "contextOverflowPolicy", "stopStrings", "toolCallStopStrings", "structured", "topKSampling", "repeatPenalty", "minPSampling", "topPSampling", "logProbs", "speculativeDecoding.draftModel", "speculativeDecoding.minContinueDraftingProbability", "speculativeDecoding.minDraftLengthToConsider", "speculativeDecoding.maxTokensToDraft", "speculativeDecoding.numReuseTokens")); -llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("mlx.*", "contextOverflowPolicy", "stopStrings", "toolCallStopStrings", "structured", "repeatPenalty", "minPSampling", "topPSampling", "topKSampling", "speculativeDecoding.draftModel", "speculativeDecoding.numDraftTokensExact")); -llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("transformers.*")); -llmSharedPredictionConfigSchematics.union(llmPredictionConfigSchematics.sliced("onnx.*", "repeatPenalty", "topPSampling", "topKSampling")); -const llmLoadSchematics = globalConfigSchematics - .scoped("llm.load") - .union(globalConfigSchematics.sliced("envVars")); -const llmSharedLoadConfigSchematics = llmLoadSchematics.sliced("contextLength", "seed", "envVars"); -const llamaLoadConfigSchematics = globalConfigSchematics.sliced("llama.load.*", "load.*"); -const llmLlamaLoadConfigSchematics = llmSharedLoadConfigSchematics - .union(llmLoadSchematics.sliced("llama.*", "load.*", "offloadKVCacheToGpu")) - .union(llamaLoadConfigSchematics); -llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("mlx.*")); -llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("transformers.*")); -llmSharedLoadConfigSchematics.union(llmLoadSchematics.sliced("onnx.*")); -const llmLlamaMoeAdditionalLoadConfigSchematics = llmLoadSchematics.sliced("numExperts", "numCpuExpertLayersRatio"); -const llmLlamaMoeLoadConfigSchematics = llmLlamaLoadConfigSchematics.union(llmLlamaMoeAdditionalLoadConfigSchematics); -const embeddingLoadSchematics = globalConfigSchematics - .scoped("embedding.load") - .union(globalConfigSchematics.sliced("load.*")); -const embeddingSharedLoadConfigSchematics = embeddingLoadSchematics.sliced("contextLength", "seed"); -const retrievalSchematics = globalConfigSchematics.scoped("retrieval"); -const embeddingLlamaLoadConfigSchematics = embeddingSharedLoadConfigSchematics - .union(embeddingLoadSchematics.sliced("llama.*")) - .union(llamaLoadConfigSchematics); -new KVConfigSchematicsBuilder(kvValueTypesLibrary).build(); - -/** - * Convert a number that can be false to checkbox numeric value. - * - * @param maybeFalseNumber - The value to translate. - * @param valueWhenUnchecked - The value to use when the checkbox is unchecked. - */ -function maybeFalseNumberToCheckboxNumeric(maybeFalseNumber, valueWhenUnchecked) { - if (maybeFalseNumber === undefined) { - return undefined; - } - if (maybeFalseNumber === false) { - return { checked: false, value: valueWhenUnchecked }; - } - return { checked: true, value: maybeFalseNumber }; -} - -function llmPredictionConfigToKVConfig(config) { - const top = llmPredictionConfigSchematics.buildPartialConfig({ - "temperature": config.temperature, - "contextOverflowPolicy": config.contextOverflowPolicy, - "maxPredictedTokens": maybeFalseNumberToCheckboxNumeric(config.maxTokens, 1), - "stopStrings": config.stopStrings, - "toolCallStopStrings": config.toolCallStopStrings, - "structured": config.structured, - "tools": config.rawTools, - "toolNaming": config.toolNaming, - "topKSampling": config.topKSampling, - "repeatPenalty": maybeFalseNumberToCheckboxNumeric(config.repeatPenalty, 1.1), - "minPSampling": maybeFalseNumberToCheckboxNumeric(config.minPSampling, 0.05), - "topPSampling": maybeFalseNumberToCheckboxNumeric(config.topPSampling, 0.95), - "llama.xtcProbability": maybeFalseNumberToCheckboxNumeric(config.xtcProbability, 0), - "llama.xtcThreshold": maybeFalseNumberToCheckboxNumeric(config.xtcThreshold, 0), - "logProbs": maybeFalseNumberToCheckboxNumeric(config.logProbs, 0), - "llama.cpuThreads": config.cpuThreads, - "promptTemplate": config.promptTemplate, - "speculativeDecoding.draftModel": config.draftModel, - "speculativeDecoding.numDraftTokensExact": config.speculativeDecodingNumDraftTokensExact, - "speculativeDecoding.minDraftLengthToConsider": config.speculativeDecodingMinDraftLengthToConsider, - "speculativeDecoding.minContinueDraftingProbability": config.speculativeDecodingMinContinueDraftingProbability, - "reasoning.parsing": config.reasoningParsing, - }); - if (config.raw !== undefined) { - return collapseKVStackRaw([config.raw, top]); - } - return top; -} - -/** - * @public - */ -function createConfigSchematics() { - return new KVConfigSchematicsBuilder(kvValueTypesLibrary); -} - -var lib = {}; - -var helpers = {}; - -var hasRequiredHelpers; - -function requireHelpers () { - if (hasRequiredHelpers) return helpers; - hasRequiredHelpers = 1; - - var ValidationError = helpers.ValidationError = function ValidationError (message, instance, schema, path, name, argument) { - if(Array.isArray(path)){ - this.path = path; - this.property = path.reduce(function(sum, item){ - return sum + makeSuffix(item); - }, 'instance'); - }else if(path !== undefined){ - this.property = path; - } - if (message) { - this.message = message; - } - if (schema) { - var id = schema.$id || schema.id; - this.schema = id || schema; - } - if (instance !== undefined) { - this.instance = instance; - } - this.name = name; - this.argument = argument; - this.stack = this.toString(); - }; - - ValidationError.prototype.toString = function toString() { - return this.property + ' ' + this.message; - }; - - var ValidatorResult = helpers.ValidatorResult = function ValidatorResult(instance, schema, options, ctx) { - this.instance = instance; - this.schema = schema; - this.options = options; - this.path = ctx.path; - this.propertyPath = ctx.propertyPath; - this.errors = []; - this.throwError = options && options.throwError; - this.throwFirst = options && options.throwFirst; - this.throwAll = options && options.throwAll; - this.disableFormat = options && options.disableFormat === true; - }; - - ValidatorResult.prototype.addError = function addError(detail) { - var err; - if (typeof detail == 'string') { - err = new ValidationError(detail, this.instance, this.schema, this.path); - } else { - if (!detail) throw new Error('Missing error detail'); - if (!detail.message) throw new Error('Missing error message'); - if (!detail.name) throw new Error('Missing validator type'); - err = new ValidationError(detail.message, this.instance, this.schema, this.path, detail.name, detail.argument); - } - - this.errors.push(err); - if (this.throwFirst) { - throw new ValidatorResultError(this); - }else if(this.throwError){ - throw err; - } - return err; - }; - - ValidatorResult.prototype.importErrors = function importErrors(res) { - if (typeof res == 'string' || (res && res.validatorType)) { - this.addError(res); - } else if (res && res.errors) { - this.errors = this.errors.concat(res.errors); - } - }; - - function stringizer (v,i){ - return i+': '+v.toString()+'\n'; - } - ValidatorResult.prototype.toString = function toString(res) { - return this.errors.map(stringizer).join(''); - }; - - Object.defineProperty(ValidatorResult.prototype, "valid", { get: function() { - return !this.errors.length; - } }); - - helpers.ValidatorResultError = ValidatorResultError; - function ValidatorResultError(result) { - if(typeof Error.captureStackTrace === 'function'){ - Error.captureStackTrace(this, ValidatorResultError); - } - this.instance = result.instance; - this.schema = result.schema; - this.options = result.options; - this.errors = result.errors; - } - ValidatorResultError.prototype = new Error(); - ValidatorResultError.prototype.constructor = ValidatorResultError; - ValidatorResultError.prototype.name = "Validation Error"; - - /** - * Describes a problem with a Schema which prevents validation of an instance - * @name SchemaError - * @constructor - */ - var SchemaError = helpers.SchemaError = function SchemaError (msg, schema) { - this.message = msg; - this.schema = schema; - Error.call(this, msg); - if(typeof Error.captureStackTrace === 'function'){ - Error.captureStackTrace(this, SchemaError); - } - }; - SchemaError.prototype = Object.create(Error.prototype, - { - constructor: {value: SchemaError, enumerable: false}, - name: {value: 'SchemaError', enumerable: false}, - }); - - var SchemaContext = helpers.SchemaContext = function SchemaContext (schema, options, path, base, schemas) { - this.schema = schema; - this.options = options; - if(Array.isArray(path)){ - this.path = path; - this.propertyPath = path.reduce(function(sum, item){ - return sum + makeSuffix(item); - }, 'instance'); - }else { - this.propertyPath = path; - } - this.base = base; - this.schemas = schemas; - }; - - SchemaContext.prototype.resolve = function resolve (target) { - return (() => resolveUrl(this.base,target))(); - }; - - SchemaContext.prototype.makeChild = function makeChild(schema, propertyName){ - var path = (propertyName===undefined) ? this.path : this.path.concat([propertyName]); - var id = schema.$id || schema.id; - let base = (() => resolveUrl(this.base,id||''))(); - var ctx = new SchemaContext(schema, this.options, path, base, Object.create(this.schemas)); - if(id && !ctx.schemas[base]){ - ctx.schemas[base] = schema; - } - return ctx; - }; - - var FORMAT_REGEXPS = helpers.FORMAT_REGEXPS = { - // 7.3.1. Dates, Times, and Duration - 'date-time': /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])[tT ](2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])(\.\d+)?([zZ]|[+-]([0-5][0-9]):(60|[0-5][0-9]))$/, - 'date': /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])$/, - 'time': /^(2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])$/, - 'duration': /P(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S)|\d+(D|M(\d+D)?|Y(\d+M(\d+D)?)?)(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S))?|\d+W)/i, - - // 7.3.2. Email Addresses - // TODO: fix the email production - 'email': /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/, - 'idn-email': /^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u, - - // 7.3.3. Hostnames - - // 7.3.4. IP Addresses - 'ip-address': /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, - // FIXME whitespace is invalid - 'ipv6': /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0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iu, - 'relative-json-pointer': /^\d+(#|(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*)$/iu, - - // hostname regex from: http://stackoverflow.com/a/1420225/5628 - 'hostname': /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/, - 'host-name': /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/, - - 'utc-millisec': function (input) { - return (typeof input === 'string') && parseFloat(input) === parseInt(input, 10) && !isNaN(input); - }, - - // 7.3.8. regex - 'regex': function (input) { - var result = true; - try { - new RegExp(input); - } catch (e) { - result = false; - } - return result; - }, - - // Other definitions - // "style" was removed from JSON Schema in draft-4 and is deprecated - 'style': /[\r\n\t ]*[^\r\n\t ][^:]*:[\r\n\t ]*[^\r\n\t ;]*[\r\n\t ]*;?/, - // "color" was removed from JSON Schema in draft-4 and is deprecated - 'color': /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/, - 'phone': /^\+(?:[0-9] ?){6,14}[0-9]$/, - 'alpha': /^[a-zA-Z]+$/, - 'alphanumeric': /^[a-zA-Z0-9]+$/, - }; - - FORMAT_REGEXPS.regexp = FORMAT_REGEXPS.regex; - FORMAT_REGEXPS.pattern = FORMAT_REGEXPS.regex; - FORMAT_REGEXPS.ipv4 = FORMAT_REGEXPS['ip-address']; - - helpers.isFormat = function isFormat (input, format, validator) { - if (typeof input === 'string' && FORMAT_REGEXPS[format] !== undefined) { - if (FORMAT_REGEXPS[format] instanceof RegExp) { - return FORMAT_REGEXPS[format].test(input); - } - if (typeof FORMAT_REGEXPS[format] === 'function') { - return FORMAT_REGEXPS[format](input); - } - } else if (validator && validator.customFormats && - typeof validator.customFormats[format] === 'function') { - return validator.customFormats[format](input); - } - return true; - }; - - var makeSuffix = helpers.makeSuffix = function makeSuffix (key) { - key = key.toString(); - // This function could be capable of outputting valid a ECMAScript string, but the - // resulting code for testing which form to use would be tens of thousands of characters long - // That means this will use the name form for some illegal forms - if (!key.match(/[.\s\[\]]/) && !key.match(/^[\d]/)) { - return '.' + key; - } - if (key.match(/^\d+$/)) { - return '[' + key + ']'; - } - return '[' + JSON.stringify(key) + ']'; - }; - - helpers.deepCompareStrict = function deepCompareStrict (a, b) { - if (typeof a !== typeof b) { - return false; - } - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - if (a.length !== b.length) { - return false; - } - return a.every(function (v, i) { - return deepCompareStrict(a[i], b[i]); - }); - } - if (typeof a === 'object') { - if (!a || !b) { - return a === b; - } - var aKeys = Object.keys(a); - var bKeys = Object.keys(b); - if (aKeys.length !== bKeys.length) { - return false; - } - return aKeys.every(function (v) { - return deepCompareStrict(a[v], b[v]); - }); - } - return a === b; - }; - - function deepMerger (target, dst, e, i) { - if (typeof e === 'object') { - dst[i] = deepMerge(target[i], e); - } else { - if (target.indexOf(e) === -1) { - dst.push(e); - } - } - } - - function copyist (src, dst, key) { - dst[key] = src[key]; - } - - function copyistWithDeepMerge (target, src, dst, key) { - if (typeof src[key] !== 'object' || !src[key]) { - dst[key] = src[key]; - } - else { - if (!target[key]) { - dst[key] = src[key]; - } else { - dst[key] = deepMerge(target[key], src[key]); - } - } - } - - function deepMerge (target, src) { - var array = Array.isArray(src); - var dst = array && [] || {}; - - if (array) { - target = target || []; - dst = dst.concat(target); - src.forEach(deepMerger.bind(null, target, dst)); - } else { - if (target && typeof target === 'object') { - Object.keys(target).forEach(copyist.bind(null, target, dst)); - } - Object.keys(src).forEach(copyistWithDeepMerge.bind(null, target, src, dst)); - } - - return dst; - } - - helpers.deepMerge = deepMerge; - - /** - * Validates instance against the provided schema - * Implements URI+JSON Pointer encoding, e.g. "%7e"="~0"=>"~", "~1"="%2f"=>"/" - * @param o - * @param s The path to walk o along - * @return any - */ - helpers.objectGetPath = function objectGetPath(o, s) { - var parts = s.split('/').slice(1); - var k; - while (typeof (k=parts.shift()) == 'string') { - var n = decodeURIComponent(k.replace(/~0/,'~').replace(/~1/g,'/')); - if (!(n in o)) return; - o = o[n]; - } - return o; - }; - - function pathEncoder (v) { - return '/'+encodeURIComponent(v).replace(/~/g,'%7E'); - } - /** - * Accept an Array of property names and return a JSON Pointer URI fragment - * @param Array a - * @return {String} - */ - helpers.encodePath = function encodePointer(a){ - // ~ must be encoded explicitly because hacks - // the slash is encoded by encodeURIComponent - return a.map(pathEncoder).join(''); - }; - - - /** - * Calculate the number of decimal places a number uses - * We need this to get correct results out of multipleOf and divisibleBy - * when either figure is has decimal places, due to IEEE-754 float issues. - * @param number - * @returns {number} - */ - helpers.getDecimalPlaces = function getDecimalPlaces(number) { - - var decimalPlaces = 0; - if (isNaN(number)) return decimalPlaces; - - if (typeof number !== 'number') { - number = Number(number); - } - - var parts = number.toString().split('e'); - if (parts.length === 2) { - if (parts[1][0] !== '-') { - return decimalPlaces; - } else { - decimalPlaces = Number(parts[1].slice(1)); - } - } - - var decimalParts = parts[0].split('.'); - if (decimalParts.length === 2) { - decimalPlaces += decimalParts[1].length; - } - - return decimalPlaces; - }; - - helpers.isSchema = function isSchema(val){ - return (typeof val === 'object' && val) || (typeof val === 'boolean'); - }; - - /** - * Resolve target URL from a base and relative URL. - * Similar to Node's URL Lib's legacy resolve function. - * Code from example in deprecation note in said library. - * @param string - * @param string - * @returns {string} - */ - var resolveUrl = helpers.resolveUrl = function resolveUrl(from, to) { - const resolvedUrl = new URL(to, new URL(from, 'resolve://')); - if (resolvedUrl.protocol === 'resolve:') { - const { pathname, search, hash } = resolvedUrl; - return pathname + search + hash; - } - return resolvedUrl.toString(); - }; - return helpers; -} - -var attribute_1; -var hasRequiredAttribute; - -function requireAttribute () { - if (hasRequiredAttribute) return attribute_1; - hasRequiredAttribute = 1; - - var helpers = requireHelpers(); - - /** @type ValidatorResult */ - var ValidatorResult = helpers.ValidatorResult; - /** @type SchemaError */ - var SchemaError = helpers.SchemaError; - - var attribute = {}; - - attribute.ignoreProperties = { - // informative properties - 'id': true, - 'default': true, - 'description': true, - 'title': true, - // arguments to other properties - 'additionalItems': true, - 'then': true, - 'else': true, - // special-handled properties - '$schema': true, - '$ref': true, - 'extends': true, - }; - - /** - * @name validators - */ - var validators = attribute.validators = {}; - - /** - * Validates whether the instance if of a certain type - * @param instance - * @param schema - * @param options - * @param ctx - * @return {ValidatorResult|null} - */ - validators.type = function validateType (instance, schema, options, ctx) { - // Ignore undefined instances - if (instance === undefined) { - return null; - } - var result = new ValidatorResult(instance, schema, options, ctx); - var types = Array.isArray(schema.type) ? schema.type : [schema.type]; - if (!types.some(this.testType.bind(this, instance, schema, options, ctx))) { - var list = types.map(function (v) { - if(!v) return; - var id = v.$id || v.id; - return id ? ('<' + id + '>') : (v+''); - }); - result.addError({ - name: 'type', - argument: list, - message: "is not of a type(s) " + list, - }); - } - return result; - }; - - function testSchemaNoThrow(instance, options, ctx, callback, schema){ - var throwError = options.throwError; - var throwAll = options.throwAll; - options.throwError = false; - options.throwAll = false; - var res = this.validateSchema(instance, schema, options, ctx); - options.throwError = throwError; - options.throwAll = throwAll; - - if (!res.valid && callback instanceof Function) { - callback(res); - } - return res.valid; - } - - /** - * Validates whether the instance matches some of the given schemas - * @param instance - * @param schema - * @param options - * @param ctx - * @return {ValidatorResult|null} - */ - validators.anyOf = function validateAnyOf (instance, schema, options, ctx) { - // Ignore undefined instances - if (instance === undefined) { - return null; - } - var result = new ValidatorResult(instance, schema, options, ctx); - var inner = new ValidatorResult(instance, schema, options, ctx); - if (!Array.isArray(schema.anyOf)){ - throw new SchemaError("anyOf must be an array"); - } - if (!schema.anyOf.some( - testSchemaNoThrow.bind( - this, instance, options, ctx, function(res){inner.importErrors(res);} - ))) { - var list = schema.anyOf.map(function (v, i) { - var id = v.$id || v.id; - if(id) return '<' + id + '>'; - return (v.title && JSON.stringify(v.title)) || (v['$ref'] && ('<' + v['$ref'] + '>')) || '[subschema '+i+']'; - }); - if (options.nestedErrors) { - result.importErrors(inner); - } - result.addError({ - name: 'anyOf', - argument: list, - message: "is not any of " + list.join(','), - }); - } - return result; - }; - - /** - * Validates whether the instance matches every given schema - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null} - */ - validators.allOf = function validateAllOf (instance, schema, options, ctx) { - // Ignore undefined instances - if (instance === undefined) { - return null; - } - if (!Array.isArray(schema.allOf)){ - throw new SchemaError("allOf must be an array"); - } - var result = new ValidatorResult(instance, schema, options, ctx); - var self = this; - schema.allOf.forEach(function(v, i){ - var valid = self.validateSchema(instance, v, options, ctx); - if(!valid.valid){ - var id = v.$id || v.id; - var msg = id || (v.title && JSON.stringify(v.title)) || (v['$ref'] && ('<' + v['$ref'] + '>')) || '[subschema '+i+']'; - result.addError({ - name: 'allOf', - argument: { id: msg, length: valid.errors.length, valid: valid }, - message: 'does not match allOf schema ' + msg + ' with ' + valid.errors.length + ' error[s]:', - }); - result.importErrors(valid); - } - }); - return result; - }; - - /** - * Validates whether the instance matches exactly one of the given schemas - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null} - */ - validators.oneOf = function validateOneOf (instance, schema, options, ctx) { - // Ignore undefined instances - if (instance === undefined) { - return null; - } - if (!Array.isArray(schema.oneOf)){ - throw new SchemaError("oneOf must be an array"); - } - var result = new ValidatorResult(instance, schema, options, ctx); - var inner = new ValidatorResult(instance, schema, options, ctx); - var count = schema.oneOf.filter( - testSchemaNoThrow.bind( - this, instance, options, ctx, function(res) {inner.importErrors(res);} - ) ).length; - var list = schema.oneOf.map(function (v, i) { - var id = v.$id || v.id; - return id || (v.title && JSON.stringify(v.title)) || (v['$ref'] && ('<' + v['$ref'] + '>')) || '[subschema '+i+']'; - }); - if (count!==1) { - if (options.nestedErrors) { - result.importErrors(inner); - } - result.addError({ - name: 'oneOf', - argument: list, - message: "is not exactly one from " + list.join(','), - }); - } - return result; - }; - - /** - * Validates "then" or "else" depending on the result of validating "if" - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null} - */ - validators.if = function validateIf (instance, schema, options, ctx) { - // Ignore undefined instances - if (instance === undefined) return null; - if (!helpers.isSchema(schema.if)) throw new Error('Expected "if" keyword to be a schema'); - var ifValid = testSchemaNoThrow.call(this, instance, options, ctx, null, schema.if); - var result = new ValidatorResult(instance, schema, options, ctx); - var res; - if(ifValid){ - if (schema.then === undefined) return; - if (!helpers.isSchema(schema.then)) throw new Error('Expected "then" keyword to be a schema'); - res = this.validateSchema(instance, schema.then, options, ctx.makeChild(schema.then)); - result.importErrors(res); - }else { - if (schema.else === undefined) return; - if (!helpers.isSchema(schema.else)) throw new Error('Expected "else" keyword to be a schema'); - res = this.validateSchema(instance, schema.else, options, ctx.makeChild(schema.else)); - result.importErrors(res); - } - return result; - }; - - function getEnumerableProperty(object, key){ - // Determine if `key` shows up in `for(var key in object)` - // First test Object.hasOwnProperty.call as an optimization: that guarantees it does - if(Object.hasOwnProperty.call(object, key)) return object[key]; - // Test `key in object` as an optimization; false means it won't - if(!(key in object)) return; - while( (object = Object.getPrototypeOf(object)) ){ - if(Object.propertyIsEnumerable.call(object, key)) return object[key]; - } - } - - /** - * Validates propertyNames - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null|ValidatorResult} - */ - validators.propertyNames = function validatePropertyNames (instance, schema, options, ctx) { - if(!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var subschema = schema.propertyNames!==undefined ? schema.propertyNames : {}; - if(!helpers.isSchema(subschema)) throw new SchemaError('Expected "propertyNames" to be a schema (object or boolean)'); - - for (var property in instance) { - if(getEnumerableProperty(instance, property) !== undefined){ - var res = this.validateSchema(property, subschema, options, ctx.makeChild(subschema)); - result.importErrors(res); - } - } - - return result; - }; - - /** - * Validates properties - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null|ValidatorResult} - */ - validators.properties = function validateProperties (instance, schema, options, ctx) { - if(!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var properties = schema.properties || {}; - for (var property in properties) { - var subschema = properties[property]; - if(subschema===undefined){ - continue; - }else if(subschema===null){ - throw new SchemaError('Unexpected null, expected schema in "properties"'); - } - if (typeof options.preValidateProperty == 'function') { - options.preValidateProperty(instance, property, subschema, options, ctx); - } - var prop = getEnumerableProperty(instance, property); - var res = this.validateSchema(prop, subschema, options, ctx.makeChild(subschema, property)); - if(res.instance !== result.instance[property]) result.instance[property] = res.instance; - result.importErrors(res); - } - return result; - }; - - /** - * Test a specific property within in instance against the additionalProperties schema attribute - * This ignores properties with definitions in the properties schema attribute, but no other attributes. - * If too many more types of property-existence tests pop up they may need their own class of tests (like `type` has) - * @private - * @return {boolean} - */ - function testAdditionalProperty (instance, schema, options, ctx, property, result) { - if(!this.types.object(instance)) return; - if (schema.properties && schema.properties[property] !== undefined) { - return; - } - if (schema.additionalProperties === false) { - result.addError({ - name: 'additionalProperties', - argument: property, - message: "is not allowed to have the additional property " + JSON.stringify(property), - }); - } else { - var additionalProperties = schema.additionalProperties || {}; - - if (typeof options.preValidateProperty == 'function') { - options.preValidateProperty(instance, property, additionalProperties, options, ctx); - } - - var res = this.validateSchema(instance[property], additionalProperties, options, ctx.makeChild(additionalProperties, property)); - if(res.instance !== result.instance[property]) result.instance[property] = res.instance; - result.importErrors(res); - } - } - - /** - * Validates patternProperties - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null|ValidatorResult} - */ - validators.patternProperties = function validatePatternProperties (instance, schema, options, ctx) { - if(!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var patternProperties = schema.patternProperties || {}; - - for (var property in instance) { - var test = true; - for (var pattern in patternProperties) { - var subschema = patternProperties[pattern]; - if(subschema===undefined){ - continue; - }else if(subschema===null){ - throw new SchemaError('Unexpected null, expected schema in "patternProperties"'); - } - try { - var regexp = new RegExp(pattern, 'u'); - } catch(_e) { - // In the event the stricter handling causes an error, fall back on the forgiving handling - // DEPRECATED - regexp = new RegExp(pattern); - } - if (!regexp.test(property)) { - continue; - } - test = false; - - if (typeof options.preValidateProperty == 'function') { - options.preValidateProperty(instance, property, subschema, options, ctx); - } - - var res = this.validateSchema(instance[property], subschema, options, ctx.makeChild(subschema, property)); - if(res.instance !== result.instance[property]) result.instance[property] = res.instance; - result.importErrors(res); - } - if (test) { - testAdditionalProperty.call(this, instance, schema, options, ctx, property, result); - } - } - - return result; - }; - - /** - * Validates additionalProperties - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null|ValidatorResult} - */ - validators.additionalProperties = function validateAdditionalProperties (instance, schema, options, ctx) { - if(!this.types.object(instance)) return; - // if patternProperties is defined then we'll test when that one is called instead - if (schema.patternProperties) { - return null; - } - var result = new ValidatorResult(instance, schema, options, ctx); - for (var property in instance) { - testAdditionalProperty.call(this, instance, schema, options, ctx, property, result); - } - return result; - }; - - /** - * Validates whether the instance value is at least of a certain length, when the instance value is a string. - * @param instance - * @param schema - * @return {String|null} - */ - validators.minProperties = function validateMinProperties (instance, schema, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var keys = Object.keys(instance); - if (!(keys.length >= schema.minProperties)) { - result.addError({ - name: 'minProperties', - argument: schema.minProperties, - message: "does not meet minimum property length of " + schema.minProperties, - }); - } - return result; - }; - - /** - * Validates whether the instance value is at most of a certain length, when the instance value is a string. - * @param instance - * @param schema - * @return {String|null} - */ - validators.maxProperties = function validateMaxProperties (instance, schema, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var keys = Object.keys(instance); - if (!(keys.length <= schema.maxProperties)) { - result.addError({ - name: 'maxProperties', - argument: schema.maxProperties, - message: "does not meet maximum property length of " + schema.maxProperties, - }); - } - return result; - }; - - /** - * Validates items when instance is an array - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null|ValidatorResult} - */ - validators.items = function validateItems (instance, schema, options, ctx) { - var self = this; - if (!this.types.array(instance)) return; - if (schema.items===undefined) return; - var result = new ValidatorResult(instance, schema, options, ctx); - instance.every(function (value, i) { - if(Array.isArray(schema.items)){ - var items = schema.items[i]===undefined ? schema.additionalItems : schema.items[i]; - }else { - var items = schema.items; - } - if (items === undefined) { - return true; - } - if (items === false) { - result.addError({ - name: 'items', - message: "additionalItems not permitted", - }); - return false; - } - var res = self.validateSchema(value, items, options, ctx.makeChild(items, i)); - if(res.instance !== result.instance[i]) result.instance[i] = res.instance; - result.importErrors(res); - return true; - }); - return result; - }; - - /** - * Validates the "contains" keyword - * @param instance - * @param schema - * @param options - * @param ctx - * @return {String|null|ValidatorResult} - */ - validators.contains = function validateContains (instance, schema, options, ctx) { - var self = this; - if (!this.types.array(instance)) return; - if (schema.contains===undefined) return; - if (!helpers.isSchema(schema.contains)) throw new Error('Expected "contains" keyword to be a schema'); - var result = new ValidatorResult(instance, schema, options, ctx); - var count = instance.some(function (value, i) { - var res = self.validateSchema(value, schema.contains, options, ctx.makeChild(schema.contains, i)); - return res.errors.length===0; - }); - if(count===false){ - result.addError({ - name: 'contains', - argument: schema.contains, - message: "must contain an item matching given schema", - }); - } - return result; - }; - - /** - * Validates minimum and exclusiveMinimum when the type of the instance value is a number. - * @param instance - * @param schema - * @return {String|null} - */ - validators.minimum = function validateMinimum (instance, schema, options, ctx) { - if (!this.types.number(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - if (schema.exclusiveMinimum && schema.exclusiveMinimum === true) { - if(!(instance > schema.minimum)){ - result.addError({ - name: 'minimum', - argument: schema.minimum, - message: "must be greater than " + schema.minimum, - }); - } - } else { - if(!(instance >= schema.minimum)){ - result.addError({ - name: 'minimum', - argument: schema.minimum, - message: "must be greater than or equal to " + schema.minimum, - }); - } - } - return result; - }; - - /** - * Validates maximum and exclusiveMaximum when the type of the instance value is a number. - * @param instance - * @param schema - * @return {String|null} - */ - validators.maximum = function validateMaximum (instance, schema, options, ctx) { - if (!this.types.number(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - if (schema.exclusiveMaximum && schema.exclusiveMaximum === true) { - if(!(instance < schema.maximum)){ - result.addError({ - name: 'maximum', - argument: schema.maximum, - message: "must be less than " + schema.maximum, - }); - } - } else { - if(!(instance <= schema.maximum)){ - result.addError({ - name: 'maximum', - argument: schema.maximum, - message: "must be less than or equal to " + schema.maximum, - }); - } - } - return result; - }; - - /** - * Validates the number form of exclusiveMinimum when the type of the instance value is a number. - * @param instance - * @param schema - * @return {String|null} - */ - validators.exclusiveMinimum = function validateExclusiveMinimum (instance, schema, options, ctx) { - // Support the boolean form of exclusiveMinimum, which is handled by the "minimum" keyword. - if(typeof schema.exclusiveMinimum === 'boolean') return; - if (!this.types.number(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var valid = instance > schema.exclusiveMinimum; - if (!valid) { - result.addError({ - name: 'exclusiveMinimum', - argument: schema.exclusiveMinimum, - message: "must be strictly greater than " + schema.exclusiveMinimum, - }); - } - return result; - }; - - /** - * Validates the number form of exclusiveMaximum when the type of the instance value is a number. - * @param instance - * @param schema - * @return {String|null} - */ - validators.exclusiveMaximum = function validateExclusiveMaximum (instance, schema, options, ctx) { - // Support the boolean form of exclusiveMaximum, which is handled by the "maximum" keyword. - if(typeof schema.exclusiveMaximum === 'boolean') return; - if (!this.types.number(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var valid = instance < schema.exclusiveMaximum; - if (!valid) { - result.addError({ - name: 'exclusiveMaximum', - argument: schema.exclusiveMaximum, - message: "must be strictly less than " + schema.exclusiveMaximum, - }); - } - return result; - }; - - /** - * Perform validation for multipleOf and divisibleBy, which are essentially the same. - * @param instance - * @param schema - * @param validationType - * @param errorMessage - * @returns {String|null} - */ - var validateMultipleOfOrDivisbleBy = function validateMultipleOfOrDivisbleBy (instance, schema, options, ctx, validationType, errorMessage) { - if (!this.types.number(instance)) return; - - var validationArgument = schema[validationType]; - if (validationArgument == 0) { - throw new SchemaError(validationType + " cannot be zero"); - } - - var result = new ValidatorResult(instance, schema, options, ctx); - - var instanceDecimals = helpers.getDecimalPlaces(instance); - var divisorDecimals = helpers.getDecimalPlaces(validationArgument); - - var maxDecimals = Math.max(instanceDecimals , divisorDecimals); - var multiplier = Math.pow(10, maxDecimals); - - if (Math.round(instance * multiplier) % Math.round(validationArgument * multiplier) !== 0) { - result.addError({ - name: validationType, - argument: validationArgument, - message: errorMessage + JSON.stringify(validationArgument), - }); - } - - return result; - }; - - /** - * Validates divisibleBy when the type of the instance value is a number. - * @param instance - * @param schema - * @return {String|null} - */ - validators.multipleOf = function validateMultipleOf (instance, schema, options, ctx) { - return validateMultipleOfOrDivisbleBy.call(this, instance, schema, options, ctx, "multipleOf", "is not a multiple of (divisible by) "); - }; - - /** - * Validates multipleOf when the type of the instance value is a number. - * @param instance - * @param schema - * @return {String|null} - */ - validators.divisibleBy = function validateDivisibleBy (instance, schema, options, ctx) { - return validateMultipleOfOrDivisbleBy.call(this, instance, schema, options, ctx, "divisibleBy", "is not divisible by (multiple of) "); - }; - - /** - * Validates whether the instance value is present. - * @param instance - * @param schema - * @return {String|null} - */ - validators.required = function validateRequired (instance, schema, options, ctx) { - var result = new ValidatorResult(instance, schema, options, ctx); - if (instance === undefined && schema.required === true) { - // A boolean form is implemented for reverse-compatibility with schemas written against older drafts - result.addError({ - name: 'required', - message: "is required", - }); - } else if (this.types.object(instance) && Array.isArray(schema.required)) { - schema.required.forEach(function(n){ - if(getEnumerableProperty(instance, n)===undefined){ - result.addError({ - name: 'required', - argument: n, - message: "requires property " + JSON.stringify(n), - }); - } - }); - } - return result; - }; - - /** - * Validates whether the instance value matches the regular expression, when the instance value is a string. - * @param instance - * @param schema - * @return {String|null} - */ - validators.pattern = function validatePattern (instance, schema, options, ctx) { - if (!this.types.string(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var pattern = schema.pattern; - try { - var regexp = new RegExp(pattern, 'u'); - } catch(_e) { - // In the event the stricter handling causes an error, fall back on the forgiving handling - // DEPRECATED - regexp = new RegExp(pattern); - } - if (!instance.match(regexp)) { - result.addError({ - name: 'pattern', - argument: schema.pattern, - message: "does not match pattern " + JSON.stringify(schema.pattern.toString()), - }); - } - return result; - }; - - /** - * Validates whether the instance value is of a certain defined format or a custom - * format. - * The following formats are supported for string types: - * - date-time - * - date - * - time - * - ip-address - * - ipv6 - * - uri - * - color - * - host-name - * - alpha - * - alpha-numeric - * - utc-millisec - * @param instance - * @param schema - * @param [options] - * @param [ctx] - * @return {String|null} - */ - validators.format = function validateFormat (instance, schema, options, ctx) { - if (instance===undefined) return; - var result = new ValidatorResult(instance, schema, options, ctx); - if (!result.disableFormat && !helpers.isFormat(instance, schema.format, this)) { - result.addError({ - name: 'format', - argument: schema.format, - message: "does not conform to the " + JSON.stringify(schema.format) + " format", - }); - } - return result; - }; - - /** - * Validates whether the instance value is at least of a certain length, when the instance value is a string. - * @param instance - * @param schema - * @return {String|null} - */ - validators.minLength = function validateMinLength (instance, schema, options, ctx) { - if (!this.types.string(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - var hsp = instance.match(/[\uDC00-\uDFFF]/g); - var length = instance.length - (hsp ? hsp.length : 0); - if (!(length >= schema.minLength)) { - result.addError({ - name: 'minLength', - argument: schema.minLength, - message: "does not meet minimum length of " + schema.minLength, - }); - } - return result; - }; - - /** - * Validates whether the instance value is at most of a certain length, when the instance value is a string. - * @param instance - * @param schema - * @return {String|null} - */ - validators.maxLength = function validateMaxLength (instance, schema, options, ctx) { - if (!this.types.string(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - // TODO if this was already computed in "minLength", use that value instead of re-computing - var hsp = instance.match(/[\uDC00-\uDFFF]/g); - var length = instance.length - (hsp ? hsp.length : 0); - if (!(length <= schema.maxLength)) { - result.addError({ - name: 'maxLength', - argument: schema.maxLength, - message: "does not meet maximum length of " + schema.maxLength, - }); - } - return result; - }; - - /** - * Validates whether instance contains at least a minimum number of items, when the instance is an Array. - * @param instance - * @param schema - * @return {String|null} - */ - validators.minItems = function validateMinItems (instance, schema, options, ctx) { - if (!this.types.array(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - if (!(instance.length >= schema.minItems)) { - result.addError({ - name: 'minItems', - argument: schema.minItems, - message: "does not meet minimum length of " + schema.minItems, - }); - } - return result; - }; - - /** - * Validates whether instance contains no more than a maximum number of items, when the instance is an Array. - * @param instance - * @param schema - * @return {String|null} - */ - validators.maxItems = function validateMaxItems (instance, schema, options, ctx) { - if (!this.types.array(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - if (!(instance.length <= schema.maxItems)) { - result.addError({ - name: 'maxItems', - argument: schema.maxItems, - message: "does not meet maximum length of " + schema.maxItems, - }); - } - return result; - }; - - /** - * Deep compares arrays for duplicates - * @param v - * @param i - * @param a - * @private - * @return {boolean} - */ - function testArrays (v, i, a) { - var j, len = a.length; - for (j = i + 1, len; j < len; j++) { - if (helpers.deepCompareStrict(v, a[j])) { - return false; - } - } - return true; - } - - /** - * Validates whether there are no duplicates, when the instance is an Array. - * @param instance - * @return {String|null} - */ - validators.uniqueItems = function validateUniqueItems (instance, schema, options, ctx) { - if (schema.uniqueItems!==true) return; - if (!this.types.array(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - if (!instance.every(testArrays)) { - result.addError({ - name: 'uniqueItems', - message: "contains duplicate item", - }); - } - return result; - }; - - /** - * Validate for the presence of dependency properties, if the instance is an object. - * @param instance - * @param schema - * @param options - * @param ctx - * @return {null|ValidatorResult} - */ - validators.dependencies = function validateDependencies (instance, schema, options, ctx) { - if (!this.types.object(instance)) return; - var result = new ValidatorResult(instance, schema, options, ctx); - for (var property in schema.dependencies) { - if (instance[property] === undefined) { - continue; - } - var dep = schema.dependencies[property]; - var childContext = ctx.makeChild(dep, property); - if (typeof dep == 'string') { - dep = [dep]; - } - if (Array.isArray(dep)) { - dep.forEach(function (prop) { - if (instance[prop] === undefined) { - result.addError({ - // FIXME there's two different "dependencies" errors here with slightly different outputs - // Can we make these the same? Or should we create different error types? - name: 'dependencies', - argument: childContext.propertyPath, - message: "property " + prop + " not found, required by " + childContext.propertyPath, - }); - } - }); - } else { - var res = this.validateSchema(instance, dep, options, childContext); - if(result.instance !== res.instance) result.instance = res.instance; - if (res && res.errors.length) { - result.addError({ - name: 'dependencies', - argument: childContext.propertyPath, - message: "does not meet dependency required by " + childContext.propertyPath, - }); - result.importErrors(res); - } - } - } - return result; - }; - - /** - * Validates whether the instance value is one of the enumerated values. - * - * @param instance - * @param schema - * @return {ValidatorResult|null} - */ - validators['enum'] = function validateEnum (instance, schema, options, ctx) { - if (instance === undefined) { - return null; - } - if (!Array.isArray(schema['enum'])) { - throw new SchemaError("enum expects an array", schema); - } - var result = new ValidatorResult(instance, schema, options, ctx); - if (!schema['enum'].some(helpers.deepCompareStrict.bind(null, instance))) { - result.addError({ - name: 'enum', - argument: schema['enum'], - message: "is not one of enum values: " + schema['enum'].map(String).join(','), - }); - } - return result; - }; - - /** - * Validates whether the instance exactly matches a given value - * - * @param instance - * @param schema - * @return {ValidatorResult|null} - */ - validators['const'] = function validateEnum (instance, schema, options, ctx) { - if (instance === undefined) { - return null; - } - var result = new ValidatorResult(instance, schema, options, ctx); - if (!helpers.deepCompareStrict(schema['const'], instance)) { - result.addError({ - name: 'const', - argument: schema['const'], - message: "does not exactly match expected constant: " + schema['const'], - }); - } - return result; - }; - - /** - * Validates whether the instance if of a prohibited type. - * @param instance - * @param schema - * @param options - * @param ctx - * @return {null|ValidatorResult} - */ - validators.not = validators.disallow = function validateNot (instance, schema, options, ctx) { - var self = this; - if(instance===undefined) return null; - var result = new ValidatorResult(instance, schema, options, ctx); - var notTypes = schema.not || schema.disallow; - if(!notTypes) return null; - if(!Array.isArray(notTypes)) notTypes=[notTypes]; - notTypes.forEach(function (type) { - if (self.testType(instance, schema, options, ctx, type)) { - var id = type && (type.$id || type.id); - var schemaId = id || type; - result.addError({ - name: 'not', - argument: schemaId, - message: "is of prohibited type " + schemaId, - }); - } - }); - return result; - }; - - attribute_1 = attribute; - return attribute_1; -} - -var scan = {}; - -var hasRequiredScan; - -function requireScan () { - if (hasRequiredScan) return scan; - hasRequiredScan = 1; - - var helpers = requireHelpers(); - - scan.SchemaScanResult = SchemaScanResult; - function SchemaScanResult(found, ref){ - this.id = found; - this.ref = ref; - } - - /** - * Adds a schema with a certain urn to the Validator instance. - * @param string uri - * @param object schema - * @return {Object} - */ - scan.scan = function scan(base, schema){ - function scanSchema(baseuri, schema){ - if(!schema || typeof schema!='object') return; - // Mark all referenced schemas so we can tell later which schemas are referred to, but never defined - if(schema.$ref){ - let resolvedUri = helpers.resolveUrl(baseuri,schema.$ref); - ref[resolvedUri] = ref[resolvedUri] ? ref[resolvedUri]+1 : 0; - return; - } - var id = schema.$id || schema.id; - let resolvedBase = helpers.resolveUrl(baseuri,id); - var ourBase = id ? resolvedBase : baseuri; - if (ourBase) { - // If there's no fragment, append an empty one - if(ourBase.indexOf('#')<0) ourBase += '#'; - if(found[ourBase]){ - if(!helpers.deepCompareStrict(found[ourBase], schema)){ - throw new Error('Schema <'+ourBase+'> already exists with different definition'); - } - return found[ourBase]; - } - found[ourBase] = schema; - // strip trailing fragment - if(ourBase[ourBase.length-1]=='#'){ - found[ourBase.substring(0, ourBase.length-1)] = schema; - } - } - scanArray(ourBase+'/items', (Array.isArray(schema.items)?schema.items:[schema.items])); - scanArray(ourBase+'/extends', (Array.isArray(schema.extends)?schema.extends:[schema.extends])); - scanSchema(ourBase+'/additionalItems', schema.additionalItems); - scanObject(ourBase+'/properties', schema.properties); - scanSchema(ourBase+'/additionalProperties', schema.additionalProperties); - scanObject(ourBase+'/definitions', schema.definitions); - scanObject(ourBase+'/patternProperties', schema.patternProperties); - scanObject(ourBase+'/dependencies', schema.dependencies); - scanArray(ourBase+'/disallow', schema.disallow); - scanArray(ourBase+'/allOf', schema.allOf); - scanArray(ourBase+'/anyOf', schema.anyOf); - scanArray(ourBase+'/oneOf', schema.oneOf); - scanSchema(ourBase+'/not', schema.not); - } - function scanArray(baseuri, schemas){ - if(!Array.isArray(schemas)) return; - for(var i=0; i", schema); - } - var subschema = helpers.objectGetPath(ctx.schemas[document], fragment.substr(1)); - if(subschema===undefined){ - throw new SchemaError("no such schema " + fragment + " located in <" + document + ">", schema); - } - return {subschema: subschema, switchSchema: switchSchema}; - }; - - /** - * Tests whether the instance if of a certain type. - * @private - * @param instance - * @param schema - * @param options - * @param ctx - * @param type - * @return {boolean} - */ - Validator.prototype.testType = function validateType (instance, schema, options, ctx, type) { - if(type===undefined){ - return; - }else if(type===null){ - throw new SchemaError('Unexpected null in "type" keyword'); - } - if (typeof this.types[type] == 'function') { - return this.types[type].call(this, instance); - } - if (type && typeof type == 'object') { - var res = this.validateSchema(instance, type, options, ctx); - return res === undefined || !(res && res.errors.length); - } - // Undefined or properties not on the list are acceptable, same as not being defined - return true; - }; - - var types = Validator.prototype.types = {}; - types.string = function testString (instance) { - return typeof instance == 'string'; - }; - types.number = function testNumber (instance) { - // isFinite returns false for NaN, Infinity, and -Infinity - return typeof instance == 'number' && isFinite(instance); - }; - types.integer = function testInteger (instance) { - return (typeof instance == 'number') && instance % 1 === 0; - }; - types.boolean = function testBoolean (instance) { - return typeof instance == 'boolean'; - }; - types.array = function testArray (instance) { - return Array.isArray(instance); - }; - types['null'] = function testNull (instance) { - return instance === null; - }; - types.date = function testDate (instance) { - return instance instanceof Date; - }; - types.any = function testAny (instance) { - return true; - }; - types.object = function testObject (instance) { - // TODO: fix this - see #15 - return instance && (typeof instance === 'object') && !(Array.isArray(instance)) && !(instance instanceof Date); - }; - - validator = Validator; - return validator; -} - -var hasRequiredLib; - -function requireLib () { - if (hasRequiredLib) return lib; - hasRequiredLib = 1; - - var Validator = lib.Validator = requireValidator(); - - lib.ValidatorResult = requireHelpers().ValidatorResult; - lib.ValidatorResultError = requireHelpers().ValidatorResultError; - lib.ValidationError = requireHelpers().ValidationError; - lib.SchemaError = requireHelpers().SchemaError; - lib.SchemaScanResult = requireScan().SchemaScanResult; - lib.scan = requireScan().scan; - - lib.validate = function (instance, schema, options) { - var v = new Validator(); - return v.validate(instance, schema, options); - }; - return lib; -} - -var libExports = requireLib(); - -const toolBaseSchema = z.object({ - name: z.string(), - description: z.string(), -}); -class SimpleToolCallContext { - constructor(logger, signal, callId) { - this.logger = logger; - this.signal = signal; - this.callId = callId; - } - status(text) { - this.logger.info(text); - } - warn(text) { - this.logger.warn(text); - } -} -const functionToolSchema = toolBaseSchema.extend({ - type: z.literal("function"), - parametersSchema: zodSchemaSchema, - checkParameters: z.function(), - implementation: z.function(), -}); -const rawFunctionToolSchema = toolBaseSchema.extend({ - type: z.literal("rawFunction"), - parametersSchema: zodSchemaSchema, - checkParameters: z.function(), - implementation: z.function(), -}); -const unimplementedRawFunctionToolSchema = toolBaseSchema.extend({ - type: z.literal("unimplementedRawFunction"), - parametersJsonSchema: zodSchemaSchema, - checkParameters: z.function(), - implementation: z.function(), -}); -const remoteToolSchema = toolBaseSchema.extend({ - type: z.literal("remoteTool"), - pluginIdentifier: z.string(), - parametersJsonSchema: zodSchemaSchema, - checkParameters: z.function(), - implementation: z.function(), -}); -z.discriminatedUnion("type", [ - functionToolSchema, - rawFunctionToolSchema, - unimplementedRawFunctionToolSchema, - remoteToolSchema, -]); -/** - * A function that can be used to create a function `Tool` given a function definition and its - * implementation. - * - * @public - */ -function tool({ name, description, parameters, implementation, }) { - const parametersSchema = z.object(parameters); - return { - name, - description, - type: "function", - parametersSchema, - checkParameters(params) { - const parametersParseResult = parametersSchema.safeParse(params); - if (!parametersParseResult.success) { - throw new Error(text ` - Failed to parse arguments for tool "${name}": - ${parametersParseResult.error.message} - `); - } - }, - implementation: (params, ctx) => { - const parametersParseResult = parametersSchema.safeParse(params); - if (!parametersParseResult.success) { - throw new Error(text ` - Failed to parse arguments for tool "${name}": - ${parametersParseResult.error.message} - `); - } - return implementation(parametersParseResult.data, ctx); // Erase the types - }, - }; -} -function jsonSchemaValidationErrorToAIReadableText(root, validationErrors) { - return validationErrors - .map(validatioNError => { - const fullPath = [root, ...validatioNError.path].join("."); - return `${fullPath} ${validatioNError.message}`; - }) - .join("\n"); -} -/** - * A function that can be used to create a raw function `Tool` given a function definition and its - * implementation. - * - * @public - * @experimental Not stable, will likely change in the future. - */ -function rawFunctionTool({ name, description, parametersJsonSchema, implementation, }) { - const jsonSchemaValidator = new libExports.Validator(); - return { - name, - description, - type: "rawFunction", - parametersJsonSchema, - checkParameters(params) { - const validationResult = jsonSchemaValidator.validate(params, parametersJsonSchema); - if (validationResult.errors.length > 0) { - throw new Error(text ` - Failed to parse arguments for tool "${name}": - ${jsonSchemaValidationErrorToAIReadableText("params", validationResult.errors)} - `); - } - }, - implementation, - }; -} -class UnimplementedToolError extends Error { - constructor(toolName) { - super(`Tool "${toolName}" is not implemented.`); - } -} -/** - * A function that can be used to create a raw function `Tool` that is not implemented yet. When - * using `.act`, upon encountering an unimplemented tool, the `.act` will stop gracefully. - * - * @public - * @experimental Not stable, will likely change in the future. - */ -function unimplementedRawFunctionTool({ name, description, parametersJsonSchema, }) { - const jsonSchemaValidator = new libExports.Validator(); - return { - name, - description, - type: "unimplementedRawFunction", - parametersJsonSchema, - checkParameters(params) { - const validationResult = jsonSchemaValidator.validate(params, parametersJsonSchema); - if (validationResult.errors.length > 0) { - throw new Error(text ` - Failed to parse arguments for tool "${name}": - ${jsonSchemaValidationErrorToAIReadableText("params", validationResult.errors)} - `); - } - }, - implementation: () => { - throw new UnimplementedToolError(name); - }, - }; -} -/** - * Creates a tool that represents a remote tool exposed by an LMStudio plugin. This function is not - * exposed and is used internally by the plugins namespace. - */ -function internalCreateRemoteTool({ name, description, pluginIdentifier, parametersJsonSchema, implementation, }) { - return { - name, - description, - type: "remoteTool", - pluginIdentifier, - parametersJsonSchema, - checkParameters: params => { - const jsonSchemaValidator = new libExports.Validator(); - const validationResult = jsonSchemaValidator.validate(params, parametersJsonSchema); - if (validationResult.errors.length > 0) { - throw new Error(text ` - Failed to parse arguments for tool "${name}": - ${jsonSchemaValidationErrorToAIReadableText("params", validationResult.errors)} - `); - } - }, - implementation, - }; -} -function functionToolToLLMTool(tool) { - return { - type: "function", - function: { - name: tool.name, - description: tool.description, - parameters: zodToJsonSchema(tool.parametersSchema), - }, - }; -} -function rawFunctionToolToLLMTool(tool) { - return { - type: "function", - function: { - name: tool.name, - description: tool.description, - parameters: tool.parametersJsonSchema, - }, - }; -} -function remoteToolToLLMTool(tool) { - return { - type: "function", - function: { - name: tool.name, - description: tool.description, - parameters: tool.parametersJsonSchema, - }, - }; -} -/** - * Convert a `Tool` to a internal `LLMTool`. - */ -function toolToLLMTool(tool) { - const type = tool.type; - switch (type) { - case "function": - return functionToolToLLMTool(tool); - case "rawFunction": - case "unimplementedRawFunction": - return rawFunctionToolToLLMTool(tool); - case "remoteTool": - return remoteToolToLLMTool(tool); - default: { - const exhaustiveCheck = type; - throw new Error(`Unhandled type: ${exhaustiveCheck}`); - } - } -} - -/** - * Represents an error that is caused by invalid tool call request. - * - * @public - * @experimental [EXP-GRANULAR-ACT] More granular .act status reporting is experimental and may - * change in the future - */ -class ToolCallRequestError extends Error { - constructor(message, - /** - * The raw output that was generated by the model before the tool call. The exact nature of this - * fields depends on the error. It sometimes include the entire tool calls section, or sometimes - * just the single tool call that failed. - * - * This field is not always available, and may be `undefined`. - * - * @experimental [EXP-GRANULAR-ACT] More granular .act status reporting is experimental and may - * change in the future - * @experimental [EXP-NON-ACT-TOOL-CALLBACKS] Tool call callbacks in .respond/.complete is in an - * experimental feature. This may change in the future without warning. - */ - rawContent) { - super(message); - this.rawContent = rawContent; - } -} - -class BackendInterface { - constructor() { - this.unhandledEndpoints = new Set(); - this.existingEndpointNames = new Set(); - this.rpcEndpoints = new Map(); - this.channelEndpoints = new Map(); - this.signalEndpoints = new Map(); - this.writableSignalEndpoints = new Map(); - } - withContextType() { - return this; - } - assertEndpointNameNotExists(endpointName) { - if (this.existingEndpointNames.has(endpointName)) { - throw new Error(`Endpoint with name ${endpointName} already exists`); - } - } - /** - * Register an Rpc endpoint. - */ - addRpcEndpoint(endpointName, { parameter, returns, serialization = "raw", }) { - this.assertEndpointNameNotExists(endpointName); - this.existingEndpointNames.add(endpointName); - this.rpcEndpoints.set(endpointName, { - name: endpointName, - parameter, - returns, - serialization, - handler: null, - }); - return this; - } - addChannelEndpoint(endpointName, { creationParameter, toServerPacket, toClientPacket, serialization = "raw", }) { - this.assertEndpointNameNotExists(endpointName); - this.existingEndpointNames.add(endpointName); - this.channelEndpoints.set(endpointName, { - name: endpointName, - creationParameter, - toServerPacket, - toClientPacket, - serialization, - handler: null, - }); - return this; - } - addSignalEndpoint(endpointName, { creationParameter, signalData, serialization = "raw", }) { - this.assertEndpointNameNotExists(endpointName); - this.existingEndpointNames.add(endpointName); - this.signalEndpoints.set(endpointName, { - name: endpointName, - creationParameter, - signalData, - serialization, - handler: null, - }); - return this; - } - addWritableSignalEndpoint(endpointName, { creationParameter, signalData, serialization = "raw", }) { - this.assertEndpointNameNotExists(endpointName); - this.existingEndpointNames.add(endpointName); - this.writableSignalEndpoints.set(endpointName, { - name: endpointName, - creationParameter, - signalData, - serialization, - handler: null, - }); - return this; - } - /** - * Adds a handler for an Rpc endpoint. - * - * @param endpointName - The name of the endpoint. - * @param handler - The handler function. Will be called when the endpoint is invoked. When - * called, the first parameter is the context, and the second parameter is the "parameter" for the - * RPC call. Can return a value or a promise that resolves to the result. - */ - handleRpcEndpoint(endpointName, handler) { - const endpoint = this.rpcEndpoints.get(endpointName); - if (endpoint === undefined) { - throw new Error(`No Rpc endpoint with name ${endpointName}`); - } - if (endpoint.handler !== null) { - throw new Error(`Rpc endpoint with name ${endpointName} already has a handler`); - } - endpoint.handler = handler; - this.unhandledEndpoints.delete(endpointName); - } - /** - * Adds a handler for a channel endpoint. - * - * @param endpointName - The name of the endpoint. - * @param handler - The handler function. Will be called when the client creates a channel for - * this endpoint. When called, the first parameter is the context, the second parameter is the - * "creationParameter" for the channel, and the third parameter is a channel object that can be - * used to send and receive messages from the client. - * - * Must return a promise. Once that promise is settled, the channel will be closed. - */ - handleChannelEndpoint(endpointName, handler) { - const endpoint = this.channelEndpoints.get(endpointName); - if (endpoint === undefined) { - throw new Error(`No channel endpoint with name ${endpointName}`); - } - if (endpoint.handler !== null) { - throw new Error(`Channel endpoint with name ${endpointName} already has a handler`); - } - endpoint.handler = handler; - this.unhandledEndpoints.delete(endpointName); - } - /** - * Adds a handler for a signal endpoint. - * - * @param endpointName - The name of the endpoint. - * @param handler - The handler function. Will be called when the client creates a signal, and at - * least one subscriber is attached to that signal. When called, the first parameter is the - * context, and the second parameter is the "creationParameter" for the signal. This method should - * return a SignalLike, or a promise that resolves to a SignalLike. - * - * Note: There is no 1-to-1 correlation between the signal on the client side and the number of - * times this handler is called. Every time the number of client subscribers changes from 0 to 1, - * this handler will be called. Every time the number of client subscribers changes from 1 to 0, - * the signal returned from this handler will be unsubscribed. - * - * Caution: Do NOT create new subscriptions that don't self-terminate in this handler, as it will - * cause memory leaks. That is, either: - * - * - Return a signal that already exists - * - Create and return a LazySignal - */ - handleSignalEndpoint(endpointName, handler) { - const endpoint = this.signalEndpoints.get(endpointName); - if (endpoint === undefined) { - throw new Error(`No signal endpoint with name ${endpointName}`); - } - if (endpoint.handler !== null) { - throw new Error(`Signal endpoint with name ${endpointName} already has a handler`); - } - endpoint.handler = handler; - this.unhandledEndpoints.delete(endpointName); - } - /** - * Adds a handler for a writable signal endpoint. - * - * @param endpointName - The name of the endpoint. - * @param handler - The handler function. Will be called when the client creates a writable - * signal, and at least one subscriber is attached to that signal. When called, the first - * parameter is the context, and the second parameter is the "creationParameter" for the signal. - * This method should return a tuple of the signal and an update function. The update function - * should be called with the new data, patches, and tags to update the signal. - * - * Note: There is no 1-to-1 correlation between the signal on the client side and the number of - * times this handler is called. Every time the number of client subscribers changes from 0 to 1, - * this handler will be called. Every time the number of client subscribers changes from 1 to 0 - * the signal returned from this handler will be unsubscribed. - * - * Caution: Do NOT create new subscriptions that don't self-terminate in this handler, as it will - * cause memory leaks. That is, either: - * - * - Return a signal that already exists - * - Create and return a LazySignal - */ - handleWritableSignalEndpoint(endpointName, handler) { - const endpoint = this.writableSignalEndpoints.get(endpointName); - if (endpoint === undefined) { - throw new Error(`No writable signal endpoint with name ${endpointName}`); - } - if (endpoint.handler !== null) { - throw new Error(`Writable signal endpoint with name ${endpointName} already has a handler`); - } - endpoint.handler = handler; - this.unhandledEndpoints.delete(endpointName); - } - assertAllEndpointsHandled() { - if (this.unhandledEndpoints.size > 0) { - throw new Error(`The following endpoints were not handled: ${Array.from(this.unhandledEndpoints).join(", ")}`); - } - } - getRpcEndpoint(endpointName) { - return this.rpcEndpoints.get(endpointName); - } - getAllRpcEndpoints() { - return [...this.rpcEndpoints.values()]; - } - getChannelEndpoint(endpointName) { - return this.channelEndpoints.get(endpointName); - } - getAllChannelEndpoints() { - return [...this.channelEndpoints.values()]; - } - getSignalEndpoint(endpointName) { - return this.signalEndpoints.get(endpointName); - } - getAllSignalEndpoints() { - return [...this.signalEndpoints.values()]; - } - getWritableSignalEndpoint(endpointName) { - return this.writableSignalEndpoints.get(endpointName); - } - getAllWritableSignalEndpoints() { - return [...this.writableSignalEndpoints.values()]; - } -} - -var ConnectionStatus; -(function (ConnectionStatus) { - /** - * The underlying transport is connected and is communicating properly. - */ - ConnectionStatus["Connected"] = "CONNECTED"; - /** - * The underlying transport has errored out. - */ - ConnectionStatus["Errored"] = "ERRORED"; - /** - * The channel has been properly closed and no more messages will be sent or received. - */ - ConnectionStatus["Closed"] = "CLOSED"; -})(ConnectionStatus || (ConnectionStatus = {})); -const logger = new SimpleLogger("Channel"); -class Channel { - constructor(innerSend) { - this.innerSend = innerSend; - this.nextAckId = 0; - /** - * A map for messages that are waiting for an ACK. The values are the functions to resolve or - * reject the corresponding promise. - */ - this.waitingForAck = new Map(); - /** - * Returned as a part of create. It should be called by the controlling port. - */ - this.receivedACK = (ackId) => { - if (this.connectionStatus.get() !== ConnectionStatus.Connected) { - logger.warn("Received ACK while in status", this.connectionStatus.get()); - return; - } - const waiting = this.waitingForAck.get(ackId); - if (waiting === undefined) { - logger.warn("Received ACK for a message that is no longer waiting for ACK, ackId =", ackId); - return; - } - waiting.resolve(); - this.waitingForAck.delete(ackId); - }; - /** - * Returned as a part of create. It should be called by the controlling port. - */ - this.receivedMessage = (packet) => { - if (this.connectionStatus.get() !== ConnectionStatus.Connected) { - logger.warn("Received message while in status", this.connectionStatus.get()); - return; - } - this.emitOnMessage(packet); - }; - /** - * Returned as a part of create. It should be called by the controlling port. - */ - this.errored = (error) => { - if (this.connectionStatus.get() !== ConnectionStatus.Connected) { - logger.warn("Received error while in status", this.connectionStatus.get()); - return; - } - this.rejectAllWaitingForAck(error); - this.setConnectionStatus(ConnectionStatus.Errored); - this.emitOnError(error); - }; - /** - * Returned as a part of create. It should be called by the controlling port. - */ - this.closed = () => { - this.rejectAllWaitingForAck(new Error("Channel closed")); - this.setConnectionStatus(ConnectionStatus.Closed); - this.emitOnClose(); - }; - [this.onMessage, this.emitOnMessage] = BufferedEvent.create(); - [this.onError, this.emitOnError] = BufferedEvent.create(); - [this.onClose, this.emitOnClose] = BufferedEvent.create(); - [this.connectionStatus, this.setConnectionStatus] = Signal.create(ConnectionStatus.Connected); - } - rejectAllWaitingForAck(error) { - const rejects = Array.from(this.waitingForAck.values()).map(({ reject }) => reject); - this.waitingForAck.clear(); - for (const reject of rejects) { - reject(error); - } - } - static create(innerSend) { - const channel = new Channel(innerSend); - return { - channel, - receivedAck: channel.receivedACK, - receivedMessage: channel.receivedMessage, - errored: channel.errored, - closed: channel.closed, - }; - } - send(packet) { - this.innerSend(packet); - } - sendAndWaitForACK(packet) { - const { promise, resolve, reject } = makePromise(); - const ackId = this.nextAckId; - this.nextAckId++; - this.waitingForAck.set(ackId, { resolve, reject }); - this.innerSend(packet, ackId); - return promise; - } -} - -var DoubleIndexedKV = /** @class */ (function () { - function DoubleIndexedKV() { - this.keyToValue = new Map(); - this.valueToKey = new Map(); - } - DoubleIndexedKV.prototype.set = function (key, value) { - this.keyToValue.set(key, value); - this.valueToKey.set(value, key); - }; - DoubleIndexedKV.prototype.getByKey = function (key) { - return this.keyToValue.get(key); - }; - DoubleIndexedKV.prototype.getByValue = function (value) { - return this.valueToKey.get(value); - }; - DoubleIndexedKV.prototype.clear = function () { - this.keyToValue.clear(); - this.valueToKey.clear(); - }; - return DoubleIndexedKV; -}()); - -var Registry = /** @class */ (function () { - function Registry(generateIdentifier) { - this.generateIdentifier = generateIdentifier; - this.kv = new DoubleIndexedKV(); - } - Registry.prototype.register = function (value, identifier) { - if (this.kv.getByValue(value)) { - return; - } - if (!identifier) { - identifier = this.generateIdentifier(value); - } - this.kv.set(identifier, value); - }; - Registry.prototype.clear = function () { - this.kv.clear(); - }; - Registry.prototype.getIdentifier = function (value) { - return this.kv.getByValue(value); - }; - Registry.prototype.getValue = function (identifier) { - return this.kv.getByKey(identifier); - }; - return Registry; -}()); - -var __extends = (globalThis && globalThis.__extends) || (function () { - var extendStatics = function (d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - return function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; -})(); -var ClassRegistry = /** @class */ (function (_super) { - __extends(ClassRegistry, _super); - function ClassRegistry() { - var _this = _super.call(this, function (c) { return c.name; }) || this; - _this.classToAllowedProps = new Map(); - return _this; - } - ClassRegistry.prototype.register = function (value, options) { - if (typeof options === 'object') { - if (options.allowProps) { - this.classToAllowedProps.set(value, options.allowProps); - } - _super.prototype.register.call(this, value, options.identifier); - } - else { - _super.prototype.register.call(this, value, options); - } - }; - ClassRegistry.prototype.getAllowedProps = function (value) { - return this.classToAllowedProps.get(value); - }; - return ClassRegistry; -}(Registry)); - -var __read$3 = (globalThis && globalThis.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -}; -function valuesOfObj(record) { - if ('values' in Object) { - // eslint-disable-next-line es5/no-es6-methods - return Object.values(record); - } - var values = []; - // eslint-disable-next-line no-restricted-syntax - for (var key in record) { - if (record.hasOwnProperty(key)) { - values.push(record[key]); - } - } - return values; -} -function find(record, predicate) { - var values = valuesOfObj(record); - if ('find' in values) { - // eslint-disable-next-line es5/no-es6-methods - return values.find(predicate); - } - var valuesNotNever = values; - for (var i = 0; i < valuesNotNever.length; i++) { - var value = valuesNotNever[i]; - if (predicate(value)) { - return value; - } - } - return undefined; -} -function forEach(record, run) { - Object.entries(record).forEach(function (_a) { - var _b = __read$3(_a, 2), key = _b[0], value = _b[1]; - return run(value, key); - }); -} -function includes(arr, value) { - return arr.indexOf(value) !== -1; -} -function findArr(record, predicate) { - for (var i = 0; i < record.length; i++) { - var value = record[i]; - if (predicate(value)) { - return value; - } - } - return undefined; -} - -var CustomTransformerRegistry = /** @class */ (function () { - function CustomTransformerRegistry() { - this.transfomers = {}; - } - CustomTransformerRegistry.prototype.register = function (transformer) { - this.transfomers[transformer.name] = transformer; - }; - CustomTransformerRegistry.prototype.findApplicable = function (v) { - return find(this.transfomers, function (transformer) { - return transformer.isApplicable(v); - }); - }; - CustomTransformerRegistry.prototype.findByName = function (name) { - return this.transfomers[name]; - }; - return CustomTransformerRegistry; -}()); - -var getType$1 = function (payload) { - return Object.prototype.toString.call(payload).slice(8, -1); -}; -var isUndefined = function (payload) { - return typeof payload === 'undefined'; -}; -var isNull = function (payload) { return payload === null; }; -var isPlainObject$1 = function (payload) { - if (typeof payload !== 'object' || payload === null) - return false; - if (payload === Object.prototype) - return false; - if (Object.getPrototypeOf(payload) === null) - return true; - return Object.getPrototypeOf(payload) === Object.prototype; -}; -var isEmptyObject = function (payload) { - return isPlainObject$1(payload) && Object.keys(payload).length === 0; -}; -var isArray$1 = function (payload) { - return Array.isArray(payload); -}; -var isString = function (payload) { - return typeof payload === 'string'; -}; -var isNumber = function (payload) { - return typeof payload === 'number' && !isNaN(payload); -}; -var isBoolean = function (payload) { - return typeof payload === 'boolean'; -}; -var isRegExp = function (payload) { - return payload instanceof RegExp; -}; -var isMap = function (payload) { - return payload instanceof Map; -}; -var isSet = function (payload) { - return payload instanceof Set; -}; -var isSymbol = function (payload) { - return getType$1(payload) === 'Symbol'; -}; -var isDate = function (payload) { - return payload instanceof Date && !isNaN(payload.valueOf()); -}; -var isError = function (payload) { - return payload instanceof Error; -}; -var isNaNValue = function (payload) { - return typeof payload === 'number' && isNaN(payload); -}; -var isPrimitive = function (payload) { - return isBoolean(payload) || - isNull(payload) || - isUndefined(payload) || - isNumber(payload) || - isString(payload) || - isSymbol(payload); -}; -var isBigint = function (payload) { - return typeof payload === 'bigint'; -}; -var isInfinite = function (payload) { - return payload === Infinity || payload === -Infinity; -}; -var isTypedArray = function (payload) { - return ArrayBuffer.isView(payload) && !(payload instanceof DataView); -}; -var isURL = function (payload) { return payload instanceof URL; }; - -var escapeKey = function (key) { return key.replace(/\./g, '\\.'); }; -var stringifyPath = function (path) { - return path - .map(String) - .map(escapeKey) - .join('.'); -}; -var parsePath = function (string) { - var result = []; - var segment = ''; - for (var i = 0; i < string.length; i++) { - var char = string.charAt(i); - var isEscapedDot = char === '\\' && string.charAt(i + 1) === '.'; - if (isEscapedDot) { - segment += '.'; - i++; - continue; - } - var isEndOfSegment = char === '.'; - if (isEndOfSegment) { - result.push(segment); - segment = ''; - continue; - } - segment += char; - } - var lastSegment = segment; - result.push(lastSegment); - return result; -}; - -var __assign$1 = (globalThis && globalThis.__assign) || function () { - __assign$1 = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign$1.apply(this, arguments); -}; -var __read$2 = (globalThis && globalThis.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -}; -var __spreadArray$2 = (globalThis && globalThis.__spreadArray) || function (to, from) { - for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) - to[j] = from[i]; - return to; -}; -function simpleTransformation(isApplicable, annotation, transform, untransform) { - return { - isApplicable: isApplicable, - annotation: annotation, - transform: transform, - untransform: untransform - }; -} -var simpleRules = [ - simpleTransformation(isUndefined, 'undefined', function () { return null; }, function () { return undefined; }), - simpleTransformation(isBigint, 'bigint', function (v) { return v.toString(); }, function (v) { - if (typeof BigInt !== 'undefined') { - return BigInt(v); - } - console.error('Please add a BigInt polyfill.'); - return v; - }), - simpleTransformation(isDate, 'Date', function (v) { return v.toISOString(); }, function (v) { return new Date(v); }), - simpleTransformation(isError, 'Error', function (v, superJson) { - var baseError = { - name: v.name, - message: v.message - }; - superJson.allowedErrorProps.forEach(function (prop) { - baseError[prop] = v[prop]; - }); - return baseError; - }, function (v, superJson) { - var e = new Error(v.message); - e.name = v.name; - e.stack = v.stack; - superJson.allowedErrorProps.forEach(function (prop) { - e[prop] = v[prop]; - }); - return e; - }), - simpleTransformation(isRegExp, 'regexp', function (v) { return '' + v; }, function (regex) { - var body = regex.slice(1, regex.lastIndexOf('/')); - var flags = regex.slice(regex.lastIndexOf('/') + 1); - return new RegExp(body, flags); - }), - simpleTransformation(isSet, 'set', - // (sets only exist in es6+) - // eslint-disable-next-line es5/no-es6-methods - function (v) { return __spreadArray$2([], __read$2(v.values())); }, function (v) { return new Set(v); }), - simpleTransformation(isMap, 'map', function (v) { return __spreadArray$2([], __read$2(v.entries())); }, function (v) { return new Map(v); }), - simpleTransformation(function (v) { return isNaNValue(v) || isInfinite(v); }, 'number', function (v) { - if (isNaNValue(v)) { - return 'NaN'; - } - if (v > 0) { - return 'Infinity'; - } - else { - return '-Infinity'; - } - }, Number), - simpleTransformation(function (v) { return v === 0 && 1 / v === -Infinity; }, 'number', function () { - return '-0'; - }, Number), - simpleTransformation(isURL, 'URL', function (v) { return v.toString(); }, function (v) { return new URL(v); }), -]; -function compositeTransformation(isApplicable, annotation, transform, untransform) { - return { - isApplicable: isApplicable, - annotation: annotation, - transform: transform, - untransform: untransform - }; -} -var symbolRule = compositeTransformation(function (s, superJson) { - if (isSymbol(s)) { - var isRegistered = !!superJson.symbolRegistry.getIdentifier(s); - return isRegistered; - } - return false; -}, function (s, superJson) { - var identifier = superJson.symbolRegistry.getIdentifier(s); - return ['symbol', identifier]; -}, function (v) { return v.description; }, function (_, a, superJson) { - var value = superJson.symbolRegistry.getValue(a[1]); - if (!value) { - throw new Error('Trying to deserialize unknown symbol'); - } - return value; -}); -var constructorToName = [ - Int8Array, - Uint8Array, - Int16Array, - Uint16Array, - Int32Array, - Uint32Array, - Float32Array, - Float64Array, - Uint8ClampedArray, -].reduce(function (obj, ctor) { - obj[ctor.name] = ctor; - return obj; -}, {}); -var typedArrayRule = compositeTransformation(isTypedArray, function (v) { return ['typed-array', v.constructor.name]; }, function (v) { return __spreadArray$2([], __read$2(v)); }, function (v, a) { - var ctor = constructorToName[a[1]]; - if (!ctor) { - throw new Error('Trying to deserialize unknown typed array'); - } - return new ctor(v); -}); -function isInstanceOfRegisteredClass(potentialClass, superJson) { - if (potentialClass === null || potentialClass === void 0 ? void 0 : potentialClass.constructor) { - var isRegistered = !!superJson.classRegistry.getIdentifier(potentialClass.constructor); - return isRegistered; - } - return false; -} -var classRule = compositeTransformation(isInstanceOfRegisteredClass, function (clazz, superJson) { - var identifier = superJson.classRegistry.getIdentifier(clazz.constructor); - return ['class', identifier]; -}, function (clazz, superJson) { - var allowedProps = superJson.classRegistry.getAllowedProps(clazz.constructor); - if (!allowedProps) { - return __assign$1({}, clazz); - } - var result = {}; - allowedProps.forEach(function (prop) { - result[prop] = clazz[prop]; - }); - return result; -}, function (v, a, superJson) { - var clazz = superJson.classRegistry.getValue(a[1]); - if (!clazz) { - throw new Error('Trying to deserialize unknown class - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564'); - } - return Object.assign(Object.create(clazz.prototype), v); -}); -var customRule = compositeTransformation(function (value, superJson) { - return !!superJson.customTransformerRegistry.findApplicable(value); -}, function (value, superJson) { - var transformer = superJson.customTransformerRegistry.findApplicable(value); - return ['custom', transformer.name]; -}, function (value, superJson) { - var transformer = superJson.customTransformerRegistry.findApplicable(value); - return transformer.serialize(value); -}, function (v, a, superJson) { - var transformer = superJson.customTransformerRegistry.findByName(a[1]); - if (!transformer) { - throw new Error('Trying to deserialize unknown custom value'); - } - return transformer.deserialize(v); -}); -var compositeRules = [classRule, symbolRule, customRule, typedArrayRule]; -var transformValue = function (value, superJson) { - var applicableCompositeRule = findArr(compositeRules, function (rule) { - return rule.isApplicable(value, superJson); - }); - if (applicableCompositeRule) { - return { - value: applicableCompositeRule.transform(value, superJson), - type: applicableCompositeRule.annotation(value, superJson) - }; - } - var applicableSimpleRule = findArr(simpleRules, function (rule) { - return rule.isApplicable(value, superJson); - }); - if (applicableSimpleRule) { - return { - value: applicableSimpleRule.transform(value, superJson), - type: applicableSimpleRule.annotation - }; - } - return undefined; -}; -var simpleRulesByAnnotation = {}; -simpleRules.forEach(function (rule) { - simpleRulesByAnnotation[rule.annotation] = rule; -}); -var untransformValue = function (json, type, superJson) { - if (isArray$1(type)) { - switch (type[0]) { - case 'symbol': - return symbolRule.untransform(json, type, superJson); - case 'class': - return classRule.untransform(json, type, superJson); - case 'custom': - return customRule.untransform(json, type, superJson); - case 'typed-array': - return typedArrayRule.untransform(json, type, superJson); - default: - throw new Error('Unknown transformation: ' + type); - } - } - else { - var transformation = simpleRulesByAnnotation[type]; - if (!transformation) { - throw new Error('Unknown transformation: ' + type); - } - return transformation.untransform(json, superJson); - } -}; - -var getNthKey = function (value, n) { - var keys = value.keys(); - while (n > 0) { - keys.next(); - n--; - } - return keys.next().value; -}; -function validatePath(path) { - if (includes(path, '__proto__')) { - throw new Error('__proto__ is not allowed as a property'); - } - if (includes(path, 'prototype')) { - throw new Error('prototype is not allowed as a property'); - } - if (includes(path, 'constructor')) { - throw new Error('constructor is not allowed as a property'); - } -} -var getDeep = function (object, path) { - validatePath(path); - for (var i = 0; i < path.length; i++) { - var key = path[i]; - if (isSet(object)) { - object = getNthKey(object, +key); - } - else if (isMap(object)) { - var row = +key; - var type = +path[++i] === 0 ? 'key' : 'value'; - var keyOfRow = getNthKey(object, row); - switch (type) { - case 'key': - object = keyOfRow; - break; - case 'value': - object = object.get(keyOfRow); - break; - } - } - else { - object = object[key]; - } - } - return object; -}; -var setDeep = function (object, path, mapper) { - validatePath(path); - if (path.length === 0) { - return mapper(object); - } - var parent = object; - for (var i = 0; i < path.length - 1; i++) { - var key = path[i]; - if (isArray$1(parent)) { - var index = +key; - parent = parent[index]; - } - else if (isPlainObject$1(parent)) { - parent = parent[key]; - } - else if (isSet(parent)) { - var row = +key; - parent = getNthKey(parent, row); - } - else if (isMap(parent)) { - var isEnd = i === path.length - 2; - if (isEnd) { - break; - } - var row = +key; - var type = +path[++i] === 0 ? 'key' : 'value'; - var keyOfRow = getNthKey(parent, row); - switch (type) { - case 'key': - parent = keyOfRow; - break; - case 'value': - parent = parent.get(keyOfRow); - break; - } - } - } - var lastKey = path[path.length - 1]; - if (isArray$1(parent)) { - parent[+lastKey] = mapper(parent[+lastKey]); - } - else if (isPlainObject$1(parent)) { - parent[lastKey] = mapper(parent[lastKey]); - } - if (isSet(parent)) { - var oldValue = getNthKey(parent, +lastKey); - var newValue = mapper(oldValue); - if (oldValue !== newValue) { - parent["delete"](oldValue); - parent.add(newValue); - } - } - if (isMap(parent)) { - var row = +path[path.length - 2]; - var keyToRow = getNthKey(parent, row); - var type = +lastKey === 0 ? 'key' : 'value'; - switch (type) { - case 'key': { - var newKey = mapper(keyToRow); - parent.set(newKey, parent.get(keyToRow)); - if (newKey !== keyToRow) { - parent["delete"](keyToRow); - } - break; - } - case 'value': { - parent.set(keyToRow, mapper(parent.get(keyToRow))); - break; - } - } - } - return object; -}; - -var __read$1 = (globalThis && globalThis.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -}; -var __spreadArray$1 = (globalThis && globalThis.__spreadArray) || function (to, from) { - for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) - to[j] = from[i]; - return to; -}; -function traverse(tree, walker, origin) { - if (origin === void 0) { origin = []; } - if (!tree) { - return; - } - if (!isArray$1(tree)) { - forEach(tree, function (subtree, key) { - return traverse(subtree, walker, __spreadArray$1(__spreadArray$1([], __read$1(origin)), __read$1(parsePath(key)))); - }); - return; - } - var _a = __read$1(tree, 2), nodeValue = _a[0], children = _a[1]; - if (children) { - forEach(children, function (child, key) { - traverse(child, walker, __spreadArray$1(__spreadArray$1([], __read$1(origin)), __read$1(parsePath(key)))); - }); - } - walker(nodeValue, origin); -} -function applyValueAnnotations(plain, annotations, superJson) { - traverse(annotations, function (type, path) { - plain = setDeep(plain, path, function (v) { return untransformValue(v, type, superJson); }); - }); - return plain; -} -function applyReferentialEqualityAnnotations(plain, annotations) { - function apply(identicalPaths, path) { - var object = getDeep(plain, parsePath(path)); - identicalPaths.map(parsePath).forEach(function (identicalObjectPath) { - plain = setDeep(plain, identicalObjectPath, function () { return object; }); - }); - } - if (isArray$1(annotations)) { - var _a = __read$1(annotations, 2), root = _a[0], other = _a[1]; - root.forEach(function (identicalPath) { - plain = setDeep(plain, parsePath(identicalPath), function () { return plain; }); - }); - if (other) { - forEach(other, apply); - } - } - else { - forEach(annotations, apply); - } - return plain; -} -var isDeep = function (object, superJson) { - return isPlainObject$1(object) || - isArray$1(object) || - isMap(object) || - isSet(object) || - isInstanceOfRegisteredClass(object, superJson); -}; -function addIdentity(object, path, identities) { - var existingSet = identities.get(object); - if (existingSet) { - existingSet.push(path); - } - else { - identities.set(object, [path]); - } -} -function generateReferentialEqualityAnnotations(identitites, dedupe) { - var result = {}; - var rootEqualityPaths = undefined; - identitites.forEach(function (paths) { - if (paths.length <= 1) { - return; - } - // if we're not deduping, all of these objects continue existing. - // putting the shortest path first makes it easier to parse for humans - // if we're deduping though, only the first entry will still exist, so we can't do this optimisation. - if (!dedupe) { - paths = paths - .map(function (path) { return path.map(String); }) - .sort(function (a, b) { return a.length - b.length; }); - } - var _a = __read$1(paths), representativePath = _a[0], identicalPaths = _a.slice(1); - if (representativePath.length === 0) { - rootEqualityPaths = identicalPaths.map(stringifyPath); - } - else { - result[stringifyPath(representativePath)] = identicalPaths.map(stringifyPath); - } - }); - if (rootEqualityPaths) { - if (isEmptyObject(result)) { - return [rootEqualityPaths]; - } - else { - return [rootEqualityPaths, result]; - } - } - else { - return isEmptyObject(result) ? undefined : result; - } -} -var walker = function (object, identities, superJson, dedupe, path, objectsInThisPath, seenObjects) { - var _a; - if (path === void 0) { path = []; } - if (objectsInThisPath === void 0) { objectsInThisPath = []; } - if (seenObjects === void 0) { seenObjects = new Map(); } - var primitive = isPrimitive(object); - if (!primitive) { - addIdentity(object, path, identities); - var seen = seenObjects.get(object); - if (seen) { - // short-circuit result if we've seen this object before - return dedupe - ? { - transformedValue: null - } - : seen; - } - } - if (!isDeep(object, superJson)) { - var transformed_1 = transformValue(object, superJson); - var result_1 = transformed_1 - ? { - transformedValue: transformed_1.value, - annotations: [transformed_1.type] - } - : { - transformedValue: object - }; - if (!primitive) { - seenObjects.set(object, result_1); - } - return result_1; - } - if (includes(objectsInThisPath, object)) { - // prevent circular references - return { - transformedValue: null - }; - } - var transformationResult = transformValue(object, superJson); - var transformed = (_a = transformationResult === null || transformationResult === void 0 ? void 0 : transformationResult.value) !== null && _a !== void 0 ? _a : object; - var transformedValue = isArray$1(transformed) ? [] : {}; - var innerAnnotations = {}; - forEach(transformed, function (value, index) { - var recursiveResult = walker(value, identities, superJson, dedupe, __spreadArray$1(__spreadArray$1([], __read$1(path)), [index]), __spreadArray$1(__spreadArray$1([], __read$1(objectsInThisPath)), [object]), seenObjects); - transformedValue[index] = recursiveResult.transformedValue; - if (isArray$1(recursiveResult.annotations)) { - innerAnnotations[index] = recursiveResult.annotations; - } - else if (isPlainObject$1(recursiveResult.annotations)) { - forEach(recursiveResult.annotations, function (tree, key) { - innerAnnotations[escapeKey(index) + '.' + key] = tree; - }); - } - }); - var result = isEmptyObject(innerAnnotations) - ? { - transformedValue: transformedValue, - annotations: !!transformationResult - ? [transformationResult.type] - : undefined - } - : { - transformedValue: transformedValue, - annotations: !!transformationResult - ? [transformationResult.type, innerAnnotations] - : innerAnnotations - }; - if (!primitive) { - seenObjects.set(object, result); - } - return result; -}; - -function getType(payload) { - return Object.prototype.toString.call(payload).slice(8, -1); -} - -function isArray(payload) { - return getType(payload) === "Array"; -} - -function isPlainObject(payload) { - if (getType(payload) !== "Object") - return false; - const prototype = Object.getPrototypeOf(payload); - return !!prototype && prototype.constructor === Object && prototype === Object.prototype; -} - -function assignProp(carry, key, newVal, originalObject, includeNonenumerable) { - const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable"; - if (propType === "enumerable") - carry[key] = newVal; - if (includeNonenumerable && propType === "nonenumerable") { - Object.defineProperty(carry, key, { - value: newVal, - enumerable: false, - writable: true, - configurable: true - }); - } -} -function copy(target, options = {}) { - if (isArray(target)) { - return target.map((item) => copy(item, options)); - } - if (!isPlainObject(target)) { - return target; - } - const props = Object.getOwnPropertyNames(target); - const symbols = Object.getOwnPropertySymbols(target); - return [...props, ...symbols].reduce((carry, key) => { - if (isArray(options.props) && !options.props.includes(key)) { - return carry; - } - const val = target[key]; - const newVal = copy(val, options); - assignProp(carry, key, newVal, target, options.nonenumerable); - return carry; - }, {}); -} - -var __assign = (globalThis && globalThis.__assign) || function () { - __assign = Object.assign || function(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) - t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; -var __read = (globalThis && globalThis.__read) || function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; -}; -var __spreadArray = (globalThis && globalThis.__spreadArray) || function (to, from) { - for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) - to[j] = from[i]; - return to; -}; -var SuperJSON = /** @class */ (function () { - /** - * @param dedupeReferentialEqualities If true, SuperJSON will make sure only one instance of referentially equal objects are serialized and the rest are replaced with `null`. - */ - function SuperJSON(_a) { - var _b = _a === void 0 ? {} : _a, _c = _b.dedupe, dedupe = _c === void 0 ? false : _c; - this.classRegistry = new ClassRegistry(); - this.symbolRegistry = new Registry(function (s) { var _a; return (_a = s.description) !== null && _a !== void 0 ? _a : ''; }); - this.customTransformerRegistry = new CustomTransformerRegistry(); - this.allowedErrorProps = []; - this.dedupe = dedupe; - } - SuperJSON.prototype.serialize = function (object) { - var identities = new Map(); - var output = walker(object, identities, this, this.dedupe); - var res = { - json: output.transformedValue - }; - if (output.annotations) { - res.meta = __assign(__assign({}, res.meta), { values: output.annotations }); - } - var equalityAnnotations = generateReferentialEqualityAnnotations(identities, this.dedupe); - if (equalityAnnotations) { - res.meta = __assign(__assign({}, res.meta), { referentialEqualities: equalityAnnotations }); - } - return res; - }; - SuperJSON.prototype.deserialize = function (payload) { - var json = payload.json, meta = payload.meta; - var result = copy(json); - if (meta === null || meta === void 0 ? void 0 : meta.values) { - result = applyValueAnnotations(result, meta.values, this); - } - if (meta === null || meta === void 0 ? void 0 : meta.referentialEqualities) { - result = applyReferentialEqualityAnnotations(result, meta.referentialEqualities); - } - return result; - }; - SuperJSON.prototype.stringify = function (object) { - return JSON.stringify(this.serialize(object)); - }; - SuperJSON.prototype.parse = function (string) { - return this.deserialize(JSON.parse(string)); - }; - SuperJSON.prototype.registerClass = function (v, options) { - this.classRegistry.register(v, options); - }; - SuperJSON.prototype.registerSymbol = function (v, identifier) { - this.symbolRegistry.register(v, identifier); - }; - SuperJSON.prototype.registerCustom = function (transformer, name) { - this.customTransformerRegistry.register(__assign({ name: name }, transformer)); - }; - SuperJSON.prototype.allowErrorProps = function () { - var _a; - var props = []; - for (var _i = 0; _i < arguments.length; _i++) { - props[_i] = arguments[_i]; - } - (_a = this.allowedErrorProps).push.apply(_a, __spreadArray([], __read(props))); - }; - SuperJSON.defaultInstance = new SuperJSON(); - SuperJSON.serialize = SuperJSON.defaultInstance.serialize.bind(SuperJSON.defaultInstance); - SuperJSON.deserialize = SuperJSON.defaultInstance.deserialize.bind(SuperJSON.defaultInstance); - SuperJSON.stringify = SuperJSON.defaultInstance.stringify.bind(SuperJSON.defaultInstance); - SuperJSON.parse = SuperJSON.defaultInstance.parse.bind(SuperJSON.defaultInstance); - SuperJSON.registerClass = SuperJSON.defaultInstance.registerClass.bind(SuperJSON.defaultInstance); - SuperJSON.registerSymbol = SuperJSON.defaultInstance.registerSymbol.bind(SuperJSON.defaultInstance); - SuperJSON.registerCustom = SuperJSON.defaultInstance.registerCustom.bind(SuperJSON.defaultInstance); - SuperJSON.allowErrorProps = SuperJSON.defaultInstance.allowErrorProps.bind(SuperJSON.defaultInstance); - return SuperJSON; -}()); -var serialize$1 = SuperJSON.serialize; -var deserialize$1 = SuperJSON.deserialize; - -/** - * Serialize a value to another value using the specified serialization type. - */ -function serialize(type, value) { - switch (type) { - case "raw": - return value; - case "superjson": - return serialize$1(value); - } -} -function deserialize(type, value) { - switch (type) { - case "raw": - return value; - case "superjson": - return deserialize$1(value); - } -} -const serializedOpaqueSchema = z.any(); - -const clientToServerMessageSchema = z.discriminatedUnion("type", [ - // Communication - z.object({ - type: z.literal("communicationWarning"), - warning: z.string(), - }), - z.object({ - type: z.literal("keepAlive"), - }), - // Channel - z.object({ - type: z.literal("channelCreate"), - endpoint: z.string(), - channelId: z.number().int(), - creationParameter: serializedOpaqueSchema, - }), - z.object({ - type: z.literal("channelSend"), - channelId: z.number().int(), - message: serializedOpaqueSchema, - ackId: z.number().int().optional(), - }), - z.object({ - type: z.literal("channelAck"), - channelId: z.number().int(), - ackId: z.number().int(), - }), - // RPC - z.object({ - type: z.literal("rpcCall"), - endpoint: z.string(), - callId: z.number().int(), - parameter: serializedOpaqueSchema, - }), - // Readonly signal - z.object({ - type: z.literal("signalSubscribe"), - creationParameter: serializedOpaqueSchema, - endpoint: z.string(), - subscribeId: z.number().int(), - }), - z.object({ - type: z.literal("signalUnsubscribe"), - subscribeId: z.number().int(), - }), - // Writable signal - z.object({ - type: z.literal("writableSignalSubscribe"), - creationParameter: serializedOpaqueSchema, - endpoint: z.string(), - subscribeId: z.number().int(), - }), - z.object({ - type: z.literal("writableSignalUnsubscribe"), - subscribeId: z.number().int(), - }), - z.object({ - type: z.literal("writableSignalUpdate"), - subscribeId: z.number().int(), - patches: z.array(serializedOpaqueSchema), - tags: z.array(z.string()), - }), -]); -const serverToClientMessageSchema = z.discriminatedUnion("type", [ - // Communication - z.object({ - type: z.literal("communicationWarning"), - warning: z.string(), - }), - z.object({ - type: z.literal("keepAliveAck"), - }), - // Channel - z.object({ - type: z.literal("channelSend"), - channelId: z.number().int(), - message: serializedOpaqueSchema, - ackId: z.number().int().optional(), - }), - z.object({ - type: z.literal("channelAck"), - channelId: z.number().int(), - ackId: z.number().int(), - }), - z.object({ - type: z.literal("channelClose"), - channelId: z.number().int(), - }), - z.object({ - type: z.literal("channelError"), - channelId: z.number().int(), - error: serializedLMSExtendedErrorSchema, - }), - // RPC - z.object({ - type: z.literal("rpcResult"), - callId: z.number().int(), - result: serializedOpaqueSchema, - }), - z.object({ - type: z.literal("rpcError"), - callId: z.number().int(), - error: serializedLMSExtendedErrorSchema, - }), - // Readonly signal - z.object({ - type: z.literal("signalUpdate"), - subscribeId: z.number().int(), - patches: z.array(serializedOpaqueSchema), - tags: z.array(z.string()), - }), - z.object({ - type: z.literal("signalError"), - subscribeId: z.number().int(), - error: serializedLMSExtendedErrorSchema, - }), - // Writable signal - z.object({ - type: z.literal("writableSignalUpdate"), - subscribeId: z.number().int(), - patches: z.array(serializedOpaqueSchema), - tags: z.array(z.string()), - }), - z.object({ - type: z.literal("writableSignalError"), - subscribeId: z.number().int(), - error: serializedLMSExtendedErrorSchema, - }), -]); -class Transport { - constructor() { - /** - * Whether this transport has been disposed. - */ - this.disposed = false; - } - async [Symbol.asyncDispose]() { - if (this.disposed) { - throw new Error("Cannot dispose twice"); - } - // Only sets disposed to true, transport implementations should override this method to - // perform actual cleanup. - this.disposed = true; - } -} -class ClientTransport extends Transport { - parseIncomingMessage(message) { - return serverToClientMessageSchema.parse(message); - } - send(message) { - const result = clientToServerMessageSchema.parse(message); - this.sendViaTransport(result); - } - /** - * Called by the client port when the number of open communications changes from 0 to 1. This - * usually indicates the `socket.ref()` should be called to prevent the process from exiting. - */ - onHavingOneOrMoreOpenCommunication() { } - // The following snippet is intentionally not a tsdoc (only 1 star as oppose to 2). There is - // likely a bug in TypeScript that when we change it to tsdoc, on darwin and linux, it causes the - // generated .d.ts file to be invalid. We have considered reporting this to TypeScript, but it is - // way too difficult to narrow down, thus we just hope this is the only case that this error - // occurs. - /* - * Called by the client port when the number of open communications changes from 1 or more to 0. - * This usually indicates the `socket.unref()` should be called to allow the process to exit. - */ - onHavingNoOpenCommunication() { } -} - -const wsAuthenticationResultSchema = z.discriminatedUnion("success", [ - z.object({ - success: z.literal(true), - }), - z.object({ - success: z.literal(false), - error: z.string(), - }), -]); - -var WsClientTransportStatus; -(function (WsClientTransportStatus) { - WsClientTransportStatus["Disconnected"] = "DISCONNECTED"; - WsClientTransportStatus["Connecting"] = "CONNECTING"; - WsClientTransportStatus["Connected"] = "CONNECTED"; -})(WsClientTransportStatus || (WsClientTransportStatus = {})); -class WsClientTransport extends ClientTransport { - constructor(url, receivedMessage, errored, { abortSignal, parentLogger } = {}) { - super(); - this.url = url; - this.receivedMessage = receivedMessage; - this.errored = errored; - this.ws = null; - this.queuedMessages = []; - this.status = WsClientTransportStatus.Disconnected; - this.resolvedUrl = null; - /** - * Whether the underlying socket should hold the process open. - */ - this.shouldRef = false; - this.resolveDisposed = null; - this.abortSignal = abortSignal; - this.logger = new SimpleLogger("WsClientTransport", parentLogger); - } - static createWsClientTransportFactory(url, { abortSignal, } = {}) { - return (receivedMessage, errored, parentLogger) => new WsClientTransport(url, receivedMessage, errored, { - abortSignal, - parentLogger, - }); - } - connect() { - if (this.status !== WsClientTransportStatus.Disconnected) { - this.logger.warn("connect() called while not disconnected"); - return; - } - if (this.disposed) { - throw new Error(text ` - Cannot establish WebSocket connection because the transport has been disposed. - `); - } - if (this.abortSignal !== undefined && this.abortSignal.aborted) { - throw new Error(this.abortSignal.reason); - } - this.status = WsClientTransportStatus.Connecting; - Promise.resolve(this.url).then(url => { - this.resolvedUrl = url; - this.ws = new WebSocket(url); - this.ws.addEventListener("open", this.onWsOpen.bind(this)); - this.ws.addEventListener("error", event => this.onWsError(event.error)); - this.ws.addEventListener("close", () => { - this.onWsError(new Error("WebSocket connection closed")); - }); - const abortSignal = this.abortSignal; - if (abortSignal !== undefined) { - if (abortSignal.aborted) { - this.onWsError(abortSignal.reason); - } - else { - const abortListener = () => { - this.onWsError(abortSignal.reason); - }; - abortSignal.addEventListener("abort", abortListener, { once: true }); - this.ws.addEventListener("close", () => { - abortSignal.removeEventListener("abort", abortListener); - }); - } - } - }); - } - onWsOpen() { - this.ws.addEventListener("message", this.onWsMessage.bind(this)); - this.status = WsClientTransportStatus.Connected; - this.queuedMessages.forEach(message => this.sendViaTransport(message)); - this.queuedMessages = []; - this.updateShouldRef(this.shouldRef); - // this.setupWebsocketKeepAlive(this.ws!, this.onWsTimeout.bind(this)); - } - onWsMessage(event) { - if (this.status !== WsClientTransportStatus.Connected) { - this.logger.warn("Received message while not connected. Message ignored:", event.data); - return; - } - let message; - try { - message = JSON.parse(String(event.data)); - } - catch (error) { - this.logger.warn("Received invalid JSON message from server:", event.data); - return; - } - let parsed; - try { - parsed = this.parseIncomingMessage(message); - } - catch (error) { - this.logger.warn("Received invalid message from server:", message); - return; - } - this.receivedMessage(parsed); - } - onWsError(error) { - if (this.status === WsClientTransportStatus.Disconnected) { - return; - } - this.logger.warn("WebSocket error:", error); - if (error.code === "ECONNREFUSED") { - this.logger.warnText ` - WebSocket connection refused. This can happen if the server is not running or the client - is trying to connect to the wrong path. The server path that this client is - attempting to connect to is: - ${this.resolvedUrl ?? "Unknown" /* Should never be Unknown */}. - - Please make sure the following: - - 1. LM Studio is running - - 2. The API server in LM Studio has started - - 3. The client is attempting to connect to the correct path - `; - } - try { - this.ws?.close(); - } - catch (error) { - // Ignore - } - this.status = WsClientTransportStatus.Disconnected; - this.errored(error); - } - onWsTimeout() { - if (this.status === WsClientTransportStatus.Disconnected) { - return; - } - this.logger.warn("Websocket timed out"); - try { - this.ws?.close(); - } - catch (error) { - // Ignore - } - this.status = WsClientTransportStatus.Disconnected; - this.errored(new Error("WebSocket timed out")); - } - onHavingNoOpenCommunication() { - this.updateShouldRef(false); - if (this.disposed && this.resolveDisposed !== null) { - // If the transport is disposed, we can resolve the disposed promise to allow the - // async dispose to complete. - this.resolveDisposed(); - this.resolveDisposed = null; - } - } - onHavingOneOrMoreOpenCommunication() { - this.updateShouldRef(true); - } - updateShouldRef(shouldRef) { - this.shouldRef = shouldRef; - if (this.ws === null) { - return; - } - if (!this.ws._socket) { - return; - } - if (shouldRef) { - this.ws._socket.ref(); - } - else { - this.ws._socket.unref(); - } - } - sendViaTransport(message) { - if (this.status === WsClientTransportStatus.Connected) { - this.ws.send(JSON.stringify(message)); - } - else { - this.queuedMessages.push(message); - if (this.status === WsClientTransportStatus.Disconnected) { - this.connect(); - } - } - } - async [Symbol.asyncDispose]() { - await super[Symbol.asyncDispose](); - if (this.shouldRef) { - // If the connection needs to held up, wait until all communications are terminates - const { promise: disposedPromise, resolve: resolveDisposed } = makePromise(); - this.resolveDisposed = resolveDisposed; - await disposedPromise; - } - if (this.ws !== null) { - try { - this.ws.close(); - } - catch (error) { - // Ignore - } - this.ws = null; - } - this.errored(new Error("WebSocket client transport disposed")); - this.status = WsClientTransportStatus.Disconnected; - } -} - -class AuthenticatedWsClientTransport extends WsClientTransport { - constructor(url, clientIdentifier, clientPasskey, receivedMessage, errored, { parentLogger, abortSignal } = {}) { - super(url, receivedMessage, errored, { parentLogger, abortSignal }); - this.clientIdentifier = clientIdentifier; - this.clientPasskey = clientPasskey; - this.logger = this.logger.subclass("AuthenticatedWsClientTransport"); - } - static createAuthenticatedWsClientTransportFactory({ url, clientIdentifier, clientPasskey, abortSignal, }) { - return (receivedMessage, errored, parentLogger) => new AuthenticatedWsClientTransport(url, clientIdentifier, clientPasskey, receivedMessage, errored, { parentLogger, abortSignal }); - } - onWsOpen() { - this.ws.send(JSON.stringify({ - authVersion: 1, - clientIdentifier: this.clientIdentifier, - clientPasskey: this.clientPasskey, - })); - this.ws.addEventListener("message", (event) => { - try { - const data = JSON.parse(event.data.toString("utf-8")); - const result = wsAuthenticationResultSchema.parse(data); - if (result.success) { - super.onWsOpen(); - } - else { - this.onWsError(new Error("Failed to authenticate: " + result.error)); - } - } - catch (error) { - this.onWsError(new Error("Failed to parse authentication result: " + error?.message)); - } - }, { - once: true, - }); - } -} - -function defaultErrorDeserializer(serialized, directCause, stack) { - return fromSerializedError(serialized, directCause, stack); -} -class ClientPort { - constructor(backendInterface, factory, { parentLogger, errorDeserializer, verboseErrorMessage, } = {}) { - this.backendInterface = backendInterface; - this.openChannels = new Map(); - this.ongoingRpcs = new Map(); - this.openSignalSubscriptions = new Map(); - this.openWritableSignalSubscriptions = new Map(); - this.openCommunicationsCount = 0; - this.nextChannelId = 0; - this.nextSubscribeId = 0; - this.nextWritableSubscribeId = 0; - this.producedCommunicationWarningsCount = 0; - this.receivedMessage = (message) => { - switch (message.type) { - case "channelSend": { - this.receivedChannelSend(message); - break; - } - case "channelAck": { - this.receivedChannelAck(message); - break; - } - case "channelClose": { - this.receivedChannelClose(message); - break; - } - case "channelError": { - this.receivedChannelError(message); - break; - } - case "rpcResult": { - this.receivedRpcResult(message); - break; - } - case "rpcError": { - this.receivedRpcError(message); - break; - } - case "signalUpdate": { - this.receivedSignalUpdate(message); - break; - } - case "signalError": { - this.receivedSignalError(message); - break; - } - case "writableSignalUpdate": { - this.receivedWritableSignalUpdate(message); - break; - } - case "writableSignalError": { - this.receivedWritableSignalError(message); - break; - } - case "communicationWarning": { - this.receivedCommunicationWarning(message); - break; - } - case "keepAliveAck": { - this.receivedKeepAliveAck(message); - break; - } - } - }; - this.errored = (error) => { - for (const openChannel of this.openChannels.values()) { - openChannel.errored(error); - } - this.openChannels.clear(); - for (const ongoingRpc of this.ongoingRpcs.values()) { - ongoingRpc.reject(error); - } - this.ongoingRpcs.clear(); - for (const openSignalSubscription of this.openSignalSubscriptions.values()) { - openSignalSubscription.errored(error); - } - this.openSignalSubscriptions.clear(); - for (const openWritableSignalSubscription of this.openWritableSignalSubscriptions.values()) { - openWritableSignalSubscription.errored(error); - } - this.openWritableSignalSubscriptions.clear(); - this.updateOpenCommunicationsCount(); - }; - this.logger = new SimpleLogger("ClientPort", parentLogger); - this.errorDeserializer = errorDeserializer ?? defaultErrorDeserializer; - this.verboseErrorMessage = verboseErrorMessage ?? true; - this.transport = factory(this.receivedMessage, this.errored, this.logger); - } - communicationWarning(warning) { - if (this.producedCommunicationWarningsCount >= 5) { - return; - } - this.logger.warnText ` - Produced communication warning: ${warning} - - This is usually caused by communication protocol incompatibility. Please make sure you are - using the up-to-date versions of the SDK and LM Studio. - `; - this.transport.send({ - type: "communicationWarning", - warning, - }); - this.producedCommunicationWarningsCount++; - if (this.producedCommunicationWarningsCount >= 5) { - this.logger.errorText ` - 5 communication warnings have been produced. Further warnings will not be printed. - `; - } - } - updateOpenCommunicationsCount() { - const previousCount = this.openCommunicationsCount; - this.openCommunicationsCount = - this.openChannels.size + - this.ongoingRpcs.size + - this.openSignalSubscriptions.size + - this.openWritableSignalSubscriptions.size; - if (this.openCommunicationsCount === 0 && previousCount > 0) { - this.transport.onHavingNoOpenCommunication(); - } - else if (this.openCommunicationsCount === 1 && previousCount === 0) { - this.transport.onHavingOneOrMoreOpenCommunication(); - } - } - receivedChannelSend(message) { - const openChannel = this.openChannels.get(message.channelId); - if (openChannel === undefined) { - this.communicationWarning(`Received channelSend for unknown channel, channelId = ${message.channelId}`); - return; - } - const deserializedMessage = deserialize(openChannel.endpoint.serialization, message.message); - const parsed = openChannel.endpoint.toClientPacket.safeParse(deserializedMessage); - if (!parsed.success) { - this.communicationWarning(text ` - Received invalid message for channel: endpointName = ${openChannel.endpoint.name}, message = - ${deserializedMessage}. Zod error: - - ${Validator.prettyPrintZod("message", parsed.error)} - `); - return; - } - openChannel.receivedMessage(parsed.data); - } - receivedChannelAck(message) { - const openChannel = this.openChannels.get(message.channelId); - if (openChannel === undefined) { - this.communicationWarning(`Received channelAck for unknown channel, channelId = ${message.channelId}`); - return; - } - openChannel.receivedAck(message.ackId); - } - receivedChannelClose(message) { - const openChannel = this.openChannels.get(message.channelId); - if (openChannel === undefined) { - this.communicationWarning(`Received channelClose for unknown channel, channelId = ${message.channelId}`); - return; - } - this.openChannels.delete(message.channelId); - openChannel.closed(); - this.updateOpenCommunicationsCount(); - } - receivedChannelError(message) { - const openChannel = this.openChannels.get(message.channelId); - if (openChannel === undefined) { - this.communicationWarning(`Received channelError for unknown channel, channelId = ${message.channelId}`); - return; - } - this.openChannels.delete(message.channelId); - const error = this.errorDeserializer(message.error, "Channel Error", this.verboseErrorMessage ? openChannel.stack : undefined); - openChannel.errored(error); - this.updateOpenCommunicationsCount(); - } - receivedRpcResult(message) { - const ongoingRpc = this.ongoingRpcs.get(message.callId); - if (ongoingRpc === undefined) { - this.communicationWarning(`Received rpcResult for unknown rpc, callId = ${message.callId}`); - return; - } - const deserializedResult = deserialize(ongoingRpc.endpoint.serialization, message.result); - const parsed = ongoingRpc.endpoint.returns.safeParse(deserializedResult); - if (!parsed.success) { - this.communicationWarning(text ` - Received invalid result for rpc, endpointName = ${ongoingRpc.endpoint.name}, result = - ${deserializedResult}. Zod error: - - ${Validator.prettyPrintZod("result", parsed.error)} - `); - return; - } - ongoingRpc.resolve(parsed.data); - this.ongoingRpcs.delete(message.callId); - this.updateOpenCommunicationsCount(); - } - receivedRpcError(message) { - const ongoingRpc = this.ongoingRpcs.get(message.callId); - if (ongoingRpc === undefined) { - this.communicationWarning(`Received rpcError for unknown rpc, callId = ${message.callId}`); - return; - } - const error = this.errorDeserializer(message.error, "RPC Error", this.verboseErrorMessage ? ongoingRpc.stack : undefined); - ongoingRpc.reject(error); - this.ongoingRpcs.delete(message.callId); - this.updateOpenCommunicationsCount(); - } - receivedSignalUpdate(message) { - const openSignalSubscription = this.openSignalSubscriptions.get(message.subscribeId); - if (openSignalSubscription === undefined) { - // This is caused by update and unsubscribe event happening at the same time. By the time the - // update has arrived at the client side, as far as the client is considered, the signal is - // already unsubscribed. This is a normal behavior and is especially prevalent when React - // StrictMode is enabled, because components are rendered twice where signals are oftentimes - // subscribed and then unsubscribed immediately after. - return; - } - const patches = message.patches.map(patch => deserialize(openSignalSubscription.endpoint.serialization, patch)); - const beforeValue = openSignalSubscription.getValue(); - let afterValue; - try { - afterValue = applyPatches(beforeValue, patches); - } - catch (error) { - this.communicationWarning(text ` - Failed to apply patches to signal on signalUpdate. subscribeId = ${message.subscribeId}. - - beforeValue = ${JSON.stringify(beforeValue, null, 2)}, - - patches = ${JSON.stringify(patches, null, 2)}. - - Error: ${String(error)} - `); - return; - } - const parseResult = openSignalSubscription.endpoint.signalData.safeParse(afterValue); - if (!parseResult.success) { - this.communicationWarning(text ` - Received invalid signal patch data, subscribeId = ${message.subscribeId} - - patches = ${patches}, - - beforeValue = ${beforeValue}, - - afterValue = ${afterValue}. - - Zod error: - - ${Validator.prettyPrintZod("value", parseResult.error)} - `); - return; - } - // Don't use the parsed value, as it loses the substructure identities - openSignalSubscription.receivedPatches(afterValue, patches, message.tags); - } - receivedSignalError(message) { - const openSignalSubscription = this.openSignalSubscriptions.get(message.subscribeId); - if (openSignalSubscription === undefined) { - this.communicationWarning(`Received signalError for unknown signal, subscribeId = ${message.subscribeId}`); - return; - } - const error = this.errorDeserializer(message.error, "Signal Error", this.verboseErrorMessage ? openSignalSubscription.stack : undefined); - openSignalSubscription.errored(error); - this.openSignalSubscriptions.delete(message.subscribeId); - this.updateOpenCommunicationsCount(); - } - receivedWritableSignalUpdate(message) { - const openSignalSubscription = this.openWritableSignalSubscriptions.get(message.subscribeId); - if (openSignalSubscription === undefined) { - // This is caused by update and unsubscribe event happening at the same time. By the time the - // update has arrived at the client side, as far as the client is considered, the signal is - // already unsubscribed. This is a normal behavior and is especially prevalent when React - // StrictMode is enabled, because components are rendered twice where signals are oftentimes - // subscribed and then unsubscribed immediately after. - return; - } - const patches = message.patches.map(patch => deserialize(openSignalSubscription.endpoint.serialization, patch)); - const beforeValue = openSignalSubscription.getValue(); - let afterValue; - try { - afterValue = applyPatches(openSignalSubscription.getValue(), patches); - } - catch (error) { - this.communicationWarning(text ` - Failed to apply patches to writable signal on writableSignalUpdate. subscribeId = - ${message.subscribeId}. - - beforeValue = ${JSON.stringify(beforeValue, null, 2)}, - - patches = ${JSON.stringify(patches, null, 2)}. - - Error: ${String(error)} - `); - } - const parseResult = openSignalSubscription.endpoint.signalData.safeParse(afterValue); - if (!parseResult.success) { - this.communicationWarning(text ` - Received invalid writable signal patch data, subscribeId = ${message.subscribeId} - - patches = ${patches}, - - beforeValue = ${beforeValue}, - - afterValue = ${afterValue}. - - Zod error: - - ${Validator.prettyPrintZod("value", parseResult.error)} - `); - return; - } - // Don't use the parsed value, as it loses the substructure identities - openSignalSubscription.firstUpdateReceived = true; - openSignalSubscription.receivedPatches(afterValue, patches, message.tags); - } - receivedWritableSignalError(message) { - const openSignalSubscription = this.openWritableSignalSubscriptions.get(message.subscribeId); - if (openSignalSubscription === undefined) { - this.communicationWarning(`Received writableSignalError for unknown signal, subscribeId = ${message.subscribeId}`); - return; - } - const error = this.errorDeserializer(message.error, "Writable Signal Error", this.verboseErrorMessage ? openSignalSubscription.stack : undefined); - openSignalSubscription.errored(error); - this.openWritableSignalSubscriptions.delete(message.subscribeId); - this.updateOpenCommunicationsCount(); - } - receivedCommunicationWarning(message) { - this.logger.warnText ` - Received communication warning from the server: ${message.warning} - - This is usually caused by communication protocol incompatibility. Please make sure you are - using the up-to-date versions of the SDK and LM Studio. - - Note: This warning was received from the server and is printed on the client for convenience. - `; - } - receivedKeepAliveAck(_message) { - // Do nothing - } - async callRpc(endpointName, param, { stack } = {}) { - const endpoint = this.backendInterface.getRpcEndpoint(endpointName); - if (endpoint === undefined) { - throw new Error(`No Rpc endpoint with name ${endpointName}`); - } - const parameter = endpoint.parameter.parse(param); - const serializedParameter = serialize(endpoint.serialization, parameter); - const callId = this.nextChannelId; - this.nextChannelId++; - const { promise, resolve, reject } = makePromise(); - stack = stack ?? getCurrentStack(1); - this.ongoingRpcs.set(callId, { - endpoint, - stack, - resolve, - reject, - }); - this.transport.send({ - type: "rpcCall", - endpoint: endpointName, - callId, - parameter: serializedParameter, - }); - this.updateOpenCommunicationsCount(); - return await promise; - } - createChannel(endpointName, param, onMessage, { stack } = {}) { - const channelEndpoint = this.backendInterface.getChannelEndpoint(endpointName); - if (channelEndpoint === undefined) { - throw new Error(`No channel endpoint with name ${endpointName}`); - } - const creationParameter = channelEndpoint.creationParameter.parse(param); - const serializedCreationParameter = serialize(channelEndpoint.serialization, creationParameter); - const channelId = this.nextChannelId; - this.nextChannelId++; - this.transport.send({ - type: "channelCreate", - endpoint: endpointName, - channelId, - creationParameter: serializedCreationParameter, - }); - stack = stack ?? getCurrentStack(1); - const openChannel = { - endpoint: channelEndpoint, - stack, - ...Channel.create(packet => { - const parsed = channelEndpoint.toServerPacket.parse(packet); - const serializedMessage = serialize(channelEndpoint.serialization, parsed); - this.transport.send({ - type: "channelSend", - channelId, - message: serializedMessage, - }); - }), - }; - if (onMessage !== undefined) { - openChannel.channel.onMessage.subscribe(onMessage); - } - this.openChannels.set(channelId, openChannel); - this.updateOpenCommunicationsCount(); - return openChannel.channel; - } - /** - * Creates a readonly lazy signal will subscribe to the signal endpoint with the given name. - */ - createSignal(endpointName, param, { stack } = {}) { - const signalEndpoint = this.backendInterface.getSignalEndpoint(endpointName); - if (signalEndpoint === undefined) { - throw new Error(`No signal endpoint with name ${endpointName}`); - } - const creationParameter = signalEndpoint.creationParameter.parse(param); - const serializedCreationParameter = serialize(signalEndpoint.serialization, creationParameter); - stack = stack ?? getCurrentStack(1); - const signal = LazySignal.createWithoutInitialValue((setDownstream, errorListener) => { - const subscribeId = this.nextSubscribeId; - this.nextSubscribeId++; - this.transport.send({ - type: "signalSubscribe", - endpoint: endpointName, - subscribeId, - creationParameter: serializedCreationParameter, - }); - this.openSignalSubscriptions.set(subscribeId, { - endpoint: signalEndpoint, - getValue: () => signal.get(), - receivedPatches: setDownstream.withValueAndPatches, - errored: errorListener, - stack, - }); - this.updateOpenCommunicationsCount(); - return () => { - this.transport.send({ - type: "signalUnsubscribe", - subscribeId, - }); - this.openSignalSubscriptions.delete(subscribeId); - }; - }); - return signal; - } - createWritableSignal(endpointName, param, { stack } = {}) { - const signalEndpoint = this.backendInterface.getWritableSignalEndpoint(endpointName); - if (signalEndpoint === undefined) { - throw new Error(`No writable signal endpoint with name ${endpointName}`); - } - const creationParameter = signalEndpoint.creationParameter.parse(param); - const serializedCreationParameter = serialize(signalEndpoint.serialization, creationParameter); - stack = stack ?? getCurrentStack(1); - let currentSubscribeId = null; - const writeUpstream = (_data, patches, tags) => { - if (currentSubscribeId === null) { - console.warn("writeUpstream called when not subscribed"); - return false; - } - const subscription = this.openWritableSignalSubscriptions.get(currentSubscribeId); - if (!subscription?.firstUpdateReceived) { - console.warn("writeUpstream called before the first update is received"); - return false; - } - this.transport.send({ - type: "writableSignalUpdate", - subscribeId: currentSubscribeId, - patches: patches.map(patch => serialize(signalEndpoint.serialization, patch)), - tags, - }); - return true; - }; - const [signal, setter] = OWLSignal.createWithoutInitialValue((setDownstream, errorListener) => { - const subscribeId = this.nextWritableSubscribeId; - currentSubscribeId = subscribeId; - this.nextWritableSubscribeId++; - this.transport.send({ - type: "writableSignalSubscribe", - endpoint: endpointName, - subscribeId, - creationParameter: serializedCreationParameter, - }); - this.openWritableSignalSubscriptions.set(subscribeId, { - endpoint: signalEndpoint, - getValue: () => signal.getPessimistic(), - receivedPatches: setDownstream.withValueAndPatches, - firstUpdateReceived: false, - errored: errorListener, - stack, - }); - this.updateOpenCommunicationsCount(); - return () => { - currentSubscribeId = null; - this.transport.send({ - type: "writableSignalUnsubscribe", - subscribeId, - }); - this.openWritableSignalSubscriptions.delete(subscribeId); - }; - }, writeUpstream); - return [signal, setter]; - } - async [Symbol.asyncDispose]() { - await this.transport[Symbol.asyncDispose](); - } -} - -class GenericClientTransport extends ClientTransport { - constructor(onMessage, onClose, sendMessage, receivedMessage, errored, parentLogger) { - super(); - this.sendMessage = sendMessage; - this.receivedMessage = receivedMessage; - this.errored = errored; - this.closed = false; - this.logger = new SimpleLogger("GenericClientTransport", parentLogger); - onMessage.subscribe(message => { - let parsed; - try { - parsed = this.parseIncomingMessage(message); - } - catch (error) { - this.logger.warn("Received invalid message from server:", message); - return; - } - this.receivedMessage(parsed); - }); - onClose.subscribeOnce(() => { - if (this.closed) { - return; - } - this.closed = true; - this.errored(new Error("Server closed the connection")); - }); - } - static createFactory(onMessage, onClose, sendMessage) { - return (receivedMessage, errored, parentLogger) => new GenericClientTransport(onMessage, onClose, sendMessage, receivedMessage, errored, parentLogger); - } - sendViaTransport(message) { - this.sendMessage(message); - } -} - -function getHostedEnv() { - let anyWindow; - try { - anyWindow = window; - } - catch (error) { - anyWindow = undefined; - } - if (anyWindow !== undefined && anyWindow.lmsHostedEnv !== undefined) { - return anyWindow.lmsHostedEnv; - } - return null; -} - -/** - * Create a base model backend interface that are used by all domain-specific model backend - * interfaces. - */ -function createBaseModelBackendInterface(specificModelInstanceInfoSchemaInput, specificModelInfoSchemaInput) { - const specificModelInstanceInfoSchema = specificModelInstanceInfoSchemaInput; - const specificModelInfoSchema = specificModelInfoSchemaInput; - return new BackendInterface() - .addChannelEndpoint("loadModel", { - creationParameter: z.object({ - modelKey: z.string(), - identifier: z.string().optional(), - /** - * If provided, when the model is not used for this amount of time, it will be unloaded. - */ - ttlMs: z.number().int().min(1).optional(), - loadConfigStack: kvConfigStackSchema, - }), - toClientPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("resolved"), - info: specificModelInfoSchema, - ambiguous: z.array(z.string()).optional(), - }), - z.object({ - type: z.literal("progress"), - progress: z.number(), - }), - z.object({ - type: z.literal("success"), - info: specificModelInstanceInfoSchema, - }), - ]), - toServerPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("cancel"), - }), - ]), - }) - .addRpcEndpoint("unloadModel", { - parameter: z.object({ - identifier: z.string(), - }), - returns: z.void(), - }) - .addRpcEndpoint("listLoaded", { - parameter: z.undefined(), - returns: z.array(specificModelInstanceInfoSchema), - }) - .addRpcEndpoint("getModelInfo", { - parameter: z.object({ - specifier: modelSpecifierSchema, - throwIfNotFound: z.boolean(), - }), - returns: specificModelInstanceInfoSchema.optional(), - }) - .addRpcEndpoint("getLoadConfig", { - parameter: z.object({ - specifier: modelSpecifierSchema, - }), - returns: kvConfigSchema, - }) - .addChannelEndpoint("getOrLoad", { - creationParameter: z.object({ - identifier: z.string(), - /** - * If provided and a new instance is loaded as a result of this call, it will be unloaded - * after idling for this amount of time. - */ - loadTtlMs: z.number().int().min(1).optional(), - loadConfigStack: kvConfigStackSchema, - }), - toClientPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("alreadyLoaded"), - info: specificModelInstanceInfoSchema, - }), - z.object({ - type: z.literal("startLoading"), - identifier: z.string(), - info: specificModelInfoSchema, - }), - z.object({ - // We are unloading other JIT model - type: z.literal("unloadingOtherJITModel"), - info: modelInstanceInfoSchema, - }), - z.object({ - type: z.literal("loadProgress"), - progress: z.number(), - }), - z.object({ - type: z.literal("loadSuccess"), - info: specificModelInstanceInfoSchema, - }), - ]), - toServerPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("cancel"), - }), - ]), - }); -} - -function createDiagnosticsBackendInterface() { - return new BackendInterface().addChannelEndpoint("streamLogs", { - creationParameter: z.void(), - toServerPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("stop"), - }), - ]), - toClientPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("log"), - log: diagnosticsLogEventSchema, - }), - ]), - }); -} - -function createEmbeddingBackendInterface() { - const baseModelBackendInterface = createBaseModelBackendInterface(embeddingModelInstanceInfoSchema, embeddingModelInfoSchema); - return baseModelBackendInterface - .addRpcEndpoint("embedString", { - parameter: z.object({ - modelSpecifier: modelSpecifierSchema, - inputString: z.string(), - }), - returns: z.object({ - embedding: z.array(z.number()), - }), - }) - .addRpcEndpoint("tokenize", { - parameter: z.object({ - specifier: modelSpecifierSchema, - inputString: z.string(), - }), - returns: z.object({ - tokens: z.array(z.number()), - }), - }) - .addRpcEndpoint("countTokens", { - parameter: z.object({ - specifier: modelSpecifierSchema, - inputString: z.string(), - }), - returns: z.object({ - tokenCount: z.number().int(), - }), - }); -} - -function createFilesBackendInterface() { - return new BackendInterface() - .addRpcEndpoint("getLocalFileAbsolutePath", { - parameter: z.object({ - fileName: z.string(), - }), - returns: z.object({ - path: z.string(), - }), - }) - .addRpcEndpoint("uploadFileBase64", { - parameter: z.object({ - name: z.string(), - contentBase64: z.string(), - }), - returns: z.object({ - identifier: z.string(), - fileType: fileTypeSchema, - sizeBytes: z.number().int(), - }), - }) - .addChannelEndpoint("retrieve", { - creationParameter: z.object({ - query: z.string(), - fileIdentifiers: z.array(z.string()), - config: kvConfigSchema, - }), - toServerPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("stop"), - }), - ]), - toClientPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("onFileProcessList"), - indices: z.array(z.number().int()), - }), - z.object({ - type: z.literal("onFileProcessingStart"), - index: z.number().int(), - }), - z.object({ - type: z.literal("onFileProcessingEnd"), - index: z.number().int(), - }), - z.object({ - type: z.literal("onFileProcessingStepStart"), - index: z.number().int(), - step: retrievalFileProcessingStepSchema, - }), - z.object({ - type: z.literal("onFileProcessingStepProgress"), - index: z.number().int(), - step: retrievalFileProcessingStepSchema, - progress: z.number(), - }), - z.object({ - type: z.literal("onFileProcessingStepEnd"), - index: z.number().int(), - step: retrievalFileProcessingStepSchema, - }), - z.object({ - type: z.literal("onSearchingStart"), - }), - z.object({ - type: z.literal("onSearchingEnd"), - }), - z.object({ - type: z.literal("result"), - result: internalRetrievalResultSchema, - }), - ]), - }) - .addChannelEndpoint("parseDocument", { - creationParameter: z.object({ - fileIdentifier: z.string(), - parseOpts: documentParsingOptsSchema, - }), - toClientPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("parserLoaded"), - parser: documentParsingLibraryIdentifierSchema, - }), - z.object({ - type: z.literal("progress"), - progress: z.number(), - }), - z.object({ - type: z.literal("result"), - content: z.string(), - parser: documentParsingLibraryIdentifierSchema, - }), - ]), - toServerPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("cancel"), - }), - ]), - }) - .addRpcEndpoint("getDocumentParsingLibrary", { - parameter: z.object({ - fileIdentifier: z.string(), - }), - returns: z.object({ - library: z.string(), - version: z.string(), - }), - }); -} - -function createLlmBackendInterface() { - const baseModelBackendInterface = createBaseModelBackendInterface(llmInstanceInfoSchema, llmInfoSchema); - return (baseModelBackendInterface - .addChannelEndpoint("predict", { - creationParameter: z.object({ - modelSpecifier: modelSpecifierSchema, - history: chatHistoryDataSchema, - predictionConfigStack: kvConfigStackSchema, - /** - * Which preset to use. Supports limited fuzzy matching. - */ - fuzzyPresetIdentifier: z.string().optional(), - ignoreServerSessionConfig: z.boolean().optional(), - }), - toClientPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("fragment"), - fragment: llmPredictionFragmentSchema, - logprobs: z - .array(z.array(z.object({ text: z.string(), logprob: z.number() }))) - .optional(), - }), - z.object({ - type: z.literal("promptProcessingProgress"), - progress: z.number(), - }), - z.object({ - type: z.literal("toolCallGenerationStart"), - /** - * The LLM specific call id of the tool call. - */ - toolCallId: z.string().optional(), - }), - z.object({ - type: z.literal("toolCallGenerationNameReceived"), - name: z.string(), - }), - z.object({ - type: z.literal("toolCallGenerationArgumentFragmentGenerated"), - content: z.string(), - }), - z.object({ - type: z.literal("toolCallGenerationEnd"), - toolCallRequest: toolCallRequestSchema, - /** - * The raw output that represents this tool call. It is recommended to present this to - * the user as is, if desired. - * - * @remarks It is not guaranteed to be valid JSON as the model does not necessarily use - * JSON to represent tool calls. - */ - rawContent: z.string().optional(), - }), - z.object({ - type: z.literal("toolCallGenerationFailed"), - error: serializedLMSExtendedErrorSchema, - /** - * The raw output that was generated by the model before the tool call. The exact nature - * of this fields depends on the error. It sometimes include the entire tool calls - * section, or sometimes just the single tool call that failed. - * - * It is recommended to present this to the user as is, if desired. - */ - rawContent: z.string().optional(), - }), - z.object({ - type: z.literal("success"), - stats: llmPredictionStatsSchema, - modelInfo: llmInstanceInfoSchema, - loadModelConfig: kvConfigSchema, - predictionConfig: kvConfigSchema, - }), - ]), - toServerPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("cancel"), - }), - ]), - }) - .addRpcEndpoint("applyPromptTemplate", { - parameter: z.object({ - specifier: modelSpecifierSchema, - history: chatHistoryDataSchema, - predictionConfigStack: kvConfigStackSchema, - opts: llmApplyPromptTemplateOptsSchema, - }), - returns: z.object({ - formatted: z.string(), - }), - }) - .addRpcEndpoint("tokenize", { - parameter: z.object({ - specifier: modelSpecifierSchema, - inputString: z.string(), - }), - returns: z.object({ - tokens: z.array(z.number()), - }), - }) - .addRpcEndpoint("countTokens", { - parameter: z.object({ - specifier: modelSpecifierSchema, - inputString: z.string(), - }), - returns: z.object({ - tokenCount: z.number().int(), - }), - }) - // Starts to eagerly preload a draft model. This is useful when you want a draft model to be - // ready for speculative decoding. - .addRpcEndpoint("preloadDraftModel", { - parameter: z.object({ - specifier: modelSpecifierSchema, - draftModelKey: z.string(), - }), - returns: z.void(), - })); -} - -function createPluginsBackendInterface() { - return (new BackendInterface() - /** - * The following method is called by a client that wants to use plugins that are registered - * to LM Studio. - */ - .addChannelEndpoint("startToolUseSession", { - creationParameter: z.object({ - pluginIdentifier: z.string(), - pluginConfigSpecifier: pluginConfigSpecifierSchema, - }), - toClientPacket: z.discriminatedUnion("type", [ - /** - * The session has been started successfully. The client can now use the session. Note, - * there are no sessionError message because if a session fails to start, the channel - * will error instead. - */ - z.object({ - type: z.literal("sessionReady"), - toolDefinitions: z.array(llmToolSchema), - }), - /** - * A tool call has been completed. - */ - z.object({ - type: z.literal("toolCallComplete"), - callId: z.number(), - result: jsonSerializableSchema, - }), - /** - * A tool call has failed. - */ - z.object({ - type: z.literal("toolCallError"), - callId: z.number(), - error: serializedLMSExtendedErrorSchema, - }), - /** - * Status update for a tool call. - */ - z.object({ - type: z.literal("toolCallStatus"), - callId: z.number(), - statusText: z.string(), - }), - /** - * Warning message for a tool call. - */ - z.object({ - type: z.literal("toolCallWarn"), - callId: z.number(), - warnText: z.string(), - }), - ]), - toServerPacket: z.discriminatedUnion("type", [ - /** - * Request to start a tool call. This call can be aborted using the `abortToolCall` - * packet. When the tool call is completed, either the `toolCallResult` or `toolCallError` - * packet will be sent. - */ - z.object({ - type: z.literal("callTool"), - callId: z.number(), - name: z.string(), - arguments: jsonSerializableSchema, - }), - /** - * Request to abort a tool call. Upon calling this, no toolCallComplete or toolCallError - * packets will be sent for the call. We assume abort is done immediately. - */ - z.object({ - type: z.literal("abortToolCall"), - callId: z.number(), - }), - /** - * Client requests to discard the session. Upon calling this, the channel will be closed. - */ - z.object({ - type: z.literal("discardSession"), - }), - ]), - }) - .addChannelEndpoint("generateWithGenerator", { - creationParameter: z.object({ - pluginIdentifier: z.string(), - pluginConfigSpecifier: pluginConfigSpecifierSchema, - tools: z.array(llmToolSchema), - history: chatHistoryDataSchema, - }), - toClientPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("fragment"), - fragment: llmPredictionFragmentSchema, - }), - z.object({ - type: z.literal("promptProcessingProgress"), - progress: z.number(), - }), - z.object({ - type: z.literal("toolCallGenerationStart"), - /** - * The LLM specific call id of the tool call. - */ - toolCallId: z.string().optional(), - }), - z.object({ - type: z.literal("toolCallGenerationNameReceived"), - name: z.string(), - }), - z.object({ - type: z.literal("toolCallGenerationArgumentFragmentGenerated"), - content: z.string(), - }), - z.object({ - type: z.literal("toolCallGenerationEnd"), - toolCallRequest: toolCallRequestSchema, - }), - z.object({ - type: z.literal("toolCallGenerationFailed"), - }), - z.object({ - type: z.literal("success"), - }), - ]), - toServerPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("cancel"), - }), - ]), - }) - /** - * The following method is called by the controlling client. (e.g. lms-cli) - */ - .addChannelEndpoint("registerDevelopmentPlugin", { - creationParameter: z.object({ - manifest: pluginManifestSchema, - }), - toClientPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("ready"), - clientIdentifier: z.string(), - clientPasskey: z.string(), - }), - ]), - toServerPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("end"), - }), - ]), - }) - .addRpcEndpoint("reindexPlugins", { - parameter: z.void(), - returns: z.void(), - }) - /** - * The following method is called by the plugin client. (plugin:*) - */ - .addChannelEndpoint("setPromptPreprocessor", { - creationParameter: z.void(), - toClientPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("preprocess"), - taskId: z.string(), - input: chatMessageDataSchema, - config: kvConfigSchema, - pluginConfig: kvConfigSchema, - globalPluginConfig: kvConfigSchema, - workingDirectoryPath: z.string().nullable(), - /** - * An array of all the plugins that are enabled for this prediction. - */ - enabledPluginInfos: z.array(remotePluginInfoSchema), - /** Processing Context Identifier */ - pci: z.string(), - token: z.string(), - }), - z.object({ - type: z.literal("abort"), - taskId: z.string(), - }), - ]), - toServerPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("complete"), - taskId: z.string(), - processed: chatMessageDataSchema, - }), - z.object({ - type: z.literal("aborted"), - taskId: z.string(), - }), - z.object({ - type: z.literal("error"), - taskId: z.string(), - error: serializedLMSExtendedErrorSchema, - }), - ]), - }) - .addChannelEndpoint("setPredictionLoopHandler", { - creationParameter: z.void(), - toClientPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("handlePredictionLoop"), - taskId: z.string(), - config: kvConfigSchema, - pluginConfig: kvConfigSchema, - globalPluginConfig: kvConfigSchema, - workingDirectoryPath: z.string().nullable(), - /** - * An array of all the plugins that are enabled for this prediction. - */ - enabledPluginInfos: z.array(remotePluginInfoSchema), - /** Processing Context Identifier */ - pci: z.string(), - token: z.string(), - }), - z.object({ - type: z.literal("abort"), - taskId: z.string(), - }), - ]), - toServerPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("complete"), - taskId: z.string(), - }), - z.object({ - type: z.literal("aborted"), - taskId: z.string(), - }), - z.object({ - type: z.literal("error"), - taskId: z.string(), - error: serializedLMSExtendedErrorSchema, - }), - ]), - }) - .addChannelEndpoint("setToolsProvider", { - creationParameter: z.void(), - toClientPacket: z.discriminatedUnion("type", [ - /** - * Starts a "tool providing session". Once this is received, the plugin should call the - * tools provider and pass the tools to the server using the `sessionInitialized` packet. - * - * If the initialization failed, the plugin should send the `sessionInitializationFailed` - * packet. - */ - z.object({ - type: z.literal("initSession"), - pluginConfig: kvConfigSchema, - globalPluginConfig: kvConfigSchema, - workingDirectoryPath: z.string().nullable(), - sessionId: z.string(), - }), - z.object({ - type: z.literal("discardSession"), - sessionId: z.string(), - }), - /** - * Call a tool within a session. The plugin should call the tool and return the result - * using the `toolCallComplete` packet. - * - * If the tool call fails in an unrecoverable way the plugin can send the `toolCallError` - * packet. - */ - z.object({ - type: z.literal("callTool"), - sessionId: z.string(), - callId: z.string(), - toolName: z.string(), - parameters: jsonSerializableSchema, - }), - /** - * Abort a tool call. The plugin should abort the tool call and confirm the abort using - * the `toolCallAborted` packet. - */ - z.object({ - type: z.literal("abortToolCall"), - sessionId: z.string(), - callId: z.string(), - }), - ]), - toServerPacket: z.discriminatedUnion("type", [ - /** - * The plugin has provided a list of tools in a new session. - */ - z.object({ - type: z.literal("sessionInitialized"), - sessionId: z.string(), - toolDefinitions: z.array(llmToolSchema), - }), - z.object({ - type: z.literal("sessionInitializationFailed"), - sessionId: z.string(), - error: serializedLMSExtendedErrorSchema, - }), - z.object({ - type: z.literal("toolCallComplete"), - sessionId: z.string(), - callId: z.string(), - result: jsonSerializableSchema, - }), - z.object({ - type: z.literal("toolCallError"), - sessionId: z.string(), - callId: z.string(), - error: serializedLMSExtendedErrorSchema, - }), - z.object({ - type: z.literal("toolCallStatus"), - sessionId: z.string(), - callId: z.string(), - statusText: z.string(), - }), - z.object({ - type: z.literal("toolCallWarn"), - sessionId: z.string(), - callId: z.string(), - warnText: z.string(), - }), - ]), - }) - .addChannelEndpoint("setGenerator", { - creationParameter: z.void(), - toClientPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("generate"), - taskId: z.string(), - input: chatHistoryDataSchema, - pluginConfig: kvConfigSchema, - globalPluginConfig: kvConfigSchema, - toolDefinitions: z.array(llmToolSchema), - workingDirectoryPath: z.string().nullable(), - }), - z.object({ - type: z.literal("abort"), - taskId: z.string(), - }), - ]), - toServerPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("complete"), - taskId: z.string(), - }), - z.object({ - type: z.literal("aborted"), - taskId: z.string(), - }), - z.object({ - type: z.literal("error"), - taskId: z.string(), - error: serializedLMSExtendedErrorSchema, - }), - z.object({ - type: z.literal("fragmentGenerated"), - taskId: z.string(), - content: z.string(), - opts: llmPredictionFragmentInputOptsSchema, - }), - z.object({ - type: z.literal("toolCallGenerationStarted"), - taskId: z.string(), - toolCallId: z.string().optional(), - }), - z.object({ - type: z.literal("toolCallGenerationNameReceived"), - taskId: z.string(), - toolName: z.string(), - }), - z.object({ - type: z.literal("toolCallGenerationArgumentFragmentGenerated"), - taskId: z.string(), - content: z.string(), - }), - z.object({ - type: z.literal("toolCallGenerationEnded"), - taskId: z.string(), - toolCallRequest: toolCallRequestSchema, - }), - z.object({ - type: z.literal("toolCallGenerationFailed"), - taskId: z.string(), - error: serializedLMSExtendedErrorSchema, - }), - ]), - }) - .addRpcEndpoint("processingHandleUpdate", { - parameter: z.object({ - /** Processing Context Identifier */ - pci: z.string(), - token: z.string(), - update: processingUpdateSchema, - }), - returns: z.void(), - }) - .addRpcEndpoint("processingHandleRequest", { - parameter: z.object({ - /** Processing Context Identifier */ - pci: z.string(), - token: z.string(), - request: processingRequestSchema, - }), - returns: z.object({ - response: processingRequestResponseSchema, - }), - }) - .addRpcEndpoint("processingPullHistory", { - parameter: z.object({ - /** Processing Context Identifier */ - pci: z.string(), - token: z.string(), - includeCurrent: z.boolean(), - }), - returns: chatHistoryDataSchema, - }) - .addRpcEndpoint("processingGetOrLoadTokenSource", { - parameter: z.object({ - /** Processing Context Identifier */ - pci: z.string(), - token: z.string(), - }), - returns: z.object({ - tokenSourceIdentifier: tokenSourceIdentifierSchema, - }), - }) - .addRpcEndpoint("processingHasStatus", { - parameter: z.object({ - /** Processing Context Identifier */ - pci: z.string(), - token: z.string(), - }), - returns: z.boolean(), - }) - .addRpcEndpoint("processingNeedsNaming", { - parameter: z.object({ - /** Processing Context Identifier */ - pci: z.string(), - token: z.string(), - }), - returns: z.boolean(), - }) - .addRpcEndpoint("processingSuggestName", { - parameter: z.object({ - /** Processing Context Identifier */ - pci: z.string(), - token: z.string(), - name: z.string(), - }), - returns: z.void(), - }) - .addRpcEndpoint("processingSetSenderName", { - parameter: z.object({ - /** Processing Context Identifier */ - pci: z.string(), - token: z.string(), - name: z.string(), - }), - returns: z.void(), - }) - .addRpcEndpoint("setConfigSchematics", { - parameter: z.object({ - schematics: serializedKVConfigSchematicsSchema, - }), - returns: z.void(), - }) - .addRpcEndpoint("setGlobalConfigSchematics", { - parameter: z.object({ - schematics: serializedKVConfigSchematicsSchema, - }), - returns: z.void(), - }) - .addRpcEndpoint("pluginInitCompleted", { - parameter: z.void(), - returns: z.void(), - })); -} - -function createRepositoryBackendInterface() { - return (new BackendInterface() - .addRpcEndpoint("searchModels", { - parameter: z.object({ - opts: modelSearchOptsSchema, - }), - returns: z.object({ - results: z.array(modelSearchResultEntryDataSchema), - }), - }) - .addRpcEndpoint("getModelDownloadOptions", { - parameter: z.object({ - modelSearchResultIdentifier: modelSearchResultIdentifierSchema, - }), - returns: z.object({ - results: z.array(modelSearchResultDownloadOptionDataSchema), - }), - }) - .addChannelEndpoint("downloadModel", { - creationParameter: z.object({ - downloadIdentifier: z.string(), - }), - toClientPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("downloadProgress"), - update: downloadProgressUpdateSchema, - }), - z.object({ - type: z.literal("startFinalizing"), - }), - z.object({ - type: z.literal("success"), - defaultIdentifier: z.string(), - }), - ]), - toServerPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("cancel"), - }), - ]), - }) - /** - * Downloads one singular artifact at a certain revision. Ignore dependencies. - */ - .addChannelEndpoint("downloadArtifact", { - creationParameter: z.object({ - artifactOwner: kebabCaseSchema, - artifactName: kebabCaseWithDotsSchema, - revisionNumber: z.number().int().nullable(), - path: z.string(), - }), - toClientPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("downloadProgress"), - update: downloadProgressUpdateSchema, - }), - z.object({ - type: z.literal("startFinalizing"), - }), - z.object({ - type: z.literal("success"), - }), - ]), - toServerPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("cancel"), - }), - ]), - }) - .addRpcEndpoint("installPluginDependencies", { - parameter: z.object({ - pluginFolder: z.string(), - }), - returns: z.void(), - }) - /** - * Given the path to a local artifact folder, returns the list of files in that folder that - * would be pushed when invoking the pushArtifact endpoint. - */ - .addRpcEndpoint("getLocalArtifactFiles", { - parameter: z.object({ - path: z.string(), - }), - returns: z.object({ - fileList: localArtifactFileListSchema, - }), - }) - .addChannelEndpoint("pushArtifact", { - creationParameter: z.object({ - path: z.string(), - description: z.string().max(1000).optional(), - /** - * Request to make the artifact private. Only effective if the artifact did not exist - * before. Will not change the visibility of an existing artifact. - */ - makePrivate: z.boolean().optional(), - /** - * If true, will write the revision number of the artifact after the push back to the - * artifact manifest.json. - */ - writeRevision: z.boolean().optional(), - overrides: jsonSerializableSchema.optional(), - }), - toServerPacket: z.void(), - toClientPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("message"), - message: z.string(), - }), - ]), - }) - .addChannelEndpoint("ensureAuthenticated", { - creationParameter: z.void(), - toServerPacket: z.void(), - toClientPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("authenticationUrl"), - url: z.string(), - }), - z.object({ - type: z.literal("authenticated"), - }), - ]), - }) - .addRpcEndpoint("loginWithPreAuthenticatedKeys", { - parameter: z.object({ - keyId: z.string(), - publicKey: z.string(), - privateKey: z.string(), - }), - returns: z.object({ - userName: z.string(), - }), - }) - /** - * Given the owner and name of an artifact, creates a download plan for the artifact. Throws - * an error is the artifact is not found. - */ - .addChannelEndpoint("createArtifactDownloadPlan", { - creationParameter: z.object({ - owner: kebabCaseSchema, - name: kebabCaseWithDotsSchema, - }), - toServerPacket: z.discriminatedUnion("type", [ - /** - * If called before committing the plan, the plan is aborted. If called after committing - * the plan, the download is canceled. - */ - z.object({ - type: z.literal("cancel"), - }), - /** - * Can only be called after plan ready. Once called, starts the plan. - */ - z.object({ - type: z.literal("commit"), - }), - ]), - toClientPacket: z.discriminatedUnion("type", [ - z.object({ - type: z.literal("planUpdated"), - plan: artifactDownloadPlanSchema, - }), - z.object({ - type: z.literal("planReady"), - plan: artifactDownloadPlanSchema, - }), - z.object({ - type: z.literal("downloadProgress"), - update: downloadProgressUpdateSchema, - }), - z.object({ - type: z.literal("startFinalizing"), - }), - z.object({ - type: z.literal("success"), - }), - ]), - })); -} - -function createSystemBackendInterface() { - return (new BackendInterface() - .addRpcEndpoint("listDownloadedModels", { - parameter: z.void(), - returns: z.array(modelInfoSchema), - }) - .addChannelEndpoint("alive", { - creationParameter: z.void(), - toServerPacket: z.void(), - toClientPacket: z.void(), - }) - .addRpcEndpoint("notify", { - parameter: backendNotificationSchema, - returns: z.void(), - }) - /** - * Get the LM Studio version - */ - .addRpcEndpoint("version", { - parameter: z.void(), - returns: z.object({ - /** - * `major.minor.patch` - */ - version: z.string(), - /** - * LM Studio build number - */ - build: z.number(), - }), - }) - .addRpcEndpoint("setExperimentFlag", { - parameter: z.object({ - code: z.string(), - value: z.boolean(), - }), - returns: z.void(), - }) - .addRpcEndpoint("getExperimentFlags", { - parameter: z.void(), - returns: z.array(z.string()), - }) - .addRpcEndpoint("startHttpServer", { - parameter: z.object({ - port: z.number().int().min(1).max(65535).optional(), - cors: z.boolean().optional(), - }), - returns: z.void(), - }) - .addRpcEndpoint("stopHttpServer", { - parameter: z.void(), - returns: z.void(), - })); -} - -function createAuthenticatedIpcTransportFactory(apiNamespace, hostedEnv, clientIdentifier, clientPasskey) { - const [onMessage, emitOnMessage] = BufferedEvent.create(); - const [onClose, emitOnClose] = BufferedEvent.create(); - const sendToServer = hostedEnv.getApiIpcTunnel(apiNamespace, { - authVersion: 1, - clientIdentifier: clientIdentifier, - clientPasskey: clientPasskey, - }, emitOnMessage, emitOnClose); - return GenericClientTransport.createFactory(onMessage, onClose, sendToServer); -} -function createAuthenticatedWsTransportFactory(apiNamespace, wsAddress, clientIdentifier, clientPasskey) { - return AuthenticatedWsClientTransport.createAuthenticatedWsClientTransportFactory({ - url: Promise.resolve(wsAddress).then(wsAddress => `${wsAddress}/${apiNamespace}`), - clientIdentifier: clientIdentifier, - clientPasskey: clientPasskey, - }); -} -function createAuthenticatedClientPort(backendInterface, wsAddress, apiNamespace, clientIdentifier, clientPasskey, logger, { errorDeserializer, verboseErrorMessage, } = {}) { - const hostedEnv = getHostedEnv(); - if (hostedEnv !== null) { - if (wsAddress !== undefined) { - logger.debug("Ignoring wsAddress parameter when constructing the client because the client is" + - " running in a hosted environment. This is not an error."); - } - return new ClientPort(backendInterface, createAuthenticatedIpcTransportFactory(apiNamespace, hostedEnv, clientIdentifier, clientPasskey), { parentLogger: logger, errorDeserializer, verboseErrorMessage }); - } - else { - return new ClientPort(backendInterface, createAuthenticatedWsTransportFactory(apiNamespace, wsAddress, clientIdentifier, clientPasskey), { parentLogger: logger, errorDeserializer, verboseErrorMessage }); - } -} - -/** @public */ -class DiagnosticsNamespace { - /** @internal */ - constructor(diagnosticsPort, validator, parentLogger) { - this.diagnosticsPort = diagnosticsPort; - this.validator = validator; - this.logger = new SimpleLogger("Diagnostics", parentLogger); - } - /** - * Register a callback to receive log events. Return a function to stop receiving log events. - * - * This method is in alpha. Do not use this method in production yet. - * @alpha - */ - unstable_streamLogs(listener) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("client.diagnostics", "unstable_streamLogs", "listener", z.function(), listener, stack); - const channel = this.diagnosticsPort.createChannel("streamLogs", undefined, undefined, { - stack, - }); - const unsubscribe = channel.onMessage.subscribe(message => { - if (message.type === "log") { - listener(message.log); - } - }); - return () => { - unsubscribe(); - channel.send({ - type: "stop", - }); - }; - } -} - -function makeLoadModelOptsSchema(loadModelConfigSchema) { - return z.object({ - identifier: z.string().optional(), - config: loadModelConfigSchema.optional(), - signal: z.instanceof(AbortSignal).optional(), - ttl: z.number().optional(), - verbose: z.union([z.boolean(), logLevelSchema]).optional(), - onProgress: z.function().optional(), - }); -} -/** - * Abstract namespace for namespaces that deal with models. - * - * @public - */ -class ModelNamespace { - /** @internal */ - getLoadModelOptsSchema() { - if (this.loadModelOptsSchema === null) { - this.loadModelOptsSchema = makeLoadModelOptsSchema(this.loadModelConfigSchema); - } - return this.loadModelOptsSchema; - } - /** @internal */ - constructor( - /** @internal */ - client, - /** @internal */ - port, - /** @internal */ - logger, - /** @internal */ - validator) { - this.client = client; - this.port = port; - this.logger = logger; - this.validator = validator; - /** @internal */ - this.loadModelOptsSchema = null; - } - /** - * Load a model for inferencing. The first parameter is the model key. The second parameter is an - * optional object with additional options. - * - * To find out what models are available, you can use the `lms ls` command, or programmatically - * use the `client.system.listDownloadedModels` method. - * - * Here are some examples: - * - * Loading Llama 3.2: - * - * ```typescript - * const model = await client.llm.load("llama-3.2-3b-instruct"); - * ``` - * - * Once loaded, see {@link LLMDynamicHandle} or {@link EmbeddingDynamicHandle} for how to use the - * model for inferencing or other things you can do with the model. - * - * @param modelKey - The path of the model to load. - * @param opts - Options for loading the model. - * @returns A promise that resolves to the model that can be used for inferencing - */ - async load(modelKey, opts = {}) { - const stack = getCurrentStack(1); - [modelKey, opts] = this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`, "load", ["modelKey", "opts"], [reasonableKeyStringSchema, this.getLoadModelOptsSchema()], [modelKey, opts], stack); - const { identifier, signal, verbose = "info", config, onProgress } = opts; - let lastVerboseCallTime = 0; - const { promise, resolve, reject } = makePromise(); - const verboseLevel = typeof verbose === "boolean" ? "info" : verbose; - const startTime = Date.now(); - if (verbose) { - this.logger.logAtLevel(verboseLevel, text ` - Verbose logging is enabled. To hide progress logs, set the "verbose" option to false in - client.llm.load. - `); - } - let fullPath = modelKey; - const channel = this.port.createChannel("loadModel", { - modelKey, - identifier, - ttlMs: opts.ttl === undefined ? undefined : opts.ttl * 1000, - loadConfigStack: singleLayerKVConfigStackOf("apiOverride", this.loadConfigToKVConfig(config ?? this.defaultLoadConfig)), - }, message => { - switch (message.type) { - case "resolved": { - fullPath = message.info.modelKey; - if (message.ambiguous !== undefined) { - this.logger.warn(text ` - Multiple models found for key ${modelKey}: - - ${message.ambiguous.map(x => ` - ${x}`).join("\n")} - - Using the first one. - `); - } - if (verbose) { - this.logger.logAtLevel(verboseLevel, text ` - Start loading model ${fullPath}... - `); - } - break; - } - case "success": { - if (verbose) { - this.logger.logAtLevel(verboseLevel, text ` - Successfully loaded model ${fullPath} in ${Date.now() - startTime}ms - `); - } - resolve(this.createDomainSpecificModel(this.port, message.info, this.validator, this.logger)); - break; - } - case "progress": { - const { progress } = message; - if (onProgress !== undefined) { - safeCallCallback(this.logger, "onProgress", onProgress, [progress]); - } - else if (verbose) { - const now = Date.now(); - if (now - lastVerboseCallTime > 500 || progress === 1) { - const progressText = (progress * 100).toFixed(1); - this.logger.logAtLevel(verboseLevel, `Loading the model, progress: ${progressText}%`); - lastVerboseCallTime = now; - } - } - } - } - }, { stack }); - channel.onError.subscribeOnce(reject); - if (signal !== undefined) { - if (signal.aborted) { - // If the signal is already aborted, we should reject immediately. - channel.send({ type: "cancel" }); - reject(signal.reason); - } - else { - signal.addEventListener("abort", () => { - channel.send({ type: "cancel" }); - reject(signal.reason); - }, { once: true }); - } - } - return await promise; - } - /** - * Unload a model. Once a model is unloaded, it can no longer be used. If you wish to use the - * model afterwards, you will need to load it with {@link LLMNamespace#loadModel} again. - * - * @param identifier - The identifier of the model to unload. - */ - unload(identifier) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow(`client.${this.namespace}`, "unload", "identifier", reasonableKeyStringSchema, identifier, stack); - return this.port.callRpc("unloadModel", { identifier }, { stack }); - } - /** - * List all the currently loaded models. - */ - async listLoaded() { - const stack = getCurrentStack(1); - const infos = await this.port.callRpc("listLoaded", undefined, { stack }); - return infos.map(info => this.createDomainSpecificModel(this.port, info, this.validator, this.logger)); - } - /** - * Get any loaded model of this domain. - */ - async getAny(stack) { - const info = await this.port.callRpc("getModelInfo", { specifier: { type: "query", query: {} }, throwIfNotFound: true }, { stack }); - if (info === undefined) { - throw new Error("Backend should have thrown."); - } - return this.createDomainSpecificModel(this.port, info, this.validator, new SimpleLogger("LLM", this.logger)); - } - createDynamicHandle(param) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow(`client.${this.namespace}`, "createDynamicHandle", "param", z.union([reasonableKeyStringSchema, modelQuerySchema]), param, stack); - let query; - if (typeof param === "string") { - query = { - identifier: param, - }; - } - else { - query = param; - } - if (query.path?.includes("\\")) { - throw makePrettyError(text ` - Model path should not contain backslashes, even if you are on Windows. Use forward - slashes instead. - `, stack); - } - return this.createDomainDynamicHandle(this.port, { - type: "query", - query, - }, this.validator, new SimpleLogger("DynamicHandle", this.logger)); - } - /** - * Create a dynamic handle from the internal instance reference. - * - * @alpha - */ - createDynamicHandleFromInstanceReference(instanceReference) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow(`client.${this.namespace}`, "createDynamicHandleFromInstanceReference", "instanceReference", z.string(), instanceReference, stack); - return this.createDomainDynamicHandle(this.port, { - type: "instanceReference", - instanceReference, - }, this.validator, new SimpleLogger("DynamicHandle", this.logger)); - } - async model(modelKey, opts = {}) { - const stack = getCurrentStack(1); - if (modelKey === undefined) { - // We want to get any loaded model. - return await this.getAny(stack); - } - [modelKey, opts] = this.validator.validateMethodParamsOrThrow(`client.${this.namespace}`, "model", ["modelKey", "opts"], [reasonableKeyStringSchema, this.getLoadModelOptsSchema()], [modelKey, opts], stack); - const { identifier, signal, verbose = "info", config, onProgress } = opts; - if (identifier !== undefined) { - throw new Error("The identifier option is not allowed when using `.model`."); - } - let lastVerboseCallTime = 0; - const { promise, resolve, reject } = makePromise(); - const verboseLevel = typeof verbose === "boolean" ? "info" : verbose; - const startTime = Date.now(); - const channel = this.port.createChannel("getOrLoad", { - identifier: modelKey, - loadTtlMs: opts.ttl === undefined ? undefined : opts.ttl * 1000, - loadConfigStack: singleLayerKVConfigStackOf("apiOverride", this.loadConfigToKVConfig(config ?? this.defaultLoadConfig)), - }, message => { - switch (message.type) { - case "alreadyLoaded": { - return resolve(this.createDomainSpecificModel(this.port, message.info, this.validator, this.logger)); - } - case "unloadingOtherJITModel": { - if (verbose) { - this.logger.logAtLevel(verboseLevel, text ` - Unloading other JIT model ${message.info.modelKey}. (You can disable this behavior - by going to LM Studio -> Settings -> Developer -> Turn OFF JIT models auto-evict) - `); - } - break; - } - case "startLoading": { - if (verbose) { - this.logger.logAtLevel(verboseLevel, text ` - Verbose logging is enabled. To hide progress logs, set the "verbose" option to - false in .model(). - `); - this.logger.logAtLevel(verboseLevel, text ` - Model ${modelKey} is not loaded. Start loading... - `); - } - break; - } - case "loadProgress": { - const { progress } = message; - if (onProgress !== undefined) { - safeCallCallback(this.logger, "onProgress", onProgress, [progress]); - } - else if (verbose) { - const now = Date.now(); - if (now - lastVerboseCallTime > 500 || progress === 1) { - const progressText = (progress * 100).toFixed(1); - this.logger.logAtLevel(verboseLevel, `Loading the model, progress: ${progressText}%`); - lastVerboseCallTime = now; - } - } - break; - } - case "loadSuccess": { - if (verbose) { - this.logger.logAtLevel(verboseLevel, text ` - Successfully loaded model ${message.info.modelKey} in ${Date.now() - startTime}ms - `); - } - resolve(this.createDomainSpecificModel(this.port, message.info, this.validator, this.logger)); - } - } - }, { stack }); - channel.onError.subscribeOnce(reject); - signal?.addEventListener("abort", () => { - channel.send({ type: "cancel" }); - reject(signal.reason); - }); - return await promise; - } -} - -/** - * Translate a number to a checkbox numeric value. - * - * @param value - The value to translate. - * @param uncheckedValue - The value to use when the checkbox is unchecked. - * @param valueWhenUnchecked - The value to use when the checkbox is unchecked. - */ -function numberToCheckboxNumeric(value, uncheckedValue, valueWhenUnchecked) { - if (value === undefined) { - return undefined; - } - if (value === uncheckedValue) { - return { checked: false, value: valueWhenUnchecked }; - } - return { checked: true, value }; -} - -/** - * This represents a set of requirements for a model. It is not tied to a specific model, but rather - * to a set of requirements that a model must satisfy. - * - * For example, if you got the model via `client.llm.get("my-identifier")`, you will get a - * `LLMModel` for the model with the identifier `my-identifier`. If the model is unloaded, and - * another model is loaded with the same identifier, using the same `LLMModel` will use the new - * model. - * - * @public - */ -class DynamicHandle { - /** - * Don't construct this on your own. Use {@link LLMNamespace#get} or {@link LLMNamespace#load} - * instead. - * - * @internal - */ - constructor( - /** @internal */ - port, - /** @internal */ - specifier) { - this.port = port; - this.specifier = specifier; - } - /** - * Gets the information of the model that is currently associated with this `DynamicHandle`. If no - * model is currently associated, this will return `undefined`. - * - * Note: As models are loaded/unloaded, the model associated with this `LLMModel` may change at - * any moment. - */ - async getModelInfo() { - const info = await this.port.callRpc("getModelInfo", { specifier: this.specifier, throwIfNotFound: false }, { stack: getCurrentStack(1) }); - if (info === undefined) { - return undefined; - } - return info; - } - async getLoadConfig(stack) { - const loadConfig = await this.port.callRpc("getLoadConfig", { specifier: this.specifier }, { stack }); - return loadConfig; - } -} - -/** - * This represents a set of requirements for a model. It is not tied to a specific model, but rather - * to a set of requirements that a model must satisfy. - * - * For example, if you got the model via `client.embedding.get("my-identifier")`, you will get a - * `EmbeddingModel` for the model with the identifier `my-identifier`. If the model is unloaded, and - * another model is loaded with the same identifier, using the same `EmbeddingModel` will use the - * new model. - * - * @public - */ -class EmbeddingDynamicHandle extends DynamicHandle { - /** - * Don't construct this on your own. Use {@link EmbeddingNamespace#get} or - * {@link EmbeddingNamespace#load} - * instead. - * - * @internal - */ - constructor( - /** @internal */ - port, - /** @internal */ - specifier, - /** @internal */ - validator, - /** @internal */ - logger = new SimpleLogger(`EmbeddingModel`)) { - super(port, specifier); - this.validator = validator; - this.logger = logger; - } - async embed(inputString) { - const stack = getCurrentStack(1); - inputString = this.validator.validateMethodParamOrThrow("client.embedding", "embed", "inputString", z.string().or(z.array(z.string())), inputString, stack); - if (Array.isArray(inputString)) { - return await Promise.all(inputString.map(s => this.port.callRpc("embedString", { inputString: s, modelSpecifier: this.specifier }, { stack }))); - } - else { - return await this.port.callRpc("embedString", { inputString, modelSpecifier: this.specifier }, { stack }); - } - } - async getContextLength() { - const stack = getCurrentStack(1); - const loadConfig = await this.getLoadConfig(stack); - return embeddingSharedLoadConfigSchematics.access(loadConfig, "contextLength"); - } - async getEvalBatchSize() { - const stack = getCurrentStack(1); - const loadConfig = await this.getLoadConfig(stack); - return globalConfigSchematics.access(loadConfig, "embedding.load.llama.evalBatchSize"); - } - async tokenize(inputString) { - const stack = getCurrentStack(1); - inputString = this.validator.validateMethodParamOrThrow("model", "tokenize", "inputString", z.string().or(z.array(z.string())), inputString, stack); - if (Array.isArray(inputString)) { - return (await Promise.all(inputString.map(s => this.port.callRpc("tokenize", { specifier: this.specifier, inputString: s }, { stack })))).map(r => r.tokens); - } - else { - return (await this.port.callRpc("tokenize", { - specifier: this.specifier, - inputString, - }, { stack })).tokens; - } - } - async countTokens(inputString) { - const stack = getCurrentStack(1); - inputString = this.validator.validateMethodParamOrThrow("model", "countTokens", "inputString", z.string(), inputString, stack); - return (await this.port.callRpc("countTokens", { - specifier: this.specifier, - inputString, - }, { stack })).tokenCount; - } -} - -/** - * Represents a specific loaded Embedding. Most Embedding related operations are inherited from - * {@link EmbeddingDynamicHandle}. - * - * @public - */ -class EmbeddingModel extends EmbeddingDynamicHandle { - /** @internal */ - constructor(embeddingPort, info, validator, logger = new SimpleLogger(`EmbeddingModel`)) { - const specifier = { - type: "instanceReference", - instanceReference: info.instanceReference, - }; - super(embeddingPort, specifier, validator, logger); - this.identifier = info.identifier; - this.path = info.path; - this.modelKey = info.modelKey; - this.format = info.format; - this.displayName = info.displayName; - this.sizeBytes = info.sizeBytes; - } - async unload() { - const stack = getCurrentStack(1); - await this.port.callRpc("unloadModel", { identifier: this.identifier }, { stack }); - } - async getModelInfo() { - const info = await super.getModelInfo(); - if (info === undefined) { - const stack = getCurrentStack(1); - throw makePrettyError("This model has already been unloaded", stack); - } - return info; - } -} - -/** @public */ -class EmbeddingNamespace extends ModelNamespace { - constructor() { - super(...arguments); - /** @internal */ - this.namespace = "embedding"; - /** @internal */ - this.defaultLoadConfig = {}; - /** @internal */ - this.loadModelConfigSchema = embeddingLoadModelConfigSchema; - } - /** @internal */ - loadConfigToKVConfig(config) { - return embeddingLlamaLoadConfigSchematics.buildPartialConfig({ - "llama.acceleration.offloadRatio": config.gpu?.ratio, - "load.gpuSplitConfig": convertGPUSettingToGPUSplitConfig(config.gpu), - "contextLength": config.contextLength, - "llama.ropeFrequencyBase": numberToCheckboxNumeric(config.ropeFrequencyBase, 0, 0), - "llama.ropeFrequencyScale": numberToCheckboxNumeric(config.ropeFrequencyScale, 0, 0), - "llama.keepModelInMemory": config.keepModelInMemory, - "llama.tryMmap": config.tryMmap, - }); - } - /** @internal */ - createDomainSpecificModel(port, info, validator, logger) { - return new EmbeddingModel(port, info, validator, logger); - } - /** @internal */ - createDomainDynamicHandle(port, specifier, validator, logger) { - return new EmbeddingDynamicHandle(port, specifier, validator, logger); - } -} - -const parseDocumentOptsSchema = documentParsingOptsSchema.extend({ - onProgress: z.function().optional(), - signal: z.instanceof(AbortSignal).optional(), -}); - -const retrievalCallbacksSchema = z.object({ - onFileProcessList: z.function().optional(), - onFileProcessingStart: z.function().optional(), - onFileProcessingEnd: z.function().optional(), - onFileProcessingStepStart: z.function().optional(), - onFileProcessingStepProgress: z.function().optional(), - onFileProcessingStepEnd: z.function().optional(), - onSearchingStart: z.function().optional(), - onSearchingEnd: z.function().optional(), - verbose: z.union([z.boolean(), z.string()]).optional(), -}); -const retrievalOptsSchema = z.object({ - chunkingMethod: retrievalChunkingMethodSchema.optional(), - limit: z.number().int().optional(), - embeddingModel: z.instanceof(EmbeddingDynamicHandle).optional(), - databasePath: z.string().optional(), - signal: z.instanceof(AbortSignal).optional(), - ...retrievalCallbacksSchema.shape, -}); - -function getProcessingStepName(processingStep) { - switch (processingStep) { - case "loading": - return "Loading"; - case "chunking": - return "Chunking"; - case "embedding": - return "Embedding"; - default: { - const exhaustiveCheck = processingStep; - throw new Error(`Unexpected processing step: ${exhaustiveCheck}`); - } - } -} -/** - * @public - * - * The namespace for file-related operations. - */ -class FilesNamespace { - /** @internal */ - constructor( - /** @internal */ - filesPort, validator, parentLogger) { - this.filesPort = filesPort; - this.validator = validator; - this.logger = new SimpleLogger("File", parentLogger); - } - /** - * Gets the absolute path to a local file. - * - * @internal - */ - async getLocalFileAbsolutePath(fileName, stack) { - return await this.filesPort.callRpc("getLocalFileAbsolutePath", { fileName }, { stack }); - } - /** - * Creates a file handle from a chat message part file data. Used internally. - * - * @internal - */ - createFileHandleFromChatMessagePartFileData(data) { - return new FileHandle(this, data.identifier, data.fileType, data.sizeBytes, data.name); - } - /** - * Adds a temporary image to LM Studio, and returns a FileHandle that can be used to reference - * this image. This image will be deleted when the client disconnects. - * - * This method can only be used in environments that have file system access (such as Node.js). - */ - async prepareImage(path) { - const result = await readFileAsBase64(path); - if (result.success === false) { - throw new Error(text ` - Your current JavaScript environment does not support reading files. If you can read the file - using other methods, please use "prepareImageBase64". - `); - } - const fileName = path.split(/[\\/]/).at(-1); - const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", { - name: fileName, - contentBase64: result.base64, - }); - return new FileHandle(this, identifier, fileType, sizeBytes, fileName); - } - /** - * Adds a temporary image to LM Studio. The content of the file is specified using base64. If you - * are using Node.js and have a file laying around, consider using `prepareImage` instead. - */ - async prepareImageBase64(fileName, contentBase64) { - const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", { - name: fileName, - contentBase64, - }); - return new FileHandle(this, identifier, fileType, sizeBytes, fileName); - } - /** - * Adds a temporary file to LM Studio, and returns a FileHandle that can be used to reference this - * file. This file will be deleted when the client disconnects. - * - * This method can only be used in environments that have file system access (such as Node.js). - * - * @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for - * updates. - */ - async prepareFile(path) { - // Currently, exactly the same as prepareImage. - const result = await readFileAsBase64(path); - if (result.success === false) { - throw new Error(text ` - Your current JavaScript environment does not support reading files. If you can read the file - using other methods, please use "prepareFileBase64". - `); - } - const fileName = path.split(/[\\/]/).at(-1); - const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", { - name: fileName, - contentBase64: result.base64, - }); - return new FileHandle(this, identifier, fileType, sizeBytes, fileName); - } - /** - * Adds a temporary file to LM Studio. The content of the file is specified using base64. If you - * are using Node.js and have a file laying around, consider using `prepareFile` instead. - * - * @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for - * updates. */ - async prepareFileBase64(fileName, contentBase64) { - // Currently, exactly the same as prepareImageBase64. - const { identifier, fileType, sizeBytes } = await this.filesPort.callRpc("uploadFileBase64", { - name: fileName, - contentBase64, - }); - return new FileHandle(this, identifier, fileType, sizeBytes, fileName); - } - /** - * @deprecated [DEP-RETRIEVAL] Retrieval API is still in active development. Stay tuned for - * updates. */ - async retrieve(query, files, opts = {}) { - const logger = this.logger; - const stack = getCurrentStack(1); - this.validator.validateMethodParamsOrThrow("client.retrieval", "retrieve", ["query", "filePaths", "opts"], [z.string(), z.array(z.instanceof(FileHandle)), retrievalOptsSchema], [query, files, opts], stack); - const { verbose = "info" } = opts; - const verboseLevel = typeof verbose === "boolean" ? "info" : verbose; - const shouldLog = verbose && - opts.onFileProcessList === undefined && - opts.onFileProcessingStart === undefined && - opts.onFileProcessingEnd === undefined && - opts.onFileProcessingStepStart === undefined && - opts.onFileProcessingStepProgress === undefined && - opts.onFileProcessingStepEnd === undefined && - opts.onSearchingStart === undefined && - opts.onSearchingEnd === undefined; - if (opts.embeddingModel === undefined) { - throw new Error("Embedding model currently is required."); - } - const resolveFileIndex = (index) => { - const file = files[index]; - if (file === undefined) { - throw new Error(`File not found: ${index}`); - } - return file; - }; - const resolveFileIndices = (indices) => { - return indices.map(resolveFileIndex); - }; - const kvConfig = retrievalSchematics.buildPartialConfig({ - chunkingMethod: opts.chunkingMethod, - databaseFile: opts.databasePath, - embeddingModel: (await opts.embeddingModel.getModelInfo())?.identifier, - limit: opts.limit, - }); - let filesToProcess; - const filesProcessingStartTimes = []; - let searchingStartTime = 0; - let lastVerboseCallTime = 0; - let lastVerboseLine = ""; - return await new Promise((resolve, reject) => { - const channel = this.filesPort.createChannel("retrieve", { query, fileIdentifiers: files.map(file => file.identifier), config: kvConfig }, message => { - switch (message.type) { - case "onFileProcessList": - filesToProcess = resolveFileIndices(message.indices); - safeCallCallback(logger, "onFileProcessList", opts.onFileProcessList, [ - filesToProcess, - ]); - if (shouldLog) { - logger.logAtLevel(verboseLevel, text ` - Found ${filesToProcess.length} files need processing: - ${filesToProcess.map(file => file.name).join(", ")} - `); - } - break; - case "onFileProcessingStart": { - if (filesToProcess === null) { - throw new Error("onFileProcessList must be called before onFileProcessingStart"); - } - const file = resolveFileIndex(message.index); - safeCallCallback(logger, "onFileProcessingStart", opts.onFileProcessingStart, [ - file, - filesToProcess.indexOf(file), - filesToProcess, - ]); - if (shouldLog) { - filesProcessingStartTimes[message.index] = Date.now(); - logger.logAtLevel(verboseLevel, text ` - Start processing file: ${file.name} - (${message.index + 1}/${filesToProcess.length}) - `); - } - break; - } - case "onFileProcessingEnd": { - if (filesToProcess === null) { - throw new Error("onFileProcessList must be called before onFileProcessingEnd"); - } - const file = resolveFileIndex(message.index); - safeCallCallback(logger, "onFileProcessingEnd", opts.onFileProcessingEnd, [ - file, - filesToProcess.indexOf(file), - filesToProcess, - ]); - if (shouldLog) { - logger.logAtLevel(verboseLevel, text ` - File processed: ${file.name}. - Time took: ${Date.now() - filesProcessingStartTimes[message.index]}ms - `); - } - break; - } - case "onFileProcessingStepStart": - safeCallCallback(logger, "onFileProcessingStepStart", opts.onFileProcessingStepStart, [resolveFileIndex(message.index), message.step]); - break; - case "onFileProcessingStepProgress": { - safeCallCallback(logger, "onFileProcessingStepProgress", opts.onFileProcessingStepProgress, [resolveFileIndex(message.index), message.step, message.progress]); - const now = Date.now(); - if (shouldLog && (now - lastVerboseCallTime > 500 || message.progress === 1)) { - lastVerboseCallTime = now; - const line = text ` - > ${getProcessingStepName(message.step)}: ${Math.round(message.progress * 100)}% - `; - if (lastVerboseLine !== line) { - lastVerboseLine = line; - logger.logAtLevel(verboseLevel, line); - } - } - break; - } - case "onFileProcessingStepEnd": - safeCallCallback(logger, "onFileProcessingStepEnd", opts.onFileProcessingStepEnd, [ - resolveFileIndex(message.index), - message.step, - ]); - break; - case "onSearchingStart": - safeCallCallback(logger, "onSearchingStart", opts.onSearchingStart, []); - if (shouldLog) { - searchingStartTime = Date.now(); - logger.logAtLevel(verboseLevel, "Start searching in the vector database..."); - } - break; - case "onSearchingEnd": - safeCallCallback(logger, "onSearchingEnd", opts.onSearchingEnd, []); - if (shouldLog) { - logger.logAtLevel(verboseLevel, text ` - Finished searching in the vector database. - Time took: ${Date.now() - searchingStartTime}ms - `); - } - break; - case "result": { - resolve({ - entries: message.result.entries.map(entry => ({ - content: entry.content, - score: entry.score, - source: files[entry.sourceIndex], - })), - }); - break; - } - } - }); - if (opts.signal !== undefined) { - if (opts.signal.aborted) { - reject(opts.signal.reason); - channel.send({ type: "stop" }); - } - else { - opts.signal?.addEventListener("abort", () => { - reject(opts.signal.reason); - channel.send({ type: "stop" }); - }); - } - } - channel.onError.subscribeOnce(reject); - }); - } - /** - * Parse a document - * - * @deprecated [DEP-DOC-PARSE] Document parsing API is still in active development. Stay tuned for - * updates. - */ - async parseDocument(fileHandle, opts = {}) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamsOrThrow("client.files", "parseDocument", ["fileHandle", "opts"], [z.instanceof(FileHandle), parseDocumentOptsSchema], [fileHandle, opts], stack); - const { onParserLoaded, onProgress, signal, ...config } = opts; - const { promise, resolve, reject } = makePromise(); - opts.signal?.throwIfAborted(); - let finished = false; - const channel = this.filesPort.createChannel("parseDocument", { fileIdentifier: fileHandle.identifier, parseOpts: config }, message => { - const messageType = message.type; - switch (messageType) { - case "progress": { - safeCallCallback(this.logger, "onProgress", onProgress, [message.progress]); - break; - } - case "parserLoaded": { - safeCallCallback(this.logger, "onParserLoaded", onParserLoaded, [message.parser]); - break; - } - case "result": { - resolve({ - content: message.content, - parser: message.parser, - }); - finished = true; - break; - } - } - }, { stack }); - signal?.addEventListener("abort", () => { - if (finished) { - return; - } - reject(signal.reason); - channel.send({ type: "cancel" }); - }); - channel.onError.subscribeOnce(reject); - channel.onClose.subscribeOnce(() => { - if (!finished) { - reject(new Error("Channel closed before receiving a result.")); - } - }); - return await promise; - } - /** - * Get the parsing method for a document. - * - * @deprecated [DEP-DOC-PARSE] Document parsing API is still in active development. Stay tuned for - * updates. - */ - async getDocumentParsingLibrary(fileHandle) { - const stack = getCurrentStack(1); - return await this.filesPort.callRpc("getDocumentParsingLibrary", { fileIdentifier: fileHandle.identifier }, { stack }); - } -} - -function deserializeOtherError(serialized, stack) { - let content = chalk.redBright(` ${serialized.title} `); - if (serialized.suggestion !== undefined) { - content += - "\n\n\n " + - chalk.bgWhite.black(" (!) SUGGESTION ") + - "\n\n" + - chalk.white(serialized.suggestion); - } - if (serialized.cause !== undefined) { - content += - "\n\n\n " + chalk.bgWhite.black(" (X) CAUSE ") + "\n\n" + chalk.gray(serialized.cause); - } - return makePrettyError(content, stack); -} -const errorDeserializersMap = new Map(); -function registerErrorDeserializer(code, deserializer) { - errorDeserializersMap.set(code, deserializer); -} -function formatAvailableLLMs(availablePathsSample, totalModels) { - if (availablePathsSample.length === 0) { - return chalk.gray(" You don't have any LLMs downloaded."); - } - let text = availablePathsSample.map(path => chalk.cyanBright(" • " + path)).join("\n"); - if (availablePathsSample.length < totalModels) { - text += chalk.gray(`\n ... (and ${totalModels - availablePathsSample.length} more)`); - } - return text; -} -registerErrorDeserializer("generic.pathNotFound", ({ availablePathsSample, path, totalModels }, stack) => { - return makeTitledPrettyError(`Cannot find a model with path "${chalk.yellowBright(path)}"`, text ` - Here are your available models: - - ${formatAvailableLLMs(availablePathsSample, totalModels)} - - Run - - ${chalk.yellowBright("lms ls")} - - to see a full list of loadable models - `, stack); -}); -function formatLoadedModels(loadedModelsSample, totalLoadedModels) { - if (loadedModelsSample.length === 0) { - return chalk.gray(" You don't have any models loaded."); - } - let text = loadedModelsSample.map(path => chalk.cyanBright(" • " + path)).join("\n"); - if (loadedModelsSample.length < totalLoadedModels) { - text += chalk.gray(`\n ... (and ${totalLoadedModels - loadedModelsSample.length} more)`); - } - return text; -} -registerErrorDeserializer("generic.identifierNotFound", ({ loadedModelsSample, identifier, totalLoadedModels }, stack) => { - return makeTitledPrettyError(`Cannot find a model with identifier "${chalk.yellowBright(identifier)}"`, text ` - Here are your loaded models: - - ${formatLoadedModels(loadedModelsSample, totalLoadedModels)} - - Run - - ${chalk.yellowBright("lms ps")} - - to see a full list of loaded models - `, stack); -}); -registerErrorDeserializer("generic.specificModelUnloaded", (_, stack) => { - return makePrettyError(chalk.bgRed.white(text ` - This model has already been unloaded. - `), stack); -}); -function getModelDomainTypeDisplayNameSingular(domain) { - switch (domain) { - case "llm": - return "an LLM"; - case "embedding": - return "an embedding model"; - case "imageGen": - return "an image generation model"; - case "transcription": - return "a transcription model"; - case "tts": - return "a text-to-speech model"; - default: { - const exhaustiveCheck = domain; - console.error(`Unexpected domain type: ${exhaustiveCheck}`); - return "Unknown Model Domain"; - } - } -} -function formatQuery(query) { - const requirements = []; - if (query.domain !== undefined) { - requirements.push(text ` - The model must be ${chalk.yellowBright(getModelDomainTypeDisplayNameSingular(query.domain))} - `); - } - if (query.identifier !== undefined) { - requirements.push(`The identifier must be exactly "${chalk.yellowBright(query.identifier)}"`); - } - if (query.path !== undefined) { - requirements.push(`The path must match "${chalk.yellowBright(query.path)}"`); - } - if (requirements.length === 0) { - return chalk.gray(" • Any Model"); - } - return requirements.map(req => chalk.white(" • " + req)).join("\n"); -} -registerErrorDeserializer("generic.noModelMatchingQuery", ({ loadedModelsSample, totalLoadedModels, query }, stack) => { - return makePrettyError(text ` - ${chalk.bgRed.white(" No loaded model satisfies all requirements specified in the query. ")} - - Loaded Models: - - ${formatLoadedModels(loadedModelsSample, totalLoadedModels)} - - Your query: - - ${formatQuery(query)} - - Run - - ${chalk.yellowBright("lms ps")} - - to see a full list of loaded models with details - `, stack); -}); -registerErrorDeserializer("generic.domainMismatch", ({ actualDomain, expectedDomain, path }, stack) => { - return makePrettyError(text ` - ${chalk.bgRed.white(" Model has wrong domain. ")} - - Expecting ${chalk.greenBright(path)} to be ${chalk.yellowBright(getModelDomainTypeDisplayNameSingular(expectedDomain))}, but it is actually ${chalk.yellowBright(getModelDomainTypeDisplayNameSingular(actualDomain))}. - `, stack); -}); -function formatAvailablePresets(presets, totalAvailablePresets) { - if (presets.length === 0) { - return chalk.gray(" You don't have any presets available."); - } - let text = presets - .map(({ identifier, name }) => chalk.cyanBright(` • ${name} (${chalk.cyan(identifier)})`)) - .join("\n"); - if (presets.length < totalAvailablePresets) { - text += chalk.gray(`\n ... (and ${totalAvailablePresets - presets.length} more)`); - } - return text; -} -registerErrorDeserializer("generic.presetNotFound", ({ specifiedFuzzyPresetIdentifier, availablePresetsSample, totalAvailablePresets }) => { - return makeTitledPrettyError(`Cannot find a preset with identifier "${chalk.yellowBright(specifiedFuzzyPresetIdentifier)}"`, text ` - Here are your available presets: - - ${formatAvailablePresets(availablePresetsSample, totalAvailablePresets)} - - Note: To specify a preset in the SDK, you need to use its identifier (in parentheses). You - can get a preset's identifier by right-clicking on it and then select "Copy Preset - Identifier". - `); -}); -function friendlyErrorDeserializer(serialized, _directCause, stack) { - if (serialized.displayData === undefined) { - return deserializeOtherError(serialized, stack); - } - let error; - const specificDeserializer = errorDeserializersMap.get(serialized.displayData.code); - if (specificDeserializer !== undefined) { - error = specificDeserializer(serialized.displayData, stack); - attachSerializedErrorData(error, serialized); - return error; - } - else { - return deserializeOtherError(serialized, stack); - } -} - -function cacheQuantizationTypeToCheckbox({ value, falseDefault, }) { - return value === undefined - ? undefined - : value === false - ? { checked: false, value: falseDefault } - : { checked: true, value: value }; -} - -/** - * Represents the result of running `llm.act`. Currently only contains minimum amount of - * information. - * - * If you think more information/fields should be added, please open an issue or a PR on GitHub. - * - * @public - */ -class ActResult { - constructor( - /** - * Number of rounds performed. - * - * For example, in the following scenario: - * - * - User asks the model to add 1234 and 5678. - * - The model requests to use a calculator tool. - * - The calculator tool outputs 6912. - * - The calculator's output is then fed back to the model for a second round of prediction. - * - The model sees the output and generates a paragraph explaining the result. - * - * There are 2 rounds. On the beginning of a round, the callback `onRoundStart` is triggered. - * On the end of a round, the callback `onRoundEnd` is triggered. - */ - rounds, - /** - * Total time taken to run `.act` in seconds. measured from beginning of the `.act` invocation - * to when the entire operation is finished. - */ - totalExecutionTimeSeconds) { - this.rounds = rounds; - this.totalExecutionTimeSeconds = totalExecutionTimeSeconds; - } -} - -/** - * Each call uses a globally unique call ID that starts somewhere before the half of the - * `Number.MAX_SAFE_INTEGER`. - */ -const callIdGiver = new IdGiver(Math.floor(Math.random() * (Number.MAX_SAFE_INTEGER / 2 / 10000)) * 10000); -class NoQueueQueue { - needsQueueing() { - return false; - } - async runInQueue(fn, signal) { - if (signal?.aborted) { - throw new Error("Operation aborted"); - } - return fn(); - } -} -class FIFOQueue { - constructor() { - this.queue = []; - this.executing = false; - this.poisoned = false; - this.poisonError = null; - } - needsQueueing() { - return this.executing || this.queue.length > 0; - } - async runInQueue(fn, signal) { - // Check if the operation is already aborted - if (signal?.aborted) { - throw new Error("Operation aborted"); - } - // If the queue is poisoned, fail immediately with the saved error - if (this.poisoned) { - throw this.poisonError ?? new Error("Queue has been poisoned by a previous error"); - } - if (!this.needsQueueing()) { - // If nothing is in the queue, execute immediately - this.executing = true; - try { - // Check for abort before execution - if (signal?.aborted) { - throw new Error("Operation aborted"); - } - return await fn(); - } - catch (error) { - // Poison the queue - this.poisoned = true; - this.poisonError = error; - // Clear the queue since nothing will run after this - this.clearQueue(error); - throw error; - } - finally { - this.executing = false; - this.processQueue(); - } - } - // Otherwise, add to queue and wait for execution - return new Promise((resolve, reject) => { - // Add abort listener if a signal was provided - if (signal) { - if (signal.aborted) { - return reject(new Error("Operation aborted")); - } - signal.addEventListener("abort", () => { - // Remove from queue if it hasn't started yet - const index = this.queue.findIndex(item => item.resolve === resolve && item.reject === reject); - if (index !== -1) { - this.queue.splice(index, 1); - reject(new Error("Operation aborted")); - } - }, { once: true }); - } - this.queue.push({ - fn: async () => { - try { - // Check for abort before execution - if (signal?.aborted) { - throw new Error("Operation aborted"); - } - const result = await fn(); - resolve(result); - return result; - } - catch (error) { - reject(error); - throw error; - } - }, - resolve, - reject, - signal, - }); - }); - } - async processQueue() { - if (this.executing || this.queue.length === 0 || this.poisoned) { - return; - } - const nextItem = this.queue.shift(); - if (!nextItem) - return; - // Skip if this task has been aborted - if (nextItem.signal?.aborted) { - nextItem.reject(new Error("Operation aborted")); - this.processQueue(); - return; - } - this.executing = true; - try { - await nextItem.fn(); - } - catch (error) { - // Poison the queue - this.poisoned = true; - this.poisonError = error; - // Clear the queue since nothing will run after this - this.clearQueue(error); - } - finally { - this.executing = false; - // Only continue processing if not poisoned - if (!this.poisoned) { - this.processQueue(); - } - } - } - clearQueue(error) { - // Reject all pending promises in the queue - for (const item of this.queue) { - item.reject(error); - } - this.queue = []; - } -} -/** - * Controller object used to allow/modify/deny a tool call. - */ -class GuardToolCallController { - /** - * Don't construct this object yourself. - */ - constructor(toolCallRequest, tool, resultContainer) { - this.toolCallRequest = toolCallRequest; - this.tool = tool; - this.resultContainer = resultContainer; - /** - * Allows the tool call to proceed without any modifications. - */ - this.allow = () => { - this.assertNoResultYet("allow", getCurrentStack(1)); - this.resultContainer[0] = { type: "allow" }; - }; - /** - * Allows the tool call to proceed, but overrides the parameters with the provided ones. - */ - this.allowAndOverrideParameters = (newParameters) => { - this.assertNoResultYet("allowAndOverrideParameters", getCurrentStack(1)); - this.resultContainer[0] = { type: "allowAndOverrideParameters", parameters: newParameters }; - }; - /** - * Denys the tool call with a specified reason. This will not interrupt the `.act` call. Instead, - * the reason you provide will be provided to the model as the tool call result. - * - * If `reason` is not provided, a generic default reason will be used. - * - * If you wish to immediately fail the `.act` call, you can throw an error instead. - */ - this.deny = (reason) => { - this.assertNoResultYet("deny", getCurrentStack(1)); - this.resultContainer[0] = { type: "deny", reason }; - }; - } - assertNoResultYet(calledMethodName, stack) { - if (this.resultContainer[0] === null) { - return; - } - // Oh no, the result has already been set! Make an error message. - throw makeTitledPrettyError(`Cannot call ${calledMethodName} after a result has been set`, text ` - This tool call guard has already set a result previously (${this.resultContainer[0].type}). - You cannot set a result more than once. - `, stack); - } -} -const llmActBaseOptsSchema = z.object({ - onFirstToken: z.function().optional(), - onPredictionFragment: z.function().optional(), - onMessage: z.function().optional(), - onRoundStart: z.function().optional(), - onRoundEnd: z.function().optional(), - onPredictionCompleted: z.function().optional(), - onPromptProcessingProgress: z.function().optional(), - onToolCallRequestStart: z.function().optional(), - onToolCallRequestNameReceived: z.function().optional(), - onToolCallRequestArgumentFragmentGenerated: z.function().optional(), - onToolCallRequestEnd: z.function().optional(), - onToolCallRequestFinalized: z.function().optional(), - onToolCallRequestFailure: z.function().optional(), - onToolCallRequestDequeued: z.function().optional(), - guardToolCall: z.function().optional(), - handleInvalidToolRequest: z.function().optional(), - maxPredictionRounds: z.number().int().min(1).optional(), - signal: z.instanceof(AbortSignal).optional(), - allowParallelToolExecution: z.boolean().optional(), -}); -const defaultHandleInvalidToolRequest = (error, request) => { - if (request) { - return error.message; - } - throw error; -}; -/** - * The internal method for performing .act(). This is used by both `LLMDynamicHandle` and - * `LLMGeneratorHandle`. - * - * @param TPredictionResult - The type of the prediction result. - * @param TEndPacket - The type of the success packet that is returned. This type is received from - * `handlePredictionEnd` and is passed to the `makePredictionResult` function to create the - * `TPredictionResult`. - * @param chat - The chat to use for the prediction. - * @param tools - The tools to use for the prediction. This is an array of tools that the model can - * use during the prediction. - * @param baseOpts - The base options for the prediction. This includes callbacks and other - * options that control the prediction process. - * @param stack - The stack trace to use for the prediction. This is used for generating errors. - * @param logger - The logger to use for the prediction. This is used for logging messages during - * the prediction. - * @param startTime - The start time of the prediction. This is used to calculate the duration of - * the act. - * @param predictImpl - The implementation of the prediction. This is a function that takes the - * prediction arguments and performs the prediction. This is the main abstraction - `internalAct` - * performs the prediction loop while this function handles the actual prediction itself. - * @param makePredictionResult - A function that takes the end packet and the content of the - * prediction and creates the `TPredictionResult`. This is used to create the prediction result - * object for each round of the prediction. - */ -async function internalAct(chat, tools, baseOpts, stack, logger, startTime, predictImpl, makePredictionResult) { - const abortController = new AbortController(); - const mutableChat = Chat.from(chat); // Make a copy - let currentCallId = -1; - /** - * A flag that will be set if any unimplemented tool is called. In which case, the loop will - * terminate after all the parallel tool calls are resolved. - */ - let hasCalledUnimplementedTool = false; - if (baseOpts.signal !== undefined) { - if (baseOpts.signal.aborted) { - // If the signal is already aborted, we should not continue. - abortController.abort(baseOpts.signal.reason); - } - else { - baseOpts.signal.addEventListener("abort", () => { - abortController.abort(baseOpts.signal?.reason); - }, { once: true }); - } - } - let shouldContinue = false; - let predictionsPerformed = 0; - const toolsMap = new Map(); - for (const tool of tools) { - if (toolsMap.has(tool.name)) { - logger.warnText ` - Duplicate tool (${tool.name}) found in the tools array. The last tool with the same name - will be used. - `; - } - toolsMap.set(tool.name, tool); - } - do { - // Main loop - execute as many times as the model requests tools - let allowTools = true; - if ( - // If there is a defined number of max predictions, - baseOpts.maxPredictionRounds !== undefined && - // ... and this is the last chance to perform predictions, don't allow the model to use - // tools. - predictionsPerformed + 1 >= baseOpts.maxPredictionRounds) { - allowTools = false; - } - // Start the prediction - let finished = false; - let firstTokenTriggered = false; - const contentArray = []; - const reasoningContentArray = []; - const nonReasoningContentArray = []; - const toolCallRequests = []; - let nextToolCallIndex = 0; - const toolCallResults = []; - /** - * All promises that need to be awaited. Once they are done, they will add their own results - * to the toolCallResults array in-place. - */ - const toolCallPromises = []; - /** - * The promise that represents the prediction itself (The RPC call). - */ - const { promise: predictionPromise, resolve: predictionResolve, reject: predictionReject, } = makePromise(); - /** - * The final promise that will be awaited on for this prediction. It is resolved when the - * prediction is done and all tool calls have been resolved. - */ - const { promise: finalPromise, resolve: finalResolve, reject: finalReject, } = makePromise(); - const internalHandleInvalidToolCallRequest = async (error, request, - /** - * In the case this tool call got a replacement, the index to use. - */ - toolCallIndex) => { - let result; - try { - result = await (baseOpts.handleInvalidToolRequest ?? defaultHandleInvalidToolRequest)(error, request); - } - catch (error) { - if (abortController.signal.aborted) { - throw abortController.signal.reason; - } - abortController.abort(); - throw error; // Rethrow the error. - } - if (result === undefined) { - // No replacement. - return; - } - let resultString; - try { - resultString = JSON.stringify(result); - } - catch (error) { - abortController.abort(); - throw makePrettyError("handleInvalidToolRequest returned a value that cannot be converted to JSON.", stack); - } - // The handleInvalidToolRequest has returned a "replacement" - if (request === undefined) { - // We cannot provide a result to a tool call that has failed to parse. - logger.warnText ` - The "handleInvalidToolRequest" callback has returned a result, but the tool request has - completely failed to parse, thus LM Studio cannot provide the result to the tool call. - Please avoid returning a result when the second parameter of the callback is undefined. - See the documentation for "handleInvalidToolRequest" for more information. - `; - } - else { - toolCallResults.push({ - index: toolCallIndex, - data: { - type: "toolCallResult", - toolCallId: request.id, - content: resultString, - }, - }); - nextToolCallIndex++; - } - }; - abortController.signal.throwIfAborted(); - // Round start callback - safeCallCallback(logger, "onRoundStart", baseOpts.onRoundStart, [predictionsPerformed]); - let isGeneratingToolCall = false; - /** - * Abort controller for the current round. - */ - const roundAbortController = new AbortController(); - const queue = baseOpts.allowParallelToolExecution - ? new NoQueueQueue() - : new FIFOQueue(); - let receivedEagerToolNameReporting = false; - let receivedToolArgumentsStreaming = false; - predictImpl({ - allowTools, - history: accessMaybeMutableInternals(mutableChat)._internalGetData(), - signal: roundAbortController.signal, - handleFragment: fragment => { - if (!firstTokenTriggered) { - firstTokenTriggered = true; - safeCallCallback(logger, "onFirstToken", baseOpts.onFirstToken, [predictionsPerformed]); - } - safeCallCallback(logger, "onFragment", baseOpts.onPredictionFragment, [ - { roundIndex: predictionsPerformed, ...fragment }, - ]); - contentArray.push(fragment.content); - if (!fragment.isStructural) { - if (fragment.reasoningType === "reasoning") { - reasoningContentArray.push(fragment.content); - } - else { - nonReasoningContentArray.push(fragment.content); - } - } - }, - handlePromptProcessingProgress: progress => { - safeCallCallback(logger, "onPromptProcessingProgress", baseOpts.onPromptProcessingProgress, [predictionsPerformed, progress]); - }, - handleToolCallGenerationStart: toolCallId => { - currentCallId = callIdGiver.next(); - receivedEagerToolNameReporting = false; - receivedToolArgumentsStreaming = false; - isGeneratingToolCall = true; - safeCallCallback(logger, "onToolCallRequestStart", baseOpts.onToolCallRequestStart, [ - predictionsPerformed, - currentCallId, - { toolCallId: toolCallId }, - ]); - }, - handleToolCallGenerationNameReceived: name => { - receivedEagerToolNameReporting = true; - safeCallCallback(logger, "onToolCallRequestNameReceived", baseOpts.onToolCallRequestNameReceived, [predictionsPerformed, currentCallId, name]); - }, - handleToolCallGenerationArgumentFragmentGenerated: content => { - receivedToolArgumentsStreaming = true; - safeCallCallback(logger, "onToolCallRequestArgumentFragmentGenerated", baseOpts.onToolCallRequestArgumentFragmentGenerated, [predictionsPerformed, currentCallId, content]); - }, - handleToolCallGenerationEnd: (request, rawContent) => { - const callId = currentCallId; - isGeneratingToolCall = false; - const toolCallIndex = nextToolCallIndex; - nextToolCallIndex++; - if (!receivedEagerToolNameReporting) { - // If eager name reporting not received, report it. - safeCallCallback(logger, "onToolCallRequestNameReceived", baseOpts.onToolCallRequestNameReceived, [predictionsPerformed, callId, request.name]); - } - if (!receivedToolArgumentsStreaming) { - // If arguments streaming not received, just pretend we have received all the arguments - // as a single JSON - safeCallCallback(logger, "onToolCallRequestArgumentFragmentGenerated", baseOpts.onToolCallRequestArgumentFragmentGenerated, [predictionsPerformed, callId, JSON.stringify(request.arguments ?? {}, null, 2)]); - } - const pushedRequest = { ...request }; - // We have now received a tool call request. Now let's see if we can call the tool and - // get the result. - toolCallRequests.push(pushedRequest); - const tool = toolsMap.get(request.name); - if (tool === undefined) { - // Tool does not exist. - const toolCallRequestError = new ToolCallRequestError(`Cannot find tool with name ${request.name}.`, rawContent); - toolCallPromises.push(internalHandleInvalidToolCallRequest(toolCallRequestError, request, toolCallIndex).catch(finalReject)); - safeCallCallback(logger, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [ - predictionsPerformed, - callId, - toolCallRequestError, - ]); - return; - } - // Try check the parameters: - try { - tool.checkParameters(pushedRequest.arguments); // Defaults to empty object - } - catch (error) { - // Failed to parse the parameters - const toolCallRequestError = new ToolCallRequestError(error.message, rawContent); - toolCallPromises.push(internalHandleInvalidToolCallRequest(toolCallRequestError, request, toolCallIndex).catch(finalReject)); - safeCallCallback(logger, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [ - predictionsPerformed, - callId, - toolCallRequestError, - ]); - return; - } - const toolCallContext = new SimpleToolCallContext(new SimpleLogger(`Tool(${request.name})`, logger), abortController.signal, callId); - const isQueued = queue.needsQueueing(); - safeCallCallback(logger, "onToolCallRequestEnd", baseOpts.onToolCallRequestEnd, [ - predictionsPerformed, - callId, - { - isQueued, - toolCallRequest: request, - rawContent, - }, - ]); - // We have successfully parsed the parameters. Let's call the tool. - toolCallPromises.push(queue - .runInQueue(async () => { - // Emit the dequeued event if the tool call was queued. - if (isQueued) { - safeCallCallback(logger, "onToolCallRequestDequeued", baseOpts.onToolCallRequestDequeued, [predictionsPerformed, callId]); - } - // Guard the tool call if have a tool call guard. - if (baseOpts.guardToolCall !== undefined) { - const resultContainer = [null]; - await baseOpts.guardToolCall(predictionsPerformed, callId, new GuardToolCallController(request, tool, resultContainer)); - if (resultContainer[0] === null) { - // The guard did not return anything, thus we will report this error. - throw makeTitledPrettyError("Tool call guard did not allow or deny the tool call.", text ` - The \`guardToolCall\` handler must call one of the methods on the controller - to allow or deny the tool call. - `, stack); - } - const guardResult = resultContainer[0]; - const guardResultType = guardResult.type; - switch (guardResultType) { - case "allow": { - // 1. The guard allowed the tool call without overriding the parameters. In this - // case, we will use the original parameters. - break; - } - case "allowAndOverrideParameters": { - // 2. The guard allowed the tool call and provided new parameters. In this case, - // we will use the new parameters. This will update the request in-place. - pushedRequest.arguments = guardResult.parameters; - break; - } - case "deny": { - // 3. The guard denied the tool call. In this case, we will early return and not - // call the tool. - toolCallResults.push({ - index: toolCallIndex, - data: { - type: "toolCallResult", - toolCallId: request.id, - content: JSON.stringify({ - error: guardResult.reason, - }), - }, - }); - return; - } - } - } - // Now we need to call RequestFinalized - safeCallCallback(logger, "onToolCallRequestFinalized", baseOpts.onToolCallRequestFinalized, [ - predictionsPerformed, - callId, - { - toolCallRequest: request, - rawContent, - }, - ]); - let result; - try { - result = await tool.implementation(pushedRequest.arguments ?? {}, toolCallContext); - } - catch (error) { - if (!(error instanceof UnimplementedToolError)) { - throw error; - } - hasCalledUnimplementedTool = true; - } - let resultString; - if (result === undefined) { - resultString = "undefined"; - } - else { - try { - resultString = JSON.stringify(result); - } - catch (error) { - throw makePrettyError(`Return value of tool ${tool.name} cannot be converted to JSON.`, stack); - } - } - toolCallResults.push({ - index: toolCallIndex, - data: { - type: "toolCallResult", - toolCallId: request.id, - content: resultString, - }, - }); - }, abortController.signal) - .catch(finalReject)); - }, - handleToolCallGenerationFailed: (error, rawContent) => { - isGeneratingToolCall = false; - const toolCallRequestError = new ToolCallRequestError(error.message, rawContent); - toolCallPromises.push(internalHandleInvalidToolCallRequest(toolCallRequestError, - // We don't have a request in this because the model has failed miserably. - undefined, - // Tool call index. Doesn't matter because if there is no request, there cannot be - // a replacement. - 0).catch(finalReject)); - safeCallCallback(logger, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [ - predictionsPerformed, - currentCallId, - toolCallRequestError, - ]); - }, - handlePredictionEnd: endPacket => { - const predictionResult = makePredictionResult({ - endPacket, - content: contentArray.join(""), - reasoningContent: reasoningContentArray.join(""), - nonReasoningContent: nonReasoningContentArray.join(""), - predictionsPerformed, - }); - safeCallCallback(logger, "onPredictionCompleted", baseOpts.onPredictionCompleted, [ - predictionResult, - ]); - predictionResolve(); - }, - handleError: error => { - if (isGeneratingToolCall) { - const toolCallRequestError = new ToolCallRequestError(`Generation failed: ${error.message}`, undefined); - // Notify tool call generation failure. - isGeneratingToolCall = false; - safeCallCallback(logger, "onToolCallRequestFailure", baseOpts.onToolCallRequestFailure, [ - predictionsPerformed, - currentCallId, - toolCallRequestError, - ]); - } - finished = true; - predictionReject(error); - }, - }); - const abortListener = () => { - if (finished) { - return; - } - finished = true; - roundAbortController.abort(abortController.signal.reason); - }; - abortController.signal.addEventListener("abort", abortListener); - predictionPromise - .then(() => { - // Append and emit the assistant message. - const assistantMessage = ChatMessage.from({ - role: "assistant", - content: [ - { - type: "text", - text: contentArray.join(""), - }, - ...toolCallRequests.map(toolCallRequest => ({ - type: "toolCallRequest", - toolCallRequest, - })), - ], - }); - mutableChat.append(assistantMessage.asMutableCopy()); - safeCallCallback(logger, "onMessage", baseOpts.onMessage, [assistantMessage]); - }) - // When the prediction is completed, wait for all tool calls to be completed. - .then(() => Promise.all(toolCallPromises)) - .then(() => finalResolve(), finalReject); - await finalPromise; - shouldContinue = false; - if (toolCallResults.length > 0) { - // Sort the tool call results back into the order they were requested. - toolCallResults.sort((a, b) => a.index - b.index); - // Emit the tool call results. - const toolMessage = ChatMessage.from({ - role: "tool", - content: toolCallResults.map(r => r.data), - }); - mutableChat.append(toolMessage.asMutableCopy()); - safeCallCallback(logger, "onMessage", baseOpts.onMessage, [toolMessage]); - shouldContinue = true; - } - safeCallCallback(logger, "onRoundEnd", baseOpts.onRoundEnd, [predictionsPerformed]); - predictionsPerformed++; - // Don't continue if we've reached the max predictions. - if (baseOpts.maxPredictionRounds !== undefined && - predictionsPerformed >= baseOpts.maxPredictionRounds) { - shouldContinue = false; - } - shouldContinue &&= !hasCalledUnimplementedTool; // Stop loop if unimplemented tool was called. - } while (shouldContinue); - return new ActResult(predictionsPerformed, (performance.now() - startTime) / 1_000); -} - -/** - * Represents the result of an LLM prediction. - * - * The most notably property is {@link PredictionResult#content}, which contains the generated text. - * Additionally, the {@link PredictionResult#stats} property contains statistics about the - * prediction. - * - * @public - */ -class PredictionResult { - constructor( - /** - * The newly generated text as predicted by the LLM. - */ - content, - /** - * Part of the generated text that is "reasoning" content. For example, text inside - * tags. You can adjust what is considered reasoning content by changing the `reasoningParsing` - * field when performing the prediction. - */ - reasoningContent, - /** - * Part of the generated that is not "reasoning" content. For example, text outside - * tags. You can adjust what is considered reasoning content by changing the `reasoningParsing` - * field when performing the prediction. - */ - nonReasoningContent, - /** - * Statistics about the prediction. - */ - stats, - /** - * Information about the model used for the prediction. - */ - modelInfo, - /** - * The 0-indexed round index of the prediction in multi-round scenario (for example, - * `.act`). Will always be 0 for single-round predictions such as `.respond` or `.complete`. - */ - roundIndex, - /** - * The configuration used to load the model. Not stable, subject to change. - * - * @deprecated [DEP-RAW-CONFIG] Raw config access API is still in active development. Stay - * turned for updates. - */ - loadConfig, - /** - * The configuration used for the prediction. Not stable, subject to change. - * - * @deprecated [DEP-RAW-CONFIG] Raw config access API is still in active development. Stay - * turned for updates. - */ - predictionConfig) { - this.content = content; - this.reasoningContent = reasoningContent; - this.nonReasoningContent = nonReasoningContent; - this.stats = stats; - this.modelInfo = modelInfo; - this.roundIndex = roundIndex; - this.loadConfig = loadConfig; - this.predictionConfig = predictionConfig; - } -} -/** - * Result of a typed structured prediction. In addition to a regular {@link PredictionResult}, there - * is one additional field: {@link StructuredPredictionResult#parsed}. - * - * To enable typed structured prediction, you should pass in a zod schema as the structured option - * when constructing the prediction config. - * - * @public - */ -class StructuredPredictionResult extends PredictionResult { - constructor(content, reasoningContent, nonReasoningContent, stats, modelInfo, roundIndex, loadConfig, predictionConfig, - /** - * Parsed result of the structured output. - */ - parsed) { - super(content, reasoningContent, nonReasoningContent, stats, modelInfo, roundIndex, loadConfig, predictionConfig); - this.parsed = parsed; - } -} - -/** - * Represents an ongoing prediction. - * - * Note, this class is Promise-like, meaning you can use it as a promise. It resolves to a - * {@link PredictionResult}, which contains the generated text in the `.content` property. Example - * usage: - * - * ```typescript - * const result = await model.complete("When will The Winds of Winter be released?"); - * console.log(result.content); - * ``` - * - * Or you can use instances methods like `then` and `catch` to handle the result or error of the - * prediction. - * - * ```typescript - * model.complete("When will The Winds of Winter be released?") - * .then(result =\> console.log(result.content)) - * .catch(error =\> console.error(error)); - * ``` - * - * Alternatively, you can also stream the result (process the results as more content is being - * generated). For example: - * - * ```typescript - * for await (const { content } of model.complete("When will The Winds of Winter be released?")) { - * process.stdout.write(content); - * } - * ``` - * - * @public - */ -class OngoingPrediction extends StreamablePromise { - async collect(fragments) { - const content = fragments.map(({ content }) => content).join(""); - const reasoningContent = fragments - .filter(({ isStructural }) => !isStructural) - .filter(({ reasoningType }) => reasoningType === "reasoning") - .map(({ content }) => content) - .join(""); - const nonReasoningContent = fragments - .filter(({ isStructural }) => !isStructural) - .filter(({ reasoningType }) => reasoningType === "none") - .map(({ content }) => content) - .join(""); - if (this.stats === null) { - throw new Error("Stats should not be null"); - } - if (this.modelInfo === null) { - throw new Error("Model info should not be null"); - } - if (this.loadModelConfig === null) { - throw new Error("Load model config should not be null"); - } - if (this.predictionConfig === null) { - throw new Error("Prediction config should not be null"); - } - if (this.parser === null) { - return new PredictionResult(content, reasoningContent, nonReasoningContent, this.stats, this.modelInfo, - // Currently, OngoingPrediction is only used with single round predictions. Thus always - // use roundIndex 0. - /* roundIndex */ 0, this.loadModelConfig, this.predictionConfig); - } - else { - return new StructuredPredictionResult(content, reasoningContent, nonReasoningContent, this.stats, this.modelInfo, - // Currently, OngoingPrediction is only used with single round predictions. Thus always - // use roundIndex 0. - /* predictionIndex */ 0, this.loadModelConfig, this.predictionConfig, this.parser(content)); - } - } - constructor(onCancel, parser) { - super(); - this.onCancel = onCancel; - this.parser = parser; - this.stats = null; - this.modelInfo = null; - this.loadModelConfig = null; - this.predictionConfig = null; - } - /** @internal */ - static create(onCancel, parser) { - const ongoingPrediction = new OngoingPrediction(onCancel, parser); - const finished = (stats, modelInfo, loadModelConfig, predictionConfig) => { - ongoingPrediction.stats = stats; - ongoingPrediction.modelInfo = modelInfo; - ongoingPrediction.loadModelConfig = loadModelConfig; - ongoingPrediction.predictionConfig = predictionConfig; - ongoingPrediction.finished(); - }; - const failed = (error) => ongoingPrediction.finished(error); - const push = (fragment) => ongoingPrediction.push(fragment); - return { ongoingPrediction, finished, failed, push }; - } - /** - * Get the final prediction results. If you have been streaming the results, awaiting on this - * method will take no extra effort, as the results are already available in the internal buffer. - * - * Example: - * - * ```typescript - * const prediction = model.complete("When will The Winds of Winter be released?"); - * for await (const { content } of prediction) { - * process.stdout.write(content); - * } - * const result = await prediction.result(); - * console.log(result.stats); - * ``` - * - * Technically, awaiting on this method is the same as awaiting on the instance itself: - * - * ```typescript - * await prediction.result(); - * - * // Is the same as: - * - * await prediction; - * ``` - */ - async result() { - return (await this); - } - /** - * Cancels the prediction. This will stop the prediction with stop reason `userStopped`. See - * {@link LLMPredictionStopReason} for other reasons that a prediction might stop. - */ - async cancel() { - this.onCancel(); - } -} - -const llmPredictionOptsSchema = llmPredictionConfigInputSchema.extend({ - onPromptProcessingProgress: z.function().optional(), - onFirstToken: z.function().optional(), - onPredictionFragment: z.function().optional(), - onToolCallRequestStart: z.function().optional(), - onToolCallRequestNameReceived: z.function().optional(), - onToolCallRequestArgumentFragmentGenerated: z.function().optional(), - onToolCallRequestEnd: z.function().optional(), - onToolCallRequestFailure: z.function().optional(), - signal: z.instanceof(AbortSignal).optional(), - preset: z.string().optional(), -}); -function splitPredictionOpts(opts) { - const { onPromptProcessingProgress, onFirstToken, onPredictionFragment, onToolCallRequestStart, onToolCallRequestNameReceived, onToolCallRequestArgumentFragmentGenerated, onToolCallRequestEnd, onToolCallRequestFailure, signal, preset, ...config } = opts; - return [ - config, - { - onPromptProcessingProgress, - onFirstToken, - onPredictionFragment, - onToolCallRequestStart, - onToolCallRequestNameReceived, - onToolCallRequestArgumentFragmentGenerated, - onToolCallRequestEnd, - onToolCallRequestFailure, - signal, - preset, - }, - ]; -} -const llmRespondOptsSchema = llmPredictionOptsSchema.extend({ - onMessage: z.function().optional(), - onToolCallRequestStart: z.function().optional(), - onToolCallRequestNameReceived: z.function().optional(), - onToolCallRequestArgumentFragmentGenerated: z.function().optional(), - onToolCallRequestEnd: z.function().optional(), - onToolCallRequestFailure: z.function().optional(), -}); -/** - * Split a llmRespondOpts into its parts. - */ -function splitRespondOpts(opts) { - const { onMessage, ...remaining } = opts; - const [config, llmPredictionOpts] = splitPredictionOpts(remaining); - return [ - config, - llmPredictionOpts, - { - onMessage, - }, - ]; -} -const llmActionOptsSchema = llmPredictionConfigInputSchema - .extend(llmActBaseOptsSchema.shape) - .extend({ - preset: z.string().optional(), -}); -function splitActOpts(opts) { - const { onFirstToken, onPredictionFragment, onMessage, onRoundStart, onRoundEnd, onPredictionCompleted, onPromptProcessingProgress, onToolCallRequestStart, onToolCallRequestNameReceived, onToolCallRequestArgumentFragmentGenerated, onToolCallRequestEnd, onToolCallRequestFinalized, onToolCallRequestFailure, onToolCallRequestDequeued, guardToolCall, handleInvalidToolRequest, maxPredictionRounds, signal, preset, allowParallelToolExecution, ...config } = opts; - return [ - config, - { - onFirstToken, - onPredictionFragment, - onMessage, - onRoundStart, - onRoundEnd, - onPredictionCompleted, - onPromptProcessingProgress, - onToolCallRequestStart, - onToolCallRequestNameReceived, - onToolCallRequestArgumentFragmentGenerated, - onToolCallRequestEnd, - onToolCallRequestFinalized, - onToolCallRequestFailure, - onToolCallRequestDequeued, - guardToolCall, - handleInvalidToolRequest, - maxPredictionRounds, - signal, - preset, - allowParallelToolExecution, - }, - ]; -} -const noFormattingTemplate = text ` - {% for message in messages %}{{ message['content'] }}{% endfor %} -`; -/** - * This represents a set of requirements for a model. It is not tied to a specific model, but rather - * to a set of requirements that a model must satisfy. - * - * For example, if you got the model via `client.llm.model("my-identifier")`, you will get a - * `LLMDynamicHandle` for the model with the identifier `my-identifier`. If the model is unloaded, - * and another model is loaded with the same identifier, using the same `LLMDynamicHandle` will use - * the new model. - * - * @public - */ -class LLMDynamicHandle extends DynamicHandle { - /** - * Don't construct this on your own. Use {@link LLMNamespace#model} or - * {@link LLMNamespace#createDynamicHandle} instead. - * - * @internal - */ - constructor( - /** @internal */ - port, - /** @internal */ - specifier, - /** @internal */ - validator, - /** @internal */ - logger = new SimpleLogger(`LLMModel`)) { - super(port, specifier); - this.validator = validator; - this.logger = logger; - /** @internal */ - this.internalKVConfigStack = { layers: [] }; - /** @internal */ - this.internalIgnoreServerSessionConfig = undefined; - } - /** @internal */ - internalPredict(history, predictionConfigStack, cancelEvent, extraOpts, onFragment, onFinished, onError) { - let finished = false; - let firstTokenTriggered = false; - let currentCallId = null; - let receivedEagerToolNameReporting = false; - let receivedToolArgumentsStreaming = false; - const channel = this.port.createChannel("predict", { - modelSpecifier: this.specifier, - history, - predictionConfigStack, - fuzzyPresetIdentifier: extraOpts.preset, - ignoreServerSessionConfig: this.internalIgnoreServerSessionConfig, - }, message => { - switch (message.type) { - case "fragment": { - if (!firstTokenTriggered) { - firstTokenTriggered = true; - safeCallCallback(this.logger, "onFirstToken", extraOpts.onFirstToken, []); - } - safeCallCallback(this.logger, "onFragment", extraOpts.onPredictionFragment, [ - message.fragment, - ]); - onFragment(message.fragment); - break; - } - case "promptProcessingProgress": { - safeCallCallback(this.logger, "onPromptProcessingProgress", extraOpts.onPromptProcessingProgress, [message.progress]); - break; - } - case "toolCallGenerationStart": { - if (currentCallId === null) { - currentCallId = 0; - } - else { - currentCallId++; - } - receivedEagerToolNameReporting = false; - receivedToolArgumentsStreaming = false; - safeCallCallback(this.logger, "onToolCallGenerationStart", extraOpts.onToolCallRequestStart, [currentCallId, { toolCallId: message.toolCallId }]); - break; - } - case "toolCallGenerationNameReceived": { - receivedEagerToolNameReporting = true; - safeCallCallback(this.logger, "onToolCallGenerationNameReceived", extraOpts.onToolCallRequestNameReceived, [currentCallId ?? -1, message.name]); - break; - } - case "toolCallGenerationArgumentFragmentGenerated": { - receivedToolArgumentsStreaming = true; - safeCallCallback(this.logger, "onToolCallGenerationArgumentFragmentGenerated", extraOpts.onToolCallRequestArgumentFragmentGenerated, [currentCallId ?? -1, message.content]); - break; - } - case "toolCallGenerationEnd": { - if (!receivedEagerToolNameReporting) { - // If eager name reporting not received, report it. - safeCallCallback(this.logger, "onToolCallGenerationNameReceived", extraOpts.onToolCallRequestNameReceived, [currentCallId ?? -1, message.toolCallRequest.name]); - } - if (!receivedToolArgumentsStreaming) { - // If arguments streaming not received, just pretend we have received all the - // arguments as a single JSON - safeCallCallback(this.logger, "onToolCallGenerationArgumentFragmentGenerated", extraOpts.onToolCallRequestArgumentFragmentGenerated, [ - currentCallId ?? -1, - JSON.stringify(message.toolCallRequest.arguments ?? {}, null, 2), - ]); - } - safeCallCallback(this.logger, "onToolCallGenerationEnd", extraOpts.onToolCallRequestEnd, [ - currentCallId ?? -1, - { toolCallRequest: message.toolCallRequest, rawContent: message.rawContent }, - ]); - break; - } - case "toolCallGenerationFailed": { - const toolCallRequestError = new ToolCallRequestError(fromSerializedError(message.error).message, message.rawContent); - safeCallCallback(this.logger, "onToolCallGenerationFailed", extraOpts.onToolCallRequestFailure, [currentCallId ?? -1, toolCallRequestError]); - break; - } - case "success": { - finished = true; - onFinished(message.stats, message.modelInfo, message.loadModelConfig, message.predictionConfig); - break; - } - } - }, { stack: getCurrentStack(2) }); - cancelEvent.subscribeOnce(() => { - if (finished) { - return; - } - channel.send({ type: "cancel" }); - }); - channel.onError.subscribeOnce(onError); - } - predictionConfigInputToKVConfig(config) { - let structuredField = undefined; - if (typeof config.structured?.parse === "function") { - structuredField = { - type: "json", - jsonSchema: zodToJsonSchema(config.structured), - }; - } - else { - structuredField = config.structured; - } - const convertedConfig = { - ...config, - structured: structuredField, - }; - return llmPredictionConfigToKVConfig(convertedConfig); - } - createZodParser(zodSchema) { - return content => { - try { - return zodSchema.parse(JSON.parse(content)); - } - catch (e) { - throw new Error("Failed to parse structured output: " + JSON.stringify(content), { - cause: e, - }); - } - }; - } - /** - * Use the loaded model to predict text. - * - * This method returns an {@link OngoingPrediction} object. An ongoing prediction can be used as a - * promise (if you only care about the final result) or as an async iterable (if you want to - * stream the results as they are being generated). - * - * Example usage as a promise (Resolves to a {@link PredictionResult}): - * - * ```typescript - * const result = await model.complete("When will The Winds of Winter be released?"); - * console.log(result.content); - * ``` - * - * Or - * - * ```typescript - * model.complete("When will The Winds of Winter be released?") - * .then(result =\> console.log(result.content)) - * .catch(error =\> console.error(error)); - * ``` - * - * Example usage as an async iterable (streaming): - * - * ```typescript - * for await (const { content } of model.complete("When will The Winds of Winter be released?")) { - * process.stdout.write(content); - * } - * ``` - * - * If you wish to stream the result, but also getting the final prediction results (for example, - * you wish to get the prediction stats), you can use the following pattern: - * - * ```typescript - * const prediction = model.complete("When will The Winds of Winter be released?"); - * for await (const { content } of prediction) { - * process.stdout.write(content); - * } - * const result = await prediction.result(); - * console.log(result.stats); - * ``` - * - * @param prompt - The prompt to use for prediction. - * @param opts - Options for the prediction. - */ - complete(prompt, opts = {}) { - const stack = getCurrentStack(1); - [prompt, opts] = this.validator.validateMethodParamsOrThrow("model", "complete", ["prompt", "opts"], [z.string(), llmPredictionOptsSchema], [prompt, opts], stack); - const [config, extraOpts] = splitPredictionOpts(opts); - const [cancelEvent, emitCancelEvent] = BufferedEvent.create(); - if (extraOpts.signal !== undefined) { - if (extraOpts.signal.aborted) { - // If the signal is already aborted, we need to cancel the prediction immediately. - emitCancelEvent(); - } - else { - extraOpts.signal.addEventListener("abort", () => { - emitCancelEvent(); - }, { once: true }); - } - } - const zodSchemaParseResult = zodSchemaSchema.safeParse(config.structured); - const { ongoingPrediction, finished, failed, push } = OngoingPrediction.create(emitCancelEvent, !zodSchemaParseResult.success ? null : this.createZodParser(zodSchemaParseResult.data)); - this.internalPredict(this.resolveCompletionContext(prompt), { - layers: [ - ...this.internalKVConfigStack.layers, - { - layerName: "apiOverride", - config: this.predictionConfigInputToKVConfig({ - // If the user did not specify `stopStrings`, we default to an empty array. This is to - // prevent the model from using the value set in the preset. - stopStrings: [], - ...config, - }), - }, - { - layerName: "completeModeFormatting", - config: llmSharedPredictionConfigSchematics.buildPartialConfig({ - promptTemplate: { - type: "jinja", - jinjaPromptTemplate: { - template: noFormattingTemplate, - }, - stopStrings: [], - }, - }), - }, - ], - }, cancelEvent, extraOpts, fragment => push(fragment), (stats, modelInfo, loadModelConfig, predictionConfig) => finished(stats, modelInfo, loadModelConfig, predictionConfig), error => failed(error)); - return ongoingPrediction; - } - resolveCompletionContext(contextInput) { - return { - messages: [ - { - role: "user", - content: [{ type: "text", text: contextInput }], - }, - ], - }; - } - /** - * Use the loaded model to generate a response based on the given history. - * - * This method returns an {@link OngoingPrediction} object. An ongoing prediction can be used as a - * promise (if you only care about the final result) or as an async iterable (if you want to - * stream the results as they are being generated). - * - * Example usage as a promise (Resolves to a {@link PredictionResult}): - * - * ```typescript - * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }]; - * const result = await model.respond(history); - * console.log(result.content); - * ``` - * - * Or - * - * ```typescript - * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }]; - * model.respond(history) - * .then(result => console.log(result.content)) - * .catch(error => console.error(error)); - * ``` - * - * Example usage as an async iterable (streaming): - * - * ```typescript - * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }]; - * for await (const { content } of model.respond(history)) { - * process.stdout.write(content); - * } - * ``` - * - * If you wish to stream the result, but also getting the final prediction results (for example, - * you wish to get the prediction stats), you can use the following pattern: - * - * ```typescript - * const history = [{ role: 'user', content: "When will The Winds of Winter be released?" }]; - * const prediction = model.respond(history); - * for await (const { content } of prediction) { - * process.stdout.write(content); - * } - * const result = await prediction; - * console.log(result.stats); - * ``` - * - * @param chat - The LLMChatHistory array to use for generating a response. - * @param opts - Options for the prediction. - */ - respond(chat, opts = {}) { - const stack = getCurrentStack(1); - [chat, opts] = this.validator.validateMethodParamsOrThrow("model", "respond", ["chat", "opts"], [chatHistoryLikeSchema, llmRespondOptsSchema], [chat, opts], stack); - const [cancelEvent, emitCancelEvent] = BufferedEvent.create(); - const [config, predictionOpts, respondOpts] = splitRespondOpts(opts); - if (predictionOpts.signal !== undefined) { - if (predictionOpts.signal.aborted) { - // If the signal is already aborted, we need to cancel the prediction immediately. - emitCancelEvent(); - } - else { - predictionOpts.signal.addEventListener("abort", () => { - emitCancelEvent(); - }, { once: true }); - } - } - const zodSchemaParseResult = zodSchemaSchema.safeParse(config.structured); - const { ongoingPrediction, finished, failed, push } = OngoingPrediction.create(emitCancelEvent, !zodSchemaParseResult.success ? null : this.createZodParser(zodSchemaParseResult.data)); - this.internalPredict(accessMaybeMutableInternals(Chat.from(chat))._internalGetData(), addKVConfigToStack(this.internalKVConfigStack, "apiOverride", this.predictionConfigInputToKVConfig(config)), cancelEvent, predictionOpts, fragment => push(fragment), (stats, modelInfo, loadModelConfig, predictionConfig) => finished(stats, modelInfo, loadModelConfig, predictionConfig), error => failed(error)); - ongoingPrediction.then(result => { - // Call the onMessage callback with the result. - safeCallCallback(this.logger, "onMessage", respondOpts.onMessage, [ - ChatMessage.create("assistant", result.content), - ]); - }, () => { }); - return ongoingPrediction; - } - /** - * @param chat - The LLMChatHistory array to act from as the base - * @param tool - An array of tools that the model can use during the operation. You can create - * tools by using the `tool` function. - * @param opts - Additional options - * - * Example: - * - * ``` - * import { LMStudioClient, tool } from "@lmstudio/sdk"; - * import { z } from "zod"; - * - * const client = new LMStudioClient(); - * const model = await client.llm.model(); - * - * const additionTool = tool({ - * name: "add", - * description: "Add two numbers", - * parameters: { - * a: z.number(), - * b: z.number(), - * }, - * implementation: ({ a, b }) => a + b, - * }); - * - * await model.act("What is 1234 + 4321?", [additionTool], { - * onMessage: message => console.log(message.toString()), - * }); - * ``` - */ - async act(chat, tools, opts = {}) { - const startTime = performance.now(); - const stack = getCurrentStack(1); - [chat, opts] = this.validator.validateMethodParamsOrThrow("model", "act", ["chat", "opts"], [chatHistoryLikeSchema, llmActionOptsSchema], [chat, opts], stack); - const [config, { preset, ...baseOpts }] = splitActOpts(opts); - if (config.structured !== undefined && - config.structured.type !== "none" && - tools.length > 0) { - throw makePrettyError("Structured output is currently not supported in .act() when there are tools.", stack); - } - if (config.structured !== undefined && config.structured.parse !== undefined) { - throw makePrettyError("zod schema is not supported in .act().", stack); - } - if (config.rawTools !== undefined) { - throw makePrettyError("`rawTools` is not supported in act. Use `tools` instead", stack); - } - let rawTools; - if (tools.length === 0) { - rawTools = { type: "none" }; - } - else { - rawTools = { - type: "toolArray", - tools: tools.map(toolToLLMTool), - }; - } - const configWithTools = addKVConfigToStack(this.internalKVConfigStack, "apiOverride", this.predictionConfigInputToKVConfig({ - ...config, - rawTools, - })); - const configWithoutTools = addKVConfigToStack(this.internalKVConfigStack, "apiOverride", this.predictionConfigInputToKVConfig({ - ...config, - rawTools: { type: "none" }, - })); - return await internalAct(chat, tools, baseOpts, stack, this.logger, startTime, - // Implementation of the prediction function. This performs the prediction by creating a - // predict channel and redirect the messages to the appropriate handlers. - async ({ allowTools, history, signal, handleFragment, handlePromptProcessingProgress, handleToolCallGenerationStart, handleToolCallGenerationNameReceived, handleToolCallGenerationArgumentFragmentGenerated, handleToolCallGenerationEnd, handleToolCallGenerationFailed, handlePredictionEnd, handleError, }) => { - // Use predict channel - const channel = this.port.createChannel("predict", { - modelSpecifier: this.specifier, - history, - predictionConfigStack: allowTools ? configWithTools : configWithoutTools, - fuzzyPresetIdentifier: preset, - ignoreServerSessionConfig: this.internalIgnoreServerSessionConfig, - }, message => { - const messageType = message.type; - switch (messageType) { - case "fragment": { - handleFragment(message.fragment); - break; - } - case "promptProcessingProgress": { - handlePromptProcessingProgress(message.progress); - break; - } - case "toolCallGenerationStart": { - handleToolCallGenerationStart(message.toolCallId); - break; - } - case "toolCallGenerationNameReceived": { - handleToolCallGenerationNameReceived(message.name); - break; - } - case "toolCallGenerationArgumentFragmentGenerated": { - handleToolCallGenerationArgumentFragmentGenerated(message.content); - break; - } - case "toolCallGenerationEnd": { - handleToolCallGenerationEnd(message.toolCallRequest, message.rawContent); - break; - } - case "toolCallGenerationFailed": { - handleToolCallGenerationFailed(fromSerializedError(message.error), message.rawContent); - break; - } - case "success": { - // This is the end of the prediction. The following object is passed to the - // `makePredictionResult` function to create the final PredictionResult. (see below) - handlePredictionEnd({ - stats: message.stats, - modelInfo: message.modelInfo, - loadModelConfig: message.loadModelConfig, - predictionConfig: message.predictionConfig, - }); - break; - } - } - }, { stack }); - if (signal.aborted) { - // If the signal is already aborted, we need to cancel the prediction immediately. - channel.send({ type: "cancel" }); - } - else { - signal.addEventListener("abort", () => { - channel.send({ type: "cancel" }); - }, { once: true }); - } - channel.onError.subscribeOnce(handleError); - }, ({ endPacket, content, nonReasoningContent, reasoningContent, predictionsPerformed }) => { - return new PredictionResult(content, reasoningContent, nonReasoningContent, endPacket.stats, endPacket.modelInfo, predictionsPerformed, endPacket.loadModelConfig, endPacket.predictionConfig); - }); - } - async getContextLength() { - const stack = getCurrentStack(1); - const loadConfig = await this.getLoadConfig(stack); - return llmSharedLoadConfigSchematics.access(loadConfig, "contextLength"); - } - async applyPromptTemplate(history, opts = {}) { - const stack = getCurrentStack(1); - [history, opts] = this.validator.validateMethodParamsOrThrow("model", "applyPromptTemplate", ["history", "opts"], [chatHistoryLikeSchema, llmApplyPromptTemplateOptsSchema], [history, opts], stack); - return (await this.port.callRpc("applyPromptTemplate", { - specifier: this.specifier, - history: accessMaybeMutableInternals(Chat.from(history))._internalGetData(), - predictionConfigStack: this.internalKVConfigStack, - opts, - }, { - stack, - })).formatted; - } - async tokenize(inputString) { - const stack = getCurrentStack(1); - inputString = this.validator.validateMethodParamOrThrow("model", "tokenize", "inputString", z.string().or(z.array(z.string())), inputString, stack); - if (Array.isArray(inputString)) { - return (await Promise.all(inputString.map(s => this.port.callRpc("tokenize", { specifier: this.specifier, inputString: s }, { stack })))).map(r => r.tokens); - } - else { - return (await this.port.callRpc("tokenize", { - specifier: this.specifier, - inputString, - }, { stack })).tokens; - } - } - async countTokens(inputString) { - const stack = getCurrentStack(1); - inputString = this.validator.validateMethodParamOrThrow("model", "countTokens", "inputString", z.string(), inputString, stack); - return (await this.port.callRpc("countTokens", { - specifier: this.specifier, - inputString, - }, { stack })).tokenCount; - } - /** - * Starts to eagerly preload a draft model. This is useful when you want a draft model to be ready - * for speculative decoding. - * - * Preloading is done on a best-effort basis and may not always succeed. It is not guaranteed that - * the draft model is actually loaded when this method returns. Thus, this method should only be - * used as an optimization. The actual draft model used only depends on the parameter set when - * performing the prediction. - */ - async unstable_preloadDraftModel(draftModelKey) { - const stack = getCurrentStack(1); - draftModelKey = this.validator.validateMethodParamOrThrow("model", "unstable_preloadDraftModel", "draftModelKey", z.string(), draftModelKey, stack); - await this.port.callRpc("preloadDraftModel", { specifier: this.specifier, draftModelKey }, { stack }); - } -} - -/** - * Represents a specific loaded LLM. Most LLM related operations are inherited from - * {@link LLMDynamicHandle}. - * - * @public - */ -class LLM extends LLMDynamicHandle { - /** @internal */ - constructor(llmPort, info, validator, logger = new SimpleLogger(`LLM`)) { - const specifier = { - type: "instanceReference", - instanceReference: info.instanceReference, - }; - super(llmPort, specifier, validator, logger); - this.identifier = info.identifier; - this.path = info.path; - this.modelKey = info.modelKey; - this.format = info.format; - this.displayName = info.displayName; - this.sizeBytes = info.sizeBytes; - this.vision = info.vision; - this.trainedForToolUse = info.trainedForToolUse; - } - async unload() { - const stack = getCurrentStack(1); - await this.port.callRpc("unloadModel", { identifier: this.identifier }, { stack }); - } - async getModelInfo() { - const info = await super.getModelInfo(); - if (info === undefined) { - const stack = getCurrentStack(1); - throw makePrettyError("This model has already been unloaded", stack); - } - return info; - } -} - -/** @public */ -class LLMNamespace extends ModelNamespace { - constructor() { - super(...arguments); - /** @internal */ - this.namespace = "llm"; - /** @internal */ - this.defaultLoadConfig = {}; - /** @internal */ - this.loadModelConfigSchema = llmLoadModelConfigSchema; - } - /** @internal */ - loadConfigToKVConfig(config) { - return llmLlamaMoeLoadConfigSchematics.buildPartialConfig({ - "contextLength": config.contextLength, - "llama.evalBatchSize": config.evalBatchSize, - "llama.acceleration.offloadRatio": config.gpu?.ratio, - "numCpuExpertLayersRatio": config.gpu?.numCpuExpertLayersRatio, - "load.gpuSplitConfig": convertGPUSettingToGPUSplitConfig(config.gpu), - "llama.flashAttention": config.flashAttention, - "llama.ropeFrequencyBase": numberToCheckboxNumeric(config.ropeFrequencyBase, 0, 0), - "llama.ropeFrequencyScale": numberToCheckboxNumeric(config.ropeFrequencyScale, 0, 0), - "llama.keepModelInMemory": config.keepModelInMemory, - "seed": numberToCheckboxNumeric(config.seed, -1, 0), - "llama.useFp16ForKVCache": config.useFp16ForKVCache, - "llama.tryMmap": config.tryMmap, - "numExperts": config.numExperts, - "llama.kCacheQuantizationType": cacheQuantizationTypeToCheckbox({ - value: config.llamaKCacheQuantizationType, - falseDefault: "f16", - }), - "llama.vCacheQuantizationType": cacheQuantizationTypeToCheckbox({ - value: config.llamaVCacheQuantizationType, - falseDefault: "f16", - }), - }); - } - /** @internal */ - createDomainSpecificModel(port, info, validator, logger) { - return new LLM(port, info, validator, logger); - } - /** @internal */ - createDomainDynamicHandle(port, specifier, validator, logger) { - return new LLMDynamicHandle(port, specifier, validator, logger); - } -} - -/** - * Represents the result of a prediction from a generator plugin. - * - * The most notably property is {@link GeneratorPredictionResult#content}, which contains the - * generated text. - * - * @public - * @experimental [EXP-GEN-PREDICT] Using generator plugins programmatically is still in development. - * This may change in the future without warning. - */ -class GeneratorPredictionResult { - constructor( - /** - * The newly generated text as generated by the generator plugin. - */ - content, - /** - * Part of the generated text that is "reasoning" content. For example, text inside - * tags. The generator is responsible for determining what is considered reasoning content. - */ - reasoningContent, - /** - * Part of the generated text that is not "reasoning" content. For example, text outside - * tags. The generator is responsible for determining what is considered reasoning - * content. - */ - nonReasoningContent, - /** - * The identifier of the plugin that generated this result. - */ - pluginIdentifier) { - this.content = content; - this.reasoningContent = reasoningContent; - this.nonReasoningContent = nonReasoningContent; - this.pluginIdentifier = pluginIdentifier; - } -} - -/** - * Represents an ongoing prediction from a generator. - * - * Note, this class is Promise-like, meaning you can use it as a promise. It resolves to a - * {@link GeneratorPredictionResult}, which contains the generated text in the `.content` property. Example - * usage: - * - * ```typescript - * const result = await generator.complete("When will The Winds of Winter be released?"); - * console.log(result.content); - * ``` - * - * Or you can use instances methods like `then` and `catch` to handle the result or error of the - * prediction. - * - * ```typescript - * generator.complete("When will The Winds of Winter be released?") - * .then(result =\> console.log(result.content)) - * .catch(error =\> console.error(error)); - * ``` - * - * Alternatively, you can also stream the result (process the results as more content is being - * generated). For example: - * - * ```typescript - * for await (const { content } of generator.complete("When will The Winds of Winter be released?")) { - * process.stdout.write(content); - * } - * ``` - * - * @public - * @experimental [EXP-GEN-PREDICT] Using generator plugins programmatically is still in development. - * This may change in the future without warning. - */ -class OngoingGeneratorPrediction extends StreamablePromise { - async collect(fragments) { - const content = fragments.map(({ content }) => content).join(""); - const reasoningContent = fragments - .filter(({ isStructural }) => !isStructural) - .filter(({ reasoningType }) => reasoningType === "reasoning") - .map(({ content }) => content) - .join(""); - const nonReasoningContent = fragments - .filter(({ isStructural }) => !isStructural) - .filter(({ reasoningType }) => reasoningType === "none") - .map(({ content }) => content) - .join(""); - return new GeneratorPredictionResult(content, reasoningContent, nonReasoningContent, this.pluginIdentifier); - } - constructor(pluginIdentifier, onCancel) { - super(); - this.pluginIdentifier = pluginIdentifier; - this.onCancel = onCancel; - } - /** @internal */ - static create(pluginIdentifier, onCancel) { - const ongoingPrediction = new OngoingGeneratorPrediction(pluginIdentifier, onCancel); - const finished = () => ongoingPrediction.finished(); - const failed = (error) => ongoingPrediction.finished(error); - const push = (fragment) => ongoingPrediction.push(fragment); - return { ongoingPrediction, finished, failed, push }; - } - /** - * Get the final prediction results. If you have been streaming the results, awaiting on this - * method will take no extra effort, as the results are already available in the internal buffer. - * - * Example: - * - * ```typescript - * const prediction = generator.complete("When will The Winds of Winter be released?"); - * for await (const { content } of prediction) { - * process.stdout.write(content); - * } - * const result = await prediction.result(); - * console.log(result.stats); - * ``` - * - * Technically, awaiting on this method is the same as awaiting on the instance itself: - * - * ```typescript - * await prediction.result(); - * - * // Is the same as: - * - * await prediction; - * ``` - */ - async result() { - return await this; - } - /** - * Cancels the prediction. - */ - async cancel() { - this.onCancel(); - } -} - -const llmGeneratorPredictionOptsSchema = z.object({ - onFirstToken: z.function().optional(), - onPredictionFragment: z.function().optional(), - onMessage: z.function().optional(), - signal: z.instanceof(AbortSignal).optional(), - pluginConfig: kvConfigSchema.optional(), - workingDirectory: z.string().optional(), -}); -const llmGeneratorActOptsSchema = llmActBaseOptsSchema.extend({ - pluginConfig: kvConfigSchema.optional(), - workingDirectory: z.string().optional(), -}); -/** - * Represents a handle for a generator that can act as a LLM. - * - * @public - * @experimental [EXP-GEN-PREDICT] Using generator plugins programmatically is still in development. - * This may change in the future without warning. - */ -class LLMGeneratorHandle { - /** - * Don't use this method directly, use {@link LLMNamespace#createGeneratorHandle} instead. - * - * @internal - */ - constructor( - /** @internal */ - port, - /** @internal */ - pluginIdentifier, - /** @internal */ - validator, - /** @internal */ - associatedPredictionProcess, - /** @internal */ - logger = new SimpleLogger(`LLMGeneratorHandle`)) { - this.port = port; - this.pluginIdentifier = pluginIdentifier; - this.validator = validator; - this.associatedPredictionProcess = associatedPredictionProcess; - this.logger = logger; - /** - * The identifier of the plugin that this handle is associated with. - */ - this.identifier = this.pluginIdentifier; - } - getPluginConfigSpecifier(userSuppliedPluginConfig, userSuppliedWorkingDirectory, stack) { - if (this.associatedPredictionProcess === null) { - // If there is no associated prediction process, we can use the user-supplied config directly. - return { - type: "direct", - config: userSuppliedPluginConfig ?? emptyKVConfig, - workingDirectoryPath: userSuppliedWorkingDirectory ?? undefined, - }; - } - // If there is an associated prediction process, we first need to make sure that the user has - // not supplied a plugin config or working directory, as these are not allowed in this case. - // (The plugin config/working directory of the prediction process will be used instead.) - if (userSuppliedPluginConfig !== undefined) { - throw makeTitledPrettyError("Cannot use plugin config with prediction process", text ` - You cannot provide a plugin config to the generator handle when it is associated with a - prediction process. The plugin config that was configured for the prediction process will - be used instead. - - If you want to use a different plugin config, you will need to create a separate - GeneratorHandle instead. - `, stack); - } - if (userSuppliedWorkingDirectory !== undefined) { - throw makeTitledPrettyError("Cannot use working directory with prediction process", text ` - You cannot provide a working directory to the generator handle when it is associated with - a prediction process. The working directory that was configured for the prediction process - will be used instead. - - If you want to use a different working directory, you will need to create a separate - GeneratorHandle instead. - `, stack); - } - // If we reach here, we can safely return the plugin config specifier for the prediction - // process. - return { - type: "predictionProcess", - pci: this.associatedPredictionProcess.pci, - token: this.associatedPredictionProcess.token, - }; - } - /** - * Use the generator to produce a response based on the given history. - */ - respond(chat, opts = {}) { - const stack = getCurrentStack(1); - [chat, opts] = this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle", "respond", ["chat", "opts"], [chatHistoryLikeSchema, llmGeneratorPredictionOptsSchema], [chat, opts], stack); - const { onFirstToken, onPredictionFragment, onMessage, signal, pluginConfig, workingDirectory, } = opts; - let resolved = false; - let firstTokenTriggered = false; - const cancelEvent = new CancelEvent(); - if (signal !== undefined) { - if (signal.aborted) { - // If the signal is already aborted, we can immediately cancel the event. - cancelEvent.cancel(); - } - else { - signal.addEventListener("abort", () => cancelEvent.cancel(), { once: true }); - } - } - const { ongoingPrediction, finished, failed, push } = OngoingGeneratorPrediction.create(this.pluginIdentifier, () => { - cancelEvent.cancel(); - }); - const channel = this.port.createChannel("generateWithGenerator", { - pluginIdentifier: this.pluginIdentifier, - pluginConfigSpecifier: this.getPluginConfigSpecifier(pluginConfig, workingDirectory, stack), - tools: [], - history: accessMaybeMutableInternals(Chat.from(chat))._internalGetData(), - }, message => { - const messageType = message.type; - switch (messageType) { - case "fragment": { - if (!firstTokenTriggered) { - firstTokenTriggered = true; - safeCallCallback(this.logger, "onFirstToken", onFirstToken, []); - } - safeCallCallback(this.logger, "onPredictionFragment", onPredictionFragment, [ - message.fragment, - ]); - push(message.fragment); - break; - } - case "success": { - resolved = true; - finished(); - break; - } - } - }, { stack }); - channel.onError.subscribeOnce(error => { - if (resolved) { - return; - } - resolved = true; - failed(error); - }); - cancelEvent.subscribeOnce(() => { - if (resolved) { - return; - } - channel.send({ type: "cancel" }); - }); - ongoingPrediction.then(result => { - // Call the onMessage callback with the result. - safeCallCallback(this.logger, "onMessage", onMessage, [ - ChatMessage.create("assistant", result.content), - ]); - }, () => { }); - return ongoingPrediction; - } - async act(chat, tools, opts = {}) { - const startTime = performance.now(); - const stack = getCurrentStack(1); - [chat, opts] = this.validator.validateMethodParamsOrThrow("LLMGeneratorHandle", "act", ["chat", "opts"], [chatHistoryLikeSchema, llmGeneratorActOptsSchema], [chat, opts], stack); - const { pluginConfig, workingDirectory, ...baseOpts } = opts; - const toolDefinitions = tools.map(toolToLLMTool); - return await internalAct(chat, tools, baseOpts, stack, this.logger, startTime, - // Implementation of the prediction function. This performs the prediction by creating a - // predict channel and redirect the messages to the appropriate handlers. - async ({ allowTools, history, signal, handleFragment, handlePromptProcessingProgress, handleToolCallGenerationStart, handleToolCallGenerationNameReceived, handleToolCallGenerationArgumentFragmentGenerated, handleToolCallGenerationEnd, handleToolCallGenerationFailed, handlePredictionEnd, handleError, }) => { - // Use predict channel - const channel = this.port.createChannel("generateWithGenerator", { - pluginIdentifier: this.pluginIdentifier, - pluginConfigSpecifier: this.getPluginConfigSpecifier(pluginConfig, workingDirectory, stack), - tools: allowTools ? toolDefinitions : [], - history, - }, message => { - const messageType = message.type; - switch (messageType) { - case "fragment": { - handleFragment(message.fragment); - break; - } - case "promptProcessingProgress": { - handlePromptProcessingProgress(message.progress); - break; - } - case "toolCallGenerationStart": { - handleToolCallGenerationStart(message.toolCallId); - break; - } - case "toolCallGenerationNameReceived": { - handleToolCallGenerationNameReceived(message.name); - break; - } - case "toolCallGenerationArgumentFragmentGenerated": { - handleToolCallGenerationArgumentFragmentGenerated(message.content); - break; - } - case "toolCallGenerationEnd": { - handleToolCallGenerationEnd(message.toolCallRequest, undefined); - break; - } - case "toolCallGenerationFailed": { - handleToolCallGenerationFailed(new Error("Tool call generation failed"), // Placeholder error for now - undefined); - break; - } - case "success": { - // Nothing to hand to the `makePredictionResult` function. Just pass in `undefined`. - handlePredictionEnd(undefined); - break; - } - } - }, { stack }); - if (signal.aborted) { - // If the signal is already aborted, we can immediately cancel the channel. - channel.send({ type: "cancel" }); - } - else { - signal.addEventListener("abort", () => { - channel.send({ type: "cancel" }); - }, { once: true }); - } - channel.onError.subscribeOnce(handleError); - }, ({ content, nonReasoningContent, reasoningContent }) => new GeneratorPredictionResult(content, reasoningContent, nonReasoningContent, this.pluginIdentifier)); - } -} - -const generatorSchema = z.function(); - -/** - * The base class for all controllers. - * - * @public - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ -class BaseController { - constructor( - /** - * The LM Studio client instance. Use this to interact with the LM Studio API. - */ - client, - /** - * The abort signal that you should listen to for cancellation requests. - * - * See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal for more information about - * abort signals. - */ - abortSignal, pluginConfig, globalPluginConfig, workingDirectoryPath) { - this.client = client; - this.abortSignal = abortSignal; - this.pluginConfig = pluginConfig; - this.globalPluginConfig = globalPluginConfig; - this.workingDirectoryPath = workingDirectoryPath; - } - /** - * Gets the working directory for the current prediction. If your plugin produces files, you - * should aim to put them in this directory. - */ - getWorkingDirectory() { - if (this.workingDirectoryPath === null) { - throw new Error("This prediction process is not attached to a working directory."); - } - return this.workingDirectoryPath; - } - /** - * Get the per-chat config for the plugin. Takes in the configSchematics. You can get the - * values of fields like so: - * - * ```ts - * const config = ctl.getPluginConfig(configSchematics); - * const value = config.get("fieldKey"); - * ``` - * - * @remarks - * - * If you need to name the type of the returned value, use: - * - * `InferParsedConfig`. - * - * Example: - * - * ```ts - * function myFunction(config: InferParsedConfig) { - * // ... - * } - * - * myFunction(ctl.getPluginConfig(configSchematics)); - * ``` - */ - getPluginConfig(configSchematics) { - return configSchematics.parse(this.pluginConfig); - } - /** - * Get the application-wide config for the plugin. Takes in the globalConfigSchematics. You can - * get the values of fields like so: - * - * ```ts - * const config = ctl.getGlobalPluginConfig(globalConfigSchematics); - * const value = config.get("fieldKey"); - * ``` - * - * @remarks - * - * If you need to name the type of the returned value, use: - * - * `InferParsedConfig`. - * - * Example: - * - * ```ts - * function myFunction(config: InferParsedConfig) { - * // ... - * } - * - * myFunction(ctl.getGlobalPluginConfig(globalConfigSchematics)); - * ``` - */ - getGlobalPluginConfig(globalConfigSchematics) { - return globalConfigSchematics.parse(this.globalPluginConfig); - } - /** - * Provides a callback that will be called when the prediction is aborted. If the prediction is - * already aborted, the callback will be called immediately. - * - * You can also use {@link BaseController.abortSignal} if you are using an async function that - * supports abort signals. - * - * See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal for more information about - * abort signals. - */ - onAborted(callback) { - if (this.abortSignal.aborted) { - callback(); - } - else { - this.abortSignal.addEventListener("abort", callback, { once: true }); - } - } -} - -/** - * Controller for a generator. - * - * @public - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ -class GeneratorController extends BaseController { - /** - * @internal Do not construct this class yourself. - */ - constructor(client, pluginConfig, globalPluginConfig, workingDirectoryPath, abortSignal, toolDefinitions, connector, validator) { - super(client, abortSignal, pluginConfig, globalPluginConfig, workingDirectoryPath); - this.toolDefinitions = toolDefinitions; - this.connector = connector; - this.validator = validator; - } - /** - * Get the definitions of the tools available for this generation. - */ - getToolDefinitions() { - return this.toolDefinitions; - } - /** - * Use this function to report a text fragment has been generated. - * - * @param content - The content that has been generated. - * @param opts - Additional info about the generated content, such as how many tokens it contains. - * See {@link LLMPredictionFragmentInputOpts} for more info. All the fields are optional. - */ - fragmentGenerated(content, opts = {}) { - const stack = getCurrentStack(1); - [content, opts] = this.validator.validateMethodParamsOrThrow("GeneratorController", "fragmentGenerated", ["content", "opts"], [z.string(), llmPredictionFragmentInputOptsSchema], [content, opts], stack); - this.connector.fragmentGenerated(content, opts); - } - /** - * Use this function to report that a tool call generation has started. Each - * `toolCallGenerationStarted` must be paired up with a `toolCallGenerationEnded` call for - * successfully generated tool calls, or a `toolCallGenerationFailed` call for - * failed tool calls. - */ - toolCallGenerationStarted({ toolCallId, } = {}) { - this.connector.toolCallGenerationStarted(toolCallId); - } - /** - * Use this function to report that the name of the tool call has been generated. This function - * should only be called once for each `toolCallGenerationStarted`. - * - * @param toolName - The name of the tool that has been generated. - */ - toolCallGenerationNameReceived(toolName) { - const stack = getCurrentStack(1); - toolName = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationNameReceived", "toolName", z.string(), toolName, stack); - this.connector.toolCallGenerationNameReceived(toolName); - } - /** - * Use this function to report that a new argument fragment has been generated for the tool call. - * This function can be called multiple times for each `toolCallGenerationStarted`. - * - * @param content - The new fragment that has been generated for the tool call. - */ - toolCallGenerationArgumentFragmentGenerated(content) { - const stack = getCurrentStack(1); - content = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationArgumentFragmentGenerated", "content", z.string(), content, stack); - this.connector.toolCallGenerationArgumentFragmentGenerated(content); - } - /** - * Use this function to report that a tool call generation has successfully ended. This function - * should only be called after a `toolCallGenerationStarted` call. - */ - toolCallGenerationEnded(toolCallRequest) { - const stack = getCurrentStack(1); - toolCallRequest = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationEnded", "toolCallRequest", toolCallRequestSchema, toolCallRequest, stack); - this.connector.toolCallGenerationEnded(toolCallRequest); - } - /** - * Use this function to report that a tool call generation has failed. This function should only - * be called after a `toolCallGenerationStarted` call. - * - * @param error - The error that occurred during the tool call generation. - */ - toolCallGenerationFailed(error) { - const stack = getCurrentStack(1); - error = this.validator.validateMethodParamOrThrow("GeneratorController", "toolCallGenerationFailed", "error", z.instanceof(Error), error, stack); - this.connector.toolCallGenerationFailed(error); - } -} - -var __addDisposableResource$1 = (globalThis && globalThis.__addDisposableResource) || function (env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose, inner; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; - } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - if (async) inner = dispose; - } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; - env.stack.push({ value: value, dispose: dispose, async: async }); - } - else if (async) { - env.stack.push({ async: true }); - } - return value; -}; -var __disposeResources$1 = (globalThis && globalThis.__disposeResources) || (function (SuppressedError) { - return function (env) { - function fail(e) { - env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; - } - var r, s = 0; - function next() { - while (r = env.stack.pop()) { - try { - if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); - if (r.dispose) { - var result = r.dispose.call(r.value); - if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); - } - else s |= 1; - } - catch (e) { - fail(e); - } - } - if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); - if (env.hasError) throw env.error; - } - return next(); - }; -})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; -}); -function stringifyAny(message) { - switch (typeof message) { - case "string": - return message; - case "number": - return message.toString(); - case "boolean": - return message ? "true" : "false"; - case "undefined": - return "undefined"; - case "object": - if (message === null) { - return "null"; - } - if (message instanceof Error) { - return message.stack; - } - return JSON.stringify(message, null, 2); - case "bigint": - return message.toString(); - case "symbol": - return message.toString(); - case "function": - return message.toString(); - default: - return "unknown"; - } -} -function concatenateDebugMessages(...messages) { - return messages.map(stringifyAny).join(" "); -} -function createId() { - return `${Date.now()}-${Math.random()}`; -} -class ProcessingConnector { - constructor(pluginsPort, abortSignal, processingContextIdentifier, token, logger) { - this.pluginsPort = pluginsPort; - this.abortSignal = abortSignal; - this.processingContextIdentifier = processingContextIdentifier; - this.token = token; - this.logger = logger; - } - handleUpdate(update) { - this.pluginsPort - .callRpc("processingHandleUpdate", { - pci: this.processingContextIdentifier, - token: this.token, - update, - }) - .catch(error => { - this.logger.error("Failed to send update", error); - }); - } - async handleRequest(request) { - const { response } = await this.pluginsPort.callRpc("processingHandleRequest", { - pci: this.processingContextIdentifier, - token: this.token, - request, - }); - return response; - } - async pullHistory(includeCurrent) { - const chatHistoryData = await this.pluginsPort.callRpc("processingPullHistory", { - pci: this.processingContextIdentifier, - token: this.token, - includeCurrent, - }); - // We know the result of callRpc is immutable, so we can safely pass false as the second - // argument. - return Chat.createRaw(chatHistoryData, /* mutable */ false).asMutableCopy(); - } - async getOrLoadTokenSource() { - const result = await this.pluginsPort.callRpc("processingGetOrLoadTokenSource", { - pci: this.processingContextIdentifier, - token: this.token, - }); - return result.tokenSourceIdentifier; - } - async hasStatus() { - return await this.pluginsPort.callRpc("processingHasStatus", { - pci: this.processingContextIdentifier, - token: this.token, - }); - } - async needsNaming() { - return await this.pluginsPort.callRpc("processingNeedsNaming", { - pci: this.processingContextIdentifier, - token: this.token, - }); - } - async suggestName(name) { - await this.pluginsPort.callRpc("processingSuggestName", { - pci: this.processingContextIdentifier, - token: this.token, - name, - }); - } -} -/** - * @public - */ -class ProcessingController extends BaseController { - /** @internal */ - constructor(client, pluginConfig, globalPluginConfig, workingDirectoryPath, enabledPluginInfos, - /** @internal */ - connector, - /** @internal */ - config, - /** - * When getting history, should the latest user input be included in the history? - * - * @internal - */ - shouldIncludeCurrentInHistory) { - super(client, connector.abortSignal, pluginConfig, globalPluginConfig, workingDirectoryPath); - this.enabledPluginInfos = enabledPluginInfos; - this.connector = connector; - this.config = config; - this.shouldIncludeCurrentInHistory = shouldIncludeCurrentInHistory; - this.processingControllerHandle = { - abortSignal: connector.abortSignal, - sendUpdate: update => { - connector.handleUpdate(update); - }, - sendRequest: async (request) => { - const type = request.type; - const response = await connector.handleRequest(request); - if (response.type !== type) { - throw new Error(`Expected response type ${type}, but got ${response.type}. This is a bug.`); - } - return response; - }, - }; - } - sendUpdate(update) { - this.processingControllerHandle.sendUpdate(update); - } - /** - * Gets a mutable copy of the current history. The returned history is a copy, so mutating it will - * not affect the actual history. It is mutable for convenience reasons. - * - * - If you are a promptPreprocessor, this will not include the user message you are currently - * preprocessing. - * - If you are a prediction loop handler, this will include the user message, and can be fed into - * the {@link LLMDynamicHandle#respond} method directly. - */ - async pullHistory() { - return await this.connector.pullHistory(this.shouldIncludeCurrentInHistory); - } - createStatus(initialState) { - const id = createId(); - this.sendUpdate({ - type: "status.create", - id, - state: initialState, - }); - const statusController = new PredictionProcessStatusController(this.processingControllerHandle, initialState, id); - return statusController; - } - addCitations(arg) { - if (Array.isArray(arg)) { - for (const entry of arg) { - this.createCitationBlock(entry.content, { - fileName: entry.source.name, - fileIdentifier: entry.source.identifier, - }); - } - } - else { - for (const entry of arg.entries) { - this.createCitationBlock(entry.content, { - fileName: entry.source.name, - fileIdentifier: entry.source.identifier, - }); - } - } - } - createCitationBlock(citedText, source) { - const id = createId(); - this.sendUpdate({ - type: "citationBlock.create", - id, - citedText, - ...source, - }); - const citationBlockController = new PredictionProcessCitationBlockController(this.processingControllerHandle, id); - return citationBlockController; - } - /** - * @internal - */ - createDebugInfoBlock(debugInfo) { - const id = createId(); - this.sendUpdate({ - type: "debugInfoBlock.create", - id, - debugInfo, - }); - const debugInfoBlockController = new PredictionProcessDebugInfoBlockController(this.processingControllerHandle, id); - return debugInfoBlockController; - } - createContentBlock({ roleOverride, includeInContext = true, style, prefix, suffix, } = {}) { - const id = createId(); - this.sendUpdate({ - type: "contentBlock.create", - id, - roleOverride, - includeInContext, - style, - prefix, - suffix, - }); - const contentBlockController = new PredictionProcessContentBlockController(this.processingControllerHandle, id, roleOverride ?? "assistant"); - return contentBlockController; - } - debug(...messages) { - this.createDebugInfoBlock(concatenateDebugMessages(...messages)); - } - /** - * Gets the token source associated with this prediction process (i.e. what the user has selected - * on the top navigation bar). - * - * The token source can either be a model or a generator plugin. In both cases, the returned - * object will contain a ".act" and a ".respond" method, which can be used to generate text. - * - * The token source is already pre-configured to use user's prediction config - you don't need to - * pass through any additional configuration. - */ - async tokenSource() { - const tokenSourceIdentifier = await this.connector.getOrLoadTokenSource(); - const tokenSourceIdentifierType = tokenSourceIdentifier.type; - switch (tokenSourceIdentifierType) { - case "model": { - const model = await this.client.llm.model(tokenSourceIdentifier.identifier); - // Don't use the server session config for this model - model.internalIgnoreServerSessionConfig = true; - // Inject the prediction config - model.internalKVConfigStack = { - layers: [ - { - layerName: "conversationSpecific", - config: this.config, - }, - ], - }; - return model; - } - case "generator": { - const generator = this.client.plugins.createGeneratorHandleAssociatedWithPredictionProcess(tokenSourceIdentifier.pluginIdentifier, this.connector.processingContextIdentifier, this.connector.token); - return generator; - } - } - } - /** - * Sets the sender name for this message. The sender name shown above the message in the chat. - */ - async setSenderName(name) { - this.sendUpdate({ - type: "setSenderName", - name, - }); - } - /** - * Throws an error if the prediction process has been aborted. Sprinkle this throughout your code - * to ensure that the prediction process is aborted as soon as possible. - */ - guardAbort() { - this.abortSignal.throwIfAborted(); - } - /** - * Whether this prediction process has had any status. - */ - async hasStatus() { - return await this.connector.hasStatus(); - } - /** - * Returns whether this conversation needs a name. - */ - async needsNaming() { - return await this.connector.needsNaming(); - } - /** - * Suggests a name for this conversation. - */ - async suggestName(name) { - await this.connector.suggestName(name); - } - async requestConfirmToolCall({ callId, pluginIdentifier, name, parameters, }) { - const { result } = await raceWithAbortSignal(this.processingControllerHandle.sendRequest({ - type: "confirmToolCall", - callId, - pluginIdentifier, - name, - parameters, - }), this.abortSignal); - const resultType = result.type; - switch (resultType) { - case "allow": { - return { - type: "allow", - toolArgsOverride: result.toolArgsOverride, - }; - } - case "deny": { - return { - type: "deny", - denyReason: result.denyReason, - }; - } - default: { - const exhaustiveCheck = resultType; - throw new Error(`Unexpected result type ${exhaustiveCheck}. This is a bug. Please report it.`); - } - } - } - createToolStatus(callId, initialStatus) { - const id = createId(); - this.sendUpdate({ - type: "toolStatus.create", - id, - callId, - state: { - status: initialStatus, - customStatus: "", - customWarnings: [], - }, - }); - const toolStatusController = new PredictionProcessToolStatusController(this.processingControllerHandle, id, initialStatus); - return toolStatusController; - } - /** - * Starts a tool use session with tools available in the prediction process. Note, this method - * should be used with "Explicit Resource Management". That is, you should use it like so: - * - * ```typescript - * using toolUseSession = await ctl.startToolUseSession(); - * // ^ Notice the `using` keyword here. - * ``` - * - * If you do not `using`, you should call `toolUseSession[Symbol.dispose]()` after you are done. - * - * If you don't, lmstudio-js will close the session upon the end of the prediction step - * automatically. However, it is not recommended. - * - * @public - * @deprecated WIP - */ - async startToolUseSession() { - const identifiersOfPluginsWithTools = this.enabledPluginInfos - .filter(({ hasToolsProvider }) => hasToolsProvider) - .map(({ identifier }) => identifier); - return await this.client.plugins.startToolUseSessionUsingPredictionProcess( - // We start a tool use session with all the plugins that have tools available - identifiersOfPluginsWithTools, this.connector.processingContextIdentifier, this.connector.token); - } -} -/** - * Controller for a status block in the prediction process. - * - * @public - */ -class PredictionProcessStatusController { - /** @internal */ - constructor( - /** @internal */ - handle, initialState, id, indentation = 0) { - this.handle = handle; - this.id = id; - this.indentation = indentation; - this.lastSubStatus = this; - this.lastState = initialState; - } - setText(text) { - this.lastState.text = text; - this.handle.sendUpdate({ - type: "status.update", - id: this.id, - state: this.lastState, - }); - } - setState(state) { - this.lastState = state; - this.handle.sendUpdate({ - type: "status.update", - id: this.id, - state, - }); - } - remove() { - this.handle.sendUpdate({ - type: "status.remove", - id: this.id, - }); - } - getNestedLastSubStatusBlockId() { - let current = this.lastSubStatus; - while (current !== current.lastSubStatus) { - current = current.lastSubStatus; - } - return current.id; - } - addSubStatus(initialState) { - const id = createId(); - this.handle.sendUpdate({ - type: "status.create", - id, - state: initialState, - location: { - type: "afterId", - id: this.getNestedLastSubStatusBlockId(), - }, - indentation: this.indentation + 1, - }); - const controller = new PredictionProcessStatusController(this.handle, initialState, id, this.indentation + 1); - this.lastSubStatus = controller; - return controller; - } -} -/** - * Controller for a citation block in the prediction process. Currently cannot do anything. - * - * @public - */ -class PredictionProcessCitationBlockController { - /** @internal */ - constructor( - /** @internal */ - handle, id) { - this.handle = handle; - this.id = id; - } -} -/** - * Controller for a debug info block in the prediction process. Currently cannot do anything. - * - * @public - */ -class PredictionProcessDebugInfoBlockController { - /** @internal */ - constructor( - /** @internal */ - handle, id) { - this.handle = handle; - this.id = id; - } -} -/** - * @public - * - * TODO: Documentation - */ -class PredictionProcessContentBlockController { - /** @internal */ - constructor( - /** @internal */ - handle, id, role) { - this.handle = handle; - this.id = id; - this.role = role; - } - appendText(text, { tokensCount, fromDraftModel, isStructural } = {}) { - if (this.role === "tool") { - throw new Error("Text cannot be appended to tool blocks."); - } - this.handle.sendUpdate({ - type: "contentBlock.appendText", - id: this.id, - text, - tokensCount, - fromDraftModel, - isStructural, - }); - } - appendToolRequest({ callId, toolCallRequestId, name, parameters, pluginIdentifier, }) { - if (this.role !== "assistant") { - throw new Error(`Tool requests can only be appended to assistant blocks. This is a ${this.role} block.`); - } - this.handle.sendUpdate({ - type: "contentBlock.appendToolRequest", - id: this.id, - callId, - toolCallRequestId, - name, - parameters, - pluginIdentifier, - }); - } - replaceToolRequest({ callId, toolCallRequestId, name, parameters, pluginIdentifier, }) { - if (this.role !== "assistant") { - throw new Error(`Tool requests can only be replaced in assistant blocks. This is a ${this.role} block.`); - } - this.handle.sendUpdate({ - type: "contentBlock.replaceToolRequest", - id: this.id, - callId, - toolCallRequestId, - name, - parameters, - pluginIdentifier, - }); - } - appendToolResult({ callId, toolCallRequestId, content, }) { - if (this.role !== "tool") { - throw new Error(`Tool results can only be appended to tool blocks. This is a ${this.role} block.`); - } - this.handle.sendUpdate({ - type: "contentBlock.appendToolResult", - id: this.id, - callId, - toolCallRequestId, - content, - }); - } - replaceText(text) { - if (this.role === "tool") { - throw new Error("Text cannot be set in tool blocks."); - } - this.handle.sendUpdate({ - type: "contentBlock.replaceText", - id: this.id, - text, - }); - } - setStyle(style) { - this.handle.sendUpdate({ - type: "contentBlock.setStyle", - id: this.id, - style, - }); - } - setPrefix(prefix) { - this.handle.sendUpdate({ - type: "contentBlock.setPrefix", - id: this.id, - prefix, - }); - } - setSuffix(suffix) { - this.handle.sendUpdate({ - type: "contentBlock.setSuffix", - id: this.id, - suffix, - }); - } - attachGenInfo(genInfo) { - this.handle.sendUpdate({ - type: "contentBlock.attachGenInfo", - id: this.id, - genInfo, - }); - } - async pipeFrom(prediction) { - const env_1 = { stack: [], error: void 0, hasError: false }; - try { - const cleaner = __addDisposableResource$1(env_1, new Cleaner(), false); - const abortListener = () => { - prediction.cancel(); - }; - this.handle.abortSignal.addEventListener("abort", abortListener); - cleaner.register(() => { - this.handle.abortSignal.removeEventListener("abort", abortListener); - }); - for await (const { content } of prediction) { - this.appendText(content); - } - const result = await prediction; - this.attachGenInfo({ - indexedModelIdentifier: result.modelInfo.path, - identifier: result.modelInfo.identifier, - loadModelConfig: result.loadConfig, - predictionConfig: result.predictionConfig, - stats: result.stats, - }); - this.handle.abortSignal.throwIfAborted(); - return result; - } - catch (e_1) { - env_1.error = e_1; - env_1.hasError = true; - } - finally { - __disposeResources$1(env_1); - } - } -} -/** - * Controller for a tool status block in the prediction process. - * - * @public - */ -class PredictionProcessToolStatusController { - /** @internal */ - constructor( - /** @internal */ - handle, id, initialStatus) { - this.handle = handle; - this.id = id; - this.customStatus = ""; - this.customWarnings = []; - this.status = initialStatus; - } - updateState() { - this.handle.sendUpdate({ - type: "toolStatus.update", - id: this.id, - state: { - status: this.status, - customStatus: this.customStatus, - customWarnings: this.customWarnings, - }, - }); - } - setCustomStatusText(status) { - this.customStatus = status; - this.updateState(); - } - addWarning(warning) { - this.customWarnings.push(warning); - this.updateState(); - } - setStatus(status) { - this.status = status; - this.updateState(); - } - appendArgumentFragment(content) { - this.handle.sendUpdate({ - type: "toolStatus.argumentFragment", - id: this.id, - content, - }); - } -} - -/** - * Controller for tools provider. - * - * @public - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ -class ToolsProviderController extends BaseController { - /** - * @internal Do not construct this class yourself. - */ - constructor(client, signal, pluginConfig, globalPluginConfig, workingDirectoryPath) { - super(client, signal, pluginConfig, globalPluginConfig, workingDirectoryPath); - } -} - -class GeneratorConnectorImpl { - constructor(channel, taskId) { - this.channel = channel; - this.taskId = taskId; - } - fragmentGenerated(content, opts) { - this.channel.send({ - type: "fragmentGenerated", - taskId: this.taskId, - content, - opts: opts, - }); - } - toolCallGenerationStarted(toolCallId) { - this.channel.send({ - type: "toolCallGenerationStarted", - taskId: this.taskId, - toolCallId, - }); - } - toolCallGenerationNameReceived(toolName) { - this.channel.send({ - type: "toolCallGenerationNameReceived", - taskId: this.taskId, - toolName, - }); - } - toolCallGenerationArgumentFragmentGenerated(content) { - this.channel.send({ - type: "toolCallGenerationArgumentFragmentGenerated", - taskId: this.taskId, - content, - }); - } - toolCallGenerationEnded(toolCallRequest) { - this.channel.send({ - type: "toolCallGenerationEnded", - taskId: this.taskId, - toolCallRequest, - }); - } - toolCallGenerationFailed(error) { - this.channel.send({ - type: "toolCallGenerationFailed", - taskId: this.taskId, - error: serializeError(error), - }); - } -} -/** - * @deprecated This class is used internally by a plugin to register hooks. Do not use directly. - * @public - */ -class PluginSelfRegistrationHost { - constructor(port, client, rootLogger, validator) { - this.port = port; - this.client = client; - this.rootLogger = rootLogger; - this.validator = validator; - } - /** - * Sets the promptPreprocessor to be used by the plugin represented by this client. - * - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - setPromptPreprocessor(promptPreprocessor) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("plugins", "registerPromptPreprocessor", "promptPreprocessor", z.function(), promptPreprocessor, stack); - const logger = new SimpleLogger(`PromptPreprocessor`, this.rootLogger); - logger.info("Register with LM Studio"); - const tasks = new Map(); - const channel = this.port.createChannel("setPromptPreprocessor", undefined, message => { - switch (message.type) { - case "preprocess": { - const taskLogger = new SimpleLogger(`Request (${message.taskId.substring(0, 6)})`, logger); - taskLogger.info(`New preprocess request received.`); - const abortController = new AbortController(); - const connector = new ProcessingConnector(this.port, abortController.signal, message.pci, message.token, taskLogger); - const input = ChatMessage.createRaw(message.input, /* mutable */ false); - const controller = new ProcessingController(this.client, message.pluginConfig, message.globalPluginConfig, message.workingDirectoryPath, message.enabledPluginInfos, connector, message.config, - /* shouldIncludeInputInHistory */ false); - tasks.set(message.taskId, { - cancel: () => { - abortController.abort(); - }, - taskLogger, - }); - // We know the input from the channel is immutable, so we can safely pass false as the - // second argument. - promptPreprocessor(controller, input.asMutableCopy()) - .then(result => { - taskLogger.info(`Preprocess request completed.`); - const parsedReturned = z - .union([z.string(), z.custom(v => v instanceof ChatMessage)]) - .safeParse(result); - if (!parsedReturned.success) { - throw new Error("PromptPreprocessor returned an invalid value:" + - Validator.prettyPrintZod("result", parsedReturned.error)); - } - const returned = parsedReturned.data; - let processed; - if (typeof returned === "string") { - const messageCopy = input.asMutableCopy(); - messageCopy.replaceText(returned); - processed = messageCopy.getRaw(); - } - else { - processed = returned.getRaw(); - } - channel.send({ - type: "complete", - taskId: message.taskId, - processed, - }); - }) - .catch(error => { - if (error.name === "AbortError") { - logger.info(`Request successfully aborted.`); - channel.send({ - type: "aborted", - taskId: message.taskId, - }); - return; - } - logger.warn(`Preprocessing failed.`, error); - channel.send({ - type: "error", - taskId: message.taskId, - error: serializeError(error), - }); - }) - .finally(() => { - tasks.delete(message.taskId); - }); - break; - } - case "abort": { - const task = tasks.get(message.taskId); - if (task !== undefined) { - task.taskLogger.info(`Received abort request.`); - task.cancel(); - tasks.delete(message.taskId); - } - break; - } - } - }, { stack }); - } - /** - * Sets the prediction loop handler to be used by the plugin represented by this client. - * - * @deprecated [DEP-PLUGIN-PREDICTION-LOOP-HANDLER] Prediction loop handler support is still in - * development. Stay tuned for updates. - */ - setPredictionLoopHandler(predictionLoopHandler) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("plugins", "setPredictionLoopHandler", "predictionLoopHandler", z.function(), predictionLoopHandler, stack); - const logger = new SimpleLogger(` PredictionLoopHandler`, this.rootLogger); - logger.info("Register with LM Studio"); - const tasks = new Map(); - const channel = this.port.createChannel("setPredictionLoopHandler", undefined, message => { - switch (message.type) { - case "handlePredictionLoop": { - const taskLogger = new SimpleLogger(`Request (${message.taskId.substring(0, 6)})`, logger); - taskLogger.info(`New prediction loop handling request received.`); - const abortController = new AbortController(); - const connector = new ProcessingConnector(this.port, abortController.signal, message.pci, message.token, taskLogger); - const controller = new ProcessingController(this.client, message.pluginConfig, message.globalPluginConfig, message.workingDirectoryPath, message.enabledPluginInfos, connector, message.config, - /* shouldIncludeInputInHistory */ true); - tasks.set(message.taskId, { - cancel: () => { - abortController.abort(); - }, - taskLogger, - }); - // We know the input from the channel is immutable, so we can safely pass false as the - // second argument. - predictionLoopHandler(controller) - .then(() => { - channel.send({ - type: "complete", - taskId: message.taskId, - }); - }) - .catch(error => { - if (error.name === "AbortError") { - logger.info(`Request successfully aborted.`); - channel.send({ - type: "aborted", - taskId: message.taskId, - }); - return; - } - logger.warn(`Generation failed.`, error); - channel.send({ - type: "error", - taskId: message.taskId, - error: serializeError(error), - }); - }) - .finally(() => { - tasks.delete(message.taskId); - }); - break; - } - case "abort": { - const task = tasks.get(message.taskId); - if (task !== undefined) { - task.taskLogger.info(`Received abort request.`); - task.cancel(); - tasks.delete(message.taskId); - } - break; - } - } - }, { stack }); - } - /** - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - async setConfigSchematics(configSchematics) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("plugins", "setConfigSchematics", "configSchematics", z.instanceof(KVConfigSchematics), configSchematics, stack); - await this.port.callRpc("setConfigSchematics", { - schematics: configSchematics.serialize(), - }, { stack }); - } - /** - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - async setGlobalConfigSchematics(globalConfigSchematics) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("plugins", "setGlobalConfigSchematics", "globalConfigSchematics", z.instanceof(KVConfigSchematics), globalConfigSchematics, stack); - await this.port.callRpc("setGlobalConfigSchematics", { - schematics: globalConfigSchematics.serialize(), - }, { stack }); - } - /** - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - setToolsProvider(toolsProvider) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("plugins", "setToolsProvider", "toolsProvider", z.function(), toolsProvider, stack); - const logger = new SimpleLogger(`Tools Prvdr.`, this.rootLogger); - logger.info("Register with LM Studio"); - /** - * Map from sessionId to the open session. - */ - const openSessions = new Map(); - const channel = this.port.createChannel("setToolsProvider", undefined, message => { - const messageType = message.type; - switch (messageType) { - case "initSession": { - const sessionId = message.sessionId; - const sessionAbortController = new AbortController(); - const openSession = { - tools: null, - ongoingToolCalls: new Map(), - discarded: false, - abortController: sessionAbortController, - }; - openSessions.set(sessionId, openSession); - const controller = new ToolsProviderController(this.client, sessionAbortController.signal, message.pluginConfig, message.globalPluginConfig, message.workingDirectoryPath); - toolsProvider(controller).then(tools => { - const llmTools = tools.map(toolToLLMTool); - if (openSession.discarded) { - // By the time initialization is done, the session was already discarded. Don't - // do anything. - return; - } - channel.send({ - type: "sessionInitialized", - sessionId, - toolDefinitions: llmTools, - }); - openSession.tools = new Map(tools.map(tool => [tool.name, tool])); - }, error => { - if (openSession.discarded) { - // If the session was already discarded, don't do anything. - return; - } - channel.send({ - type: "sessionInitializationFailed", - sessionId, - error: serializeError(error), - }); - openSession.discarded = true; - openSessions.delete(sessionId); - }); - break; - } - case "discardSession": { - const sessionId = message.sessionId; - const openSession = openSessions.get(sessionId); - if (openSession === undefined) { - // Session was already discarded or doesn't exist. Ignore. - return; - } - openSession.discarded = true; - openSession.abortController.abort(); - openSessions.delete(sessionId); - break; - } - case "callTool": { - const sessionId = message.sessionId; - const openSession = openSessions.get(sessionId); - if (openSession === undefined) { - // Session was already discarded or doesn't exist. Ignore. - return; - } - if (openSession.tools === null) { - throw new Error("Tool called before initialization completed. This is unexpected."); - } - const tool = openSession.tools.get(message.toolName); - if (tool === undefined) { - throw new Error(`Tool ${message.toolName} not found.`); - } - const callId = message.callId; - const ongoingToolCall = { - settled: false, - abortController: new AbortController(), - }; - openSession.ongoingToolCalls.set(callId, ongoingToolCall); - new SimpleLogger(`Tool (${message.toolName})`, this.rootLogger); - const toolCallContext = { - status(text) { - channel.send({ - type: "toolCallStatus", - sessionId, - callId, - statusText: text, - }); - }, - warn(text) { - channel.send({ - type: "toolCallWarn", - sessionId, - callId, - warnText: text, - }); - }, - signal: ongoingToolCall.abortController.signal, - // Call ID is used to match up life cycle events of the same tool call. In this case, - // each call does not have different parts, thus call ID is useless. We can just use 0. - // If the user wants a "unique" ID, they can just have variable that goes up by one - // each time the function is called. - callId: 0, - }; - (async () => { - return await tool.implementation(message.parameters, toolCallContext); - })().then(result => { - if (openSession.discarded) { - // Session was already discarded. Ignore. - return; - } - if (ongoingToolCall.settled) { - // Tool call was already settled. Ignore. - return; - } - if (ongoingToolCall.abortController.signal.aborted) { - // Tool call was aborted. Ignore. - return; - } - if (result === undefined) { - result = "undefined"; // Default to "undefined" if no result is provided. - channel.send({ - type: "toolCallWarn", - sessionId, - callId, - warnText: text ` - Tool call returned undefined. This is not expected as the model always expects - a result. If you don't want to return anything, you can just return a string - reporting that the tool call was successful. For example: "operation - successful." In this case, we will give the model string "${result}". - `, - }); - } - // Try to see if the result is JSON serializable. If it is not, we will print a - // warning. - try { - JSON.stringify(result); - } - catch (error) { - result = text ` - Error: Tool call completed but returned a value that cannot be serialized to JSON - `; - channel.send({ - type: "toolCallWarn", - sessionId, - callId, - warnText: text ` - Tool call succeeded, but returned a value that is not JSON serializable. In - order to provide the result to the model, return values of tools must be JSON - serializable. In this case, we will give the model string "${result}". - `, - }); - } - channel.send({ - type: "toolCallComplete", - sessionId, - callId, - result, - }); - ongoingToolCall.settled = true; - openSession.ongoingToolCalls.delete(callId); - }, error => { - if (openSession.discarded) { - // Session was already discarded. Ignore. - return; - } - if (ongoingToolCall.settled) { - // Tool call was already settled. Ignore. - return; - } - if (ongoingToolCall.abortController.signal.aborted) { - // Tool call was aborted. Ignore. - return; - } - channel.send({ - type: "toolCallError", - sessionId, - callId, - error: serializeError(error), - }); - ongoingToolCall.settled = true; - openSession.ongoingToolCalls.delete(callId); - }); - break; - } - case "abortToolCall": { - const sessionId = message.sessionId; - const callId = message.callId; - const openSession = openSessions.get(sessionId); - if (openSession === undefined) { - // Session was already discarded or doesn't exist. Ignore. - return; - } - const ongoingToolCall = openSession.ongoingToolCalls.get(callId); - if (ongoingToolCall === undefined) { - // Tool call was already completed or doesn't exist. Ignore. - return; - } - ongoingToolCall.settled = true; - ongoingToolCall.abortController.abort(); - openSession.ongoingToolCalls.delete(callId); - break; - } - default: { - const exhaustiveCheck = messageType; - throw new Error(`Unexpected message type: ${exhaustiveCheck}`); - } - } - }); - } - /** - * Sets the generator to be used by the plugin represented by this client. - * - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - setGenerator(generator) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("plugins", "setGenerator", "generator", generatorSchema, generator, stack); - const logger = new SimpleLogger(`Generator`, this.rootLogger); - logger.info("Register with LM Studio"); - const tasks = new Map(); - const channel = this.port.createChannel("setGenerator", undefined, message => { - const messageType = message.type; - switch (messageType) { - case "generate": { - const taskLogger = new SimpleLogger(`Request (${message.taskId.substring(0, 6)})`, logger); - taskLogger.info(`New generate request received.`); - const abortController = new AbortController(); - const connector = new GeneratorConnectorImpl(channel, message.taskId); - const controller = new GeneratorController(this.client, message.pluginConfig, message.globalPluginConfig, message.workingDirectoryPath, abortController.signal, message.toolDefinitions, connector, this.validator); - tasks.set(message.taskId, { - cancel: () => { - abortController.abort(); - }, - taskLogger, - }); - const history = Chat.createRaw(message.input, false); - generator(controller, history) - .then(result => { - if (result !== undefined) { - taskLogger.warnText ` - The generator has returned a value. This it not expected. You should report - generated content using method on the controller. The returned value will be - ignored. - `; - } - channel.send({ - type: "complete", - taskId: message.taskId, - }); - }, error => { - if (error.name === "AbortError") { - taskLogger.info(`Request successfully aborted.`); - channel.send({ - type: "aborted", - taskId: message.taskId, - }); - } - else { - channel.send({ - type: "error", - taskId: message.taskId, - error: serializeError(error), - }); - taskLogger.warn(`Generation failed.`, error); - } - }) - .finally(() => { - tasks.delete(message.taskId); - }); - break; - } - case "abort": { - const task = tasks.get(message.taskId); - if (task !== undefined) { - task.taskLogger.info(`Received abort request.`); - task.cancel(); - tasks.delete(message.taskId); - } - break; - } - default: { - const exhaustiveCheck = messageType; - throw new Error(`Unexpected message type: ${exhaustiveCheck}`); - } - } - }); - } - /** - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - async initCompleted() { - const stack = getCurrentStack(1); - await this.port.callRpc("pluginInitCompleted", undefined, { stack }); - } -} - -var __addDisposableResource = (globalThis && globalThis.__addDisposableResource) || function (env, value, async) { - if (value !== null && value !== void 0) { - if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); - var dispose, inner; - if (async) { - if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); - dispose = value[Symbol.asyncDispose]; - } - if (dispose === void 0) { - if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); - dispose = value[Symbol.dispose]; - if (async) inner = dispose; - } - if (typeof dispose !== "function") throw new TypeError("Object not disposable."); - if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; - env.stack.push({ value: value, dispose: dispose, async: async }); - } - else if (async) { - env.stack.push({ async: true }); - } - return value; -}; -var __disposeResources = (globalThis && globalThis.__disposeResources) || (function (SuppressedError) { - return function (env) { - function fail(e) { - env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; - env.hasError = true; - } - var r, s = 0; - function next() { - while (r = env.stack.pop()) { - try { - if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); - if (r.dispose) { - var result = r.dispose.call(r.value); - if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); - } - else s |= 1; - } - catch (e) { - fail(e); - } - } - if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); - if (env.hasError) throw env.error; - } - return next(); - }; -})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; -}); -/** - * Represents a tool use session backed by a single plugin. Don't construct this class yourself. - * - * @public - */ -class SingleRemoteToolUseSession { - static async create(pluginsPort, pluginIdentifier, pluginConfigSpecifier, logger, stack) { - const session = new SingleRemoteToolUseSession(pluginsPort, pluginIdentifier, pluginConfigSpecifier, logger); - await session.init(stack); - return session; - } - constructor(pluginsPort, pluginIdentifier, pluginConfigSpecifier, logger) { - this.pluginsPort = pluginsPort; - this.pluginIdentifier = pluginIdentifier; - this.pluginConfigSpecifier = pluginConfigSpecifier; - this.logger = logger; - this.status = "initializing"; - /** - * Whether this session is "poisoned". A session is poisoned either when the underlying channel - * has errored/closed. - */ - this.poison = null; - /** - * Map to track all the ongoing tool calls. - */ - this.ongoingToolCalls = new Map(); - this.callIdGiver = new IdGiver(0); - } - async init(stack) { - const { promise: initPromise, resolve: resolveInit, reject: rejectInit } = makePromise(); - const channel = this.pluginsPort.createChannel("startToolUseSession", { - pluginIdentifier: this.pluginIdentifier, - pluginConfigSpecifier: this.pluginConfigSpecifier, - }, message => { - const messageType = message.type; - switch (messageType) { - // Upon receiving session ready, mark self as ready and resolve the promise. - case "sessionReady": { - if (this.status !== "initializing") { - this.logger.error("Received sessionReady message while not initializing"); - return; - } - this.status = "ready"; - resolveInit(); - this.tools = message.toolDefinitions.map(toolDefinition => this.makeTool(toolDefinition)); - break; - } - case "toolCallComplete": { - const ongoingCall = this.ongoingToolCalls.get(message.callId); - if (ongoingCall === undefined) { - return; - } - ongoingCall.resolve(message.result); - break; - } - case "toolCallError": { - const ongoingCall = this.ongoingToolCalls.get(message.callId); - if (ongoingCall === undefined) { - return; - } - ongoingCall.reject(fromSerializedError(message.error)); - break; - } - case "toolCallStatus": { - const ongoingCall = this.ongoingToolCalls.get(message.callId); - if (ongoingCall === undefined) { - return; - } - ongoingCall.reportStatus(message.statusText); - break; - } - case "toolCallWarn": { - const ongoingCall = this.ongoingToolCalls.get(message.callId); - if (ongoingCall === undefined) { - return; - } - ongoingCall.reportWarning(message.warnText); - break; - } - default: { - const exhaustiveCheck = messageType; - this.logger.warn(`Received unexpected message type in tool use session: ${exhaustiveCheck}`); - } - } - }, { stack }); - channel.onError.subscribeOnce(error => { - if (this.status === "initializing") { - // If still initializing, reject the promise with the error. - rejectInit(error); - } - else { - this.logger.error("Tool use session error.", error); - this.poison = error; - } - // Reject all ongoing tool calls with the error. - for (const ongoingCall of this.ongoingToolCalls.values()) { - ongoingCall.reject(error); - } - this.status = "disposed"; - }); - channel.onClose.subscribeOnce(() => { - let error; - if (this.status === "initializing") { - // If still initializing, reject the promise with the error. - error = new Error("Tool use session channel closed unexpectedly during initialization."); - rejectInit(error); - } - else { - error = new Error("Tool use session has already ended."); - // We don't print an error here because channel can close normally. We only poison this - // session so it throws the error when used. - this.poison = error; - } - // Reject all ongoing tool calls with the error. - for (const ongoingCall of this.ongoingToolCalls.values()) { - ongoingCall.reject(error); - } - this.status = "disposed"; - }); - this.channel = channel; - await initPromise; - } - [Symbol.dispose]() { - // As long as we are not already disposed, we send a discard message to the channel. - if (this.status !== "disposed") { - this.channel.send({ type: "discardSession" }); - this.status = "disposed"; - const error = new Error("Session disposed by client."); - // Reject all ongoing tool calls with the error. - for (const ongoingCall of this.ongoingToolCalls.values()) { - ongoingCall.reject(error); - } - this.poison = error; - } - } - makeTool(toolDefinition) { - return internalCreateRemoteTool({ - name: toolDefinition.function.name, - description: toolDefinition.function.description ?? "", - pluginIdentifier: this.pluginIdentifier, - parametersJsonSchema: toolDefinition.function.parameters ?? {}, - implementation: async (args, ctx) => { - const env_1 = { stack: [], error: void 0, hasError: false }; - try { - // We now need to provide an implementation that basically proxies the execution of the tool - // to the backend. - if (this.poison !== null) { - // If the session is already poisoned, throw the error. - throw this.poison; - } - // Handling the case where the request is already aborted before we start the tool call. - if (ctx.signal.aborted) { - throw ctx.signal.reason; - } - const callId = this.callIdGiver.next(); - const { promise, resolve, reject } = makePromise(); - const cleaner = __addDisposableResource(env_1, new Cleaner(), false); - this.ongoingToolCalls.set(callId, { - callId, - resolve, - reject, - reportStatus: status => ctx.status(status), - reportWarning: warning => ctx.warn(warning), - }); - cleaner.register(() => { - this.ongoingToolCalls.delete(callId); - }); - this.channel.send({ - type: "callTool", - callId, - name: toolDefinition.function.name, - arguments: args, - }); - ctx.signal.addEventListener("abort", () => { - if (this.status === "disposed") { - return; - } - this.channel.send({ - type: "abortToolCall", - callId, - }); - reject(ctx.signal.reason); - }, { once: true }); - return await promise; - } - catch (e_1) { - env_1.error = e_1; - env_1.hasError = true; - } - finally { - __disposeResources(env_1); - } - }, - }); - } -} -/** - * Represents a tool use session backed by multiple plugins. Don't construct this class yourself. - * - * @public - */ -class MultiRemoteToolUseSession { - static async createUsingPredictionProcess(pluginsPort, pluginIdentifiers, predictionContextIdentifier, token, logger, stack) { - // Start initializing all the sessions in parallel. This is OK because usually all the plugins - // are already loaded for the prediction process anyway. - const results = await Promise.allSettled(pluginIdentifiers.map(pluginIdentifier => SingleRemoteToolUseSession.create(pluginsPort, pluginIdentifier, { - type: "predictionProcess", - pci: predictionContextIdentifier, - token, - }, logger, stack))); - const failed = results.filter(result => result.status === "rejected"); - if (failed.length > 0) { - // Some sessions failed to initialize. We need to terminate all the sessions that - // successfully initialized. - for (const result of results) { - if (result.status === "fulfilled") { - try { - result.value[Symbol.dispose](); - } - catch (error) { - logger.error("Failed to dispose a session after initialization failure.", error); - } - } - } - throw new AggregateError(failed.map(result => result.reason), "Failed to initialize some tool use sessions."); - } - return new MultiRemoteToolUseSession(results.map(result => result.value), logger); - } - constructor(sessions, logger) { - this.sessions = sessions; - this.logger = logger; - this.tools = []; - this.tools = sessions.flatMap(session => session.tools); - } - [Symbol.dispose]() { - // Dispose all the sessions. - for (const session of this.sessions) { - try { - session[Symbol.dispose](); - } - catch (error) { - this.logger.error("Failed to dispose a session.", error); - } - } - } -} - -const pluginToolsOptsSchema = z.object({ - pluginConfig: kvConfigSchema.optional(), - workingDirectory: z.string().optional(), -}); -const registerDevelopmentPluginOptsSchema = z.object({ - manifest: pluginManifestSchema, -}); -/** - * @public - * - * The namespace for file-related operations. Currently no public-facing methods. - */ -class PluginsNamespace { - /** @internal */ - constructor( - /** @internal */ - port, client, validator, parentLogger, rootLogger) { - this.port = port; - this.client = client; - this.validator = validator; - this.rootLogger = rootLogger; - this.logger = new SimpleLogger("Plugins", parentLogger); - } - /** - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - async registerDevelopmentPlugin(opts) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("plugins", "registerDevelopmentPlugin", "opts", registerDevelopmentPluginOptsSchema, opts, stack); - const { promise, resolve } = makePromise(); - const channel = this.port.createChannel("registerDevelopmentPlugin", opts, message => { - if (message.type === "ready") { - resolve({ - clientIdentifier: message.clientIdentifier, - clientPasskey: message.clientPasskey, - }); - } - }, { stack }); - let unregisterCalled = false; - const unregister = async () => { - if (unregisterCalled) { - return; - } - unregisterCalled = true; - channel.send({ type: "end" }); - const { promise, resolve } = makePromise(); - channel.onClose.subscribeOnce(resolve); - await promise; - }; - const base = await promise; - return { - ...base, - unregister, - }; - } - /** - * Requests LM Studio to reindex all the plugins. - * - * CAVEAT: Currently, we do not wait for the reindex to complete before returning. In the future, - * we will change this behavior and only return after the reindex is completed. - * - * @experimental [EXP-PLUGIN-CORE] Plugin support is still in development. This may change in the - * future without warning. - */ - async reindexPlugins() { - const stack = getCurrentStack(1); - await this.port.callRpc("reindexPlugins", undefined, { stack }); - } - /** - * If this client is currently running as a plugin, get the self registration host which can be - * used to register hooks. - * - * @deprecated This method is used by plugins internally to register hooks. Do not use directly. - */ - getSelfRegistrationHost() { - return new PluginSelfRegistrationHost(this.port, this.client, this.rootLogger, this.validator); - } - /** - * Starts a tool use session use any config specifier. - */ - async internalStartToolUseSession(pluginIdentifier, pluginConfigSpecifier, _stack) { - return await SingleRemoteToolUseSession.create(this.port, pluginIdentifier, pluginConfigSpecifier, this.logger); - } - /** - * Start a tool use session with a plugin. Note, this method must be used with "Explicit Resource - * Management". That is, you should use it like so: - * - * ```typescript - * using pluginTools = await client.plugins.pluginTools("owner/name", { ... }); - * // ^ Notice the `using` keyword here. - * ``` - * - * If you do not use `using`, you must call `pluginTools[Symbol.dispose]()` after you are done. - * Otherwise, there will be a memory leak and the plugins you requested tools from will be loaded - * indefinitely. - * - * @experimental [EXP-USE-USE-PLUGIN-TOOLS] Using tools from other applications is still in - * development. This may change in the future without warning. - */ - async pluginTools(pluginIdentifier, opts = {}) { - const stack = getCurrentStack(1); - [pluginIdentifier, opts] = this.validator.validateMethodParamsOrThrow("plugins", "pluginTools", ["pluginIdentifier", "opts"], [artifactIdentifierSchema, pluginToolsOptsSchema], [pluginIdentifier, opts], stack); - return await this.internalStartToolUseSession(pluginIdentifier, { - type: "direct", - config: opts.pluginConfig ?? emptyKVConfig, - workingDirectoryPath: opts.workingDirectory, - }); - } - /** - * Start a tool use session associated with a prediction process. - * - * This method is used internally by processing controllers and will be stripped by the internal - * tag. - * - * @internal - */ - async startToolUseSessionUsingPredictionProcess(pluginIdentifiers, predictionContextIdentifier, token, stack) { - return await MultiRemoteToolUseSession.createUsingPredictionProcess(this.port, pluginIdentifiers, predictionContextIdentifier, token, this.logger, stack); - } - /** - * @experimental [EXP-GEN-PREDICT] Using generator plugins programmatically is still in - * development. This may change in the future without warning. - */ - createGeneratorHandle(pluginIdentifier) { - return new LLMGeneratorHandle(this.port, pluginIdentifier, this.validator, null, this.logger); - } - /** - * Creates a generator handle that is already associated with a prediction process. - * - * This method is used internally by the processing controllers to create generator handles. It is - * marked as internal and will be stripped. - * - * @internal - */ - createGeneratorHandleAssociatedWithPredictionProcess(pluginIdentifier, predictionContextIdentifier, token) { - return new LLMGeneratorHandle(this.port, pluginIdentifier, this.validator, { pci: predictionContextIdentifier, token }, this.logger); - } -} - -const artifactDownloadPlannerDownloadOptsSchema = z.object({ - onStartFinalizing: z.function().optional(), - onProgress: z.function().optional(), - signal: z.instanceof(AbortSignal).optional(), -}); -/** - * Represents a planner to download an artifact. The plan is not guaranteed to be ready until you - * await on the method "untilReady". - * - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - * @public - */ -class ArtifactDownloadPlanner { - /** - * @internal Do not construct this class yourself. - */ - constructor(owner, name, onPlanUpdated, - /** @internal */ - channel, validator, onDisposed) { - this.owner = owner; - this.name = name; - this.onPlanUpdated = onPlanUpdated; - this.channel = channel; - this.validator = validator; - this.onDisposed = onDisposed; - this.readyDeferredPromise = makePromise(); - this.isReadyBoolean = false; - this.currentDownload = null; - /** - * If we received an error after the download starts, we will just raise the error in the download - * promise. - * - * However, if the error was received before download was called (e.g. plan resolution failed), - * we will store the error here and throw it as soon as `.download` is called. In addition, we - * will also raise the error in the ready promise. However, since it is not required to attach - * a listener there - */ - this.errorReceivedBeforeDownloadStart = null; - this.logger = new SimpleLogger(`ArtifactDownloadPlanner(${owner}/${name})`); - // Don't unhandled rejection - we don't require user to await on this promise. - this.readyDeferredPromise.promise.catch(() => { }); - this.planValue = { - nodes: [ - { - type: "artifact", - owner, - name, - state: "pending", - dependencyNodes: [], - }, - ], - downloadSizeBytes: 0, - }; - this.channel.onMessage.subscribe(message => { - const messageType = message.type; - switch (messageType) { - case "planReady": { - this.isReadyBoolean = true; - this.readyDeferredPromise.resolve(); - this.planValue = message.plan; - break; - } - case "planUpdated": { - this.planValue = message.plan; - safeCallCallback(this.logger, "onPlanUpdated", this.onPlanUpdated, [message.plan]); - break; - } - case "success": { - if (this.currentDownload === null) { - throw new Error("Unexpected: received success message without a download."); - } - this.currentDownload.downloadFinished(); - break; - } - case "downloadProgress": { - if (this.currentDownload === null) { - throw new Error("Unexpected: received progress message without a download."); - } - this.currentDownload.progressUpdate(message.update); - break; - } - case "startFinalizing": { - if (this.currentDownload === null) { - throw new Error("Unexpected: received startFinalizing message without a download."); - } - this.currentDownload.startFinalizing(); - break; - } - } - }); - this.channel.onError.subscribeOnce(error => { - if (this.currentDownload === null) { - this.errorReceivedBeforeDownloadStart = error; - this.readyDeferredPromise.reject(error); - } - else { - this.currentDownload.downloadFailed(error); - } - }); - } - [Symbol.dispose]() { - this.channel.send({ type: "cancel" }); - this.onDisposed(); - } - isReady() { - return this.isReadyBoolean; - } - async untilReady() { - return await this.readyDeferredPromise.promise; - } - getPlan() { - return this.planValue; - } - /** - * Download this artifact. `download` can only be called once. - */ - async download(opts) { - const stack = getCurrentStack(1); - opts = this.validator.validateMethodParamOrThrow("ArtifactDownloadPlanner", "download", "opts", artifactDownloadPlannerDownloadOptsSchema, opts, stack); - const { onProgress, onStartFinalizing, signal = new AbortController().signal } = opts; - if (this.currentDownload !== null) { - throw new Error("You can only call `download` once for each planner."); - } - if (this.errorReceivedBeforeDownloadStart !== null) { - // There has been an error. Raise it immediately. - const error = this.errorReceivedBeforeDownloadStart; - this.errorReceivedBeforeDownloadStart = null; - throw error; - } - const { promise, resolve, reject } = makePromise(); - this.currentDownload = { - downloadFinished: () => { - resolve(); - }, - startFinalizing: () => { - safeCallCallback(this.logger, "onStartFinalizing", onStartFinalizing, []); - }, - progressUpdate: update => { - safeCallCallback(this.logger, "onProgress", onProgress, [update]); - }, - downloadFailed: error => { - reject(error); - }, - }; - this.channel.send({ type: "commit" }); - if (signal.aborted) { - this.channel.send({ type: "cancel" }); - } - else { - signal.addEventListener("abort", () => { - this.channel.send({ type: "cancel" }); - }); - } - return await promise.catch(error => { - if (signal.aborted) { - // If the signal was aborted, we need to reject with the reason of the abort. - throw signal.reason; - } - else { - // Otherwise, we just reject with the error. - throw error; - } - }); - } -} - -const downloadOptsSchema = z.object({ - onProgress: z.function().optional(), - onStartFinalizing: z.function().optional(), - signal: z.instanceof(AbortSignal).optional(), -}); -/** @public */ -class ModelSearchResultDownloadOption { - /** @internal */ - constructor( - /** @internal */ - repositoryPort, - /** @internal */ - validator, logger, data) { - this.repositoryPort = repositoryPort; - this.validator = validator; - this.logger = logger; - this.data = data; - this.quantization = data.quantization; - this.name = data.name; - this.sizeBytes = data.sizeBytes; - this.fitEstimation = this.data.fitEstimation; - this.indexedModelIdentifier = this.data.indexedModelIdentifier; - } - isRecommended() { - return this.data.recommended ?? false; - } - /** - * Download the model. Returns the model key which can be used to load the model. - */ - async download(opts = {}) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("ModelSearchResultDownloadOption", "download", "opts", downloadOptsSchema, opts, stack); - const { promise, resolve, reject } = makePromise(); - const channel = this.repositoryPort.createChannel("downloadModel", { - downloadIdentifier: this.data.downloadIdentifier, - }, message => { - switch (message.type) { - case "downloadProgress": { - safeCallCallback(this.logger, "onProgress", opts.onProgress, [message.update]); - break; - } - case "startFinalizing": { - safeCallCallback(this.logger, "onStartFinalizing", opts.onStartFinalizing, []); - break; - } - case "success": { - resolve(message.defaultIdentifier); - break; - } - default: { - const exhaustiveCheck = message; - throw new Error(`Unexpected message type: ${exhaustiveCheck}`); - } - } - }, { stack }); - channel.onError.subscribeOnce(error => { - if (opts.signal?.aborted) { - reject(opts.signal.reason); - } - else { - reject(error); - } - }); - channel.onClose.subscribeOnce(() => { - if (opts.signal?.aborted) { - reject(opts.signal.reason); - } - else { - reject(new Error("Channel closed unexpectedly.")); - } - }); - const abortListener = () => { - channel.send({ type: "cancel" }); - }; - opts.signal?.addEventListener("abort", abortListener); - promise.finally(() => { - opts.signal?.removeEventListener("abort", abortListener); - }); - return await promise; - } -} - -/** @public */ -class ModelSearchResultEntry { - /** - * @internal - */ - constructor( - /** @internal */ - repositoryPort, - /** @internal */ - validator, logger, data) { - this.repositoryPort = repositoryPort; - this.validator = validator; - this.logger = logger; - this.data = data; - this.name = data.name; - } - isExactMatch() { - return this.data.exact ?? false; - } - isStaffPick() { - return this.data.staffPick ?? false; - } - async getDownloadOptions() { - const { results } = await this.repositoryPort.callRpc("getModelDownloadOptions", { - modelSearchResultIdentifier: this.data.identifier, - }); - return results.map(data => new ModelSearchResultDownloadOption(this.repositoryPort, this.validator, this.logger, data)); - } -} - -const downloadArtifactOptsSchema = z.object({ - owner: z.string(), - name: z.string(), - revisionNumber: z.number(), - path: z.string(), - onProgress: z.function().optional(), - onStartFinalizing: z.function().optional(), - signal: z.instanceof(AbortSignal).optional(), -}); -const pushArtifactOptsSchema = z.object({ - path: z.string(), - description: z.string().optional(), - makePrivate: z.boolean().optional(), - writeRevision: z.boolean().optional(), - overrides: jsonSerializableSchema.optional(), - onMessage: z.function().optional(), -}); -const ensureAuthenticatedOptsSchema = z.object({ - onAuthenticationUrl: z.function(), -}); -const loginWithPreAuthenticatedKeysOptsSchema = z.object({ - keyId: z.string(), - publicKey: z.string(), - privateKey: z.string(), -}); -z.object({ - userName: z.string(), -}); -const createArtifactDownloadPlannerOptsSchema = z.object({ - owner: z.string(), - name: z.string(), - onPlanUpdated: z.function().optional(), -}); -/** @public */ -class RepositoryNamespace { - /** @internal */ - constructor(repositoryPort, validator, parentLogger) { - this.repositoryPort = repositoryPort; - this.validator = validator; - this.downloadPlanFinalizationRegistry = new FinalizationRegistry(({ owner, name }) => { - this.logger.warn(` - A download plan for artifact ${owner}/${name} has been garbage collected without being - disposed. Please make sure you are creating the download plan with the "using" keyword. - - This is a memory leak and needs to be fixed. - `); - }); - this.logger = new SimpleLogger("Repository", parentLogger); - } - async searchModels(opts) { - const stack = getCurrentStack(1); - opts = this.validator.validateMethodParamOrThrow("repository", "search", "opts", modelSearchOptsSchema, opts, stack); - const { results } = await this.repositoryPort.callRpc("searchModels", { opts }, { stack }); - return results.map(data => new ModelSearchResultEntry(this.repositoryPort, this.validator, this.logger, data)); - } - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - async installPluginDependencies(pluginFolder) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("repository", "installPluginDependencies", "pluginFolder", z.string(), pluginFolder, stack); - await this.repositoryPort.callRpc("installPluginDependencies", { pluginFolder }, { stack }); - } - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - async downloadArtifact(opts) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("client.repository", "downloadArtifact", "opts", downloadArtifactOptsSchema, opts, stack); - const { owner, name, revisionNumber, path, onProgress, onStartFinalizing, signal } = opts; - const { promise, resolve, reject } = makePromise(); - const channel = this.repositoryPort.createChannel("downloadArtifact", { artifactOwner: owner, artifactName: name, revisionNumber, path }, message => { - switch (message.type) { - case "downloadProgress": { - safeCallCallback(this.logger, "onProgress", onProgress, [message.update]); - break; - } - case "startFinalizing": { - safeCallCallback(this.logger, "onStartFinalizing", onStartFinalizing, []); - break; - } - case "success": { - resolve(); - break; - } - default: { - const exhaustiveCheck = message; - throw new Error(`Unexpected message type: ${exhaustiveCheck}`); - } - } - }, { stack }); - channel.onError.subscribeOnce(reject); - channel.onClose.subscribeOnce(() => { - if (signal?.aborted) { - reject(signal.reason); - } - else { - reject(new Error("Channel closed unexpectedly.")); - } - }); - const abortListener = () => { - channel.send({ type: "cancel" }); - }; - signal?.addEventListener("abort", abortListener); - promise.finally(() => { - signal?.removeEventListener("abort", abortListener); - }); - return await promise; - } - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - async pushArtifact(opts) { - const stack = getCurrentStack(1); - const { path, description, makePrivate, writeRevision, overrides, onMessage } = this.validator.validateMethodParamOrThrow("repository", "pushArtifact", "opts", pushArtifactOptsSchema, opts, stack); - const channel = this.repositoryPort.createChannel("pushArtifact", { path, description, makePrivate, writeRevision, overrides }, message => { - const type = message.type; - switch (type) { - case "message": { - safeCallCallback(this.logger, "onMessage", onMessage, [message.message]); - break; - } - default: { - const exhaustiveCheck = type; - throw new Error(`Unexpected message type: ${exhaustiveCheck}`); - } - } - }, { stack }); - const { promise, resolve, reject } = makePromise(); - channel.onError.subscribeOnce(reject); - channel.onClose.subscribeOnce(resolve); - await promise; - } - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - async getLocalArtifactFileList(path) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("repository", "getLocalArtifactFileList", "path", z.string(), path, stack); - const { fileList } = await this.repositoryPort.callRpc("getLocalArtifactFiles", { path }, { stack }); - return fileList; - } - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - async ensureAuthenticated(opts) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("repository", "ensureAuthenticated", "opts", ensureAuthenticatedOptsSchema, opts, stack); - const { promise, resolve, reject } = makePromise(); - const channel = this.repositoryPort.createChannel("ensureAuthenticated", undefined, message => { - const type = message.type; - switch (type) { - case "authenticationUrl": { - safeCallCallback(this.logger, "onAuthenticationUrl", opts.onAuthenticationUrl, [ - message.url, - ]); - break; - } - case "authenticated": { - resolve(); - break; - } - default: { - const exhaustiveCheck = type; - throw new Error(`Unexpected message type: ${exhaustiveCheck}`); - } - } - }); - channel.onError.subscribeOnce(reject); - await promise; - } - async loginWithPreAuthenticatedKeys(opts) { - const stack = getCurrentStack(1); - this.validator.validateMethodParamOrThrow("repository", "loginWithPreAuthenticatedKeys", "opts", loginWithPreAuthenticatedKeysOptsSchema, opts, stack); - const { keyId, publicKey, privateKey } = opts; - const { userName } = await this.repositoryPort.callRpc("loginWithPreAuthenticatedKeys", { keyId, publicKey, privateKey }, { stack }); - return { userName }; - } - /** - * @deprecated [DEP-HUB-API-ACCESS] LM Studio Hub API access is still in active development. Stay - * tuned for updates. - */ - createArtifactDownloadPlanner(opts) { - const { owner, name, onPlanUpdated } = this.validator.validateMethodParamOrThrow("repository", "createArtifactDownloadPlanner", "opts", createArtifactDownloadPlannerOptsSchema, opts); - const stack = getCurrentStack(1); - const channel = this.repositoryPort.createChannel("createArtifactDownloadPlan", { owner, name }, undefined, // Don't listen to the messages yet. - { stack }); - const planner = new ArtifactDownloadPlanner(owner, name, onPlanUpdated, channel, this.validator, () => { - this.downloadPlanFinalizationRegistry.unregister(planner); - }); - this.downloadPlanFinalizationRegistry.register(planner, { owner, name }, planner); - return planner; - } -} - -const startHttpServerOptsSchema = z.object({ - port: z - .number() - .int() - .min(1) - .max(65535) - .describe("Port to run the API server on. Must be between 1 and 65535."), - cors: z - .boolean() - .describe("Enable CORS on the API server. Allows any website to access the server."), -}); -/** @public */ -class SystemNamespace { - /** @internal */ - constructor(systemPort, validator, parentLogger) { - this.systemPort = systemPort; - this.validator = validator; - this.logger = new SimpleLogger("System", parentLogger); - } - async listDownloadedModels(domain) { - const stack = getCurrentStack(1); - domain = this.validator.validateMethodParamOrThrow("client.system", "listDownloadedModels", "domain", z.union([z.literal("llm"), z.literal("embedding"), z.undefined()]), domain, stack); - const models = await this.systemPort.callRpc("listDownloadedModels", undefined, { - stack: getCurrentStack(1), - }); - if (domain === undefined) { - return models; - } - return models.filter(model => model.type === domain); - } - async whenDisconnected() { - const stack = getCurrentStack(1); - const channel = this.systemPort.createChannel("alive", undefined, undefined, { stack }); - const { promise, resolve } = makePromise(); - channel.onError.subscribeOnce(resolve); - channel.onClose.subscribeOnce(resolve); - await promise; - } - async notify(notification) { - const stack = getCurrentStack(1); - notification = this.validator.validateMethodParamOrThrow("client.system", "notify", "notification", backendNotificationSchema, notification, stack); - await this.systemPort.callRpc("notify", notification, { stack }); - } - async getLMStudioVersion() { - const stack = getCurrentStack(1); - return await this.systemPort.callRpc("version", undefined, { stack }); - } - /** - * Sets an experiment flags for LM Studio. This is an unstable API and may change without notice. - * - * @experimental - */ - async unstable_setExperimentFlag(flag, value) { - const stack = getCurrentStack(1); - [flag, value] = this.validator.validateMethodParamsOrThrow("client.system", "setExperimentFlag", ["flag", "value"], [z.string(), z.boolean()], [flag, value], stack); - await this.systemPort.callRpc("setExperimentFlag", { code: flag, value }, { stack }); - } - /** - * Gets all experiment flags for LM Studio. This is an unstable API and may change without notice. - * - * @experimental - */ - async unstable_getExperimentFlags() { - const stack = getCurrentStack(1); - return await this.systemPort.callRpc("getExperimentFlags", undefined, { stack }); - } - /** - * Starts the API server on the specified port. - * - * @experimental - */ - async startHttpServer(opts) { - const stack = getCurrentStack(1); - opts = this.validator.validateMethodParamOrThrow("client.system", "startHttpServer", "args", startHttpServerOptsSchema, opts); - return await this.systemPort.callRpc("startHttpServer", { port: opts.port, cors: opts.cors }, { - stack, - }); - } - /** - * Stops the API server if it is running. - * - * @experimental - */ - async stopHttpServer() { - const stack = getCurrentStack(1); - return await this.systemPort.callRpc("stopHttpServer", undefined, { stack }); - } -} - -const constructorOptsSchema = z - .object({ - logger: z.any().optional(), - baseUrl: z.string().optional(), - verboseErrorMessages: z.boolean().optional(), - clientIdentifier: z.string().optional(), - clientPasskey: z.string().optional(), - // Internal testing options - disableConnection: z.boolean().optional(), - llmPort: z.any().optional(), - embeddingPort: z.any().optional(), - systemPort: z.any().optional(), - diagnosticsPort: z.any().optional(), - retrievalPort: z.any().optional(), - filesPort: z.any().optional(), - repositoryPort: z.any().optional(), - pluginsPort: z.any().optional(), -}) - .strict(); -/** @public */ -class LMStudioClient { - /** @internal */ - validateBaseUrlOrThrow(baseUrl) { - let url; - try { - url = new URL(baseUrl); - } - catch (e) { - this.logger.throw(text ` - Failed to construct LMStudioClient. The baseUrl passed in is invalid. Received: ${baseUrl} - `); - } - if (!["ws:", "wss:"].includes(url.protocol)) { - this.logger.throw(text ` - Failed to construct LMStudioClient. The baseUrl passed in must have protocol "ws" or "wss". - Received: ${baseUrl} - `); - } - if (url.search !== "") { - this.logger.throw(text ` - Failed to construct LMStudioClient. The baseUrl passed contains search parameters - ("${url.search}"). - `); - } - if (url.hash !== "") { - this.logger.throw(text ` - Failed to construct LMStudioClient. The baseUrl passed contains a hash ("${url.hash}"). - `); - } - if (url.username !== "" || url.password !== "") { - this.logger.throw(text ` - Failed to construct LMStudioClient. The baseUrl passed contains a username or password. We - do not support these in the baseUrl. Received: ${baseUrl} - `); - } - if (baseUrl.endsWith("/")) { - this.logger.throw(text ` - Failed to construct LMStudioClient. The baseUrl passed in must not end with a "/". If you - are reverse-proxying, you should remove the trailing slash from the baseUrl. Received: - ${baseUrl} - `); - } - } - async isLocalhostWithGivenPortLMStudioServer(port) { - const response = await fetch(`http://127.0.0.1:${port}/lmstudio-greeting`); - if (response.status !== 200) { - throw new Error("Status is not 200."); - } - const json = await response.json(); - if (json?.lmstudio !== true) { - throw new Error("Not an LM Studio server."); - } - return port; - } - /** - * Guess the base URL of the LM Studio server by visiting localhost on various default ports. - */ - async guessBaseUrl(stack) { - if (getHostedEnv() !== null) { - return Promise.resolve("Using hosted env"); - } - // On browser, those apiServerPorts are not accessible anyway. We will just try to see if we can - // reach the server on 127.0.0.1:1234 (the default port). - if (process$1.browser) { - try { - this.isLocalhostWithGivenPortLMStudioServer(1234); - return "ws://127.0.0.1:1234"; - } - catch (error) { - text ` - ${chalk.redBright("Failed to connect to LM Studio.")} - - Is LM Studio running? If not, please start it by running: - - ${chalk.yellow("lms server start --cors")} - - If you are attempting to connect to LM Studio on a separate machine, please provide the - baseUrl option when creating the LMStudioClient: - - ${chalk.blueBright(text ` - const client = new LMStudioClient({ baseUrl: 'ws://:' }); - `)} - - ${chalk.white("(i) For more information, refer to the LM Studio documentation:")} - - ${chalk.gray("https://lmstudio.ai/docs/local-server")} - `; - } - } - return Promise.any(apiServerPorts.map(this.isLocalhostWithGivenPortLMStudioServer)).then(port => `ws://127.0.0.1:${port}`, () => { - throw makePrettyError(text ` - ${chalk.redBright("Failed to connect to LM Studio.")} - - Please make sure LM Studio is running on your machine. - - If you are attempting to connect to LM Studio on a separate machine, please provide the - baseUrl option when creating the LMStudioClient: - - ${chalk.blueBright(text ` - const client = new LMStudioClient({ baseUrl: 'ws://:' }); - `)} - - ${chalk.white("(i) For more information, refer to the LM Studio documentation:")} - - ${chalk.gray("https://lmstudio.ai/docs/local-server")} - `, stack); - }); - } - createPort(namespace, name, backendInterface) { - return createAuthenticatedClientPort(backendInterface, this.resolvingBaseUrl, namespace, this.clientIdentifier, this.clientPasskey, new SimpleLogger(name, this.logger), { - errorDeserializer: friendlyErrorDeserializer, - verboseErrorMessage: this.verboseErrorMessages, - }); - } - constructor(opts = {}) { - const { logger, baseUrl, verboseErrorMessages, clientIdentifier, clientPasskey, disableConnection, llmPort, embeddingPort, systemPort, diagnosticsPort, retrievalPort, filesPort, repositoryPort, pluginsPort, } = new Validator().validateConstructorParamOrThrow("LMStudioClient", "opts", constructorOptsSchema, opts); - if (globalThis.__LMS_PLUGIN_CONTEXT && opts.baseUrl === undefined) { - throw new Error(text ` - You cannot create a local LMStudioClient in a plugin context. To use LM Studio APIs, use - the "client" property attached to the Controllers. - - For example, instead of: - - ${"const client = new LMStudioClient(); // <-- Error\n" + - "export async function generate(ctl: GeneratorController) {\n" + - " const model = await client.llm.model(...);\n" + - "}"} - - Do this: - - ${"export async function generate(ctl: GeneratorController) {\n" + - " const model = await ctl.client.llm.model(...);\n" + - "}"} - - If you need to connect to a remote LM Studio, you should pass in the \`baseUrl\` option to - the LMStudioClient constructor: - - ${"const client = new LMStudioClient({ baseUrl: 'ws://:' });"} - `); - } - this.logger = new SimpleLogger("LMStudioClient", logger); - this.clientIdentifier = clientIdentifier ?? generateRandomBase64(18); - this.clientPasskey = clientPasskey ?? generateRandomBase64(18); - const stack = getCurrentStack(1); - if (disableConnection) { - this.resolvingBaseUrl = new Promise(() => undefined); - } - else { - if (baseUrl === undefined) { - this.resolvingBaseUrl = this.guessBaseUrl(verboseErrorMessages ? stack : undefined); - } - else { - this.validateBaseUrlOrThrow(baseUrl); - this.resolvingBaseUrl = baseUrl; - } - } - this.verboseErrorMessages = verboseErrorMessages ?? true; - this.llmPort = llmPort ?? this.createPort("llm", "LLM", createLlmBackendInterface()); - this.embeddingPort = - embeddingPort ?? this.createPort("embedding", "Embedding", createEmbeddingBackendInterface()); - this.systemPort = - systemPort ?? this.createPort("system", "System", createSystemBackendInterface()); - this.diagnosticsPort = - diagnosticsPort ?? - this.createPort("diagnostics", "Diagnostics", createDiagnosticsBackendInterface()); - this.filesPort = filesPort ?? this.createPort("files", "Files", createFilesBackendInterface()); - this.repositoryPort = - repositoryPort ?? - this.createPort("repository", "Repository", createRepositoryBackendInterface()); - this.pluginsPort = - pluginsPort ?? this.createPort("plugins", "Plugins", createPluginsBackendInterface()); - const validator = new Validator(); - this.llm = new LLMNamespace(this, this.llmPort, new SimpleLogger("LLM", this.logger), validator); - this.embedding = new EmbeddingNamespace(this, this.embeddingPort, new SimpleLogger("Embedding", this.logger), validator); - this.system = new SystemNamespace(this.systemPort, validator, this.logger); - this.diagnostics = new DiagnosticsNamespace(this.diagnosticsPort, validator, this.logger); - this.files = new FilesNamespace(this.filesPort, validator, this.logger); - this.repository = new RepositoryNamespace(this.repositoryPort, validator, this.logger); - this.plugins = new PluginsNamespace(this.pluginsPort, this, validator, this.logger, logger); - } - async [Symbol.asyncDispose]() { - await Promise.all([ - this.llmPort[Symbol.asyncDispose](), - this.embeddingPort[Symbol.asyncDispose](), - this.systemPort[Symbol.asyncDispose](), - this.diagnosticsPort[Symbol.asyncDispose](), - this.filesPort[Symbol.asyncDispose](), - this.repositoryPort[Symbol.asyncDispose](), - this.pluginsPort[Symbol.asyncDispose](), - ]); - } -} - -export { Chat, ChatMessage, FileHandle, LMStudioClient, MaybeMutable, ToolCallRequestError, createConfigSchematics, kvValueTypesLibrary, rawFunctionTool, text, tool, unimplementedRawFunctionTool }; diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/ansi-styles/index.d.ts b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/ansi-styles/index.d.ts deleted file mode 100644 index 44a907e58..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/ansi-styles/index.d.ts +++ /dev/null @@ -1,345 +0,0 @@ -declare type CSSColor = - | 'aliceblue' - | 'antiquewhite' - | 'aqua' - | 'aquamarine' - | 'azure' - | 'beige' - | 'bisque' - | 'black' - | 'blanchedalmond' - | 'blue' - | 'blueviolet' - | 'brown' - | 'burlywood' - | 'cadetblue' - | 'chartreuse' - | 'chocolate' - | 'coral' - | 'cornflowerblue' - | 'cornsilk' - | 'crimson' - | 'cyan' - | 'darkblue' - | 'darkcyan' - | 'darkgoldenrod' - | 'darkgray' - | 'darkgreen' - | 'darkgrey' - | 'darkkhaki' - | 'darkmagenta' - | 'darkolivegreen' - | 'darkorange' - | 'darkorchid' - | 'darkred' - | 'darksalmon' - | 'darkseagreen' - | 'darkslateblue' - | 'darkslategray' - | 'darkslategrey' - | 'darkturquoise' - | 'darkviolet' - | 'deeppink' - | 'deepskyblue' - | 'dimgray' - | 'dimgrey' - | 'dodgerblue' - | 'firebrick' - | 'floralwhite' - | 'forestgreen' - | 'fuchsia' - | 'gainsboro' - | 'ghostwhite' - | 'gold' - | 'goldenrod' - | 'gray' - | 'green' - | 'greenyellow' - | 'grey' - | 'honeydew' - | 'hotpink' - | 'indianred' - | 'indigo' - | 'ivory' - | 'khaki' - | 'lavender' - | 'lavenderblush' - | 'lawngreen' - | 'lemonchiffon' - | 'lightblue' - | 'lightcoral' - | 'lightcyan' - | 'lightgoldenrodyellow' - | 'lightgray' - | 'lightgreen' - | 'lightgrey' - | 'lightpink' - | 'lightsalmon' - | 'lightseagreen' - | 'lightskyblue' - | 'lightslategray' - | 'lightslategrey' - | 'lightsteelblue' - | 'lightyellow' - | 'lime' - | 'limegreen' - | 'linen' - | 'magenta' - | 'maroon' - | 'mediumaquamarine' - | 'mediumblue' - | 'mediumorchid' - | 'mediumpurple' - | 'mediumseagreen' - | 'mediumslateblue' - | 'mediumspringgreen' - | 'mediumturquoise' - | 'mediumvioletred' - | 'midnightblue' - | 'mintcream' - | 'mistyrose' - | 'moccasin' - | 'navajowhite' - | 'navy' - | 'oldlace' - | 'olive' - | 'olivedrab' - | 'orange' - | 'orangered' - | 'orchid' - | 'palegoldenrod' - | 'palegreen' - | 'paleturquoise' - | 'palevioletred' - | 'papayawhip' - | 'peachpuff' - | 'peru' - | 'pink' - | 'plum' - | 'powderblue' - | 'purple' - | 'rebeccapurple' - | 'red' - | 'rosybrown' - | 'royalblue' - | 'saddlebrown' - | 'salmon' - | 'sandybrown' - | 'seagreen' - | 'seashell' - | 'sienna' - | 'silver' - | 'skyblue' - | 'slateblue' - | 'slategray' - | 'slategrey' - | 'snow' - | 'springgreen' - | 'steelblue' - | 'tan' - | 'teal' - | 'thistle' - | 'tomato' - | 'turquoise' - | 'violet' - | 'wheat' - | 'white' - | 'whitesmoke' - | 'yellow' - | 'yellowgreen'; - -declare namespace ansiStyles { - interface ColorConvert { - /** - The RGB color space. - - @param red - (`0`-`255`) - @param green - (`0`-`255`) - @param blue - (`0`-`255`) - */ - rgb(red: number, green: number, blue: number): string; - - /** - The RGB HEX color space. - - @param hex - A hexadecimal string containing RGB data. - */ - hex(hex: string): string; - - /** - @param keyword - A CSS color name. - */ - keyword(keyword: CSSColor): string; - - /** - The HSL color space. - - @param hue - (`0`-`360`) - @param saturation - (`0`-`100`) - @param lightness - (`0`-`100`) - */ - hsl(hue: number, saturation: number, lightness: number): string; - - /** - The HSV color space. - - @param hue - (`0`-`360`) - @param saturation - (`0`-`100`) - @param value - (`0`-`100`) - */ - hsv(hue: number, saturation: number, value: number): string; - - /** - The HSV color space. - - @param hue - (`0`-`360`) - @param whiteness - (`0`-`100`) - @param blackness - (`0`-`100`) - */ - hwb(hue: number, whiteness: number, blackness: number): string; - - /** - Use a [4-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4-bit) to set text color. - */ - ansi(ansi: number): string; - - /** - Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. - */ - ansi256(ansi: number): string; - } - - interface CSPair { - /** - The ANSI terminal control sequence for starting this style. - */ - readonly open: string; - - /** - The ANSI terminal control sequence for ending this style. - */ - readonly close: string; - } - - interface ColorBase { - readonly ansi: ColorConvert; - readonly ansi256: ColorConvert; - readonly ansi16m: ColorConvert; - - /** - The ANSI terminal control sequence for ending this color. - */ - readonly close: string; - } - - interface Modifier { - /** - Resets the current color chain. - */ - readonly reset: CSPair; - - /** - Make text bold. - */ - readonly bold: CSPair; - - /** - Emitting only a small amount of light. - */ - readonly dim: CSPair; - - /** - Make text italic. (Not widely supported) - */ - readonly italic: CSPair; - - /** - Make text underline. (Not widely supported) - */ - readonly underline: CSPair; - - /** - Inverse background and foreground colors. - */ - readonly inverse: CSPair; - - /** - Prints the text, but makes it invisible. - */ - readonly hidden: CSPair; - - /** - Puts a horizontal line through the center of the text. (Not widely supported) - */ - readonly strikethrough: CSPair; - } - - interface ForegroundColor { - readonly black: CSPair; - readonly red: CSPair; - readonly green: CSPair; - readonly yellow: CSPair; - readonly blue: CSPair; - readonly cyan: CSPair; - readonly magenta: CSPair; - readonly white: CSPair; - - /** - Alias for `blackBright`. - */ - readonly gray: CSPair; - - /** - Alias for `blackBright`. - */ - readonly grey: CSPair; - - readonly blackBright: CSPair; - readonly redBright: CSPair; - readonly greenBright: CSPair; - readonly yellowBright: CSPair; - readonly blueBright: CSPair; - readonly cyanBright: CSPair; - readonly magentaBright: CSPair; - readonly whiteBright: CSPair; - } - - interface BackgroundColor { - readonly bgBlack: CSPair; - readonly bgRed: CSPair; - readonly bgGreen: CSPair; - readonly bgYellow: CSPair; - readonly bgBlue: CSPair; - readonly bgCyan: CSPair; - readonly bgMagenta: CSPair; - readonly bgWhite: CSPair; - - /** - Alias for `bgBlackBright`. - */ - readonly bgGray: CSPair; - - /** - Alias for `bgBlackBright`. - */ - readonly bgGrey: CSPair; - - readonly bgBlackBright: CSPair; - readonly bgRedBright: CSPair; - readonly bgGreenBright: CSPair; - readonly bgYellowBright: CSPair; - readonly bgBlueBright: CSPair; - readonly bgCyanBright: CSPair; - readonly bgMagentaBright: CSPair; - readonly bgWhiteBright: CSPair; - } -} - -declare const ansiStyles: { - readonly modifier: ansiStyles.Modifier; - readonly color: ansiStyles.ForegroundColor & ansiStyles.ColorBase; - readonly bgColor: ansiStyles.BackgroundColor & ansiStyles.ColorBase; - readonly codes: ReadonlyMap; -} & ansiStyles.BackgroundColor & ansiStyles.ForegroundColor & ansiStyles.Modifier; - -export = ansiStyles; diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/ansi-styles/index.js b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/ansi-styles/index.js deleted file mode 100644 index 5d82581a1..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/ansi-styles/index.js +++ /dev/null @@ -1,163 +0,0 @@ -'use strict'; - -const wrapAnsi16 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${code + offset}m`; -}; - -const wrapAnsi256 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${38 + offset};5;${code}m`; -}; - -const wrapAnsi16m = (fn, offset) => (...args) => { - const rgb = fn(...args); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; -}; - -const ansi2ansi = n => n; -const rgb2rgb = (r, g, b) => [r, g, b]; - -const setLazyProperty = (object, property, get) => { - Object.defineProperty(object, property, { - get: () => { - const value = get(); - - Object.defineProperty(object, property, { - value, - enumerable: true, - configurable: true - }); - - return value; - }, - enumerable: true, - configurable: true - }); -}; - -/** @type {typeof import('color-convert')} */ -let colorConvert; -const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { - if (colorConvert === undefined) { - colorConvert = require('color-convert'); - } - - const offset = isBackground ? 10 : 0; - const styles = {}; - - for (const [sourceSpace, suite] of Object.entries(colorConvert)) { - const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; - if (sourceSpace === targetSpace) { - styles[name] = wrap(identity, offset); - } else if (typeof suite === 'object') { - styles[name] = wrap(suite[targetSpace], offset); - } - } - - return styles; -}; - -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - - // Bright color - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - - // Alias bright black as gray (and grey) - styles.color.gray = styles.color.blackBright; - styles.bgColor.bgGray = styles.bgColor.bgBlackBright; - styles.color.grey = styles.color.blackBright; - styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; - - for (const [groupName, group] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group)) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; - - group[styleName] = styles[styleName]; - - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - } - - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; - - setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); - setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); - - return styles; -} - -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/ansi-styles/license b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/ansi-styles/license deleted file mode 100644 index e7af2f771..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/ansi-styles/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/ansi-styles/package.json b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/ansi-styles/package.json deleted file mode 100644 index 75393284d..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/ansi-styles/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name": "ansi-styles", - "version": "4.3.0", - "description": "ANSI escape codes for styling strings in the terminal", - "license": "MIT", - "repository": "chalk/ansi-styles", - "funding": "https://github.com/chalk/ansi-styles?sponsor=1", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=8" - }, - "scripts": { - "test": "xo && ava && tsd", - "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "ansi", - "styles", - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "string", - "tty", - "escape", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "log", - "logging", - "command-line", - "text" - ], - "dependencies": { - "color-convert": "^2.0.1" - }, - "devDependencies": { - "@types/color-convert": "^1.9.0", - "ava": "^2.3.0", - "svg-term-cli": "^2.1.1", - "tsd": "^0.11.0", - "xo": "^0.25.3" - } -} diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/ansi-styles/readme.md b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/ansi-styles/readme.md deleted file mode 100644 index 24883de80..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/ansi-styles/readme.md +++ /dev/null @@ -1,152 +0,0 @@ -# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles) - -> [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal - -You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. - - - -## Install - -``` -$ npm install ansi-styles -``` - -## Usage - -```js -const style = require('ansi-styles'); - -console.log(`${style.green.open}Hello world!${style.green.close}`); - - -// Color conversion between 16/256/truecolor -// NOTE: If conversion goes to 16 colors or 256 colors, the original color -// may be degraded to fit that color palette. This means terminals -// that do not support 16 million colors will best-match the -// original color. -console.log(style.bgColor.ansi.hsl(120, 80, 72) + 'Hello world!' + style.bgColor.close); -console.log(style.color.ansi256.rgb(199, 20, 250) + 'Hello world!' + style.color.close); -console.log(style.color.ansi16m.hex('#abcdef') + 'Hello world!' + style.color.close); -``` - -## API - -Each style has an `open` and `close` property. - -## Styles - -### Modifiers - -- `reset` -- `bold` -- `dim` -- `italic` *(Not widely supported)* -- `underline` -- `inverse` -- `hidden` -- `strikethrough` *(Not widely supported)* - -### Colors - -- `black` -- `red` -- `green` -- `yellow` -- `blue` -- `magenta` -- `cyan` -- `white` -- `blackBright` (alias: `gray`, `grey`) -- `redBright` -- `greenBright` -- `yellowBright` -- `blueBright` -- `magentaBright` -- `cyanBright` -- `whiteBright` - -### Background colors - -- `bgBlack` -- `bgRed` -- `bgGreen` -- `bgYellow` -- `bgBlue` -- `bgMagenta` -- `bgCyan` -- `bgWhite` -- `bgBlackBright` (alias: `bgGray`, `bgGrey`) -- `bgRedBright` -- `bgGreenBright` -- `bgYellowBright` -- `bgBlueBright` -- `bgMagentaBright` -- `bgCyanBright` -- `bgWhiteBright` - -## Advanced usage - -By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. - -- `style.modifier` -- `style.color` -- `style.bgColor` - -###### Example - -```js -console.log(style.color.green.open); -``` - -Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values. - -###### Example - -```js -console.log(style.codes.get(36)); -//=> 39 -``` - -## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728) - -`ansi-styles` uses the [`color-convert`](https://github.com/Qix-/color-convert) package to allow for converting between various colors and ANSI escapes, with support for 256 and 16 million colors. - -The following color spaces from `color-convert` are supported: - -- `rgb` -- `hex` -- `keyword` -- `hsl` -- `hsv` -- `hwb` -- `ansi` -- `ansi256` - -To use these, call the associated conversion function with the intended output, for example: - -```js -style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code -style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code - -style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code -style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code - -style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code -style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code -``` - -## Related - -- [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal - -## Maintainers - -- [Sindre Sorhus](https://github.com/sindresorhus) -- [Josh Junon](https://github.com/qix-) - -## For enterprise - -Available as part of the Tidelift Subscription. - -The maintainers of `ansi-styles` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-ansi-styles?utm_source=npm-ansi-styles&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/chalk/index.d.ts b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/chalk/index.d.ts deleted file mode 100644 index 9cd88f38b..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/chalk/index.d.ts +++ /dev/null @@ -1,415 +0,0 @@ -/** -Basic foreground colors. - -[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) -*/ -declare type ForegroundColor = - | 'black' - | 'red' - | 'green' - | 'yellow' - | 'blue' - | 'magenta' - | 'cyan' - | 'white' - | 'gray' - | 'grey' - | 'blackBright' - | 'redBright' - | 'greenBright' - | 'yellowBright' - | 'blueBright' - | 'magentaBright' - | 'cyanBright' - | 'whiteBright'; - -/** -Basic background colors. - -[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) -*/ -declare type BackgroundColor = - | 'bgBlack' - | 'bgRed' - | 'bgGreen' - | 'bgYellow' - | 'bgBlue' - | 'bgMagenta' - | 'bgCyan' - | 'bgWhite' - | 'bgGray' - | 'bgGrey' - | 'bgBlackBright' - | 'bgRedBright' - | 'bgGreenBright' - | 'bgYellowBright' - | 'bgBlueBright' - | 'bgMagentaBright' - | 'bgCyanBright' - | 'bgWhiteBright'; - -/** -Basic colors. - -[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) -*/ -declare type Color = ForegroundColor | BackgroundColor; - -declare type Modifiers = - | 'reset' - | 'bold' - | 'dim' - | 'italic' - | 'underline' - | 'inverse' - | 'hidden' - | 'strikethrough' - | 'visible'; - -declare namespace chalk { - /** - Levels: - - `0` - All colors disabled. - - `1` - Basic 16 colors support. - - `2` - ANSI 256 colors support. - - `3` - Truecolor 16 million colors support. - */ - type Level = 0 | 1 | 2 | 3; - - interface Options { - /** - Specify the color support for Chalk. - - By default, color support is automatically detected based on the environment. - - Levels: - - `0` - All colors disabled. - - `1` - Basic 16 colors support. - - `2` - ANSI 256 colors support. - - `3` - Truecolor 16 million colors support. - */ - level?: Level; - } - - /** - Return a new Chalk instance. - */ - type Instance = new (options?: Options) => Chalk; - - /** - Detect whether the terminal supports color. - */ - interface ColorSupport { - /** - The color level used by Chalk. - */ - level: Level; - - /** - Return whether Chalk supports basic 16 colors. - */ - hasBasic: boolean; - - /** - Return whether Chalk supports ANSI 256 colors. - */ - has256: boolean; - - /** - Return whether Chalk supports Truecolor 16 million colors. - */ - has16m: boolean; - } - - interface ChalkFunction { - /** - Use a template string. - - @remarks Template literals are unsupported for nested calls (see [issue #341](https://github.com/chalk/chalk/issues/341)) - - @example - ``` - import chalk = require('chalk'); - - log(chalk` - CPU: {red ${cpu.totalPercent}%} - RAM: {green ${ram.used / ram.total * 100}%} - DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} - `); - ``` - - @example - ``` - import chalk = require('chalk'); - - log(chalk.red.bgBlack`2 + 3 = {bold ${2 + 3}}`) - ``` - */ - (text: TemplateStringsArray, ...placeholders: unknown[]): string; - - (...text: unknown[]): string; - } - - interface Chalk extends ChalkFunction { - /** - Return a new Chalk instance. - */ - Instance: Instance; - - /** - The color support for Chalk. - - By default, color support is automatically detected based on the environment. - - Levels: - - `0` - All colors disabled. - - `1` - Basic 16 colors support. - - `2` - ANSI 256 colors support. - - `3` - Truecolor 16 million colors support. - */ - level: Level; - - /** - Use HEX value to set text color. - - @param color - Hexadecimal value representing the desired color. - - @example - ``` - import chalk = require('chalk'); - - chalk.hex('#DEADED'); - ``` - */ - hex(color: string): Chalk; - - /** - Use keyword color value to set text color. - - @param color - Keyword value representing the desired color. - - @example - ``` - import chalk = require('chalk'); - - chalk.keyword('orange'); - ``` - */ - keyword(color: string): Chalk; - - /** - Use RGB values to set text color. - */ - rgb(red: number, green: number, blue: number): Chalk; - - /** - Use HSL values to set text color. - */ - hsl(hue: number, saturation: number, lightness: number): Chalk; - - /** - Use HSV values to set text color. - */ - hsv(hue: number, saturation: number, value: number): Chalk; - - /** - Use HWB values to set text color. - */ - hwb(hue: number, whiteness: number, blackness: number): Chalk; - - /** - Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set text color. - - 30 <= code && code < 38 || 90 <= code && code < 98 - For example, 31 for red, 91 for redBright. - */ - ansi(code: number): Chalk; - - /** - Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. - */ - ansi256(index: number): Chalk; - - /** - Use HEX value to set background color. - - @param color - Hexadecimal value representing the desired color. - - @example - ``` - import chalk = require('chalk'); - - chalk.bgHex('#DEADED'); - ``` - */ - bgHex(color: string): Chalk; - - /** - Use keyword color value to set background color. - - @param color - Keyword value representing the desired color. - - @example - ``` - import chalk = require('chalk'); - - chalk.bgKeyword('orange'); - ``` - */ - bgKeyword(color: string): Chalk; - - /** - Use RGB values to set background color. - */ - bgRgb(red: number, green: number, blue: number): Chalk; - - /** - Use HSL values to set background color. - */ - bgHsl(hue: number, saturation: number, lightness: number): Chalk; - - /** - Use HSV values to set background color. - */ - bgHsv(hue: number, saturation: number, value: number): Chalk; - - /** - Use HWB values to set background color. - */ - bgHwb(hue: number, whiteness: number, blackness: number): Chalk; - - /** - Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set background color. - - 30 <= code && code < 38 || 90 <= code && code < 98 - For example, 31 for red, 91 for redBright. - Use the foreground code, not the background code (for example, not 41, nor 101). - */ - bgAnsi(code: number): Chalk; - - /** - Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color. - */ - bgAnsi256(index: number): Chalk; - - /** - Modifier: Resets the current color chain. - */ - readonly reset: Chalk; - - /** - Modifier: Make text bold. - */ - readonly bold: Chalk; - - /** - Modifier: Emitting only a small amount of light. - */ - readonly dim: Chalk; - - /** - Modifier: Make text italic. (Not widely supported) - */ - readonly italic: Chalk; - - /** - Modifier: Make text underline. (Not widely supported) - */ - readonly underline: Chalk; - - /** - Modifier: Inverse background and foreground colors. - */ - readonly inverse: Chalk; - - /** - Modifier: Prints the text, but makes it invisible. - */ - readonly hidden: Chalk; - - /** - Modifier: Puts a horizontal line through the center of the text. (Not widely supported) - */ - readonly strikethrough: Chalk; - - /** - Modifier: Prints the text only when Chalk has a color support level > 0. - Can be useful for things that are purely cosmetic. - */ - readonly visible: Chalk; - - readonly black: Chalk; - readonly red: Chalk; - readonly green: Chalk; - readonly yellow: Chalk; - readonly blue: Chalk; - readonly magenta: Chalk; - readonly cyan: Chalk; - readonly white: Chalk; - - /* - Alias for `blackBright`. - */ - readonly gray: Chalk; - - /* - Alias for `blackBright`. - */ - readonly grey: Chalk; - - readonly blackBright: Chalk; - readonly redBright: Chalk; - readonly greenBright: Chalk; - readonly yellowBright: Chalk; - readonly blueBright: Chalk; - readonly magentaBright: Chalk; - readonly cyanBright: Chalk; - readonly whiteBright: Chalk; - - readonly bgBlack: Chalk; - readonly bgRed: Chalk; - readonly bgGreen: Chalk; - readonly bgYellow: Chalk; - readonly bgBlue: Chalk; - readonly bgMagenta: Chalk; - readonly bgCyan: Chalk; - readonly bgWhite: Chalk; - - /* - Alias for `bgBlackBright`. - */ - readonly bgGray: Chalk; - - /* - Alias for `bgBlackBright`. - */ - readonly bgGrey: Chalk; - - readonly bgBlackBright: Chalk; - readonly bgRedBright: Chalk; - readonly bgGreenBright: Chalk; - readonly bgYellowBright: Chalk; - readonly bgBlueBright: Chalk; - readonly bgMagentaBright: Chalk; - readonly bgCyanBright: Chalk; - readonly bgWhiteBright: Chalk; - } -} - -/** -Main Chalk object that allows to chain styles together. -Call the last one as a method with a string argument. -Order doesn't matter, and later styles take precedent in case of a conflict. -This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`. -*/ -declare const chalk: chalk.Chalk & chalk.ChalkFunction & { - supportsColor: chalk.ColorSupport | false; - Level: chalk.Level; - Color: Color; - ForegroundColor: ForegroundColor; - BackgroundColor: BackgroundColor; - Modifiers: Modifiers; - stderr: chalk.Chalk & {supportsColor: chalk.ColorSupport | false}; -}; - -export = chalk; diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/chalk/license b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/chalk/license deleted file mode 100644 index e7af2f771..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/chalk/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/chalk/package.json b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/chalk/package.json deleted file mode 100644 index 47c23f290..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/chalk/package.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "name": "chalk", - "version": "4.1.2", - "description": "Terminal string styling done right", - "license": "MIT", - "repository": "chalk/chalk", - "funding": "https://github.com/chalk/chalk?sponsor=1", - "main": "source", - "engines": { - "node": ">=10" - }, - "scripts": { - "test": "xo && nyc ava && tsd", - "bench": "matcha benchmark.js" - }, - "files": [ - "source", - "index.d.ts" - ], - "keywords": [ - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "string", - "str", - "ansi", - "style", - "styles", - "tty", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "log", - "logging", - "command-line", - "text" - ], - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "devDependencies": { - "ava": "^2.4.0", - "coveralls": "^3.0.7", - "execa": "^4.0.0", - "import-fresh": "^3.1.0", - "matcha": "^0.7.0", - "nyc": "^15.0.0", - "resolve-from": "^5.0.0", - "tsd": "^0.7.4", - "xo": "^0.28.2" - }, - "xo": { - "rules": { - "unicorn/prefer-string-slice": "off", - "unicorn/prefer-includes": "off", - "@typescript-eslint/member-ordering": "off", - "no-redeclare": "off", - "unicorn/string-content": "off", - "unicorn/better-regex": "off" - } - } -} diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/chalk/readme.md b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/chalk/readme.md deleted file mode 100644 index a055d21c9..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@lmstudio/sdk/node_modules/chalk/readme.md +++ /dev/null @@ -1,341 +0,0 @@ -

-
-
- Chalk -
-
-
-

- -> Terminal string styling done right - -[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents) [![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) ![TypeScript-ready](https://img.shields.io/npm/types/chalk.svg) [![run on repl.it](https://repl.it/badge/github/chalk/chalk)](https://repl.it/github/chalk/chalk) - - - -
- ---- - - - ---- - -
- -## Highlights - -- Expressive API -- Highly performant -- Ability to nest styles -- [256/Truecolor color support](#256-and-truecolor-color-support) -- Auto-detects color support -- Doesn't extend `String.prototype` -- Clean and focused -- Actively maintained -- [Used by ~50,000 packages](https://www.npmjs.com/browse/depended/chalk) as of January 1, 2020 - -## Install - -```console -$ npm install chalk -``` - -## Usage - -```js -const chalk = require('chalk'); - -console.log(chalk.blue('Hello world!')); -``` - -Chalk comes with an easy to use composable API where you just chain and nest the styles you want. - -```js -const chalk = require('chalk'); -const log = console.log; - -// Combine styled and normal strings -log(chalk.blue('Hello') + ' World' + chalk.red('!')); - -// Compose multiple styles using the chainable API -log(chalk.blue.bgRed.bold('Hello world!')); - -// Pass in multiple arguments -log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz')); - -// Nest styles -log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!')); - -// Nest styles of the same type even (color, underline, background) -log(chalk.green( - 'I am a green line ' + - chalk.blue.underline.bold('with a blue substring') + - ' that becomes green again!' -)); - -// ES2015 template literal -log(` -CPU: ${chalk.red('90%')} -RAM: ${chalk.green('40%')} -DISK: ${chalk.yellow('70%')} -`); - -// ES2015 tagged template literal -log(chalk` -CPU: {red ${cpu.totalPercent}%} -RAM: {green ${ram.used / ram.total * 100}%} -DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} -`); - -// Use RGB colors in terminal emulators that support it. -log(chalk.keyword('orange')('Yay for orange colored text!')); -log(chalk.rgb(123, 45, 67).underline('Underlined reddish color')); -log(chalk.hex('#DEADED').bold('Bold gray!')); -``` - -Easily define your own themes: - -```js -const chalk = require('chalk'); - -const error = chalk.bold.red; -const warning = chalk.keyword('orange'); - -console.log(error('Error!')); -console.log(warning('Warning!')); -``` - -Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args): - -```js -const name = 'Sindre'; -console.log(chalk.green('Hello %s'), name); -//=> 'Hello Sindre' -``` - -## API - -### chalk.` -
-
- Default Header -
-
- Default Content -
- -
- `; - } -}; -ShadowCard = __decorate([ - customElement('shadow-card') -], ShadowCard); -export { ShadowCard }; -// Usage: -// -//

My Title

-//

This goes to default slot

-//

So does this

-// Copyright 2024 -//
-// ============================================================================ -// LIGHT DOM SLOT SIMULATION - Manual Implementation -// ============================================================================ -let LightCardManual = class LightCardManual extends LitElement { - constructor() { - super(...arguments); - this._slots = { header: [], footer: [], default: [] }; - } - createRenderRoot() { return this; } // Light DOM - connectedCallback() { - super.connectedCallback(); - this.style.display = 'block'; - // Store original children before rendering - this._processSlots(); - } - _processSlots() { - // Get all children and categorize by slot attribute - const children = Array.from(this.children); - this._slots = { - header: children.filter(child => child.getAttribute('slot') === 'header'), - footer: children.filter(child => child.getAttribute('slot') === 'footer'), - default: children.filter(child => !child.hasAttribute('slot')) - }; - // Remove children from DOM (we'll re-insert them in render) - children.forEach(child => child.remove()); - } - render() { - return html ` -
-
- ${this._slots.header.length - ? this._slots.header - : html `Default Header`} -
-
- ${this._slots.default.length - ? this._slots.default - : html `Default Content`} -
- -
- `; - } -}; -LightCardManual = __decorate([ - customElement('light-card-manual') -], LightCardManual); -export { LightCardManual }; -// ============================================================================ -// LIGHT DOM SLOT SIMULATION - Using Data Attributes -// ============================================================================ -let LightCardData = class LightCardData extends LitElement { - constructor() { - super(...arguments); - this._slots = new Map(); - } - createRenderRoot() { return this; } - connectedCallback() { - super.connectedCallback(); - this.style.display = 'block'; - this._collectSlots(); - } - _collectSlots() { - const slotMap = new Map(); - // Hide original children and categorize them - Array.from(this.children).forEach(child => { - const slotName = child.getAttribute('data-slot') || 'default'; - if (!slotMap.has(slotName)) { - slotMap.set(slotName, []); - } - slotMap.get(slotName).push(child); - child.style.display = 'none'; - }); - this._slots = slotMap; - } - render() { - const header = this._slots.get('header')?.[0]; - const footer = this._slots.get('footer')?.[0]; - const content = this._slots.get('default') || []; - return html ` -
- ${header ? html ` -
this._handleSlotClick('header')}> - ${header.cloneNode(true)} -
- ` : html ` -
Default Header
- `} - -
- ${content.length ? - content.map(el => el.cloneNode(true)) : - html `Default Content`} -
- - ${footer ? html ` - - ` : html ` - - `} -
- `; - } - _handleSlotClick(slotName) { - console.log(`Clicked slot: ${slotName}`); - } -}; -__decorate([ - state() -], LightCardData.prototype, "_slots", void 0); -LightCardData = __decorate([ - customElement('light-card-data') -], LightCardData); -export { LightCardData }; -// ============================================================================ -// LIGHT DOM SLOT SIMULATION - Render Props Pattern -// ============================================================================ -let LightCardRender = class LightCardRender extends LitElement { - createRenderRoot() { return this; } - render() { - return html ` -
-
- ${this.header ? this.header() : 'Default Header'} -
-
- ${this.content ? this.content() : html ``} -
- -
- `; - } -}; -__decorate([ - property({ attribute: false }) -], LightCardRender.prototype, "header", void 0); -__decorate([ - property({ attribute: false }) -], LightCardRender.prototype, "footer", void 0); -__decorate([ - property({ attribute: false }) -], LightCardRender.prototype, "content", void 0); -LightCardRender = __decorate([ - customElement('light-card-render') -], LightCardRender); -export { LightCardRender }; -// Usage: -// const card = document.createElement('light-card-render'); -// card.header = () => html`

My Title

`; -// card.content = () => html`

My Content

`; -// card.footer = () => html`Copyright`; -// ============================================================================ -// LIGHT DOM SLOT SIMULATION - Query Selectors -// ============================================================================ -let LightCardQuery = class LightCardQuery extends LitElement { - createRenderRoot() { return this; } - render() { - // Query for slotted content after render - requestAnimationFrame(() => { - this._rearrangeSlots(); - }); - return html ` -
-
- - `; - } - _rearrangeSlots() { - const header = this.querySelector('[slot="header"]'); - const footer = this.querySelector('[slot="footer"]'); - const defaultContent = Array.from(this.children).filter(child => !child.hasAttribute('slot') && - !child.classList.contains('card-header') && - !child.classList.contains('card-content') && - !child.classList.contains('card-footer')); - const headerContainer = this.querySelector('.card-header'); - const contentContainer = this.querySelector('.card-content'); - const footerContainer = this.querySelector('.card-footer'); - if (header && headerContainer) { - headerContainer.appendChild(header); - } - if (footer && footerContainer) { - footerContainer.appendChild(footer); - } - defaultContent.forEach(child => { - if (contentContainer) { - contentContainer.appendChild(child); - } - }); - } -}; -LightCardQuery = __decorate([ - customElement('light-card-query') -], LightCardQuery); -export { LightCardQuery }; -// ============================================================================ -// BEST PRACTICE: Light DOM Composition Pattern -// ============================================================================ -let MiniCard = class MiniCard extends LitElement { - constructor() { - super(...arguments); - this.hasHeader = false; - this.hasFooter = false; - } - createRenderRoot() { return this; } - connectedCallback() { - super.connectedCallback(); - this.style.display = 'block'; - // Check if slotted content exists - this.hasHeader = !!this.querySelector('[slot="header"]'); - this.hasFooter = !!this.querySelector('[slot="footer"]'); - // Hide slotted content initially - this.querySelectorAll('[slot]').forEach(el => { - el.dataset.originalDisplay = - el.style.display || 'block'; - el.style.display = 'none'; - }); - } - firstUpdated() { - this._distributeSlots(); - } - _distributeSlots() { - // Move slotted content to appropriate containers - const headerSlot = this.querySelector('[slot="header"]'); - const footerSlot = this.querySelector('[slot="footer"]'); - const defaultContent = Array.from(this.children).filter(child => !child.hasAttribute('slot') && - !child.classList.contains('mini-card-section')); - if (headerSlot) { - const container = this.querySelector('.mini-card-header'); - if (container) { - headerSlot.style.display = - headerSlot.dataset.originalDisplay || 'block'; - container.appendChild(headerSlot); - } - } - if (footerSlot) { - const container = this.querySelector('.mini-card-footer'); - if (container) { - footerSlot.style.display = - footerSlot.dataset.originalDisplay || 'block'; - container.appendChild(footerSlot); - } - } - const contentContainer = this.querySelector('.mini-card-content'); - if (contentContainer) { - defaultContent.forEach(child => { - contentContainer.appendChild(child); - }); - } - } - render() { - return html ` -
- ${this.hasHeader ? html ` -
- -
- ` : ''} - -
- -
- - ${this.hasFooter ? html ` - - ` : ''} -
- `; - } -}; -__decorate([ - property({ type: Boolean }) -], MiniCard.prototype, "hasHeader", void 0); -__decorate([ - property({ type: Boolean }) -], MiniCard.prototype, "hasFooter", void 0); -MiniCard = __decorate([ - customElement('mini-card') -], MiniCard); -export { MiniCard }; -// ============================================================================ -// Usage Examples -// ============================================================================ -let SlotDemoPage = class SlotDemoPage extends LitElement { - createRenderRoot() { return this; } - render() { - return html ` -
-

Slot Simulation in Light DOM

- -
-

Shadow DOM (Native Slots)

- -

Custom Header

-

This is the main content

-

Multiple elements go to default slot

-
Custom Footer
-
-
- -
-

Light DOM (Manual Slots)

- -

Custom Header

-

This is the main content

-

Multiple elements in default slot

-
Custom Footer
-
-
- -
-

Light DOM (Data Attributes)

- -

Custom Header

-

This is the main content

-

Multiple elements in default slot

-
Custom Footer
-
-
- -
-

Best Practice: Mini Card

- -

Card Title

-

This is the card content that goes in the default slot.

-

You can have multiple paragraphs.

-
- -
-
-
- -
-

How Shadow DOM Slots Work

-
    -
  • <slot> - Default/unnamed slot catches all unassigned content
  • -
  • <slot name="header"> - Named slot for specific content
  • -
  • slot="header" - Assigns element to named slot
  • -
  • • Elements without slot attribute go to default slot
  • -
  • • Slot can have default content shown when empty
  • -
-
- -
-

Light DOM Slot Strategies

-
    -
  • Move DOM: Physically move elements to containers
  • -
  • Clone Nodes: Clone and insert (loses event handlers)
  • -
  • Hide/Show: CSS to control visibility
  • -
  • Render Props: Pass template functions as props
  • -
  • Data Attributes: Use data-slot instead of slot
  • -
-
-
- `; - } -}; -SlotDemoPage = __decorate([ - customElement('slot-demo-page') -], SlotDemoPage); -export { SlotDemoPage }; -//# sourceMappingURL=slot-examples.js.map \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/slot-examples.js.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/slot-examples.js.map deleted file mode 100644 index 4d70ac6c2..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/slot-examples.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"slot-examples.js","sourceRoot":"","sources":["../src/slot-examples.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,KAAK,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAGnE,+EAA+E;AAC/E,mCAAmC;AACnC,+EAA+E;AAGxE,IAAM,UAAU,GAAhB,MAAM,UAAW,SAAQ,UAAU;IACxC,mCAAmC;IACnC,MAAM;QACJ,OAAO,IAAI,CAAA;;;;;;;;;;;;;;;;;KAiBV,CAAC;IACJ,CAAC;CACF,CAAA;AAtBY,UAAU;IADtB,aAAa,CAAC,aAAa,CAAC;GAChB,UAAU,CAsBtB;;AAED,SAAS;AACT,gBAAgB;AAChB,oCAAoC;AACpC,qCAAqC;AACrC,wBAAwB;AACxB,gDAAgD;AAChD,iBAAiB;AAEjB,+EAA+E;AAC/E,oDAAoD;AACpD,+EAA+E;AAGxE,IAAM,eAAe,GAArB,MAAM,eAAgB,SAAQ,UAAU;IAAxC;;QAwBG,WAAM,GAIV,EAAE,MAAM,EAA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AgB,KAAK,OAAO,IAAI,CAAC,CAAC,CAAC;IAEnC,MAAM;QACJ,OAAO,IAAI,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAsEV,CAAC;IACJ,CAAC;CACF,CAAA;AA5EY,YAAY;IADxB,aAAa,CAAC,gBAAgB,CAAC;GACnB,YAAY,CA4ExB"} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/base.css b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/base.css deleted file mode 100644 index 10424f467..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/base.css +++ /dev/null @@ -1,65 +0,0 @@ -/* Base styles for mini-lit */ - -/* Enable manual dark mode with class for Tailwind v4 */ - - -/* Utility styles that are commonly needed */ -@import "./utils/syntax-highlighting.css"; -@import "./utils/math.css"; -@import "./utils/markdown.css"; - -@custom-variant dark (&:where(.dark, .dark *)); - -/* biome-ignore lint/suspicious/noUnknownAtRules: Tailwind */ -@theme inline { - --color-background: var(--background); - --color-foreground: var(--foreground); - --color-card: var(--card); - --color-card-foreground: var(--card-foreground); - --color-popover: var(--popover); - --color-popover-foreground: var(--popover-foreground); - --color-primary: var(--primary); - --color-primary-foreground: var(--primary-foreground); - --color-secondary: var(--secondary); - --color-secondary-foreground: var(--secondary-foreground); - --color-muted: var(--muted); - --color-muted-foreground: var(--muted-foreground); - --color-accent: var(--accent); - --color-accent-foreground: var(--accent-foreground); - --color-destructive: var(--destructive); - --color-destructive-foreground: var(--destructive-foreground); - --color-border: var(--border); - --color-input: var(--input); - --color-ring: var(--ring); - --color-chart-1: var(--chart-1); - --color-chart-2: var(--chart-2); - --color-chart-3: var(--chart-3); - --color-chart-4: var(--chart-4); - --color-chart-5: var(--chart-5); - --color-sidebar: var(--sidebar); - --color-sidebar-foreground: var(--sidebar-foreground); - --color-sidebar-primary: var(--sidebar-primary); - --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); - --color-sidebar-accent: var(--sidebar-accent); - --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); - --color-sidebar-border: var(--sidebar-border); - --color-sidebar-ring: var(--sidebar-ring); - - --font-family-sans: var(--font-sans); - --font-family-mono: var(--font-mono); - --font-family-serif: var(--font-serif); - - --radius-sm: calc(var(--radius) - 4px); - --radius-md: calc(var(--radius) - 2px); - --radius-lg: var(--radius); - --radius-xl: calc(var(--radius) + 4px); - - --shadow-2xs: var(--shadow-2xs); - --shadow-xs: var(--shadow-xs); - --shadow-sm: var(--shadow-sm); - --shadow: var(--shadow); - --shadow-md: var(--shadow-md); - --shadow-lg: var(--shadow-lg); - --shadow-xl: var(--shadow-xl); - --shadow-2xl: var(--shadow-2xl); -} diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/themes/claude.css b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/themes/claude.css deleted file mode 100644 index bb0d2769f..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/themes/claude.css +++ /dev/null @@ -1,155 +0,0 @@ -/* Import base styles including dark mode variant and utilities */ -@import "../base.css"; - -:root { - --background: oklch(0.9818 0.0054 95.0986); - --foreground: oklch(0.3438 0.0269 95.7226); - --card: oklch(0.9818 0.0054 95.0986); - --card-foreground: oklch(0.1908 0.002 106.5859); - --popover: oklch(1 0 0); - --popover-foreground: oklch(0.2671 0.0196 98.939); - --primary: oklch(0.6171 0.1375 39.0427); - --primary-foreground: oklch(1 0 0); - --secondary: oklch(0.9245 0.0138 92.9892); - --secondary-foreground: oklch(0.4334 0.0177 98.6048); - --muted: oklch(0.9341 0.0153 90.239); - --muted-foreground: oklch(0.6059 0.0075 97.4233); - --accent: oklch(0.9245 0.0138 92.9892); - --accent-foreground: oklch(0.2671 0.0196 98.939); - --destructive: oklch(0.1908 0.002 106.5859); - --destructive-foreground: oklch(1 0 0); - --border: oklch(0.8847 0.0069 97.3627); - --input: oklch(0.7621 0.0156 98.3528); - --ring: oklch(0.6171 0.1375 39.0427); - --chart-1: oklch(0.5583 0.1276 42.9956); - --chart-2: oklch(0.6898 0.1581 290.4107); - --chart-3: oklch(0.8816 0.0276 93.128); - --chart-4: oklch(0.8822 0.0403 298.1792); - --chart-5: oklch(0.5608 0.1348 42.0584); - --sidebar: oklch(0.9663 0.008 98.8792); - --sidebar-foreground: oklch(0.359 0.0051 106.6524); - --sidebar-primary: oklch(0.6171 0.1375 39.0427); - --sidebar-primary-foreground: oklch(0.9881 0 0); - --sidebar-accent: oklch(0.9245 0.0138 92.9892); - --sidebar-accent-foreground: oklch(0.325 0 0); - --sidebar-border: oklch(0.9401 0 0); - --sidebar-ring: oklch(0.7731 0 0); - --font-sans: - ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, - "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; - --font-serif: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif; - --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; - --radius: 0.5rem; - --shadow-2xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05); - --shadow-xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05); - --shadow-sm: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1); - --shadow: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1); - --shadow-md: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 2px 4px -1px hsl(0 0% 0% / 0.1); - --shadow-lg: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 4px 6px -1px hsl(0 0% 0% / 0.1); - --shadow-xl: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 8px 10px -1px hsl(0 0% 0% / 0.1); - --shadow-2xl: 0 1px 3px 0px hsl(0 0% 0% / 0.25); - --tracking-normal: 0em; - --spacing: 0.25rem; -} - -.dark { - --background: oklch(0.2679 0.0036 106.6427); - --foreground: oklch(0.8074 0.0142 93.0137); - --card: oklch(0.2679 0.0036 106.6427); - --card-foreground: oklch(0.9818 0.0054 95.0986); - --popover: oklch(0.3085 0.0035 106.6039); - --popover-foreground: oklch(0.9211 0.004 106.4781); - --primary: oklch(0.6724 0.1308 38.7559); - --primary-foreground: oklch(1 0 0); - --secondary: oklch(0.9818 0.0054 95.0986); - --secondary-foreground: oklch(0.3085 0.0035 106.6039); - --muted: oklch(0.2213 0.0038 106.707); - --muted-foreground: oklch(0.7713 0.0169 99.0657); - --accent: oklch(0.213 0.0078 95.4245); - --accent-foreground: oklch(0.9663 0.008 98.8792); - --destructive: oklch(0.6368 0.2078 25.3313); - --destructive-foreground: oklch(1 0 0); - --border: oklch(0.3618 0.0101 106.8928); - --input: oklch(0.4336 0.0113 100.2195); - --ring: oklch(0.6724 0.1308 38.7559); - --chart-1: oklch(0.5583 0.1276 42.9956); - --chart-2: oklch(0.6898 0.1581 290.4107); - --chart-3: oklch(0.213 0.0078 95.4245); - --chart-4: oklch(0.3074 0.0516 289.323); - --chart-5: oklch(0.5608 0.1348 42.0584); - --sidebar: oklch(0.2357 0.0024 67.7077); - --sidebar-foreground: oklch(0.8074 0.0142 93.0137); - --sidebar-primary: oklch(0.325 0 0); - --sidebar-primary-foreground: oklch(0.9881 0 0); - --sidebar-accent: oklch(0.168 0.002 106.6177); - --sidebar-accent-foreground: oklch(0.8074 0.0142 93.0137); - --sidebar-border: oklch(0.9401 0 0); - --sidebar-ring: oklch(0.7731 0 0); - --font-sans: - ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, - "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; - --font-serif: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif; - --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; - --radius: 0.5rem; - --shadow-2xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05); - --shadow-xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05); - --shadow-sm: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1); - --shadow: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1); - --shadow-md: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 2px 4px -1px hsl(0 0% 0% / 0.1); - --shadow-lg: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 4px 6px -1px hsl(0 0% 0% / 0.1); - --shadow-xl: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 8px 10px -1px hsl(0 0% 0% / 0.1); - --shadow-2xl: 0 1px 3px 0px hsl(0 0% 0% / 0.25); -} - -@theme inline { - --color-background: var(--background); - --color-foreground: var(--foreground); - --color-card: var(--card); - --color-card-foreground: var(--card-foreground); - --color-popover: var(--popover); - --color-popover-foreground: var(--popover-foreground); - --color-primary: var(--primary); - --color-primary-foreground: var(--primary-foreground); - --color-secondary: var(--secondary); - --color-secondary-foreground: var(--secondary-foreground); - --color-muted: var(--muted); - --color-muted-foreground: var(--muted-foreground); - --color-accent: var(--accent); - --color-accent-foreground: var(--accent-foreground); - --color-destructive: var(--destructive); - --color-destructive-foreground: var(--destructive-foreground); - --color-border: var(--border); - --color-input: var(--input); - --color-ring: var(--ring); - --color-chart-1: var(--chart-1); - --color-chart-2: var(--chart-2); - --color-chart-3: var(--chart-3); - --color-chart-4: var(--chart-4); - --color-chart-5: var(--chart-5); - --color-sidebar: var(--sidebar); - --color-sidebar-foreground: var(--sidebar-foreground); - --color-sidebar-primary: var(--sidebar-primary); - --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); - --color-sidebar-accent: var(--sidebar-accent); - --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); - --color-sidebar-border: var(--sidebar-border); - --color-sidebar-ring: var(--sidebar-ring); - - --font-family-sans: var(--font-sans); - --font-family-mono: var(--font-mono); - --font-family-serif: var(--font-serif); - - --radius-sm: calc(var(--radius) - 4px); - --radius-md: calc(var(--radius) - 2px); - --radius-lg: var(--radius); - --radius-xl: calc(var(--radius) + 4px); - - --shadow-2xs: var(--shadow-2xs); - --shadow-xs: var(--shadow-xs); - --shadow-sm: var(--shadow-sm); - --shadow: var(--shadow); - --shadow-md: var(--shadow-md); - --shadow-lg: var(--shadow-lg); - --shadow-xl: var(--shadow-xl); - --shadow-2xl: var(--shadow-2xl); -} diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/themes/default.css b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/themes/default.css deleted file mode 100644 index afd4c1134..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/themes/default.css +++ /dev/null @@ -1,102 +0,0 @@ -/* Import base styles including dark mode variant and utilities */ -@import "../base.css"; - -:root { - --background: oklch(1 0 0); - --foreground: oklch(0.145 0 0); - --card: oklch(1 0 0); - --card-foreground: oklch(0.145 0 0); - --popover: oklch(1 0 0); - --popover-foreground: oklch(0.145 0 0); - --primary: oklch(0.205 0 0); - --primary-foreground: oklch(0.985 0 0); - --secondary: oklch(0.97 0 0); - --secondary-foreground: oklch(0.205 0 0); - --muted: oklch(0.97 0 0); - --muted-foreground: oklch(0.556 0 0); - --accent: oklch(0.97 0 0); - --accent-foreground: oklch(0.4 0.18 240); - --destructive: oklch(0.577 0.245 27.325); - --destructive-foreground: oklch(1 0 0); - --border: oklch(0.922 0 0); - --input: oklch(0.922 0 0); - --ring: oklch(0.708 0 0); - --chart-1: oklch(0.81 0.1 252); - --chart-2: oklch(53.553% 0.02798 259.829); - --chart-3: oklch(0.55 0.22 263); - --chart-4: oklch(0.49 0.22 264); - --chart-5: oklch(0.42 0.18 266); - --sidebar: oklch(0.985 0 0); - --sidebar-foreground: oklch(0.145 0 0); - --sidebar-primary: oklch(0.205 0 0); - --sidebar-primary-foreground: oklch(0.985 0 0); - --sidebar-accent: oklch(0.97 0 0); - --sidebar-accent-foreground: oklch(0.205 0 0); - --sidebar-border: oklch(0.922 0 0); - --sidebar-ring: oklch(0.708 0 0); - --font-sans: - ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, - "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; - --font-serif: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif; - --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; - --radius: 0.625rem; - --shadow-2xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05); - --shadow-xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05); - --shadow-sm: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1); - --shadow: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1); - --shadow-md: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 2px 4px -1px hsl(0 0% 0% / 0.1); - --shadow-lg: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 4px 6px -1px hsl(0 0% 0% / 0.1); - --shadow-xl: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 8px 10px -1px hsl(0 0% 0% / 0.1); - --shadow-2xl: 0 1px 3px 0px hsl(0 0% 0% / 0.25); - --tracking-normal: 0em; - --spacing: 0.25rem; -} - -.dark { - --background: oklch(0.145 0 0); - --foreground: oklch(0.985 0 0); - --card: oklch(0.205 0 0); - --card-foreground: oklch(0.985 0 0); - --popover: oklch(0.269 0 0); - --popover-foreground: oklch(0.985 0 0); - --primary: oklch(0.922 0 0); - --primary-foreground: oklch(0.205 0 0); - --secondary: oklch(0.269 0 0); - --secondary-foreground: oklch(0.985 0 0); - --muted: oklch(0.269 0 0); - --muted-foreground: oklch(0.708 0 0); - --accent: oklch(0.371 0 0); - --accent-foreground: oklch(0.75 0.18 85); - --destructive: oklch(0.704 0.191 22.216); - --destructive-foreground: oklch(0.985 0 0); - --border: oklch(0.275 0 0); - --input: oklch(0.325 0 0); - --ring: oklch(0.556 0 0); - --chart-1: oklch(0.81 0.1 252); - --chart-2: oklch(0.62 0.19 260); - --chart-3: oklch(0.55 0.22 263); - --chart-4: oklch(0.49 0.22 264); - --chart-5: oklch(0.42 0.18 266); - --sidebar: oklch(0.205 0 0); - --sidebar-foreground: oklch(0.985 0 0); - --sidebar-primary: oklch(0.488 0.243 264.376); - --sidebar-primary-foreground: oklch(0.985 0 0); - --sidebar-accent: oklch(0.269 0 0); - --sidebar-accent-foreground: oklch(0.985 0 0); - --sidebar-border: oklch(0.275 0 0); - --sidebar-ring: oklch(0.439 0 0); - --font-sans: - ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, - "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; - --font-serif: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif; - --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; - --radius: 0.625rem; - --shadow-2xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05); - --shadow-xs: 0 1px 3px 0px hsl(0 0% 0% / 0.05); - --shadow-sm: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1); - --shadow: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 1px 2px -1px hsl(0 0% 0% / 0.1); - --shadow-md: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 2px 4px -1px hsl(0 0% 0% / 0.1); - --shadow-lg: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 4px 6px -1px hsl(0 0% 0% / 0.1); - --shadow-xl: 0 1px 3px 0px hsl(0 0% 0% / 0.1), 0 8px 10px -1px hsl(0 0% 0% / 0.1); - --shadow-2xl: 0 1px 3px 0px hsl(0 0% 0% / 0.25); -} diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/utils/markdown.css b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/utils/markdown.css deleted file mode 100644 index e06fe168f..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/utils/markdown.css +++ /dev/null @@ -1,104 +0,0 @@ -/* Markdown content styles using Tailwind utilities */ - -.markdown-content h1 { - @apply text-2xl font-semibold mt-5 mb-2; -} - -.markdown-content h2 { - @apply text-xl font-semibold mt-4 mb-2; -} - -.markdown-content h3 { - @apply text-lg font-semibold mt-3 mb-2; -} - -.markdown-content h4 { - @apply text-base font-semibold mt-3 mb-2; -} - -.markdown-content h5 { - @apply text-sm font-semibold mt-2 mb-1; -} - -.markdown-content h6 { - @apply text-xs font-semibold mt-2 mb-1; -} - -.markdown-content p { - @apply leading-relaxed mt-4 first:mt-0; -} - -.markdown-content a { - @apply text-primary underline hover:text-primary/80; -} - -.markdown-content strong { - @apply font-semibold; -} - -.markdown-content em { - @apply italic; -} - -.markdown-content ul { - @apply list-disc my-4 pl-6 space-y-2; -} - -.markdown-content ol { - @apply list-decimal my-4 pl-6 space-y-2; -} - -.markdown-content li { - @apply leading-relaxed; -} - -/* Nested lists should have less top margin */ -.markdown-content li > ul, -.markdown-content li > ol { - @apply mt-2 mb-0; -} - -/* Paragraphs in lists need proper spacing */ -.markdown-content li > p { - @apply mb-2; -} - -.markdown-content li > p:last-child { - @apply mb-0; -} - -.markdown-content blockquote { - @apply border-l-4 border-border pl-4 my-4 text-muted-foreground; -} - -.markdown-content code:not(.hljs) { - @apply bg-muted text-foreground px-1.5 py-0.5 rounded text-sm; -} - -.markdown-content table { - @apply w-full border-collapse m-0; -} - -.markdown-content th { - @apply bg-muted text-foreground font-semibold p-2 border-b border-r border-border text-left; -} - -.markdown-content th:last-child { - @apply border-r-0; -} - -.markdown-content td { - @apply p-2 border-b border-r border-border; -} - -.markdown-content td:last-child { - @apply border-r-0; -} - -.markdown-content tr:last-child td { - @apply border-b-0; -} - -.markdown-content hr { - @apply border-0 border-t border-border my-8; -} diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/utils/math.css b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/utils/math.css deleted file mode 100644 index d9a577c7a..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/utils/math.css +++ /dev/null @@ -1,7 +0,0 @@ -/* KaTeX CSS for math rendering in markdown */ -@import "../../../node_modules/katex/dist/katex.min.css"; - -/* KaTeX display margin override */ -.katex-display { - margin: 0; -} diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/utils/syntax-highlighting.css b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/utils/syntax-highlighting.css deleted file mode 100644 index f4ddf97df..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/styles/utils/syntax-highlighting.css +++ /dev/null @@ -1,134 +0,0 @@ -/* Syntax highlighting colors - GitHub Light theme (default) */ -:root { - --syntax-keyword: oklch(0.577 0.245 27.325); /* #d73a49 */ - --syntax-entity: oklch(0.511 0.136 307.715); /* #6f42c1 */ - --syntax-constant: oklch(0.435 0.141 237.016); /* #005cc5 */ - --syntax-string: oklch(0.296 0.103 244.038); /* #032f62 */ - --syntax-variable: oklch(0.608 0.178 54.291); /* #e36209 */ - --syntax-comment: oklch(0.54 0.019 247.858); /* #6a737d */ - --syntax-tag: oklch(0.403 0.111 145.348); /* #22863a */ - --syntax-heading: oklch(0.435 0.141 237.016); /* #005cc5 */ - --syntax-list: oklch(0.537 0.108 88.766); /* #735c0f */ - --syntax-addition-bg: oklch(0.984 0.029 166.113); /* #f0fff4 */ - --syntax-addition-fg: oklch(0.403 0.111 145.348); /* #22863a */ - --syntax-deletion-bg: oklch(0.981 0.025 17.672); /* #ffeef0 */ - --syntax-deletion-fg: oklch(0.431 0.183 27.522); /* #b31d28 */ -} - -/* Syntax highlighting colors - GitHub Dark theme */ -.dark { - --syntax-keyword: oklch(0.698 0.159 21.174); /* #ff7b72 */ - --syntax-entity: oklch(0.792 0.124 307.715); /* #d2a8ff */ - --syntax-constant: oklch(0.732 0.137 237.016); /* #79c0ff */ - --syntax-string: oklch(0.786 0.08 237.016); /* #a5d6ff */ - --syntax-variable: oklch(0.74 0.141 54.291); /* #ffa657 */ - --syntax-comment: oklch(0.626 0.025 247.858); /* #8b949e */ - --syntax-tag: oklch(0.812 0.159 145.348); /* #7ee787 */ - --syntax-heading: oklch(0.523 0.181 237.016); /* #1f6feb */ - --syntax-list: oklch(0.866 0.141 88.766); /* #f2cc60 */ - --syntax-addition-bg: oklch(0.188 0.06 166.113); /* #033a16 */ - --syntax-addition-fg: oklch(0.87 0.147 145.348); /* #aff5b4 */ - --syntax-deletion-bg: oklch(0.233 0.129 17.672); /* #67060c */ - --syntax-deletion-fg: oklch(0.92 0.067 17.672); /* #ffdcd7 */ -} - -/* Keywords */ -.hljs-doctag, -.hljs-keyword, -.hljs-meta .hljs-keyword, -.hljs-template-tag, -.hljs-template-variable, -.hljs-type, -.hljs-variable.language_ { - color: var(--syntax-keyword); -} - -/* Entity (functions, classes) */ -.hljs-title, -.hljs-title.class_, -.hljs-title.class_.inherited__, -.hljs-title.function_ { - color: var(--syntax-entity); -} - -/* Constants */ -.hljs-attr, -.hljs-attribute, -.hljs-literal, -.hljs-meta, -.hljs-number, -.hljs-operator, -.hljs-variable, -.hljs-selector-attr, -.hljs-selector-class, -.hljs-selector-id { - color: var(--syntax-constant); -} - -/* Strings */ -.hljs-regexp, -.hljs-string, -.hljs-meta .hljs-string { - color: var(--syntax-string); -} - -/* Built-in variables */ -.hljs-built_in, -.hljs-symbol { - color: var(--syntax-variable); -} - -/* Comments */ -.hljs-comment, -.hljs-code, -.hljs-formula { - color: var(--syntax-comment); -} - -/* Tags */ -.hljs-name, -.hljs-quote, -.hljs-selector-tag, -.hljs-selector-pseudo { - color: var(--syntax-tag); -} - -/* Default text */ -.hljs-subst { - color: var(--color-text-primary); -} - -/* Section headings */ -.hljs-section { - color: var(--syntax-heading); - font-weight: bold; -} - -/* Bullets */ -.hljs-bullet { - color: var(--syntax-list); -} - -/* Emphasis */ -.hljs-emphasis { - color: var(--color-text-primary); - font-style: italic; -} - -/* Strong */ -.hljs-strong { - color: var(--color-text-primary); - font-weight: bold; -} - -/* Additions */ -.hljs-addition { - color: var(--syntax-addition-fg); - background-color: var(--syntax-addition-bg); -} - -/* Deletions */ -.hljs-deletion { - color: var(--syntax-deletion-fg); - background-color: var(--syntax-deletion-bg); -} diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-component.d.ts b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-component.d.ts deleted file mode 100644 index 1f5adaaa0..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-component.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { type ExtractProps } from "./props.js"; -export declare const Card: import("./mini.js").Component< - ExtractProps<{ - readonly variant: { - readonly type: "variant"; - readonly options: readonly ["default", "bordered", "elevated"]; - readonly default: "default"; - readonly description: "Card style variant"; - }; - readonly padding: { - readonly type: "variant"; - readonly options: readonly ["none", "sm", "md", "lg"]; - readonly default: "md"; - readonly description: "Padding size"; - }; - readonly title: { - readonly type: "value"; - readonly default: string; - readonly description: "Card title"; - }; - readonly children: { - readonly type: "value"; - readonly default: any; - readonly description: "Card content"; - }; - readonly onClick: { - readonly type: "function"; - readonly default: ((e: MouseEvent) => void) | undefined; - readonly description: "Click handler"; - }; - }> ->; -//# sourceMappingURL=test-component.d.ts.map diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-component.d.ts.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-component.d.ts.map deleted file mode 100644 index 616bf2eb0..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-component.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"test-component.d.ts","sourceRoot":"","sources":["../src/test-component.ts"],"names":[],"mappings":"AACA,OAAO,EAA6C,KAAK,YAAY,EAAsB,MAAM,YAAY,CAAC;AA0E9G,eAAO,MAAM,IAAI;;;;;;;;;;;;;;;0BAxDI,MAAM;;;;;0BAKC,GAAG;;;;;0BAKH,CAAC,CAAC,CAAC,EAAE,UAAU,KAAK,IAAI,CAAC,GAAG,SAAS;;;GA8CU,CAAC"} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-component.js b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-component.js deleted file mode 100644 index 83972da51..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-component.js +++ /dev/null @@ -1,77 +0,0 @@ -import { html } from "lit"; -import { createComponent } from "./props.js"; -// Test with a simple Card component -const cardDefinition = { - variant: { - type: "variant", - options: ["default", "bordered", "elevated"], - default: "default", - description: "Card style variant", - }, - padding: { - type: "variant", - options: ["none", "sm", "md", "lg"], - default: "md", - description: "Padding size", - }, - title: { - type: "value", - default: "", - description: "Card title", - }, - children: { - type: "value", - default: undefined, - description: "Card content", - }, - onClick: { - type: "function", - default: undefined, - description: "Click handler", - }, -}; -const cardStyles = { - base: "rounded-lg transition-all", - variants: { - variant: { - default: "bg-white border border-gray-200", - bordered: "bg-white border-2 border-gray-400", - elevated: "bg-white shadow-lg", - }, - padding: { - none: "p-0", - sm: "p-2", - md: "p-4", - lg: "p-8", - }, - }, - compoundVariants: [ - { - variant: "elevated", - padding: "lg", - className: "shadow-2xl", - }, - ], -}; -const renderCard = (props, variants) => { - const { variant, padding, title, children, onClick } = props; - return html ` -
- ${title ? html `

${title}

` : ""} - ${children} -
- `; -}; -export const Card = createComponent(cardDefinition, cardStyles, renderCard); -// Test usage -const testCard = Card({ - variant: "elevated", - padding: "lg", - title: "Test Card", - children: html `

This is content

`, -}); -console.log("Card component created successfully!"); -//# sourceMappingURL=test-component.js.map \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-component.js.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-component.js.map deleted file mode 100644 index 8f3775e3d..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-component.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"test-component.js","sourceRoot":"","sources":["../src/test-component.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,KAAK,CAAC;AAC3B,OAAO,EAA4B,eAAe,EAAyC,MAAM,YAAY,CAAC;AAE9G,oCAAoC;AACpC,MAAM,cAAc,GAAG;IACpB,OAAO,EAAE;QACN,IAAI,EAAE,SAAS;QACf,OAAO,EAAE,CAAC,SAAS,EAAE,UAAU,EAAE,UAAU,CAAU;QACrD,OA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CAAsC,KAAK,OAAO,CAAC,CAAC,CAAC,EAAE;WACnE,QAAQ;;IAEf,CAAC;AACL,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,IAAI,GAAG,eAAe,CAAC,cAAc,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC;AAE5E,aAAa;AACb,MAAM,QAAQ,GAAG,IAAI,CAAC;IACnB,OAAO,EAAE,UAAU;IACnB,OAAO,EAAE,IAAI;IACb,KAAK,EAAE,WAAW;IAClB,QAAQ,EAAE,IAAI,CAAA,wBAAwB;CACxC,CAAC,CAAC;AAEH,OAAO,CAAC,GAAG,CAAC,sCAAsC,CAAC,CAAC"} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-base.d.ts b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-base.d.ts deleted file mode 100644 index f00315541..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-base.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=test-lit-base.d.ts.map diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-base.d.ts.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-base.d.ts.map deleted file mode 100644 index ae8a0d989..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-base.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"test-lit-base.d.ts","sourceRoot":"","sources":["../src/test-lit-base.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-base.js b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-base.js deleted file mode 100644 index c3100566f..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-base.js +++ /dev/null @@ -1,19 +0,0 @@ -import { MiniButton } from "./ButtonLit.js"; -// Test that types work correctly -const button = new MiniButton(); -// All properties should be fully typed -button.variant = "destructive"; // ✓ autocompletes with all variant options -button.size = "lg"; // ✓ autocompletes with all size options -button.disabled = true; // ✓ typed as boolean -button.loading = false; // ✓ typed as boolean -button.className = "custom"; // ✓ typed as string -// This should show type errors: -// button.variant = "invalid"; // ❌ Type error - not a valid variant -// button.size = 123; // ❌ Type error - not a valid size -// button.disabled = "true"; // ❌ Type error - not a boolean -// Component-specific methods work -button.reset(); -// Lit lifecycle methods work -button.connectedCallback(); -button.requestUpdate(); -//# sourceMappingURL=test-lit-base.js.map \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-base.js.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-base.js.map deleted file mode 100644 index 940582e5f..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-base.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"test-lit-base.js","sourceRoot":"","sources":["../src/test-lit-base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C,iCAAiC;AACjC,MAAM,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;AAEhC,uCAAuC;AACvC,MAAM,CAAC,OAAO,GAAG,aAAa,CAAC,CAAC,2CAA2C;AAC3E,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,wCAAwC;AAC5D,MAAM,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAC,qBAAqB;AAC7C,MAAM,CAAC,OAAO,GAAG,KAAK,CAAC,CAAC,qBAAqB;AAC7C,MAAM,CAAC,SAAS,GAAG,QAAQ,CAAC,CAAC,oBAAoB;AAEjD,gCAAgC;AAChC,sEAAsE;AACtE,mEAAmE;AACnE,gEAAgE;AAEhE,kCAAkC;AAClC,MAAM,CAAC,KAAK,EAAE,CAAC;AAEf,6BAA6B;AAC7B,MAAM,CAAC,iBAAiB,EAAE,CAAC;AAC3B,MAAM,CAAC,aAAa,EAAE,CAAC"} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-component.d.ts b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-component.d.ts deleted file mode 100644 index 2d0636aa4..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-component.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -declare const ButtonClass: any; -export declare class MiniButton extends ButtonClass {} -//# sourceMappingURL=test-lit-component.d.ts.map diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-component.d.ts.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-component.d.ts.map deleted file mode 100644 index d5e288319..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-component.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"test-lit-component.d.ts","sourceRoot":"","sources":["../src/test-lit-component.ts"],"names":[],"mappings":"AAKA,QAAA,MAAM,WAAW,KAA6D,CAAC;AAG/E,qBACa,UAAW,SAAQ,WAAW;CAAG"} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-component.js b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-component.js deleted file mode 100644 index 725c59f1d..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-component.js +++ /dev/null @@ -1,29 +0,0 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { customElement } from "lit/decorators.js"; -import { defaultStyle, definition, renderButton } from "./Button.cva.js"; -import { createLitComponent } from "./createLitComponent.js"; -// Create the Lit component class -const ButtonClass = createLitComponent(definition, defaultStyle, renderButton); -// Register as custom element -let MiniButton = class MiniButton extends ButtonClass { -}; -MiniButton = __decorate([ - customElement("mini-button-lit") -], MiniButton); -export { MiniButton }; -// Test type inference -const button = new MiniButton(); -// These should all be typed correctly -button.variant = "destructive"; -button.size = "lg"; -button.disabled = true; -button.loading = false; -button.className = "extra-class"; -// Test that properties is accessible -console.log(MiniButton.properties); -//# sourceMappingURL=test-lit-component.js.map \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-component.js.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-component.js.map deleted file mode 100644 index 01d8b41be..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/test-lit-component.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"test-lit-component.js","sourceRoot":"","sources":["../src/test-lit-component.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACzE,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE7D,iCAAiC;AACjC,MAAM,WAAW,GAAG,kBAAkB,CAAC,UAAU,EAAE,YAAY,EAAE,YAAY,CAAC,CAAC;AAE/E,6BAA6B;AAEtB,IAAM,UAAU,GAAhB,MAAM,UAAW,SAAQ,WAAW;CAAG,CAAA;AAAjC,UAAU;IADtB,aAAa,CAAC,iBAAiB,CAAC;GACpB,UAAU,CAAuB;;AAE9C,sBAAsB;AACtB,MAAM,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;AAEhC,sCAAsC;AACtC,MAAM,CAAC,OAAO,GAAG,aAAa,CAAC;AAC/B,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC;AACnB,MAAM,CAAC,QAAQ,GAAG,IAAI,CAAC;AACvB,MAAM,CAAC,OAAO,GAAG,KAAK,CAAC;AACvB,MAAM,CAAC,SAAS,GAAG,aAAa,CAAC;AAEjC,qCAAqC;AACrC,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC"} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/setup.d.ts b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/setup.d.ts deleted file mode 100644 index d515c77d0..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/setup.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Window } from "happy-dom"; -export declare function setupDOM(): { - window: Window; - document: import("happy-dom").Document; -}; -export declare function cleanupDOM(window: any): void; -export declare function nextTick(): Promise; -export declare class MemoryTracker { - private refs; - track(obj: any): void; - getAliveCount(): number; - clear(): void; -} -export declare class ErrorCapture { - private errors; - private originalError; - start(): void; - stop(): void; - get(): any[]; - clear(): void; -} -//# sourceMappingURL=setup.d.ts.map \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/setup.d.ts.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/setup.d.ts.map deleted file mode 100644 index 23c0224e7..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/setup.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"setup.d.ts","sourceRoot":"","sources":["../../src/tests/setup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAGnC,wBAAgB,QAAQ;;;EAiBvB;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,GAAG,QAcrC;AAGD,wBAAgB,QAAQ,qBAEvB;AAGD,qBAAa,aAAa;IACvB,OAAO,CAAC,IAAI,CAA2B;IAEvC,KAAK,CAAC,GAAG,EAAE,GAAG;IAId,aAAa;IAQb,KAAK;CAGP;AAGD,qBAAa,YAAY;IACtB,OAAO,CAAC,MAAM,CAAa;IAC3B,OAAO,CAAC,aAAa,CAAM;IAE3B,KAAK;IAOL,IAAI;IAIJ,GAAG;IAIH,KAAK;CAGP"} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/setup.js b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/setup.js deleted file mode 100644 index b157d6214..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/setup.js +++ /dev/null @@ -1,79 +0,0 @@ -import { Window } from "happy-dom"; -// Setup DOM globals for testing -export function setupDOM() { - const window = new Window(); - const document = window.document; - // Set globals with proper type assertions - global.document = document; - global.window = window; - global.Node = window.Node; - global.Element = window.Element; - global.HTMLElement = window.HTMLElement; - global.HTMLInputElement = window.HTMLInputElement; - global.Text = window.Text; - global.Comment = window.Comment; - global.DocumentFragment = window.DocumentFragment; - global.CustomEvent = window.CustomEvent; - return { window, document }; -} -export function cleanupDOM(window) { - window.close(); - // Use optional chaining and type assertions for cleanup - const g = global; - delete g.document; - delete g.window; - delete g.Node; - delete g.Element; - delete g.HTMLElement; - delete g.HTMLInputElement; - delete g.Text; - delete g.Comment; - delete g.DocumentFragment; - delete g.CustomEvent; -} -// Helper to wait for effects to settle -export function nextTick() { - return new Promise((resolve) => setTimeout(resolve, 0)); -} -// Helper to track memory leaks -export class MemoryTracker { - constructor() { - this.refs = new Set(); - } - track(obj) { - this.refs.add(new WeakRef(obj)); - } - getAliveCount() { - let alive = 0; - for (const ref of this.refs) { - if (ref.deref() !== undefined) - alive++; - } - return alive; - } - clear() { - this.refs.clear(); - } -} -// Helper to capture console errors -export class ErrorCapture { - constructor() { - this.errors = []; - } - start() { - this.originalError = console.error; - console.error = (...args) => { - this.errors.push(args); - }; - } - stop() { - console.error = this.originalError; - } - get() { - return this.errors; - } - clear() { - this.errors = []; - } -} -//# sourceMappingURL=setup.js.map \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/setup.js.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/setup.js.map deleted file mode 100644 index 24371a5b6..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/setup.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"setup.js","sourceRoot":"","sources":["../../src/tests/setup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAEnC,gCAAgC;AAChC,MAAM,UAAU,QAAQ;IACrB,MAAM,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC;IAC5B,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;IAEjC,0CAA0C;IACzC,MAAc,CAAC,QAAQ,GAAG,QAAQ,CAAC;IACnC,MAAc,CAAC,MAAM,GAAG,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SAAI,GAAG,IAAI,GAAG,EAAgB,CAAC;IAiB1C,CAAC;IAfE,KAAK,CAAC,GAAQ;QACX,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;IACnC,CAAC;IAED,aAAa;QACV,IAAI,KAAK,GAAG,CAAC,CAAC;QACd,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YAC3B,IAAI,GAAG,CAAC,KAAK,EAAE,KAAK,SAAS;gBAAE,KAAK,EAAE,CAAC;QAC1C,CAAC;QACD,OAAO,KAAK,CAAC;IAChB,CAAC;IAED,KAAK;QACF,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;CACH;AAED,mCAAmC;AACnC,MAAM,OAAO,YAAY;IAAzB;QACW,WAAM,GAAU,EAAE,CAAC;IAqB9B,CAAC;IAlBE,KAAK;QACF,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,KAAK,CAAC;QACnC,OAAO,CAAC,KAAK,GAAG,CAAC,GAAG,IAAW,EAAE,EAAE;YAChC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC1B,CAAC,CAAC;IACL,CAAC;IAED,IAAI;QACD,OAAO,CAAC,KAAK,GAAG,IAAI,CAAC,aAAa,CAAC;IACtC,CAAC;IAED,GAAG;QACA,OAAO,IAAI,CAAC,MAAM,CAAC;IACtB,CAAC;IAED,KAAK;QACF,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC;IACpB,CAAC;CACH"} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/template.test.d.ts b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/template.test.d.ts deleted file mode 100644 index 4095e55e3..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/template.test.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=template.test.d.ts.map \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/template.test.d.ts.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/template.test.d.ts.map deleted file mode 100644 index c81826641..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/template.test.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"template.test.d.ts","sourceRoot":"","sources":["../../src/tests/template.test.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/template.test.js b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/template.test.js deleted file mode 100644 index 8bb4682c0..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/template.test.js +++ /dev/null @@ -1,282 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test } from "vitest"; -import { createComponent, mount } from "../next/component.js"; -import { repeat } from "../next/directives/repeat.js"; -import { signal } from "../next/signals.js"; -import { html, registerComponents } from "../next/template.js"; -import { cleanupDOM, ErrorCapture, nextTick, setupDOM } from "./setup.js"; -describe("Template Runtime Issues", () => { - let window; - let document; - beforeEach(() => { - const setup = setupDOM(); - window = setup.window; - document = setup.document; - }); - afterEach(() => { - cleanupDOM(window); - }); - describe("Multi-interpolation text nodes", () => { - test("multiple dynamic values in text node maintain position", async () => { - const val1 = signal("A"); - const val2 = signal("B"); - const val3 = signal("C"); - const elem = html `
First: ${val1}, Second: ${val2}, Third: ${val3}
`; - expect(elem.textContent).toBe("First: A, Second: B, Third: C"); - val1.value = "AA"; - await nextTick(); - // Values should maintain their position - expect(elem.textContent).toBe("First: AA, Second: B, Third: C"); - val2.value = "BB"; - await nextTick(); - // Order should be correct - expect(elem.textContent).toBe("First: AA, Second: BB, Third: C"); - }); - test("data attributes example", async () => { - const dataValue = signal(42); - const customAttr = signal("test"); - const elem = html ` -
data-value: ${dataValue}, data-custom: ${customAttr}
- `; - expect(elem.textContent).toBe("data-value: 42, data-custom: test"); - dataValue.value = 43; - customAttr.value = "updated"; - await nextTick(); - // Values should update correctly - expect(elem.textContent).toBe("data-value: 43, data-custom: updated"); - }); - }); - describe("Interpolated attributes with signals", () => { - test("interpolated attributes handle signals", async () => { - const count = signal(5); - const elem = html `
`; - // Initial render should show the value - expect(elem.getAttribute("title")).toBe("Count: 5"); - count.value = 10; - await nextTick(); - // Should update reactively - expect(elem.getAttribute("title")).toBe("Count: 10"); - }); - test("class attribute with signal in interpolation", async () => { - const active = signal(false); - const elem = html ` -
- `; - // Should show boolean value as string - expect(elem.className).toBe("base false"); - active.value = true; - await nextTick(); - // Should update reactively - expect(elem.className).toBe("base true"); - }); - }); - describe("Memory leaks", () => { - test("effects cleaned up properly", async () => { - const count = signal(0); - let effectRuns = 0; - const TestComp = createComponent(() => { - // Track how many times the effect runs - effectRuns++; - return html `
${count}
`; - }); - const container = document.createElement("div"); - const instance = mount(TestComp, container); - // Initial render - expect(effectRuns).toBe(1); - // Update signal - should trigger effect - count.value = 1; - await nextTick(); - expect(effectRuns).toBe(2); - // Unmount the component - instance.unmount(); - // Update signal again - should NOT trigger effect if cleaned up properly - count.value = 2; - await nextTick(); - // Effect should not have run again after unmount - expect(effectRuns).toBe(2); - }); - test("event listeners removed on cleanup", async () => { - let clickCount = 0; - const handler = signal(() => { - clickCount++; - }); - const TestComp = createComponent(() => { - return html ``; - }); - const container = document.createElement("div"); - const instance = mount(TestComp, container); - const button = container.querySelector("button"); - // Click works initially - button.click(); - expect(clickCount).toBe(1); - // Change handler - old one should be removed - handler.value = () => { - clickCount += 10; - }; - await nextTick(); - button.click(); - expect(clickCount).toBe(11); // Should be 11, not 12 (which would mean both handlers fired) - // Keep reference to button - const buttonRef = button; - // Unmount - instance.unmount(); - container.innerHTML = ""; - // Try clicking the detached button - handler should be removed - try { - buttonRef.click(); - } - catch (e) { - // Button might throw when detached, that's ok - } - // Click count shouldn't have increased - expect(clickCount).toBe(11); - }); - test("directive cleanup called when array changes", async () => { - let cleanup1Called = false; - let cleanup2Called = false; - const items1 = signal(["a", "b"]); - const items2 = signal(["c", "d"]); - // Mock directives with cleanup - const dir1 = repeat(() => items1.value, (item) => item, (item) => html `
  • ${item}
  • `); - const originalUnmount1 = dir1.unmount; - dir1.unmount = () => { - cleanup1Called = true; - originalUnmount1?.(); - }; - const dir2 = repeat(() => items2.value, (item) => item, (item) => html `
  • ${item}
  • `); - const originalUnmount2 = dir2.unmount; - dir2.unmount = () => { - cleanup2Called = true; - originalUnmount2?.(); - }; - const directives = signal([dir1, dir2]); - const elem = html `
      ${directives}
    `; - // Replace entire array - directives.value = []; - await nextTick(); - // Cleanup should have been called - expect(cleanup1Called).toBe(true); // FIXED - expect(cleanup2Called).toBe(true); // FIXED - }); - }); - describe("Event handler issues", () => { - test("changing event handler updates correctly", async () => { - let count = 0; - const handler1 = () => { - count += 1; - }; - const handler2 = () => { - count += 10; - }; - const currentHandler = signal(handler1); - const elem = html ``; - const button = elem; - button.click(); - expect(count).toBe(1); - // Change handler - currentHandler.value = handler2; - await nextTick(); - button.click(); - // Should be 11 (1 + 10) but might be 12 (1 + 1 + 10) if both handlers attached - expect(count).toBe(11); // Might fail if duplicate listeners - }); - }); - describe("Repeat directive issues", () => { - test("repeat maintains order correctly with complex templates", async () => { - const items = signal([ - { id: 1, name: "First", extra: "A" }, - { id: 2, name: "Second", extra: "B" }, - { id: 3, name: "Third", extra: "C" }, - ]); - const elem = html ` -
      - ${repeat(() => items.value, (item) => item.id, (item) => html ` -
    • - ${item.name} - ${item.extra} -
    • - `)} -
    - `; - // Reorder items - items.value = [items.value[2], items.value[0], items.value[1]]; - await nextTick(); - const lis = elem.querySelectorAll("li"); - expect(lis[0].textContent).toBe("ThirdC"); - expect(lis[1].textContent).toBe("FirstA"); - expect(lis[2].textContent).toBe("SecondB"); - // This might fail if nodes get mixed up during reordering - }); - }); - describe("Boolean attributes", () => { - test("boolean attributes handled correctly", async () => { - const isDisabled = signal(true); - const isHidden = signal(false); - const elem = html ` - - `; - const button = elem; - // Should have disabled attribute - expect(button.hasAttribute("disabled")).toBe(true); - expect(button.hasAttribute("hidden")).toBe(false); - isDisabled.value = false; - isHidden.value = true; - await nextTick(); - expect(button.hasAttribute("disabled")).toBe(false); - expect(button.hasAttribute("hidden")).toBe(true); - }); - }); - describe("Error boundaries", () => { - test("error in effect doesn't break everything", async () => { - const errorCapture = new ErrorCapture(); - errorCapture.start(); - const goodSignal = signal("good"); - const badSignal = signal("bad"); - // This effect will throw - const elem = html ` -
    - ${() => { - if (badSignal.value === "error") - throw new Error("Effect error!"); - return goodSignal.value; - }} -
    - `; - expect(elem.textContent).toContain("good"); - // Trigger error - badSignal.value = "error"; - await nextTick(); - // Should have caught error, not crashed - const errors = errorCapture.get(); - expect(errors.length).toBeGreaterThan(0); - // Good signal should still work - goodSignal.value = "still works"; - await nextTick(); - // But it probably doesn't because effect is broken - expect(elem.textContent).not.toContain("still works"); - errorCapture.stop(); - }); - }); - describe("Slot processing duplication", () => { - test("slots processed multiple times", () => { - // Component and createComponent both process slots - // This is more of a code organization issue - const Card = createComponent((props) => html ` -
    -
    ${props.header}
    -
    ${props.children}
    -
    - `, { slots: ["header"] }); - registerComponents({ Card }); - const elem = html ` - -
    Header Content
    - Main Content -
    - `; - // Check that slot processing didn't duplicate - expect(elem.textContent).toContain("Header Content"); - expect(elem.textContent).toContain("Main Content"); - }); - }); -}); -//# sourceMappingURL=template.test.js.map \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/template.test.js.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/template.test.js.map deleted file mode 100644 index d58d1f6ba..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/tests/template.test.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"template.test.js","sourceRoot":"","sources":["../../src/tests/template.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,8BAA8B,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE1E,QAAQ,CAAC,yBAAyB,EAAE,GAAG,EAAE;IACtC,IAAI,MAAW,CAAC;IAChB,IAAI,QAAa,CAAC;IAElB,UAAU,CAAC,GAAG,EAAE;QACb,MAAM,KAAK,GAAG,QAAQ,EAAE,CAAC;QACzB,MAAM,GAAG,KAAK,CAAC,MAAM,CAAC;QACtB,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;IAC7B,CAAC,CAAC,CAAC;IAEH,SAAS,CAAC,GAAG,EAAE;QACZ,UAAU,CAAC,MAAM,CAAC,CAAC;IACtB,CAAC,CAAC,CAAC;IAEH,QAAQ,CAAC,gCAAgC,EAAE,GAAG,EAAE;QAC7C,IAAI,CAAC,wDAAwD,EAAE,KAAK,IAAI,EAAE;YACvE,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;YACzB,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;YACzB,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;YA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AAI,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC;YAEtD,YAAY,CAAC,IAAI,EAAE,CAAC;QACvB,CAAC,CAAC,CAAC;IACN,CAAC,CAAC,CAAC;IAEH,QAAQ,CAAC,6BAA6B,EAAE,GAAG,EAAE;QAC1C,IAAI,CAAC,gCAAgC,EAAE,GAAG,EAAE;YACzC,mDAAmD;YACnD,4CAA4C;YAC5C,MAAM,IAAI,GAAG,eAAe,CACzB,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,CAAA;;4BAEC,KAAK,CAAC,MAAM;0BACd,KAAK,CAAC,QAAQ;;aAE3B,EACD,EAAE,KAAK,EAAE,CAAC,QAAQ,CAAC,EAAE,CACvB,CAAC;YAEF,kBAAkB,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;YAE7B,MAAM,IAAI,GAAG,IAAI,CAAA;;;;;UAKD,CAAC;YAEjB,8CAA8C;YAC9C,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,SAAS,CAAC,gBAAgB,CAAC,CAAC;YACrD,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC;QACtD,CAAC,CAAC,CAAC;IACN,CAAC,CAAC,CAAC;AACN,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/type-test.d.ts b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/type-test.d.ts deleted file mode 100644 index a5413db47..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/type-test.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=type-test.d.ts.map diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/type-test.d.ts.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/type-test.d.ts.map deleted file mode 100644 index cd4f1148d..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/type-test.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"type-test.d.ts","sourceRoot":"","sources":["../src/type-test.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/type-test.js b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/type-test.js deleted file mode 100644 index 64502f16b..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/type-test.js +++ /dev/null @@ -1,17 +0,0 @@ -const testDef = { - myString: { - type: "value", - default: "", // This becomes literal "" - description: "test", - }, - myBoolean: { - type: "value", - default: false, // This becomes literal false - description: "test", - }, -}; -export {}; -// The issue: we're using "as const" which makes everything literal types! -// The default: "" becomes type "" not string -// The default: false becomes type false not boolean -//# sourceMappingURL=type-test.js.map \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/type-test.js.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/type-test.js.map deleted file mode 100644 index 20b3dd47b..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/type-test.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"type-test.js","sourceRoot":"","sources":["../src/type-test.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,GAAG;IACb,QAAQ,EAAE;QACP,IAAI,EAAE,OAAO;QACb,OAAO,EAAE,EAAE,EAAE,0BAA0B;QACvC,WAAW,EAAE,MAAM;KACrB;IACD,SAAS,EAAE;QACR,IAAI,EAAE,OAAO;QACb,OAAO,EAAE,KAAK,EAAE,6BAA6B;QAC7C,WAAW,EAAE,MAAM;KACrB;CACoC,CAAC;;AAQzC,0EAA0E;AAC1E,6CAA6C;AAC7C,oDAAoD"} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/usage-example.next.d.ts b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/usage-example.next.d.ts deleted file mode 100644 index 9096f1142..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/usage-example.next.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { LitElement } from 'lit'; -import { MiniButton, MiniCheckbox } from './index.next.js'; -export declare class MyApp extends LitElement { - private accepted; - private loading; - createRenderRoot(): this; - render(): import("lit-html").TemplateResult<1>; - private handleSubmit; -} -export declare class MyCustomButton extends LitElement { - private count; - createRenderRoot(): this; - render(): import("lit-html").TemplateResult<1>; -} -export declare class MyStyledApp extends LitElement { - createRenderRoot(): this; - render(): import("lit-html").TemplateResult<1>; -} -export declare function generateDocs(Component: typeof MiniButton | typeof MiniCheckbox): { - name: string; - description: any; - control: any; - options: any; - type: "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"; - default: any; -}[]; -export declare function renderToString(Component: typeof MiniButton, props: any): any; -export declare class MyGlobalStyledApp extends LitElement { - createRenderRoot(): this; - render(): import("lit-html").TemplateResult<1>; -} -//# sourceMappingURL=usage-example.next.d.ts.map \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/usage-example.next.d.ts.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/usage-example.next.d.ts.map deleted file mode 100644 index f46a36acd..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/usage-example.next.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"usage-example.next.d.ts","sourceRoot":"","sources":["../src/usage-example.next.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAQ,MAAM,KAAK,CAAC;AAEvC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAa,MAAM,iBAAiB,CAAC;AAMtE,qBACa,KAAM,SAAQ,UAAU;IAC1B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,OAAO,CAAS;IAEjC,gBAAgB;IAIhB,MAAM;IA0BN,OAAO,CAAC,YAAY;CAIrB;AAMD,qBACa,cAAe,SAAQ,UAAU;IACnC,OAAO,CAAC,KAAK,CAAK;IAE3B,gBAAgB;IAIhB,MAAM;CAYP;AAiCD,qBACa,WAAY,SAAQ,UAAU;IACzC,gBAAgB;IAIhB,MAAM;CAiBP;AAMD,wBAAgB,YAAY,CAAC,SAAS,EAAE,OAAO,UAAU,GAAG,OAAO,YAAY;;;;;;;IAkB9E;AAQD,wBAAgB,cAAc,CAAC,SAAS,EAAE,OAAO,UAAU,EAAE,KAAK,EAAE,GAAG,OAOtE;AAUD,qBACa,iBAAkB,SAAQ,UAAU;IAC/C,gBAAgB;IAIhB,MAAM;CAMP"} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/usage-example.next.js b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/usage-example.next.js deleted file mode 100644 index 0ece29e16..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/usage-example.next.js +++ /dev/null @@ -1,192 +0,0 @@ -var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -}; -import { LitElement, html } from 'lit'; -import { customElement, state } from 'lit/decorators.js'; -import { MiniButton } from './index.next.js'; -// ============================================================================ -// Example 1: Using Web Components Directly (Most Common) -// ============================================================================ -let MyApp = class MyApp extends LitElement { - constructor() { - super(...arguments); - this.accepted = false; - this.loading = false; - } - createRenderRoot() { - return this; // Light DOM for Tailwind - } - render() { - return html ` -
    - -
    - { - this.accepted = e.target.checked; - }} - > - Accept terms and conditions -
    - - this.handleSubmit()} - > - Submit - -
    - `; - } - handleSubmit() { - this.loading = true; - // ... do something - } -}; -__decorate([ - state() -], MyApp.prototype, "accepted", void 0); -__decorate([ - state() -], MyApp.prototype, "loading", void 0); -MyApp = __decorate([ - customElement('my-app') -], MyApp); -export { MyApp }; -// ============================================================================ -// Example 2: Using Static Templates in Custom Components -// ============================================================================ -let MyCustomButton = class MyCustomButton extends LitElement { - constructor() { - super(...arguments); - this.count = 0; - } - createRenderRoot() { - return this; // Light DOM - } - render() { - // Use the static template when building your own components - return html ` -
    - ${MiniButton.template({ - children: `Clicked ${this.count} times`, - onClick: () => this.count++, - variant: 'primary', - })} -
    - `; - } -}; -__decorate([ - state() -], MyCustomButton.prototype, "count", void 0); -MyCustomButton = __decorate([ - customElement('my-custom-button') -], MyCustomButton); -export { MyCustomButton }; -// ============================================================================ -// Example 3: Custom Styles -// ============================================================================ -import { tv } from 'tailwind-variants'; -// Create your own button styles -const myButtonStyles = tv({ - base: "px-6 py-3 rounded-full font-bold transition-all", - variants: { - variant: { - default: "bg-blue-500 text-white hover:bg-blue-600", - destructive: "bg-red-500 text-white hover:bg-red-600", - outline: "border-2 border-gray-300 hover:border-gray-400", - secondary: "bg-gray-200 hover:bg-gray-300", - ghost: "hover:bg-gray-100", - link: "underline hover:no-underline", - }, - size: { - default: "text-base", - sm: "text-sm", - lg: "text-lg", - icon: "p-3", - }, - }, - defaultVariants: { - variant: "default", - size: "default", - }, -}); -let MyStyledApp = class MyStyledApp extends LitElement { - createRenderRoot() { - return this; // Light DOM - } - render() { - return html ` - - - Custom Styled Button - - - - ${MiniButton.template({ children: "Template with custom styles" }, myButtonStyles)} - `; - } -}; -MyStyledApp = __decorate([ - customElement('my-styled-app') -], MyStyledApp); -export { MyStyledApp }; -// ============================================================================ -// Example 4: Documentation Generation -// ============================================================================ -export function generateDocs(Component) { - const metadata = Component.getMetadata(); - // Use reflection to get all @property decorated fields - const properties = []; - for (const [key, meta] of Object.entries(metadata || {})) { - properties.push({ - name: key, - description: meta.description, - control: meta.control, - options: meta.options, - // Get type and default from the actual component instance - type: typeof Component.prototype[key], - default: Component.prototype[key], - }); - } - return properties; -} -export function renderToString(Component, props) { - // Templates are just template literals, can be rendered server-side - const template = Component.template(props); - // Render to string (you'd need a server-side renderer) - // This is pseudo-code, actual implementation would need more work - return template.strings.join(''); -} -// ============================================================================ -// Example 6: Global Style Override -// ============================================================================ -// Override default styles globally -MiniButton.defaultStyles = myButtonStyles; -// Now all buttons use the new styles by default -let MyGlobalStyledApp = class MyGlobalStyledApp extends LitElement { - createRenderRoot() { - return this; // Light DOM - } - render() { - return html ` - - Globally Styled - `; - } -}; -MyGlobalStyledApp = __decorate([ - customElement('my-global-styled-app') -], MyGlobalStyledApp); -export { MyGlobalStyledApp }; -//# sourceMappingURL=usage-example.next.js.map \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/usage-example.next.js.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/usage-example.next.js.map deleted file mode 100644 index ea5e6b70c..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/dist/usage-example.next.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"usage-example.next.js","sourceRoot":"","sources":["../src/usage-example.next.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,KAAK,CAAC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B,CAW7B"} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/.bin/marked b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/.bin/marked deleted file mode 120000 index 6827ff333..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/.bin/marked +++ /dev/null @@ -1 +0,0 @@ -../marked/bin/marked.js \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/LICENSE.md b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/LICENSE.md deleted file mode 100644 index 4bd2d4a08..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/LICENSE.md +++ /dev/null @@ -1,44 +0,0 @@ -# License information - -## Contribution License Agreement - -If you contribute code to this project, you are implicitly allowing your code -to be distributed under the MIT license. You are also implicitly verifying that -all code is your original work. `` - -## Marked - -Copyright (c) 2018+, MarkedJS (https://github.com/markedjs/) -Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -## Markdown - -Copyright © 2004, John Gruber -http://daringfireball.net/ -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. -* Neither the name “Markdown” nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -This software is provided by the copyright holders and contributors “as is” and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/README.md b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/README.md deleted file mode 100644 index 60f0b28bc..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/README.md +++ /dev/null @@ -1,107 +0,0 @@ - - - - -# Marked - -[![npm](https://badgen.net/npm/v/marked)](https://www.npmjs.com/package/marked) -[![install size](https://badgen.net/packagephobia/install/marked)](https://packagephobia.now.sh/result?p=marked) -[![downloads](https://badgen.net/npm/dt/marked)](https://www.npmjs.com/package/marked) -[![github actions](https://github.com/markedjs/marked/workflows/Tests/badge.svg)](https://github.com/markedjs/marked/actions) -[![snyk](https://snyk.io/test/npm/marked/badge.svg)](https://snyk.io/test/npm/marked) - -- ⚡ built for speed -- ⬇️ low-level compiler for parsing markdown without caching or blocking for long periods of time -- ⚖️ light-weight while implementing all markdown features from the supported flavors & specifications -- 🌐 works in a browser, on a server, or from a command line interface (CLI) - -## Demo - -Check out the [demo page](https://marked.js.org/demo/) to see Marked in action ⛹️ - -## Docs - -Our [documentation pages](https://marked.js.org) are also rendered using marked 💯 - -Also read about: - -* [Options](https://marked.js.org/using_advanced) -* [Extensibility](https://marked.js.org/using_pro) - -## Compatibility - -**Node.js:** Only [current and LTS](https://nodejs.org/en/about/releases/) Node.js versions are supported. End of life Node.js versions may become incompatible with Marked at any point in time. - -**Browser:** [Baseline Widely Available](https://developer.mozilla.org/en-US/docs/Glossary/Baseline/Compatibility) - -## Installation - -**CLI:** - -```sh -npm install -g marked -``` - -**In-browser:** - -```sh -npm install marked -``` - -## Usage - -### Warning: 🚨 Marked does not [sanitize](https://marked.js.org/using_advanced#options) the output HTML. Please use a sanitize library, like [DOMPurify](https://github.com/cure53/DOMPurify) (recommended), [sanitize-html](https://github.com/apostrophecms/sanitize-html) or [insane](https://github.com/bevacqua/insane) on the *output* HTML! 🚨 - -``` -DOMPurify.sanitize(marked.parse(``)); -``` - -**CLI** - -``` bash -# Example with stdin input -$ marked -o hello.html -hello world -^D -$ cat hello.html -

    hello world

    -``` - -```bash -# Print all options -$ marked --help -``` - -**Browser** - -```html - - - - - Marked in the browser - - -
    - - - - -``` -or import esm module - -```html - -``` - -## License - -Copyright (c) 2018+, MarkedJS. (MIT License) -Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License) diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/bin/main.js b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/bin/main.js deleted file mode 100644 index 14059affd..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/bin/main.js +++ /dev/null @@ -1,283 +0,0 @@ -#!/usr/bin/env node - -/** - * Marked CLI - * Copyright (c) 2018+, MarkedJS. (MIT License) - * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License) - */ - -import { promises } from 'node:fs'; -import { dirname, resolve } from 'node:path'; -import { homedir } from 'node:os'; -import { createRequire } from 'node:module'; -import { marked } from '../lib/marked.esm.js'; - -const { access, readFile, writeFile } = promises; -const require = createRequire(import.meta.url); - -/** - * @param {Process} nodeProcess inject process so it can be mocked in tests. - */ -export async function main(nodeProcess) { - /** - * Man Page - */ - async function help() { - const { spawn } = await import('child_process'); - const { fileURLToPath } = await import('url'); - - const options = { - cwd: nodeProcess.cwd(), - env: nodeProcess.env, - stdio: 'inherit', - }; - - const __dirname = dirname(fileURLToPath(import.meta.url)); - const helpText = await readFile(resolve(__dirname, '../man/marked.1.md'), 'utf8'); - - await new Promise(res => { - const manProcess = spawn('man', [resolve(__dirname, '../man/marked.1')], options); - nodeProcess.on('SIGINT', () => { - manProcess.kill('SIGINT'); - }); - - manProcess.on('error', () => { - console.log(helpText); - }) - .on('close', res); - }); - } - - async function version() { - const pkg = require('../package.json'); - console.log(pkg.version); - } - - /** - * Main - */ - async function start(argv) { - const files = []; - const options = {}; - let input; - let output; - let string; - let arg; - let tokens; - let config; - let opt; - let noclobber; - - function getArg() { - let arg = argv.shift(); - - if (arg.indexOf('--') === 0) { - // e.g. --opt - arg = arg.split('='); - if (arg.length > 1) { - // e.g. --opt=val - argv.unshift(arg.slice(1).join('=')); - } - arg = arg[0]; - } else if (arg[0] === '-') { - if (arg.length > 2) { - // e.g. -abc - argv = arg.substring(1).split('').map(function(ch) { - return '-' + ch; - }).concat(argv); - arg = argv.shift(); - } else { - // e.g. -a - } - } else { - // e.g. foo - } - - return arg; - } - - while (argv.length) { - arg = getArg(); - switch (arg) { - case '-o': - case '--output': - output = argv.shift(); - break; - case '-i': - case '--input': - input = argv.shift(); - break; - case '-s': - case '--string': - string = argv.shift(); - break; - case '-t': - case '--tokens': - tokens = true; - break; - case '-c': - case '--config': - config = argv.shift(); - break; - case '-n': - case '--no-clobber': - noclobber = true; - break; - case '-h': - case '--help': - return await help(); - case '-v': - case '--version': - return await version(); - default: - if (arg.indexOf('--') === 0) { - opt = camelize(arg.replace(/^--(no-)?/, '')); - if (!(opt in marked.defaults)) { - continue; - } - if (arg.indexOf('--no-') === 0) { - options[opt] = typeof marked.defaults[opt] !== 'boolean' - ? null - : false; - } else { - options[opt] = typeof marked.defaults[opt] !== 'boolean' - ? argv.shift() - : true; - } - } else { - files.push(arg); - } - break; - } - } - - async function getData() { - if (!input) { - if (files.length <= 2) { - if (string) { - return string; - } - return await getStdin(); - } - input = files.pop(); - } - return await readFile(input, 'utf8'); - } - - function resolveFile(file) { - return resolve(file.replace(/^~/, homedir)); - } - - function fileExists(file) { - return access(resolveFile(file)).then(() => true, () => false); - } - - async function runConfig(file) { - const configFile = resolveFile(file); - let markedConfig; - try { - // try require for json - markedConfig = require(configFile); - } catch(err) { - if (err.code !== 'ERR_REQUIRE_ESM') { - throw err; - } - // must import esm - markedConfig = await import('file:///' + configFile); - } - - if (markedConfig.default) { - markedConfig = markedConfig.default; - } - - if (typeof markedConfig === 'function') { - markedConfig(marked); - } else { - marked.use(markedConfig); - } - } - - const data = await getData(); - - if (config) { - if (!await fileExists(config)) { - throw Error(`Cannot load config file '${config}'`); - } - - await runConfig(config); - } else { - const defaultConfig = [ - '~/.marked.json', - '~/.marked.js', - '~/.marked/index.js', - ]; - - for (const configFile of defaultConfig) { - if (await fileExists(configFile)) { - await runConfig(configFile); - break; - } - } - } - - const html = tokens - ? JSON.stringify(marked.lexer(data, options), null, 2) - : await marked.parse(data, options); - - if (output) { - if (noclobber && await fileExists(output)) { - throw Error('marked: output file \'' + output + '\' already exists, disable the \'-n\' / \'--no-clobber\' flag to overwrite\n'); - } - return await writeFile(output, html); - } - - nodeProcess.stdout.write(html + '\n'); - } - - /** - * Helpers - */ - function getStdin() { - return new Promise((resolve, reject) => { - const stdin = nodeProcess.stdin; - let buff = ''; - - stdin.setEncoding('utf8'); - - stdin.on('data', function(data) { - buff += data; - }); - - stdin.on('error', function(err) { - reject(err); - }); - - stdin.on('end', function() { - resolve(buff); - }); - - stdin.resume(); - }); - } - - /** - * @param {string} text - */ - function camelize(text) { - return text.replace(/(\w)-(\w)/g, function(_, a, b) { - return a + b.toUpperCase(); - }); - } - - try { - await start(nodeProcess.argv.slice()); - nodeProcess.exit(0); - } catch(err) { - if (err.code === 'ENOENT') { - nodeProcess.stderr.write('marked: ' + err.path + ': No such file or directory'); - } else { - nodeProcess.stderr.write(err.message); - } - return nodeProcess.exit(1); - } -} diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/bin/marked.js b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/bin/marked.js deleted file mode 100755 index 65ff0aaa4..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/bin/marked.js +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env node - -/** - * Marked CLI - * Copyright (c) 2018+, MarkedJS. (MIT License) - * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License) - */ - -import { main } from './main.js'; - -/** - * Expose / Entry Point - */ - -process.title = 'marked'; -main(process); diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/lib/marked.d.ts b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/lib/marked.d.ts deleted file mode 100644 index 11d4901a0..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/lib/marked.d.ts +++ /dev/null @@ -1,749 +0,0 @@ -// Generated by dts-bundle-generator v9.5.1 - -export type MarkedToken = (Tokens.Blockquote | Tokens.Br | Tokens.Code | Tokens.Codespan | Tokens.Def | Tokens.Del | Tokens.Em | Tokens.Escape | Tokens.Heading | Tokens.Hr | Tokens.HTML | Tokens.Image | Tokens.Link | Tokens.List | Tokens.ListItem | Tokens.Paragraph | Tokens.Space | Tokens.Strong | Tokens.Table | Tokens.Tag | Tokens.Text); -export type Token = (MarkedToken | Tokens.Generic); -export declare namespace Tokens { - interface Blockquote { - type: "blockquote"; - raw: string; - text: string; - tokens: Token[]; - } - interface Br { - type: "br"; - raw: string; - } - interface Checkbox { - checked: boolean; - } - interface Code { - type: "code"; - raw: string; - codeBlockStyle?: "indented"; - lang?: string; - text: string; - escaped?: boolean; - } - interface Codespan { - type: "codespan"; - raw: string; - text: string; - } - interface Def { - type: "def"; - raw: string; - tag: string; - href: string; - title: string; - } - interface Del { - type: "del"; - raw: string; - text: string; - tokens: Token[]; - } - interface Em { - type: "em"; - raw: string; - text: string; - tokens: Token[]; - } - interface Escape { - type: "escape"; - raw: string; - text: string; - } - interface Generic { - [index: string]: any; - type: string; - raw: string; - tokens?: Token[]; - } - interface Heading { - type: "heading"; - raw: string; - depth: number; - text: string; - tokens: Token[]; - } - interface Hr { - type: "hr"; - raw: string; - } - interface HTML { - type: "html"; - raw: string; - pre: boolean; - text: string; - block: boolean; - } - interface Image { - type: "image"; - raw: string; - href: string; - title: string | null; - text: string; - tokens: Token[]; - } - interface Link { - type: "link"; - raw: string; - href: string; - title?: string | null; - text: string; - tokens: Token[]; - } - interface List { - type: "list"; - raw: string; - ordered: boolean; - start: number | ""; - loose: boolean; - items: ListItem[]; - } - interface ListItem { - type: "list_item"; - raw: string; - task: boolean; - checked?: boolean; - loose: boolean; - text: string; - tokens: Token[]; - } - interface Paragraph { - type: "paragraph"; - raw: string; - pre?: boolean; - text: string; - tokens: Token[]; - } - interface Space { - type: "space"; - raw: string; - } - interface Strong { - type: "strong"; - raw: string; - text: string; - tokens: Token[]; - } - interface Table { - type: "table"; - raw: string; - align: Array<"center" | "left" | "right" | null>; - header: TableCell[]; - rows: TableCell[][]; - } - interface TableCell { - text: string; - tokens: Token[]; - header: boolean; - align: "center" | "left" | "right" | null; - } - interface TableRow

    { - text: P; - } - interface Tag { - type: "html"; - raw: string; - inLink: boolean; - inRawBlock: boolean; - text: string; - block: boolean; - } - interface Text { - type: "text"; - raw: string; - text: string; - tokens?: Token[]; - escaped?: boolean; - } -} -export type Links = Record>; -export type TokensList = Token[] & { - links: Links; -}; -/** - * Renderer - */ -declare class _Renderer { - options: MarkedOptions; - parser: _Parser; - constructor(options?: MarkedOptions); - space(token: Tokens.Space): RendererOutput; - code({ text, lang, escaped }: Tokens.Code): RendererOutput; - blockquote({ tokens }: Tokens.Blockquote): RendererOutput; - html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput; - def(token: Tokens.Def): RendererOutput; - heading({ tokens, depth }: Tokens.Heading): RendererOutput; - hr(token: Tokens.Hr): RendererOutput; - list(token: Tokens.List): RendererOutput; - listitem(item: Tokens.ListItem): RendererOutput; - checkbox({ checked }: Tokens.Checkbox): RendererOutput; - paragraph({ tokens }: Tokens.Paragraph): RendererOutput; - table(token: Tokens.Table): RendererOutput; - tablerow({ text }: Tokens.TableRow): RendererOutput; - tablecell(token: Tokens.TableCell): RendererOutput; - /** - * span level renderer - */ - strong({ tokens }: Tokens.Strong): RendererOutput; - em({ tokens }: Tokens.Em): RendererOutput; - codespan({ text }: Tokens.Codespan): RendererOutput; - br(token: Tokens.Br): RendererOutput; - del({ tokens }: Tokens.Del): RendererOutput; - link({ href, title, tokens }: Tokens.Link): RendererOutput; - image({ href, title, text, tokens }: Tokens.Image): RendererOutput; - text(token: Tokens.Text | Tokens.Escape): RendererOutput; -} -/** - * TextRenderer - * returns only the textual part of the token - */ -declare class _TextRenderer { - strong({ text }: Tokens.Strong): RendererOutput; - em({ text }: Tokens.Em): RendererOutput; - codespan({ text }: Tokens.Codespan): RendererOutput; - del({ text }: Tokens.Del): RendererOutput; - html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput; - text({ text }: Tokens.Text | Tokens.Escape | Tokens.Tag): RendererOutput; - link({ text }: Tokens.Link): RendererOutput; - image({ text }: Tokens.Image): RendererOutput; - br(): RendererOutput; -} -/** - * Parsing & Compiling - */ -declare class _Parser { - options: MarkedOptions; - renderer: _Renderer; - textRenderer: _TextRenderer; - constructor(options?: MarkedOptions); - /** - * Static Parse Method - */ - static parse(tokens: Token[], options?: MarkedOptions): ParserOutput; - /** - * Static Parse Inline Method - */ - static parseInline(tokens: Token[], options?: MarkedOptions): ParserOutput; - /** - * Parse Loop - */ - parse(tokens: Token[], top?: boolean): ParserOutput; - /** - * Parse Inline Tokens - */ - parseInline(tokens: Token[], renderer?: _Renderer | _TextRenderer): ParserOutput; -} -declare const other: { - codeRemoveIndent: RegExp; - outputLinkReplace: RegExp; - indentCodeCompensation: RegExp; - beginningSpace: RegExp; - endingHash: RegExp; - startingSpaceChar: RegExp; - endingSpaceChar: RegExp; - nonSpaceChar: RegExp; - newLineCharGlobal: RegExp; - tabCharGlobal: RegExp; - multipleSpaceGlobal: RegExp; - blankLine: RegExp; - doubleBlankLine: RegExp; - blockquoteStart: RegExp; - blockquoteSetextReplace: RegExp; - blockquoteSetextReplace2: RegExp; - listReplaceTabs: RegExp; - listReplaceNesting: RegExp; - listIsTask: RegExp; - listReplaceTask: RegExp; - anyLine: RegExp; - hrefBrackets: RegExp; - tableDelimiter: RegExp; - tableAlignChars: RegExp; - tableRowBlankLine: RegExp; - tableAlignRight: RegExp; - tableAlignCenter: RegExp; - tableAlignLeft: RegExp; - startATag: RegExp; - endATag: RegExp; - startPreScriptTag: RegExp; - endPreScriptTag: RegExp; - startAngleBracket: RegExp; - endAngleBracket: RegExp; - pedanticHrefTitle: RegExp; - unicodeAlphaNumeric: RegExp; - escapeTest: RegExp; - escapeReplace: RegExp; - escapeTestNoEncode: RegExp; - escapeReplaceNoEncode: RegExp; - unescapeTest: RegExp; - caret: RegExp; - percentDecode: RegExp; - findPipe: RegExp; - splitPipe: RegExp; - slashPipe: RegExp; - carriageReturn: RegExp; - spaceLine: RegExp; - notSpaceStart: RegExp; - endingNewline: RegExp; - listItemRegex: (bull: string) => RegExp; - nextBulletRegex: (indent: number) => RegExp; - hrRegex: (indent: number) => RegExp; - fencesBeginRegex: (indent: number) => RegExp; - headingBeginRegex: (indent: number) => RegExp; - htmlBeginRegex: (indent: number) => RegExp; -}; -declare const blockNormal: { - blockquote: RegExp; - code: RegExp; - def: RegExp; - fences: RegExp; - heading: RegExp; - hr: RegExp; - html: RegExp; - lheading: RegExp; - list: RegExp; - newline: RegExp; - paragraph: RegExp; - table: RegExp; - text: RegExp; -}; -export type BlockKeys = keyof typeof blockNormal; -declare const inlineNormal: { - _backpedal: RegExp; - anyPunctuation: RegExp; - autolink: RegExp; - blockSkip: RegExp; - br: RegExp; - code: RegExp; - del: RegExp; - emStrongLDelim: RegExp; - emStrongRDelimAst: RegExp; - emStrongRDelimUnd: RegExp; - escape: RegExp; - link: RegExp; - nolink: RegExp; - punctuation: RegExp; - reflink: RegExp; - reflinkSearch: RegExp; - tag: RegExp; - text: RegExp; - url: RegExp; -}; -export type InlineKeys = keyof typeof inlineNormal; -export interface Rules { - other: typeof other; - block: Record; - inline: Record; -} -/** - * Tokenizer - */ -declare class _Tokenizer { - options: MarkedOptions; - rules: Rules; - lexer: _Lexer; - constructor(options?: MarkedOptions); - space(src: string): Tokens.Space | undefined; - code(src: string): Tokens.Code | undefined; - fences(src: string): Tokens.Code | undefined; - heading(src: string): Tokens.Heading | undefined; - hr(src: string): Tokens.Hr | undefined; - blockquote(src: string): Tokens.Blockquote | undefined; - list(src: string): Tokens.List | undefined; - html(src: string): Tokens.HTML | undefined; - def(src: string): Tokens.Def | undefined; - table(src: string): Tokens.Table | undefined; - lheading(src: string): Tokens.Heading | undefined; - paragraph(src: string): Tokens.Paragraph | undefined; - text(src: string): Tokens.Text | undefined; - escape(src: string): Tokens.Escape | undefined; - tag(src: string): Tokens.Tag | undefined; - link(src: string): Tokens.Link | Tokens.Image | undefined; - reflink(src: string, links: Links): Tokens.Link | Tokens.Image | Tokens.Text | undefined; - emStrong(src: string, maskedSrc: string, prevChar?: string): Tokens.Em | Tokens.Strong | undefined; - codespan(src: string): Tokens.Codespan | undefined; - br(src: string): Tokens.Br | undefined; - del(src: string): Tokens.Del | undefined; - autolink(src: string): Tokens.Link | undefined; - url(src: string): Tokens.Link | undefined; - inlineText(src: string): Tokens.Text | undefined; -} -declare class _Hooks { - options: MarkedOptions; - block?: boolean; - constructor(options?: MarkedOptions); - static passThroughHooks: Set; - static passThroughHooksRespectAsync: Set; - /** - * Process markdown before marked - */ - preprocess(markdown: string): string; - /** - * Process HTML after marked is finished - */ - postprocess(html: ParserOutput): ParserOutput; - /** - * Process all tokens before walk tokens - */ - processAllTokens(tokens: Token[] | TokensList): Token[] | TokensList; - /** - * Mask contents that should not be interpreted as em/strong delimiters - */ - emStrongMask(src: string): string; - /** - * Provide function to tokenize markdown - */ - provideLexer(): typeof _Lexer.lexInline; - /** - * Provide function to parse tokens - */ - provideParser(): (tokens: Token[], options?: MarkedOptions | undefined) => ParserOutput; -} -export interface TokenizerThis { - lexer: _Lexer; -} -export type TokenizerExtensionFunction = (this: TokenizerThis, src: string, tokens: Token[] | TokensList) => Tokens.Generic | undefined; -export type TokenizerStartFunction = (this: TokenizerThis, src: string) => number | void; -export interface TokenizerExtension { - name: string; - level: "block" | "inline"; - start?: TokenizerStartFunction; - tokenizer: TokenizerExtensionFunction; - childTokens?: string[]; -} -export interface RendererThis { - parser: _Parser; -} -export type RendererExtensionFunction = (this: RendererThis, token: Tokens.Generic) => RendererOutput | false | undefined; -export interface RendererExtension { - name: string; - renderer: RendererExtensionFunction; -} -export type TokenizerAndRendererExtension = TokenizerExtension | RendererExtension | (TokenizerExtension & RendererExtension); -export type HooksApi = Omit<_Hooks, "constructor" | "options" | "block">; -export type HooksObject = { - [K in keyof HooksApi]?: (this: _Hooks, ...args: Parameters[K]>) => ReturnType[K]> | Promise[K]>>; -}; -export type RendererApi = Omit<_Renderer, "constructor" | "options" | "parser">; -export type RendererObject = { - [K in keyof RendererApi]?: (this: _Renderer, ...args: Parameters[K]>) => ReturnType[K]> | false; -}; -export type TokenizerApi = Omit<_Tokenizer, "constructor" | "options" | "rules" | "lexer">; -export type TokenizerObject = { - [K in keyof TokenizerApi]?: (this: _Tokenizer, ...args: Parameters[K]>) => ReturnType[K]> | false; -}; -export interface MarkedExtension { - /** - * True will tell marked to await any walkTokens functions before parsing the tokens and returning an HTML string. - */ - async?: boolean; - /** - * Enable GFM line breaks. This option requires the gfm option to be true. - */ - breaks?: boolean; - /** - * Add tokenizers and renderers to marked - */ - extensions?: TokenizerAndRendererExtension[] | null; - /** - * Enable GitHub flavored markdown. - */ - gfm?: boolean; - /** - * Hooks are methods that hook into some part of marked. - * preprocess is called to process markdown before sending it to marked. - * processAllTokens is called with the TokensList before walkTokens. - * postprocess is called to process html after marked has finished parsing. - * emStrongMask is called to mask contents that should not be interpreted as em/strong delimiters. - * provideLexer is called to provide a function to tokenize markdown. - * provideParser is called to provide a function to parse tokens. - */ - hooks?: HooksObject | null; - /** - * Conform to obscure parts of markdown.pl as much as possible. Don't fix any of the original markdown bugs or poor behavior. - */ - pedantic?: boolean; - /** - * Type: object Default: new Renderer() - * - * An object containing functions to render tokens to HTML. - */ - renderer?: RendererObject | null; - /** - * Shows an HTML error message when rendering fails. - */ - silent?: boolean; - /** - * The tokenizer defines how to turn markdown text into tokens. - */ - tokenizer?: TokenizerObject | null; - /** - * The walkTokens function gets called with every token. - * Child tokens are called before moving on to sibling tokens. - * Each token is passed by reference so updates are persisted when passed to the parser. - * The return value of the function is ignored. - */ - walkTokens?: ((token: Token) => void | Promise) | null; -} -export interface MarkedOptions extends Omit, "hooks" | "renderer" | "tokenizer" | "extensions" | "walkTokens"> { - /** - * Hooks are methods that hook into some part of marked. - */ - hooks?: _Hooks | null; - /** - * Type: object Default: new Renderer() - * - * An object containing functions to render tokens to HTML. - */ - renderer?: _Renderer | null; - /** - * The tokenizer defines how to turn markdown text into tokens. - */ - tokenizer?: _Tokenizer | null; - /** - * Custom extensions - */ - extensions?: null | { - renderers: { - [name: string]: RendererExtensionFunction; - }; - childTokens: { - [name: string]: string[]; - }; - inline?: TokenizerExtensionFunction[]; - block?: TokenizerExtensionFunction[]; - startInline?: TokenizerStartFunction[]; - startBlock?: TokenizerStartFunction[]; - }; - /** - * walkTokens function returns array of values for Promise.all - */ - walkTokens?: null | ((token: Token) => void | Promise | (void | Promise)[]); -} -/** - * Block Lexer - */ -declare class _Lexer { - tokens: TokensList; - options: MarkedOptions; - state: { - inLink: boolean; - inRawBlock: boolean; - top: boolean; - }; - private tokenizer; - private inlineQueue; - constructor(options?: MarkedOptions); - /** - * Expose Rules - */ - static get rules(): { - block: { - normal: { - blockquote: RegExp; - code: RegExp; - def: RegExp; - fences: RegExp; - heading: RegExp; - hr: RegExp; - html: RegExp; - lheading: RegExp; - list: RegExp; - newline: RegExp; - paragraph: RegExp; - table: RegExp; - text: RegExp; - }; - gfm: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "def" | "heading" | "list" | "paragraph" | "fences" | "lheading" | "newline", RegExp>; - pedantic: Record<"code" | "blockquote" | "hr" | "html" | "table" | "text" | "def" | "heading" | "list" | "paragraph" | "fences" | "lheading" | "newline", RegExp>; - }; - inline: { - normal: { - _backpedal: RegExp; - anyPunctuation: RegExp; - autolink: RegExp; - blockSkip: RegExp; - br: RegExp; - code: RegExp; - del: RegExp; - emStrongLDelim: RegExp; - emStrongRDelimAst: RegExp; - emStrongRDelimUnd: RegExp; - escape: RegExp; - link: RegExp; - nolink: RegExp; - punctuation: RegExp; - reflink: RegExp; - reflinkSearch: RegExp; - tag: RegExp; - text: RegExp; - url: RegExp; - }; - gfm: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "nolink" | "_backpedal" | "anyPunctuation" | "autolink" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>; - breaks: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "nolink" | "_backpedal" | "anyPunctuation" | "autolink" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>; - pedantic: Record<"link" | "code" | "url" | "br" | "del" | "text" | "escape" | "tag" | "reflink" | "nolink" | "_backpedal" | "anyPunctuation" | "autolink" | "blockSkip" | "emStrongLDelim" | "emStrongRDelimAst" | "emStrongRDelimUnd" | "punctuation" | "reflinkSearch", RegExp>; - }; - }; - /** - * Static Lex Method - */ - static lex(src: string, options?: MarkedOptions): TokensList; - /** - * Static Lex Inline Method - */ - static lexInline(src: string, options?: MarkedOptions): Token[]; - /** - * Preprocessing - */ - lex(src: string): TokensList; - /** - * Lexing - */ - blockTokens(src: string, tokens?: Token[], lastParagraphClipped?: boolean): Token[]; - blockTokens(src: string, tokens?: TokensList, lastParagraphClipped?: boolean): TokensList; - inline(src: string, tokens?: Token[]): Token[]; - /** - * Lexing/Compiling - */ - inlineTokens(src: string, tokens?: Token[]): Token[]; -} -/** - * Gets the original marked default options. - */ -declare function _getDefaults(): MarkedOptions; -declare let _defaults: MarkedOptions; -export type MaybePromise = void | Promise; -export declare class Marked { - defaults: MarkedOptions; - options: (opt: MarkedOptions) => this; - parse: { - (src: string, options: MarkedOptions & { - async: true; - }): Promise; - (src: string, options: MarkedOptions & { - async: false; - }): ParserOutput; - (src: string, options?: MarkedOptions | null): ParserOutput | Promise; - }; - parseInline: { - (src: string, options: MarkedOptions & { - async: true; - }): Promise; - (src: string, options: MarkedOptions & { - async: false; - }): ParserOutput; - (src: string, options?: MarkedOptions | null): ParserOutput | Promise; - }; - Parser: { - new (options?: MarkedOptions | undefined): _Parser; - parse(tokens: Token[], options?: MarkedOptions): ParserOutput_1; - parseInline(tokens: Token[], options?: MarkedOptions): ParserOutput_1; - }; - Renderer: { - new (options?: MarkedOptions | undefined): _Renderer; - }; - TextRenderer: { - new (): _TextRenderer; - }; - Lexer: typeof _Lexer; - Tokenizer: { - new (options?: MarkedOptions | undefined): _Tokenizer; - }; - Hooks: { - new (options?: MarkedOptions | undefined): _Hooks; - passThroughHooks: Set; - passThroughHooksRespectAsync: Set; - }; - constructor(...args: MarkedExtension[]); - /** - * Run callback for every token - */ - walkTokens(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]): MaybePromise[]; - use(...args: MarkedExtension[]): this; - setOptions(opt: MarkedOptions): this; - lexer(src: string, options?: MarkedOptions): TokensList; - parser(tokens: Token[], options?: MarkedOptions): ParserOutput; - private parseMarkdown; - private onError; -} -/** - * Compiles markdown to HTML asynchronously. - * - * @param src String of markdown source to be compiled - * @param options Hash of options, having async: true - * @return Promise of string of compiled HTML - */ -export declare function marked(src: string, options: MarkedOptions & { - async: true; -}): Promise; -/** - * Compiles markdown to HTML. - * - * @param src String of markdown source to be compiled - * @param options Optional hash of options - * @return String of compiled HTML. Will be a Promise of string if async is set to true by any extensions. - */ -export declare function marked(src: string, options: MarkedOptions & { - async: false; -}): string; -export declare function marked(src: string, options: MarkedOptions & { - async: true; -}): Promise; -export declare function marked(src: string, options?: MarkedOptions | null): string | Promise; -export declare namespace marked { - var options: (options: MarkedOptions) => typeof marked; - var setOptions: (options: MarkedOptions) => typeof marked; - var getDefaults: typeof _getDefaults; - var defaults: MarkedOptions; - var use: (...args: MarkedExtension[]) => typeof marked; - var walkTokens: (tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) => MaybePromise[]; - var parseInline: { - (src: string, options: MarkedOptions & { - async: true; - }): Promise; - (src: string, options: MarkedOptions & { - async: false; - }): string; - (src: string, options?: MarkedOptions | null | undefined): string | Promise; - }; - var Parser: typeof _Parser; - var parser: typeof _Parser.parse; - var Renderer: typeof _Renderer; - var TextRenderer: typeof _TextRenderer; - var Lexer: typeof _Lexer; - var lexer: typeof _Lexer.lex; - var Tokenizer: typeof _Tokenizer; - var Hooks: typeof _Hooks; - var parse: typeof marked; -} -export declare const options: (options: MarkedOptions) => typeof marked; -export declare const setOptions: (options: MarkedOptions) => typeof marked; -export declare const use: (...args: MarkedExtension[]) => typeof marked; -export declare const walkTokens: (tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) => MaybePromise[]; -export declare const parseInline: { - (src: string, options: MarkedOptions & { - async: true; - }): Promise; - (src: string, options: MarkedOptions & { - async: false; - }): string; - (src: string, options?: MarkedOptions | null | undefined): string | Promise; -}; -export declare const parse: typeof marked; -export declare const parser: typeof _Parser.parse; -export declare const lexer: typeof _Lexer.lex; - -export { - _Hooks as Hooks, - _Lexer as Lexer, - _Parser as Parser, - _Renderer as Renderer, - _TextRenderer as TextRenderer, - _Tokenizer as Tokenizer, - _defaults as defaults, - _getDefaults as getDefaults, -}; - -export {}; diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/lib/marked.esm.js b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/lib/marked.esm.js deleted file mode 100644 index 8e4e78659..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/lib/marked.esm.js +++ /dev/null @@ -1,73 +0,0 @@ -/** - * marked v16.4.2 - a markdown parser - * Copyright (c) 2018-2025, MarkedJS. (MIT License) - * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License) - * https://github.com/markedjs/marked - */ - -/** - * DO NOT EDIT THIS FILE - * The code in this file is generated from files in ./src/ - */ - -function L(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var T=L();function G(l){T=l}var E={exec:()=>null};function d(l,e=""){let t=typeof l=="string"?l:l.source,n={replace:(r,i)=>{let s=typeof i=="string"?i:i.source;return s=s.replace(m.caret,"$1"),t=t.replace(r,s),n},getRegex:()=>new RegExp(t,e)};return n}var be=(()=>{try{return!!new RegExp("(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l=>new RegExp(`^( {0,3}${l})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}#`),htmlBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}<(?:[a-z].*>|!--)`,"i")},Re=/^(?:[ \t]*(?:\n|$))+/,Te=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Oe=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,I=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,we=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,F=/(?:[*+-]|\d{1,9}[.)])/,ie=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,oe=d(ie).replace(/bull/g,F).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),ye=d(ie).replace(/bull/g,F).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),j=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Pe=/^[^\n]+/,Q=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Se=d(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Q).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),$e=d(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,F).getRegex(),v="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",U=/|$))/,_e=d("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",U).replace("tag",v).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),ae=d(j).replace("hr",I).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex(),Le=d(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",ae).getRegex(),K={blockquote:Le,code:Te,def:Se,fences:Oe,heading:we,hr:I,html:_e,lheading:oe,list:$e,newline:Re,paragraph:ae,table:E,text:Pe},re=d("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",I).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex(),Me={...K,lheading:ye,table:re,paragraph:d(j).replace("hr",I).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",re).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex()},ze={...K,html:d(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",U).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:E,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:d(j).replace("hr",I).replace("heading",` *#{1,6} *[^ -]`).replace("lheading",oe).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Ae=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ee=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,le=/^( {2,}|\\)\n(?!\s*$)/,Ie=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",be?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ce=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,De=d(ce,"u").replace(/punct/g,D).getRegex(),He=d(ce,"u").replace(/punct/g,pe).getRegex(),he="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Ze=d(he,"gu").replace(/notPunctSpace/g,ue).replace(/punctSpace/g,W).replace(/punct/g,D).getRegex(),Ge=d(he,"gu").replace(/notPunctSpace/g,qe).replace(/punctSpace/g,Be).replace(/punct/g,pe).getRegex(),Ne=d("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ue).replace(/punctSpace/g,W).replace(/punct/g,D).getRegex(),Fe=d(/\\(punct)/,"gu").replace(/punct/g,D).getRegex(),je=d(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Qe=d(U).replace("(?:-->|$)","-->").getRegex(),Ue=d("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",Qe).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),q=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,Ke=d(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",q).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),de=d(/^!?\[(label)\]\[(ref)\]/).replace("label",q).replace("ref",Q).getRegex(),ke=d(/^!?\[(ref)\](?:\[\])?/).replace("ref",Q).getRegex(),We=d("reflink|nolink(?!\\()","g").replace("reflink",de).replace("nolink",ke).getRegex(),se=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,X={_backpedal:E,anyPunctuation:Fe,autolink:je,blockSkip:ve,br:le,code:Ee,del:E,emStrongLDelim:De,emStrongRDelimAst:Ze,emStrongRDelimUnd:Ne,escape:Ae,link:Ke,nolink:ke,punctuation:Ce,reflink:de,reflinkSearch:We,tag:Ue,text:Ie,url:E},Xe={...X,link:d(/^!?\[(label)\]\((.*?)\)/).replace("label",q).getRegex(),reflink:d(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",q).getRegex()},N={...X,emStrongRDelimAst:Ge,emStrongLDelim:He,url:d(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",se).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:d(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},ge=l=>Ve[l];function w(l,e){if(e){if(m.escapeTest.test(l))return l.replace(m.escapeReplace,ge)}else if(m.escapeTestNoEncode.test(l))return l.replace(m.escapeReplaceNoEncode,ge);return l}function J(l){try{l=encodeURI(l).replace(m.percentDecode,"%")}catch{return null}return l}function V(l,e){let t=l.replace(m.findPipe,(i,s,a)=>{let o=!1,p=s;for(;--p>=0&&a[p]==="\\";)o=!o;return o?"|":" |"}),n=t.split(m.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length0?-2:-1}function me(l,e,t,n,r){let i=e.href,s=e.title||null,a=l[1].replace(r.other.outputLinkReplace,"$1");n.state.inLink=!0;let o={type:l[0].charAt(0)==="!"?"image":"link",raw:t,href:i,title:s,text:a,tokens:n.inlineTokens(a)};return n.state.inLink=!1,o}function Ye(l,e,t){let n=l.match(t.other.indentCodeCompensation);if(n===null)return e;let r=n[1];return e.split(` -`).map(i=>{let s=i.match(t.other.beginningSpace);if(s===null)return i;let[a]=s;return a.length>=r.length?i.slice(r.length):i}).join(` -`)}var y=class{options;rules;lexer;constructor(e){this.options=e||T}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:z(n,` -`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],r=Ye(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let r=z(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:z(t[0],` -`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=z(t[0],` -`).split(` -`),r="",i="",s=[];for(;n.length>0;){let a=!1,o=[],p;for(p=0;p1,i={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let s=this.rules.other.listItemRegex(n),a=!1;for(;e;){let p=!1,u="",c="";if(!(t=s.exec(e))||this.rules.block.hr.test(e))break;u=t[0],e=e.substring(u.length);let g=t[2].split(` -`,1)[0].replace(this.rules.other.listReplaceTabs,H=>" ".repeat(3*H.length)),h=e.split(` -`,1)[0],R=!g.trim(),f=0;if(this.options.pedantic?(f=2,c=g.trimStart()):R?f=t[1].length+1:(f=t[2].search(this.rules.other.nonSpaceChar),f=f>4?1:f,c=g.slice(f),f+=t[1].length),R&&this.rules.other.blankLine.test(h)&&(u+=h+` -`,e=e.substring(h.length+1),p=!0),!p){let H=this.rules.other.nextBulletRegex(f),ee=this.rules.other.hrRegex(f),te=this.rules.other.fencesBeginRegex(f),ne=this.rules.other.headingBeginRegex(f),xe=this.rules.other.htmlBeginRegex(f);for(;e;){let Z=e.split(` -`,1)[0],A;if(h=Z,this.options.pedantic?(h=h.replace(this.rules.other.listReplaceNesting," "),A=h):A=h.replace(this.rules.other.tabCharGlobal," "),te.test(h)||ne.test(h)||xe.test(h)||H.test(h)||ee.test(h))break;if(A.search(this.rules.other.nonSpaceChar)>=f||!h.trim())c+=` -`+A.slice(f);else{if(R||g.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||te.test(g)||ne.test(g)||ee.test(g))break;c+=` -`+h}!R&&!h.trim()&&(R=!0),u+=Z+` -`,e=e.substring(Z.length+1),g=A.slice(f)}}i.loose||(a?i.loose=!0:this.rules.other.doubleBlankLine.test(u)&&(a=!0));let O=null,Y;this.options.gfm&&(O=this.rules.other.listIsTask.exec(c),O&&(Y=O[0]!=="[ ] ",c=c.replace(this.rules.other.listReplaceTask,""))),i.items.push({type:"list_item",raw:u,task:!!O,checked:Y,loose:!1,text:c,tokens:[]}),i.raw+=u}let o=i.items.at(-1);if(o)o.raw=o.raw.trimEnd(),o.text=o.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let p=0;pg.type==="space"),c=u.length>0&&u.some(g=>this.rules.other.anyLine.test(g.raw));i.loose=c}if(i.loose)for(let p=0;p({text:o,tokens:this.lexer.inline(o),header:!1,align:s.align[p]})));return s}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===` -`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let s=z(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=fe(t[2],"()");if(s===-2)return;if(s>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let r=t[2],i="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(r);s&&(r=s[1],i=s[3])}else i=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),me(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[r.toLowerCase()];if(!i){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return me(n,i,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(!r||r[3]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(r[1]||r[2]||"")||!n||this.rules.inline.punctuation.exec(n)){let s=[...r[0]].length-1,a,o,p=s,u=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+s);(r=c.exec(t))!=null;){if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a)continue;if(o=[...a].length,r[3]||r[4]){p+=o;continue}else if((r[5]||r[6])&&s%3&&!((s+o)%3)){u+=o;continue}if(p-=o,p>0)continue;o=Math.min(o,o+p+u);let g=[...r[0]][0].length,h=e.slice(0,s+r.index+g+o);if(Math.min(s,o)%2){let f=h.slice(1,-1);return{type:"em",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}let R=h.slice(2,-2);return{type:"strong",raw:h,text:R,tokens:this.lexer.inlineTokens(R)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,r;return t[2]==="@"?(n=t[1],r="mailto:"+n):(n=t[1],r=n),{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,r;if(t[2]==="@")n=t[0],r="mailto:"+n;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);n=t[0],t[1]==="www."?r="http://"+t[0]:r=t[0]}return{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}};var x=class l{tokens;options;state;tokenizer;inlineQueue;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||T,this.options.tokenizer=this.options.tokenizer||new y,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:m,block:C.normal,inline:M.normal};this.options.pedantic?(t.block=C.pedantic,t.inline=M.pedantic):this.options.gfm&&(t.block=C.gfm,this.options.breaks?t.inline=M.breaks:t.inline=M.gfm),this.tokenizer.rules=t}static get rules(){return{block:C,inline:M}}static lex(e,t){return new l(t).lex(e)}static lexInline(e,t){return new l(t).inlineTokens(e)}lex(e){e=e.replace(m.carriageReturn,` -`),this.blockTokens(e,this.tokens);for(let t=0;t(r=s.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let s=t.at(-1);r.raw.length===1&&s!==void 0?s.raw+=` -`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(` -`)?"":` -`)+r.raw,s.text+=` -`+r.text,this.inlineQueue.at(-1).src=s.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(` -`)?"":` -`)+r.raw,s.text+=` -`+r.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startBlock){let s=1/0,a=e.slice(1),o;this.options.extensions.startBlock.forEach(p=>{o=p.call({lexer:this},a),typeof o=="number"&&o>=0&&(s=Math.min(s,o))}),s<1/0&&s>=0&&(i=e.substring(0,s+1))}if(this.state.top&&(r=this.tokenizer.paragraph(i))){let s=t.at(-1);n&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(` -`)?"":` -`)+r.raw,s.text+=` -`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):t.push(r),n=i.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(` -`)?"":` -`)+r.raw,s.text+=` -`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):t.push(r);continue}if(e){let s="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(s);break}else throw new Error(s)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n=e,r=null;if(this.tokens.links){let o=Object.keys(this.tokens.links);if(o.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!=null;)o.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(n=n.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!=null;)n=n.slice(0,r.index)+"++"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!=null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+"["+"a".repeat(r[0].length-i-2)+"]"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let s=!1,a="";for(;e;){s||(a=""),s=!1;let o;if(this.options.extensions?.inline?.some(u=>(o=u.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))continue;if(o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.tag(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);let u=t.at(-1);o.type==="text"&&u?.type==="text"?(u.raw+=o.raw,u.text+=o.text):t.push(o);continue}if(o=this.tokenizer.emStrong(e,n,a)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.br(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.del(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.autolink(e)){e=e.substring(o.raw.length),t.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),t.push(o);continue}let p=e;if(this.options.extensions?.startInline){let u=1/0,c=e.slice(1),g;this.options.extensions.startInline.forEach(h=>{g=h.call({lexer:this},c),typeof g=="number"&&g>=0&&(u=Math.min(u,g))}),u<1/0&&u>=0&&(p=e.substring(0,u+1))}if(o=this.tokenizer.inlineText(p)){e=e.substring(o.raw.length),o.raw.slice(-1)!=="_"&&(a=o.raw.slice(-1)),s=!0;let u=t.at(-1);u?.type==="text"?(u.raw+=o.raw,u.text+=o.text):t.push(o);continue}if(e){let u="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(u);break}else throw new Error(u)}}return t}};var P=class{options;parser;constructor(e){this.options=e||T}space(e){return""}code({text:e,lang:t,escaped:n}){let r=(t||"").match(m.notSpaceStart)?.[0],i=e.replace(m.endingNewline,"")+` -`;return r?'

    '+(n?i:w(i,!0))+`
    -`:"
    "+(n?i:w(i,!0))+`
    -`}blockquote({tokens:e}){return`
    -${this.parser.parse(e)}
    -`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} -`}hr(e){return`
    -`}list(e){let t=e.ordered,n=e.start,r="";for(let a=0;a -`+r+" -`}listitem(e){let t="";if(e.task){let n=this.checkbox({checked:!!e.checked});e.loose?e.tokens[0]?.type==="paragraph"?(e.tokens[0].text=n+" "+e.tokens[0].text,e.tokens[0].tokens&&e.tokens[0].tokens.length>0&&e.tokens[0].tokens[0].type==="text"&&(e.tokens[0].tokens[0].text=n+" "+w(e.tokens[0].tokens[0].text),e.tokens[0].tokens[0].escaped=!0)):e.tokens.unshift({type:"text",raw:n+" ",text:n+" ",escaped:!0}):t+=n+" "}return t+=this.parser.parse(e.tokens,!!e.loose),`
  • ${t}
  • -`}checkbox({checked:e}){return"'}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    -`}table(e){let t="",n="";for(let i=0;i${r}`),` - -`+t+` -`+r+`
    -`}tablerow({text:e}){return` -${e} -`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+` -`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${w(e,!0)}`}br(e){return"
    "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=J(e);if(i===null)return r;e=i;let s='
    ",s}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=J(e);if(i===null)return w(n);e=i;let s=`${n}{let a=i[s].flat(1/0);n=n.concat(this.walkTokens(a,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let s=t.renderers[i.name];s?t.renderers[i.name]=function(...a){let o=i.renderer.apply(this,a);return o===!1&&(o=s.apply(this,a)),o}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=t[i.level];s?s.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),r.extensions=t),n.renderer){let i=this.defaults.renderer||new P(this.defaults);for(let s in n.renderer){if(!(s in i))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let a=s,o=n.renderer[a],p=i[a];i[a]=(...u)=>{let c=o.apply(i,u);return c===!1&&(c=p.apply(i,u)),c||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new y(this.defaults);for(let s in n.tokenizer){if(!(s in i))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let a=s,o=n.tokenizer[a],p=i[a];i[a]=(...u)=>{let c=o.apply(i,u);return c===!1&&(c=p.apply(i,u)),c}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new S;for(let s in n.hooks){if(!(s in i))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let a=s,o=n.hooks[a],p=i[a];S.passThroughHooks.has(s)?i[a]=u=>{if(this.defaults.async&&S.passThroughHooksRespectAsync.has(s))return(async()=>{let g=await o.call(i,u);return p.call(i,g)})();let c=o.call(i,u);return p.call(i,c)}:i[a]=(...u)=>{if(this.defaults.async)return(async()=>{let g=await o.apply(i,u);return g===!1&&(g=await p.apply(i,u)),g})();let c=o.apply(i,u);return c===!1&&(c=p.apply(i,u)),c}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,s=n.walkTokens;r.walkTokens=function(a){let o=[];return o.push(s.call(this,a)),i&&(o=o.concat(i.call(this,a))),o}}this.defaults={...this.defaults,...r}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(n,r)=>{let i={...r},s={...this.defaults,...i},a=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&i.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=e),s.async)return(async()=>{let o=s.hooks?await s.hooks.preprocess(n):n,u=await(s.hooks?await s.hooks.provideLexer():e?x.lex:x.lexInline)(o,s),c=s.hooks?await s.hooks.processAllTokens(u):u;s.walkTokens&&await Promise.all(this.walkTokens(c,s.walkTokens));let h=await(s.hooks?await s.hooks.provideParser():e?b.parse:b.parseInline)(c,s);return s.hooks?await s.hooks.postprocess(h):h})().catch(a);try{s.hooks&&(n=s.hooks.preprocess(n));let p=(s.hooks?s.hooks.provideLexer():e?x.lex:x.lexInline)(n,s);s.hooks&&(p=s.hooks.processAllTokens(p)),s.walkTokens&&this.walkTokens(p,s.walkTokens);let c=(s.hooks?s.hooks.provideParser():e?b.parse:b.parseInline)(p,s);return s.hooks&&(c=s.hooks.postprocess(c)),c}catch(o){return a(o)}}}onError(e,t){return n=>{if(n.message+=` -Please report this to https://github.com/markedjs/marked.`,e){let r="

    An error occurred:

    "+w(n.message+"",!0)+"
    ";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}};var _=new B;function k(l,e){return _.parse(l,e)}k.options=k.setOptions=function(l){return _.setOptions(l),k.defaults=_.defaults,G(k.defaults),k};k.getDefaults=L;k.defaults=T;k.use=function(...l){return _.use(...l),k.defaults=_.defaults,G(k.defaults),k};k.walkTokens=function(l,e){return _.walkTokens(l,e)};k.parseInline=_.parseInline;k.Parser=b;k.parser=b.parse;k.Renderer=P;k.TextRenderer=$;k.Lexer=x;k.lexer=x.lex;k.Tokenizer=y;k.Hooks=S;k.parse=k;var Zt=k.options,Gt=k.setOptions,Nt=k.use,Ft=k.walkTokens,jt=k.parseInline,Qt=k,Ut=b.parse,Kt=x.lex;export{S as Hooks,x as Lexer,B as Marked,b as Parser,P as Renderer,$ as TextRenderer,y as Tokenizer,T as defaults,L as getDefaults,Kt as lexer,k as marked,Zt as options,Qt as parse,jt as parseInline,Ut as parser,Gt as setOptions,Nt as use,Ft as walkTokens}; -//# sourceMappingURL=marked.esm.js.map diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/lib/marked.esm.js.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/lib/marked.esm.js.map deleted file mode 100644 index 97f11cfae..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/lib/marked.esm.js.map +++ /dev/null @@ -1,7 +0,0 @@ -{ - "version": 3, - "sources": ["../src/defaults.ts", "../src/rules.ts", "../src/helpers.ts", "../src/Tokenizer.ts", "../src/Lexer.ts", "../src/Renderer.ts", "../src/TextRenderer.ts", "../src/Parser.ts", "../src/Hooks.ts", "../src/Instance.ts", "../src/marked.ts"], - "sourcesContent": ["import type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Gets the original marked default options.\n */\nexport function _getDefaults(): MarkedOptions {\n return {\n async: false,\n breaks: false,\n extensions: null,\n gfm: true,\n hooks: null,\n pedantic: false,\n renderer: null,\n silent: false,\n tokenizer: null,\n walkTokens: null,\n };\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport let _defaults: MarkedOptions = _getDefaults();\n\nexport function changeDefaults(newDefaults: MarkedOptions) {\n _defaults = newDefaults;\n}\n", "const noopTest = { exec: () => null } as unknown as RegExp;\n\nfunction edit(regex: string | RegExp, opt = '') {\n let source = typeof regex === 'string' ? regex : regex.source;\n const obj = {\n replace: (name: string | RegExp, val: string | RegExp) => {\n let valSource = typeof val === 'string' ? val : val.source;\n valSource = valSource.replace(other.caret, '$1');\n source = source.replace(name, valSource);\n return obj;\n },\n getRegex: () => {\n return new RegExp(source, opt);\n },\n };\n return obj;\n}\n\nconst supportsLookbehind = (() => {\ntry {\n // eslint-disable-next-line prefer-regex-literals\n return !!new RegExp('(?<=1)(?/,\n blockquoteSetextReplace: /\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g,\n blockquoteSetextReplace2: /^ {0,3}>[ \\t]?/gm,\n listReplaceTabs: /^\\t+/,\n listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,\n listIsTask: /^\\[[ xX]\\] /,\n listReplaceTask: /^\\[[ xX]\\] +/,\n anyLine: /\\n.*\\n/,\n hrefBrackets: /^<(.*)>$/,\n tableDelimiter: /[:|]/,\n tableAlignChars: /^\\||\\| *$/g,\n tableRowBlankLine: /\\n[ \\t]*$/,\n tableAlignRight: /^ *-+: *$/,\n tableAlignCenter: /^ *:-+: *$/,\n tableAlignLeft: /^ *:-+ *$/,\n startATag: /^
    /i,\n startPreScriptTag: /^<(pre|code|kbd|script)(\\s|>)/i,\n endPreScriptTag: /^<\\/(pre|code|kbd|script)(\\s|>)/i,\n startAngleBracket: /^$/,\n pedanticHrefTitle: /^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/,\n unicodeAlphaNumeric: /[\\p{L}\\p{N}]/u,\n escapeTest: /[&<>\"']/,\n escapeReplace: /[&<>\"']/g,\n escapeTestNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/,\n escapeReplaceNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,\n unescapeTest: /&(#(?:\\d+)|(?:#x[0-9A-Fa-f]+)|(?:\\w+));?/ig,\n caret: /(^|[^\\[])\\^/g,\n percentDecode: /%25/g,\n findPipe: /\\|/g,\n splitPipe: / \\|/,\n slashPipe: /\\\\\\|/g,\n carriageReturn: /\\r\\n|\\r/g,\n spaceLine: /^ +$/gm,\n notSpaceStart: /^\\S*/,\n endingNewline: /\\n$/,\n listItemRegex: (bull: string) => new RegExp(`^( {0,3}${bull})((?:[\\t ][^\\\\n]*)?(?:\\\\n|$))`),\n nextBulletRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \\t][^\\\\n]*)?(?:\\\\n|$))`),\n hrRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`),\n fencesBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\\`\\`\\`|~~~)`),\n headingBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`),\n htmlBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, 'i'),\n};\n\n/**\n * Block-Level Grammar\n */\n\nconst newline = /^(?:[ \\t]*(?:\\n|$))+/;\nconst blockCode = /^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\n|$))*)?)+/;\nconst fences = /^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/;\nconst hr = /^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/;\nconst heading = /^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/;\nconst bullet = /(?:[*+-]|\\d{1,9}[.)])/;\nconst lheadingCore = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/;\nconst lheading = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // indented code blocks can interrupt\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .replace(/\\|table/g, '') // table not in commonmark\n .getRegex();\nconst lheadingGfm = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // indented code blocks can interrupt\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .replace(/table/g, / {0,3}\\|?(?:[:\\- ]*\\|)+[\\:\\- ]*\\n/) // table can interrupt\n .getRegex();\nconst _paragraph = /^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\\n)[^\\n]+)*)/;\nconst blockText = /^[^\\n]+/;\nconst _blockLabel = /(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\])+/;\nconst def = edit(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/)\n .replace('label', _blockLabel)\n .replace('title', /(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/)\n .getRegex();\n\nconst list = edit(/^( {0,3}bull)([ \\t][^\\n]+?)?(?:\\n|$)/)\n .replace(/bull/g, bullet)\n .getRegex();\n\nconst _tag = 'address|article|aside|base|basefont|blockquote|body|caption'\n + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'\n + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'\n + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'\n + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title'\n + '|tr|track|ul';\nconst _comment = /|$))/;\nconst html = edit(\n '^ {0,3}(?:' // optional indentation\n+ '<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:[^\\\\n]*\\\\n+|$)' // (1)\n+ '|comment[^\\\\n]*(\\\\n+|$)' // (2)\n+ '|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>\\\\n*|$)' // (3)\n+ '|\\\\n*|$)' // (4)\n+ '|\\\\n*|$)' // (5)\n+ '|)[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (6)\n+ '|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) open tag\n+ '|(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) closing tag\n+ ')', 'i')\n .replace('comment', _comment)\n .replace('tag', _tag)\n .replace('attribute', / +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/)\n .getRegex();\n\nconst paragraph = edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex();\n\nconst blockquote = edit(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/)\n .replace('paragraph', paragraph)\n .getRegex();\n\n/**\n * Normal Block Grammar\n */\n\nconst blockNormal = {\n blockquote,\n code: blockCode,\n def,\n fences,\n heading,\n hr,\n html,\n lheading,\n list,\n newline,\n paragraph,\n table: noopTest,\n text: blockText,\n};\n\ntype BlockKeys = keyof typeof blockNormal;\n\n/**\n * GFM Block Grammar\n */\n\nconst gfmTable = edit(\n '^ *([^\\\\n ].*)\\\\n' // Header\n+ ' {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)' // Align\n+ '(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)') // Cells\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('blockquote', ' {0,3}>')\n .replace('code', '(?: {4}| {0,3}\\t)[^\\\\n]')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // tables can be interrupted by type (6) html blocks\n .getRegex();\n\nconst blockGfm: Record = {\n ...blockNormal,\n lheading: lheadingGfm,\n table: gfmTable,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('table', gfmTable) // interrupt paragraphs with table\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex(),\n};\n\n/**\n * Pedantic grammar (original John Gruber's loose markdown specification)\n */\n\nconst blockPedantic: Record = {\n ...blockNormal,\n html: edit(\n '^ *(?:comment *(?:\\\\n|\\\\s*$)'\n + '|<(tag)[\\\\s\\\\S]+? *(?:\\\\n{2,}|\\\\s*$)' // closed tag\n + '|\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))')\n .replace('comment', _comment)\n .replace(/tag/g, '(?!(?:'\n + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'\n + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'\n + '\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b')\n .getRegex(),\n def: /^ *\\[([^\\]]+)\\]: *]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,\n heading: /^(#{1,6})(.*)(?:\\n+|$)/,\n fences: noopTest, // fences not supported\n lheading: /^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' *#{1,6} *[^\\n]')\n .replace('lheading', lheading)\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('|fences', '')\n .replace('|list', '')\n .replace('|html', '')\n .replace('|tag', '')\n .getRegex(),\n};\n\n/**\n * Inline-Level Grammar\n */\n\nconst escape = /^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/;\nconst inlineCode = /^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/;\nconst br = /^( {2,}|\\\\)\\n(?!\\s*$)/;\nconst inlineText = /^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\\nconst blockSkip = edit(/link|precode-code|html/, 'g')\n .replace('link', /\\[(?:[^\\[\\]`]|(?`+)[^`]+\\k(?!`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)/)\n .replace('precode-', supportsLookbehind ? '(?`+)[^`]+\\k(?!`)/)\n .replace('html', /<(?! )[^<>]*?>/)\n .getRegex();\n\nconst emStrongLDelimCore = /^(?:\\*+(?:((?!\\*)punct)|[^\\s*]))|^_+(?:((?!_)punct)|([^\\s_]))/;\n\nconst emStrongLDelim = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongLDelimGfm = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\nconst emStrongRDelimAstCore =\n '^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)' // Skip orphan inside strong\n+ '|[^*]+(?=[^*])' // Consume to delim\n+ '|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)' // (1) #*** can only be a Right Delimiter\n+ '|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)' // (2) a***#, a*** can only be a Right Delimiter\n+ '|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)' // (3) #***a, ***a can only be Left Delimiter\n+ '|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)' // (4) ***# can only be Left Delimiter\n+ '|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)' // (5) #***# can be either Left or Right Delimiter\n+ '|notPunctSpace(\\\\*+)(?=notPunctSpace)'; // (6) a***a can be either Left or Right Delimiter\n\nconst emStrongRDelimAst = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm)\n .replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm)\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\n// (6) Not allowed for _\nconst emStrongRDelimUnd = edit(\n '^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)' // Skip orphan inside strong\n+ '|[^_]+(?=[^_])' // Consume to delim\n+ '|(?!_)punct(_+)(?=[\\\\s]|$)' // (1) #___ can only be a Right Delimiter\n+ '|notPunctSpace(_+)(?!_)(?=punctSpace|$)' // (2) a___#, a___ can only be a Right Delimiter\n+ '|(?!_)punctSpace(_+)(?=notPunctSpace)' // (3) #___a, ___a can only be Left Delimiter\n+ '|[\\\\s](_+)(?!_)(?=punct)' // (4) ___# can only be Left Delimiter\n+ '|(?!_)punct(_+)(?!_)(?=punct)', 'gu') // (5) #___# can be either Left or Right Delimiter\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst anyPunctuation = edit(/\\\\(punct)/, 'gu')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst autolink = edit(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/)\n .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/)\n .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/)\n .getRegex();\n\nconst _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();\nconst tag = edit(\n '^comment'\n + '|^' // self-closing tag\n + '|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>' // open tag\n + '|^<\\\\?[\\\\s\\\\S]*?\\\\?>' // processing instruction, e.g. \n + '|^' // declaration, e.g. \n + '|^') // CDATA section\n .replace('comment', _inlineComment)\n .replace('attribute', /\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/)\n .getRegex();\n\nconst _inlineLabel = /(?:\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+[^`]*?`+(?!`)|[^\\[\\]\\\\`])*?/;\n\nconst link = edit(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]*(?:\\n[ \\t]*)?)(title))?\\s*\\)/)\n .replace('label', _inlineLabel)\n .replace('href', /<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]*/)\n .replace('title', /\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/)\n .getRegex();\n\nconst reflink = edit(/^!?\\[(label)\\]\\[(ref)\\]/)\n .replace('label', _inlineLabel)\n .replace('ref', _blockLabel)\n .getRegex();\n\nconst nolink = edit(/^!?\\[(ref)\\](?:\\[\\])?/)\n .replace('ref', _blockLabel)\n .getRegex();\n\nconst reflinkSearch = edit('reflink|nolink(?!\\\\()', 'g')\n .replace('reflink', reflink)\n .replace('nolink', nolink)\n .getRegex();\n\nconst _caseInsensitiveProtocol = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/;\n\n/**\n * Normal Inline Grammar\n */\n\nconst inlineNormal = {\n _backpedal: noopTest, // only used for GFM url\n anyPunctuation,\n autolink,\n blockSkip,\n br,\n code: inlineCode,\n del: noopTest,\n emStrongLDelim,\n emStrongRDelimAst,\n emStrongRDelimUnd,\n escape,\n link,\n nolink,\n punctuation,\n reflink,\n reflinkSearch,\n tag,\n text: inlineText,\n url: noopTest,\n};\n\ntype InlineKeys = keyof typeof inlineNormal;\n\n/**\n * Pedantic Inline Grammar\n */\n\nconst inlinePedantic: Record = {\n ...inlineNormal,\n link: edit(/^!?\\[(label)\\]\\((.*?)\\)/)\n .replace('label', _inlineLabel)\n .getRegex(),\n reflink: edit(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/)\n .replace('label', _inlineLabel)\n .getRegex(),\n};\n\n/**\n * GFM Inline Grammar\n */\n\nconst inlineGfm: Record = {\n ...inlineNormal,\n emStrongRDelimAst: emStrongRDelimAstGfm,\n emStrongLDelim: emStrongLDelimGfm,\n url: edit(/^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/)\n .replace('protocol', _caseInsensitiveProtocol)\n .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/)\n .getRegex(),\n _backpedal: /(?:[^?!.,:;*_'\"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'\"~)]+(?!$))+/,\n del: /^(~~?)(?=[^\\s~])((?:\\\\[\\s\\S]|[^\\\\])*?(?:\\\\[\\s\\S]|[^\\s~\\\\]))\\1(?=[^~]|$)/,\n text: edit(/^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\ = {\n ...inlineGfm,\n br: edit(br).replace('{2,}', '*').getRegex(),\n text: edit(inlineGfm.text)\n .replace('\\\\b_', '\\\\b_| {2,}\\\\n')\n .replace(/\\{2,\\}/g, '*')\n .getRegex(),\n};\n\n/**\n * exports\n */\n\nexport const block = {\n normal: blockNormal,\n gfm: blockGfm,\n pedantic: blockPedantic,\n};\n\nexport const inline = {\n normal: inlineNormal,\n gfm: inlineGfm,\n breaks: inlineBreaks,\n pedantic: inlinePedantic,\n};\n\nexport interface Rules {\n other: typeof other\n block: Record\n inline: Record\n}\n", "import { other } from './rules.ts';\n\n/**\n * Helpers\n */\nconst escapeReplacements: { [index: string]: string } = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n};\nconst getEscapeReplacement = (ch: string) => escapeReplacements[ch];\n\nexport function escape(html: string, encode?: boolean) {\n if (encode) {\n if (other.escapeTest.test(html)) {\n return html.replace(other.escapeReplace, getEscapeReplacement);\n }\n } else {\n if (other.escapeTestNoEncode.test(html)) {\n return html.replace(other.escapeReplaceNoEncode, getEscapeReplacement);\n }\n }\n\n return html;\n}\n\nexport function unescape(html: string) {\n // explicitly match decimal, hex, and named HTML entities\n return html.replace(other.unescapeTest, (_, n) => {\n n = n.toLowerCase();\n if (n === 'colon') return ':';\n if (n.charAt(0) === '#') {\n return n.charAt(1) === 'x'\n ? String.fromCharCode(parseInt(n.substring(2), 16))\n : String.fromCharCode(+n.substring(1));\n }\n return '';\n });\n}\n\nexport function cleanUrl(href: string) {\n try {\n href = encodeURI(href).replace(other.percentDecode, '%');\n } catch {\n return null;\n }\n return href;\n}\n\nexport function splitCells(tableRow: string, count?: number) {\n // ensure that every cell-delimiting pipe has a space\n // before it to distinguish it from an escaped pipe\n const row = tableRow.replace(other.findPipe, (match, offset, str) => {\n let escaped = false;\n let curr = offset;\n while (--curr >= 0 && str[curr] === '\\\\') escaped = !escaped;\n if (escaped) {\n // odd number of slashes means | is escaped\n // so we leave it alone\n return '|';\n } else {\n // add space before unescaped |\n return ' |';\n }\n }),\n cells = row.split(other.splitPipe);\n let i = 0;\n\n // First/last cell in a row cannot be empty if it has no leading/trailing pipe\n if (!cells[0].trim()) {\n cells.shift();\n }\n if (cells.length > 0 && !cells.at(-1)?.trim()) {\n cells.pop();\n }\n\n if (count) {\n if (cells.length > count) {\n cells.splice(count);\n } else {\n while (cells.length < count) cells.push('');\n }\n }\n\n for (; i < cells.length; i++) {\n // leading or trailing whitespace is ignored per the gfm spec\n cells[i] = cells[i].trim().replace(other.slashPipe, '|');\n }\n return cells;\n}\n\n/**\n * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').\n * /c*$/ is vulnerable to REDOS.\n *\n * @param str\n * @param c\n * @param invert Remove suffix of non-c chars instead. Default falsey.\n */\nexport function rtrim(str: string, c: string, invert?: boolean) {\n const l = str.length;\n if (l === 0) {\n return '';\n }\n\n // Length of suffix matching the invert condition.\n let suffLen = 0;\n\n // Step left until we fail to match the invert condition.\n while (suffLen < l) {\n const currChar = str.charAt(l - suffLen - 1);\n if (currChar === c && !invert) {\n suffLen++;\n } else if (currChar !== c && invert) {\n suffLen++;\n } else {\n break;\n }\n }\n\n return str.slice(0, l - suffLen);\n}\n\nexport function findClosingBracket(str: string, b: string) {\n if (str.indexOf(b[1]) === -1) {\n return -1;\n }\n\n let level = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '\\\\') {\n i++;\n } else if (str[i] === b[0]) {\n level++;\n } else if (str[i] === b[1]) {\n level--;\n if (level < 0) {\n return i;\n }\n }\n }\n if (level > 0) {\n return -2;\n }\n\n return -1;\n}\n", "import { _defaults } from './defaults.ts';\nimport {\n rtrim,\n splitCells,\n findClosingBracket,\n} from './helpers.ts';\nimport type { Rules } from './rules.ts';\nimport type { _Lexer } from './Lexer.ts';\nimport type { Links, Tokens, Token } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\nfunction outputLink(cap: string[], link: Pick, raw: string, lexer: _Lexer, rules: Rules): Tokens.Link | Tokens.Image {\n const href = link.href;\n const title = link.title || null;\n const text = cap[1].replace(rules.other.outputLinkReplace, '$1');\n\n lexer.state.inLink = true;\n const token: Tokens.Link | Tokens.Image = {\n type: cap[0].charAt(0) === '!' ? 'image' : 'link',\n raw,\n href,\n title,\n text,\n tokens: lexer.inlineTokens(text),\n };\n lexer.state.inLink = false;\n return token;\n}\n\nfunction indentCodeCompensation(raw: string, text: string, rules: Rules) {\n const matchIndentToCode = raw.match(rules.other.indentCodeCompensation);\n\n if (matchIndentToCode === null) {\n return text;\n }\n\n const indentToCode = matchIndentToCode[1];\n\n return text\n .split('\\n')\n .map(node => {\n const matchIndentInNode = node.match(rules.other.beginningSpace);\n if (matchIndentInNode === null) {\n return node;\n }\n\n const [indentInNode] = matchIndentInNode;\n\n if (indentInNode.length >= indentToCode.length) {\n return node.slice(indentToCode.length);\n }\n\n return node;\n })\n .join('\\n');\n}\n\n/**\n * Tokenizer\n */\nexport class _Tokenizer {\n options: MarkedOptions;\n rules!: Rules; // set by the lexer\n lexer!: _Lexer; // set by the lexer\n\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n }\n\n space(src: string): Tokens.Space | undefined {\n const cap = this.rules.block.newline.exec(src);\n if (cap && cap[0].length > 0) {\n return {\n type: 'space',\n raw: cap[0],\n };\n }\n }\n\n code(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.code.exec(src);\n if (cap) {\n const text = cap[0].replace(this.rules.other.codeRemoveIndent, '');\n return {\n type: 'code',\n raw: cap[0],\n codeBlockStyle: 'indented',\n text: !this.options.pedantic\n ? rtrim(text, '\\n')\n : text,\n };\n }\n }\n\n fences(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.fences.exec(src);\n if (cap) {\n const raw = cap[0];\n const text = indentCodeCompensation(raw, cap[3] || '', this.rules);\n\n return {\n type: 'code',\n raw,\n lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],\n text,\n };\n }\n }\n\n heading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.heading.exec(src);\n if (cap) {\n let text = cap[2].trim();\n\n // remove trailing #s\n if (this.rules.other.endingHash.test(text)) {\n const trimmed = rtrim(text, '#');\n if (this.options.pedantic) {\n text = trimmed.trim();\n } else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) {\n // CommonMark requires space before trailing #s\n text = trimmed.trim();\n }\n }\n\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[1].length,\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n hr(src: string): Tokens.Hr | undefined {\n const cap = this.rules.block.hr.exec(src);\n if (cap) {\n return {\n type: 'hr',\n raw: rtrim(cap[0], '\\n'),\n };\n }\n }\n\n blockquote(src: string): Tokens.Blockquote | undefined {\n const cap = this.rules.block.blockquote.exec(src);\n if (cap) {\n let lines = rtrim(cap[0], '\\n').split('\\n');\n let raw = '';\n let text = '';\n const tokens: Token[] = [];\n\n while (lines.length > 0) {\n let inBlockquote = false;\n const currentLines = [];\n\n let i;\n for (i = 0; i < lines.length; i++) {\n // get lines up to a continuation\n if (this.rules.other.blockquoteStart.test(lines[i])) {\n currentLines.push(lines[i]);\n inBlockquote = true;\n } else if (!inBlockquote) {\n currentLines.push(lines[i]);\n } else {\n break;\n }\n }\n lines = lines.slice(i);\n\n const currentRaw = currentLines.join('\\n');\n const currentText = currentRaw\n // precede setext continuation with 4 spaces so it isn't a setext\n .replace(this.rules.other.blockquoteSetextReplace, '\\n $1')\n .replace(this.rules.other.blockquoteSetextReplace2, '');\n raw = raw ? `${raw}\\n${currentRaw}` : currentRaw;\n text = text ? `${text}\\n${currentText}` : currentText;\n\n // parse blockquote lines as top level tokens\n // merge paragraphs if this is a continuation\n const top = this.lexer.state.top;\n this.lexer.state.top = true;\n this.lexer.blockTokens(currentText, tokens, true);\n this.lexer.state.top = top;\n\n // if there is no continuation then we are done\n if (lines.length === 0) {\n break;\n }\n\n const lastToken = tokens.at(-1);\n\n if (lastToken?.type === 'code') {\n // blockquote continuation cannot be preceded by a code block\n break;\n } else if (lastToken?.type === 'blockquote') {\n // include continuation in nested blockquote\n const oldToken = lastToken as Tokens.Blockquote;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.blockquote(newText)!;\n tokens[tokens.length - 1] = newToken;\n\n raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.text.length) + newToken.text;\n break;\n } else if (lastToken?.type === 'list') {\n // include continuation in nested list\n const oldToken = lastToken as Tokens.List;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.list(newText)!;\n tokens[tokens.length - 1] = newToken;\n\n raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;\n lines = newText.substring(tokens.at(-1)!.raw.length).split('\\n');\n continue;\n }\n }\n\n return {\n type: 'blockquote',\n raw,\n tokens,\n text,\n };\n }\n }\n\n list(src: string): Tokens.List | undefined {\n let cap = this.rules.block.list.exec(src);\n if (cap) {\n let bull = cap[1].trim();\n const isordered = bull.length > 1;\n\n const list: Tokens.List = {\n type: 'list',\n raw: '',\n ordered: isordered,\n start: isordered ? +bull.slice(0, -1) : '',\n loose: false,\n items: [],\n };\n\n bull = isordered ? `\\\\d{1,9}\\\\${bull.slice(-1)}` : `\\\\${bull}`;\n\n if (this.options.pedantic) {\n bull = isordered ? bull : '[*+-]';\n }\n\n // Get next list item\n const itemRegex = this.rules.other.listItemRegex(bull);\n let endsWithBlankLine = false;\n // Check if current bullet point can start a new List Item\n while (src) {\n let endEarly = false;\n let raw = '';\n let itemContents = '';\n if (!(cap = itemRegex.exec(src))) {\n break;\n }\n\n if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)\n break;\n }\n\n raw = cap[0];\n src = src.substring(raw.length);\n\n let line = cap[2].split('\\n', 1)[0].replace(this.rules.other.listReplaceTabs, (t: string) => ' '.repeat(3 * t.length));\n let nextLine = src.split('\\n', 1)[0];\n let blankLine = !line.trim();\n\n let indent = 0;\n if (this.options.pedantic) {\n indent = 2;\n itemContents = line.trimStart();\n } else if (blankLine) {\n indent = cap[1].length + 1;\n } else {\n indent = cap[2].search(this.rules.other.nonSpaceChar); // Find first non-space char\n indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent\n itemContents = line.slice(indent);\n indent += cap[1].length;\n }\n\n if (blankLine && this.rules.other.blankLine.test(nextLine)) { // Items begin with at most one blank line\n raw += nextLine + '\\n';\n src = src.substring(nextLine.length + 1);\n endEarly = true;\n }\n\n if (!endEarly) {\n const nextBulletRegex = this.rules.other.nextBulletRegex(indent);\n const hrRegex = this.rules.other.hrRegex(indent);\n const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent);\n const headingBeginRegex = this.rules.other.headingBeginRegex(indent);\n const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent);\n\n // Check if following lines should be included in List Item\n while (src) {\n const rawLine = src.split('\\n', 1)[0];\n let nextLineWithoutTabs;\n nextLine = rawLine;\n\n // Re-align to follow commonmark nesting rules\n if (this.options.pedantic) {\n nextLine = nextLine.replace(this.rules.other.listReplaceNesting, ' ');\n nextLineWithoutTabs = nextLine;\n } else {\n nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, ' ');\n }\n\n // End list item if found code fences\n if (fencesBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new heading\n if (headingBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of html block\n if (htmlBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new bullet\n if (nextBulletRegex.test(nextLine)) {\n break;\n }\n\n // Horizontal rule found\n if (hrRegex.test(nextLine)) {\n break;\n }\n\n if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) { // Dedent if possible\n itemContents += '\\n' + nextLineWithoutTabs.slice(indent);\n } else {\n // not enough indentation\n if (blankLine) {\n break;\n }\n\n // paragraph continuation unless last line was a different block level element\n if (line.replace(this.rules.other.tabCharGlobal, ' ').search(this.rules.other.nonSpaceChar) >= 4) { // indented code block\n break;\n }\n if (fencesBeginRegex.test(line)) {\n break;\n }\n if (headingBeginRegex.test(line)) {\n break;\n }\n if (hrRegex.test(line)) {\n break;\n }\n\n itemContents += '\\n' + nextLine;\n }\n\n if (!blankLine && !nextLine.trim()) { // Check if current line is blank\n blankLine = true;\n }\n\n raw += rawLine + '\\n';\n src = src.substring(rawLine.length + 1);\n line = nextLineWithoutTabs.slice(indent);\n }\n }\n\n if (!list.loose) {\n // If the previous item ended with a blank line, the list is loose\n if (endsWithBlankLine) {\n list.loose = true;\n } else if (this.rules.other.doubleBlankLine.test(raw)) {\n endsWithBlankLine = true;\n }\n }\n\n let istask: RegExpExecArray | null = null;\n let ischecked: boolean | undefined;\n // Check for task list items\n if (this.options.gfm) {\n istask = this.rules.other.listIsTask.exec(itemContents);\n if (istask) {\n ischecked = istask[0] !== '[ ] ';\n itemContents = itemContents.replace(this.rules.other.listReplaceTask, '');\n }\n }\n\n list.items.push({\n type: 'list_item',\n raw,\n task: !!istask,\n checked: ischecked,\n loose: false,\n text: itemContents,\n tokens: [],\n });\n\n list.raw += raw;\n }\n\n // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic\n const lastItem = list.items.at(-1);\n if (lastItem) {\n lastItem.raw = lastItem.raw.trimEnd();\n lastItem.text = lastItem.text.trimEnd();\n } else {\n // not a list since there were no items\n return;\n }\n list.raw = list.raw.trimEnd();\n\n // Item child tokens handled here at end because we needed to have the final item to trim it first\n for (let i = 0; i < list.items.length; i++) {\n this.lexer.state.top = false;\n list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);\n\n if (!list.loose) {\n // Check if list should be loose\n const spacers = list.items[i].tokens.filter(t => t.type === 'space');\n const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => this.rules.other.anyLine.test(t.raw));\n\n list.loose = hasMultipleLineBreaks;\n }\n }\n\n // Set all items to loose if list is loose\n if (list.loose) {\n for (let i = 0; i < list.items.length; i++) {\n list.items[i].loose = true;\n }\n }\n\n return list;\n }\n }\n\n html(src: string): Tokens.HTML | undefined {\n const cap = this.rules.block.html.exec(src);\n if (cap) {\n const token: Tokens.HTML = {\n type: 'html',\n block: true,\n raw: cap[0],\n pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',\n text: cap[0],\n };\n return token;\n }\n }\n\n def(src: string): Tokens.Def | undefined {\n const cap = this.rules.block.def.exec(src);\n if (cap) {\n const tag = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, ' ');\n const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';\n const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];\n return {\n type: 'def',\n tag,\n raw: cap[0],\n href,\n title,\n };\n }\n }\n\n table(src: string): Tokens.Table | undefined {\n const cap = this.rules.block.table.exec(src);\n if (!cap) {\n return;\n }\n\n if (!this.rules.other.tableDelimiter.test(cap[2])) {\n // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading\n return;\n }\n\n const headers = splitCells(cap[1]);\n const aligns = cap[2].replace(this.rules.other.tableAlignChars, '').split('|');\n const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, '').split('\\n') : [];\n\n const item: Tokens.Table = {\n type: 'table',\n raw: cap[0],\n header: [],\n align: [],\n rows: [],\n };\n\n if (headers.length !== aligns.length) {\n // header and align columns must be equal, rows can be different.\n return;\n }\n\n for (const align of aligns) {\n if (this.rules.other.tableAlignRight.test(align)) {\n item.align.push('right');\n } else if (this.rules.other.tableAlignCenter.test(align)) {\n item.align.push('center');\n } else if (this.rules.other.tableAlignLeft.test(align)) {\n item.align.push('left');\n } else {\n item.align.push(null);\n }\n }\n\n for (let i = 0; i < headers.length; i++) {\n item.header.push({\n text: headers[i],\n tokens: this.lexer.inline(headers[i]),\n header: true,\n align: item.align[i],\n });\n }\n\n for (const row of rows) {\n item.rows.push(splitCells(row, item.header.length).map((cell, i) => {\n return {\n text: cell,\n tokens: this.lexer.inline(cell),\n header: false,\n align: item.align[i],\n };\n }));\n }\n\n return item;\n }\n\n lheading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.lheading.exec(src);\n if (cap) {\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[2].charAt(0) === '=' ? 1 : 2,\n text: cap[1],\n tokens: this.lexer.inline(cap[1]),\n };\n }\n }\n\n paragraph(src: string): Tokens.Paragraph | undefined {\n const cap = this.rules.block.paragraph.exec(src);\n if (cap) {\n const text = cap[1].charAt(cap[1].length - 1) === '\\n'\n ? cap[1].slice(0, -1)\n : cap[1];\n return {\n type: 'paragraph',\n raw: cap[0],\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n text(src: string): Tokens.Text | undefined {\n const cap = this.rules.block.text.exec(src);\n if (cap) {\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n tokens: this.lexer.inline(cap[0]),\n };\n }\n }\n\n escape(src: string): Tokens.Escape | undefined {\n const cap = this.rules.inline.escape.exec(src);\n if (cap) {\n return {\n type: 'escape',\n raw: cap[0],\n text: cap[1],\n };\n }\n }\n\n tag(src: string): Tokens.Tag | undefined {\n const cap = this.rules.inline.tag.exec(src);\n if (cap) {\n if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) {\n this.lexer.state.inLink = true;\n } else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) {\n this.lexer.state.inLink = false;\n }\n if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = true;\n } else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = false;\n }\n\n return {\n type: 'html',\n raw: cap[0],\n inLink: this.lexer.state.inLink,\n inRawBlock: this.lexer.state.inRawBlock,\n block: false,\n text: cap[0],\n };\n }\n }\n\n link(src: string): Tokens.Link | Tokens.Image | undefined {\n const cap = this.rules.inline.link.exec(src);\n if (cap) {\n const trimmedUrl = cap[2].trim();\n if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) {\n // commonmark requires matching angle brackets\n if (!(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n return;\n }\n\n // ending angle bracket cannot be escaped\n const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\\\');\n if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {\n return;\n }\n } else {\n // find closing parenthesis\n const lastParenIndex = findClosingBracket(cap[2], '()');\n if (lastParenIndex === -2) {\n // more open parens than closed\n return;\n }\n\n if (lastParenIndex > -1) {\n const start = cap[0].indexOf('!') === 0 ? 5 : 4;\n const linkLen = start + cap[1].length + lastParenIndex;\n cap[2] = cap[2].substring(0, lastParenIndex);\n cap[0] = cap[0].substring(0, linkLen).trim();\n cap[3] = '';\n }\n }\n let href = cap[2];\n let title = '';\n if (this.options.pedantic) {\n // split pedantic href and title\n const link = this.rules.other.pedanticHrefTitle.exec(href);\n\n if (link) {\n href = link[1];\n title = link[3];\n }\n } else {\n title = cap[3] ? cap[3].slice(1, -1) : '';\n }\n\n href = href.trim();\n if (this.rules.other.startAngleBracket.test(href)) {\n if (this.options.pedantic && !(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n // pedantic allows starting angle bracket without ending angle bracket\n href = href.slice(1);\n } else {\n href = href.slice(1, -1);\n }\n }\n return outputLink(cap, {\n href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,\n title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title,\n }, cap[0], this.lexer, this.rules);\n }\n }\n\n reflink(src: string, links: Links): Tokens.Link | Tokens.Image | Tokens.Text | undefined {\n let cap;\n if ((cap = this.rules.inline.reflink.exec(src))\n || (cap = this.rules.inline.nolink.exec(src))) {\n const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, ' ');\n const link = links[linkString.toLowerCase()];\n if (!link) {\n const text = cap[0].charAt(0);\n return {\n type: 'text',\n raw: text,\n text,\n };\n }\n return outputLink(cap, link, cap[0], this.lexer, this.rules);\n }\n }\n\n emStrong(src: string, maskedSrc: string, prevChar = ''): Tokens.Em | Tokens.Strong | undefined {\n let match = this.rules.inline.emStrongLDelim.exec(src);\n if (!match) return;\n\n // _ can't be between two alphanumerics. \\p{L}\\p{N} includes non-english alphabet/numbers as well\n if (match[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) return;\n\n const nextChar = match[1] || match[2] || '';\n\n if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {\n // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below)\n const lLength = [...match[0]].length - 1;\n let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;\n\n const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;\n endReg.lastIndex = 0;\n\n // Clip maskedSrc to same section of string as src (move to lexer?)\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n\n while ((match = endReg.exec(maskedSrc)) != null) {\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n\n if (!rDelim) continue; // skip single * in __abc*abc__\n\n rLength = [...rDelim].length;\n\n if (match[3] || match[4]) { // found another Left Delim\n delimTotal += rLength;\n continue;\n } else if (match[5] || match[6]) { // either Left or Right Delim\n if (lLength % 3 && !((lLength + rLength) % 3)) {\n midDelimTotal += rLength;\n continue; // CommonMark Emphasis Rules 9-10\n }\n }\n\n delimTotal -= rLength;\n\n if (delimTotal > 0) continue; // Haven't found enough closing delimiters\n\n // Remove extra characters. *a*** -> *a*\n rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);\n // char length can be >1 for unicode characters;\n const lastCharLength = [...match[0]][0].length;\n const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);\n\n // Create `em` if smallest delimiter has odd char count. *a***\n if (Math.min(lLength, rLength) % 2) {\n const text = raw.slice(1, -1);\n return {\n type: 'em',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n\n // Create 'strong' if smallest delimiter has even char count. **a***\n const text = raw.slice(2, -2);\n return {\n type: 'strong',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n }\n }\n\n codespan(src: string): Tokens.Codespan | undefined {\n const cap = this.rules.inline.code.exec(src);\n if (cap) {\n let text = cap[2].replace(this.rules.other.newLineCharGlobal, ' ');\n const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text);\n const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text);\n if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {\n text = text.substring(1, text.length - 1);\n }\n return {\n type: 'codespan',\n raw: cap[0],\n text,\n };\n }\n }\n\n br(src: string): Tokens.Br | undefined {\n const cap = this.rules.inline.br.exec(src);\n if (cap) {\n return {\n type: 'br',\n raw: cap[0],\n };\n }\n }\n\n del(src: string): Tokens.Del | undefined {\n const cap = this.rules.inline.del.exec(src);\n if (cap) {\n return {\n type: 'del',\n raw: cap[0],\n text: cap[2],\n tokens: this.lexer.inlineTokens(cap[2]),\n };\n }\n }\n\n autolink(src: string): Tokens.Link | undefined {\n const cap = this.rules.inline.autolink.exec(src);\n if (cap) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[1];\n href = 'mailto:' + text;\n } else {\n text = cap[1];\n href = text;\n }\n\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text,\n },\n ],\n };\n }\n }\n\n url(src: string): Tokens.Link | undefined {\n let cap;\n if (cap = this.rules.inline.url.exec(src)) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[0];\n href = 'mailto:' + text;\n } else {\n // do extended autolink path validation\n let prevCapZero;\n do {\n prevCapZero = cap[0];\n cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';\n } while (prevCapZero !== cap[0]);\n text = cap[0];\n if (cap[1] === 'www.') {\n href = 'http://' + cap[0];\n } else {\n href = cap[0];\n }\n }\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text,\n },\n ],\n };\n }\n }\n\n inlineText(src: string): Tokens.Text | undefined {\n const cap = this.rules.inline.text.exec(src);\n if (cap) {\n const escaped = this.lexer.state.inRawBlock;\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n escaped,\n };\n }\n }\n}\n", "import { _Tokenizer } from './Tokenizer.ts';\nimport { _defaults } from './defaults.ts';\nimport { other, block, inline } from './rules.ts';\nimport type { Token, TokensList, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Block Lexer\n */\nexport class _Lexer {\n tokens: TokensList;\n options: MarkedOptions;\n state: {\n inLink: boolean;\n inRawBlock: boolean;\n top: boolean;\n };\n\n private tokenizer: _Tokenizer;\n private inlineQueue: { src: string, tokens: Token[] }[];\n\n constructor(options?: MarkedOptions) {\n // TokenList cannot be created in one go\n this.tokens = [] as unknown as TokensList;\n this.tokens.links = Object.create(null);\n this.options = options || _defaults;\n this.options.tokenizer = this.options.tokenizer || new _Tokenizer();\n this.tokenizer = this.options.tokenizer;\n this.tokenizer.options = this.options;\n this.tokenizer.lexer = this;\n this.inlineQueue = [];\n this.state = {\n inLink: false,\n inRawBlock: false,\n top: true,\n };\n\n const rules = {\n other,\n block: block.normal,\n inline: inline.normal,\n };\n\n if (this.options.pedantic) {\n rules.block = block.pedantic;\n rules.inline = inline.pedantic;\n } else if (this.options.gfm) {\n rules.block = block.gfm;\n if (this.options.breaks) {\n rules.inline = inline.breaks;\n } else {\n rules.inline = inline.gfm;\n }\n }\n this.tokenizer.rules = rules;\n }\n\n /**\n * Expose Rules\n */\n static get rules() {\n return {\n block,\n inline,\n };\n }\n\n /**\n * Static Lex Method\n */\n static lex(src: string, options?: MarkedOptions) {\n const lexer = new _Lexer(options);\n return lexer.lex(src);\n }\n\n /**\n * Static Lex Inline Method\n */\n static lexInline(src: string, options?: MarkedOptions) {\n const lexer = new _Lexer(options);\n return lexer.inlineTokens(src);\n }\n\n /**\n * Preprocessing\n */\n lex(src: string) {\n src = src.replace(other.carriageReturn, '\\n');\n\n this.blockTokens(src, this.tokens);\n\n for (let i = 0; i < this.inlineQueue.length; i++) {\n const next = this.inlineQueue[i];\n this.inlineTokens(next.src, next.tokens);\n }\n this.inlineQueue = [];\n\n return this.tokens;\n }\n\n /**\n * Lexing\n */\n blockTokens(src: string, tokens?: Token[], lastParagraphClipped?: boolean): Token[];\n blockTokens(src: string, tokens?: TokensList, lastParagraphClipped?: boolean): TokensList;\n blockTokens(src: string, tokens: Token[] = [], lastParagraphClipped = false) {\n if (this.options.pedantic) {\n src = src.replace(other.tabCharGlobal, ' ').replace(other.spaceLine, '');\n }\n\n while (src) {\n let token: Tokens.Generic | undefined;\n\n if (this.options.extensions?.block?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n\n // newline\n if (token = this.tokenizer.space(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.raw.length === 1 && lastToken !== undefined) {\n // if there's a single \\n as a spacer, it's terminating the last line,\n // so move it there so that we don't get unnecessary paragraph tags\n lastToken.raw += '\\n';\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // code\n if (token = this.tokenizer.code(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n // An indented code block cannot interrupt a paragraph.\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // fences\n if (token = this.tokenizer.fences(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // heading\n if (token = this.tokenizer.heading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // hr\n if (token = this.tokenizer.hr(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // blockquote\n if (token = this.tokenizer.blockquote(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // list\n if (token = this.tokenizer.list(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // html\n if (token = this.tokenizer.html(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // def\n if (token = this.tokenizer.def(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.raw;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else if (!this.tokens.links[token.tag]) {\n this.tokens.links[token.tag] = {\n href: token.href,\n title: token.title,\n };\n tokens.push(token);\n }\n continue;\n }\n\n // table (gfm)\n if (token = this.tokenizer.table(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // lheading\n if (token = this.tokenizer.lheading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // top-level paragraph\n // prevent paragraph consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (this.options.extensions?.startBlock) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startBlock.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {\n const lastToken = tokens.at(-1);\n if (lastParagraphClipped && lastToken?.type === 'paragraph') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n lastParagraphClipped = cutSrc.length !== src.length;\n src = src.substring(token.raw.length);\n continue;\n }\n\n // text\n if (token = this.tokenizer.text(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n\n this.state.top = true;\n return tokens;\n }\n\n inline(src: string, tokens: Token[] = []) {\n this.inlineQueue.push({ src, tokens });\n return tokens;\n }\n\n /**\n * Lexing/Compiling\n */\n inlineTokens(src: string, tokens: Token[] = []): Token[] {\n // String with links masked to avoid interference with em and strong\n let maskedSrc = src;\n let match: RegExpExecArray | null = null;\n\n // Mask out reflinks\n if (this.tokens.links) {\n const links = Object.keys(this.tokens.links);\n if (links.length > 0) {\n while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {\n if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {\n maskedSrc = maskedSrc.slice(0, match.index)\n + '[' + 'a'.repeat(match[0].length - 2) + ']'\n + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);\n }\n }\n }\n }\n\n // Mask out escaped characters\n while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);\n }\n\n // Mask out other blocks\n let offset;\n while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {\n offset = match[2] ? match[2].length : 0;\n maskedSrc = maskedSrc.slice(0, match.index + offset) + '[' + 'a'.repeat(match[0].length - offset - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);\n }\n\n // Mask out blocks from extensions\n maskedSrc = this.options.hooks?.emStrongMask?.call({ lexer: this }, maskedSrc) ?? maskedSrc;\n\n let keepPrevChar = false;\n let prevChar = '';\n while (src) {\n if (!keepPrevChar) {\n prevChar = '';\n }\n keepPrevChar = false;\n\n let token: Tokens.Generic | undefined;\n\n // extensions\n if (this.options.extensions?.inline?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n\n // escape\n if (token = this.tokenizer.escape(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // tag\n if (token = this.tokenizer.tag(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // link\n if (token = this.tokenizer.link(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // reflink, nolink\n if (token = this.tokenizer.reflink(src, this.tokens.links)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.type === 'text' && lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // em & strong\n if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // code\n if (token = this.tokenizer.codespan(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // br\n if (token = this.tokenizer.br(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // del (gfm)\n if (token = this.tokenizer.del(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // autolink\n if (token = this.tokenizer.autolink(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // url (gfm)\n if (!this.state.inLink && (token = this.tokenizer.url(src))) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // text\n // prevent inlineText consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (this.options.extensions?.startInline) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startInline.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (token = this.tokenizer.inlineText(cutSrc)) {\n src = src.substring(token.raw.length);\n if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started\n prevChar = token.raw.slice(-1);\n }\n keepPrevChar = true;\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n\n return tokens;\n }\n}\n", "import { _defaults } from './defaults.ts';\nimport {\n cleanUrl,\n escape,\n} from './helpers.ts';\nimport { other } from './rules.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Tokens } from './Tokens.ts';\nimport type { _Parser } from './Parser.ts';\n\n/**\n * Renderer\n */\nexport class _Renderer {\n options: MarkedOptions;\n parser!: _Parser; // set by the parser\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n }\n\n space(token: Tokens.Space): RendererOutput {\n return '' as RendererOutput;\n }\n\n code({ text, lang, escaped }: Tokens.Code): RendererOutput {\n const langString = (lang || '').match(other.notSpaceStart)?.[0];\n\n const code = text.replace(other.endingNewline, '') + '\\n';\n\n if (!langString) {\n return '
    '\n        + (escaped ? code : escape(code, true))\n        + '
    \\n' as RendererOutput;\n }\n\n return '
    '\n      + (escaped ? code : escape(code, true))\n      + '
    \\n' as RendererOutput;\n }\n\n blockquote({ tokens }: Tokens.Blockquote): RendererOutput {\n const body = this.parser.parse(tokens);\n return `
    \\n${body}
    \\n` as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n def(token: Tokens.Def): RendererOutput {\n return '' as RendererOutput;\n }\n\n heading({ tokens, depth }: Tokens.Heading): RendererOutput {\n return `${this.parser.parseInline(tokens)}\\n` as RendererOutput;\n }\n\n hr(token: Tokens.Hr): RendererOutput {\n return '
    \\n' as RendererOutput;\n }\n\n list(token: Tokens.List): RendererOutput {\n const ordered = token.ordered;\n const start = token.start;\n\n let body = '';\n for (let j = 0; j < token.items.length; j++) {\n const item = token.items[j];\n body += this.listitem(item);\n }\n\n const type = ordered ? 'ol' : 'ul';\n const startAttr = (ordered && start !== 1) ? (' start=\"' + start + '\"') : '';\n return '<' + type + startAttr + '>\\n' + body + '\\n' as RendererOutput;\n }\n\n listitem(item: Tokens.ListItem): RendererOutput {\n let itemBody = '';\n if (item.task) {\n const checkbox = this.checkbox({ checked: !!item.checked });\n if (item.loose) {\n if (item.tokens[0]?.type === 'paragraph') {\n item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;\n if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {\n item.tokens[0].tokens[0].text = checkbox + ' ' + escape(item.tokens[0].tokens[0].text);\n item.tokens[0].tokens[0].escaped = true;\n }\n } else {\n item.tokens.unshift({\n type: 'text',\n raw: checkbox + ' ',\n text: checkbox + ' ',\n escaped: true,\n });\n }\n } else {\n itemBody += checkbox + ' ';\n }\n }\n\n itemBody += this.parser.parse(item.tokens, !!item.loose);\n\n return `
  • ${itemBody}
  • \\n` as RendererOutput;\n }\n\n checkbox({ checked }: Tokens.Checkbox): RendererOutput {\n return '' as RendererOutput;\n }\n\n paragraph({ tokens }: Tokens.Paragraph): RendererOutput {\n return `

    ${this.parser.parseInline(tokens)}

    \\n` as RendererOutput;\n }\n\n table(token: Tokens.Table): RendererOutput {\n let header = '';\n\n // header\n let cell = '';\n for (let j = 0; j < token.header.length; j++) {\n cell += this.tablecell(token.header[j]);\n }\n header += this.tablerow({ text: cell as ParserOutput });\n\n let body = '';\n for (let j = 0; j < token.rows.length; j++) {\n const row = token.rows[j];\n\n cell = '';\n for (let k = 0; k < row.length; k++) {\n cell += this.tablecell(row[k]);\n }\n\n body += this.tablerow({ text: cell as ParserOutput });\n }\n if (body) body = `${body}`;\n\n return '\\n'\n + '\\n'\n + header\n + '\\n'\n + body\n + '
    \\n' as RendererOutput;\n }\n\n tablerow({ text }: Tokens.TableRow): RendererOutput {\n return `\\n${text}\\n` as RendererOutput;\n }\n\n tablecell(token: Tokens.TableCell): RendererOutput {\n const content = this.parser.parseInline(token.tokens);\n const type = token.header ? 'th' : 'td';\n const tag = token.align\n ? `<${type} align=\"${token.align}\">`\n : `<${type}>`;\n return tag + content + `\\n` as RendererOutput;\n }\n\n /**\n * span level renderer\n */\n strong({ tokens }: Tokens.Strong): RendererOutput {\n return `${this.parser.parseInline(tokens)}` as RendererOutput;\n }\n\n em({ tokens }: Tokens.Em): RendererOutput {\n return `${this.parser.parseInline(tokens)}` as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return `${escape(text, true)}` as RendererOutput;\n }\n\n br(token: Tokens.Br): RendererOutput {\n return '
    ' as RendererOutput;\n }\n\n del({ tokens }: Tokens.Del): RendererOutput {\n return `${this.parser.parseInline(tokens)}` as RendererOutput;\n }\n\n link({ href, title, tokens }: Tokens.Link): RendererOutput {\n const text = this.parser.parseInline(tokens) as string;\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text as RendererOutput;\n }\n href = cleanHref;\n let out = '
    ';\n return out as RendererOutput;\n }\n\n image({ href, title, text, tokens }: Tokens.Image): RendererOutput {\n if (tokens) {\n text = this.parser.parseInline(tokens, this.parser.textRenderer) as string;\n }\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return escape(text) as RendererOutput;\n }\n href = cleanHref;\n\n let out = `\"${text}\"`;\n {\n // no need for block level renderers\n strong({ text }: Tokens.Strong): RendererOutput {\n return text as RendererOutput;\n }\n\n em({ text }: Tokens.Em): RendererOutput {\n return text as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return text as RendererOutput;\n }\n\n del({ text }: Tokens.Del): RendererOutput {\n return text as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n text({ text }: Tokens.Text | Tokens.Escape | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n link({ text }: Tokens.Link): RendererOutput {\n return '' + text as RendererOutput;\n }\n\n image({ text }: Tokens.Image): RendererOutput {\n return '' + text as RendererOutput;\n }\n\n br(): RendererOutput {\n return '' as RendererOutput;\n }\n}\n", "import { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _defaults } from './defaults.ts';\nimport type { MarkedToken, Token, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Parsing & Compiling\n */\nexport class _Parser {\n options: MarkedOptions;\n renderer: _Renderer;\n textRenderer: _TextRenderer;\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n this.options.renderer = this.options.renderer || new _Renderer();\n this.renderer = this.options.renderer;\n this.renderer.options = this.options;\n this.renderer.parser = this;\n this.textRenderer = new _TextRenderer();\n }\n\n /**\n * Static Parse Method\n */\n static parse(tokens: Token[], options?: MarkedOptions) {\n const parser = new _Parser(options);\n return parser.parse(tokens);\n }\n\n /**\n * Static Parse Inline Method\n */\n static parseInline(tokens: Token[], options?: MarkedOptions) {\n const parser = new _Parser(options);\n return parser.parseInline(tokens);\n }\n\n /**\n * Parse Loop\n */\n parse(tokens: Token[], top = true): ParserOutput {\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const genericToken = anyToken as Tokens.Generic;\n const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);\n if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'def', 'paragraph', 'text'].includes(genericToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'space': {\n out += this.renderer.space(token);\n continue;\n }\n case 'hr': {\n out += this.renderer.hr(token);\n continue;\n }\n case 'heading': {\n out += this.renderer.heading(token);\n continue;\n }\n case 'code': {\n out += this.renderer.code(token);\n continue;\n }\n case 'table': {\n out += this.renderer.table(token);\n continue;\n }\n case 'blockquote': {\n out += this.renderer.blockquote(token);\n continue;\n }\n case 'list': {\n out += this.renderer.list(token);\n continue;\n }\n case 'html': {\n out += this.renderer.html(token);\n continue;\n }\n case 'def': {\n out += this.renderer.def(token);\n continue;\n }\n case 'paragraph': {\n out += this.renderer.paragraph(token);\n continue;\n }\n case 'text': {\n let textToken = token;\n let body = this.renderer.text(textToken) as string;\n while (i + 1 < tokens.length && tokens[i + 1].type === 'text') {\n textToken = tokens[++i] as Tokens.Text;\n body += ('\\n' + this.renderer.text(textToken));\n }\n if (top) {\n out += this.renderer.paragraph({\n type: 'paragraph',\n raw: body,\n text: body,\n tokens: [{ type: 'text', raw: body, text: body, escaped: true }],\n });\n } else {\n out += body;\n }\n continue;\n }\n\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n\n return out as ParserOutput;\n }\n\n /**\n * Parse Inline Tokens\n */\n parseInline(tokens: Token[], renderer: _Renderer | _TextRenderer = this.renderer): ParserOutput {\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);\n if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(anyToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'escape': {\n out += renderer.text(token);\n break;\n }\n case 'html': {\n out += renderer.html(token);\n break;\n }\n case 'link': {\n out += renderer.link(token);\n break;\n }\n case 'image': {\n out += renderer.image(token);\n break;\n }\n case 'strong': {\n out += renderer.strong(token);\n break;\n }\n case 'em': {\n out += renderer.em(token);\n break;\n }\n case 'codespan': {\n out += renderer.codespan(token);\n break;\n }\n case 'br': {\n out += renderer.br(token);\n break;\n }\n case 'del': {\n out += renderer.del(token);\n break;\n }\n case 'text': {\n out += renderer.text(token);\n break;\n }\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n return out as ParserOutput;\n }\n}\n", "import { _defaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\n\nexport class _Hooks {\n options: MarkedOptions;\n block?: boolean;\n\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n }\n\n static passThroughHooks = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n 'emStrongMask',\n ]);\n\n static passThroughHooksRespectAsync = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n ]);\n\n /**\n * Process markdown before marked\n */\n preprocess(markdown: string) {\n return markdown;\n }\n\n /**\n * Process HTML after marked is finished\n */\n postprocess(html: ParserOutput) {\n return html;\n }\n\n /**\n * Process all tokens before walk tokens\n */\n processAllTokens(tokens: Token[] | TokensList) {\n return tokens;\n }\n\n /**\n * Mask contents that should not be interpreted as em/strong delimiters\n */\n emStrongMask(src: string) {\n return src;\n }\n\n /**\n * Provide function to tokenize markdown\n */\n provideLexer() {\n return this.block ? _Lexer.lex : _Lexer.lexInline;\n }\n\n /**\n * Provide function to parse tokens\n */\n provideParser() {\n return this.block ? _Parser.parse : _Parser.parseInline;\n }\n}\n", "import { _getDefaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { escape } from './helpers.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, Tokens, TokensList } from './Tokens.ts';\n\nexport type MaybePromise = void | Promise;\n\ntype UnknownFunction = (...args: unknown[]) => unknown;\ntype GenericRendererFunction = (...args: unknown[]) => string | false;\n\nexport class Marked {\n defaults = _getDefaults();\n options = this.setOptions;\n\n parse = this.parseMarkdown(true);\n parseInline = this.parseMarkdown(false);\n\n Parser = _Parser;\n Renderer = _Renderer;\n TextRenderer = _TextRenderer;\n Lexer = _Lexer;\n Tokenizer = _Tokenizer;\n Hooks = _Hooks;\n\n constructor(...args: MarkedExtension[]) {\n this.use(...args);\n }\n\n /**\n * Run callback for every token\n */\n walkTokens(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n let values: MaybePromise[] = [];\n for (const token of tokens) {\n values = values.concat(callback.call(this, token));\n switch (token.type) {\n case 'table': {\n const tableToken = token as Tokens.Table;\n for (const cell of tableToken.header) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n for (const row of tableToken.rows) {\n for (const cell of row) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n }\n break;\n }\n case 'list': {\n const listToken = token as Tokens.List;\n values = values.concat(this.walkTokens(listToken.items, callback));\n break;\n }\n default: {\n const genericToken = token as Tokens.Generic;\n if (this.defaults.extensions?.childTokens?.[genericToken.type]) {\n this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {\n const tokens = genericToken[childTokens].flat(Infinity) as Token[] | TokensList;\n values = values.concat(this.walkTokens(tokens, callback));\n });\n } else if (genericToken.tokens) {\n values = values.concat(this.walkTokens(genericToken.tokens, callback));\n }\n }\n }\n }\n return values;\n }\n\n use(...args: MarkedExtension[]) {\n const extensions: MarkedOptions['extensions'] = this.defaults.extensions || { renderers: {}, childTokens: {} };\n\n args.forEach((pack) => {\n // copy options to new object\n const opts = { ...pack } as MarkedOptions;\n\n // set async to true if it was set to true before\n opts.async = this.defaults.async || opts.async || false;\n\n // ==-- Parse \"addon\" extensions --== //\n if (pack.extensions) {\n pack.extensions.forEach((ext) => {\n if (!ext.name) {\n throw new Error('extension name required');\n }\n if ('renderer' in ext) { // Renderer extensions\n const prevRenderer = extensions.renderers[ext.name];\n if (prevRenderer) {\n // Replace extension with func to run new extension but fall back if false\n extensions.renderers[ext.name] = function(...args) {\n let ret = ext.renderer.apply(this, args);\n if (ret === false) {\n ret = prevRenderer.apply(this, args);\n }\n return ret;\n };\n } else {\n extensions.renderers[ext.name] = ext.renderer;\n }\n }\n if ('tokenizer' in ext) { // Tokenizer Extensions\n if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {\n throw new Error(\"extension level must be 'block' or 'inline'\");\n }\n const extLevel = extensions[ext.level];\n if (extLevel) {\n extLevel.unshift(ext.tokenizer);\n } else {\n extensions[ext.level] = [ext.tokenizer];\n }\n if (ext.start) { // Function to check for start of token\n if (ext.level === 'block') {\n if (extensions.startBlock) {\n extensions.startBlock.push(ext.start);\n } else {\n extensions.startBlock = [ext.start];\n }\n } else if (ext.level === 'inline') {\n if (extensions.startInline) {\n extensions.startInline.push(ext.start);\n } else {\n extensions.startInline = [ext.start];\n }\n }\n }\n }\n if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens\n extensions.childTokens[ext.name] = ext.childTokens;\n }\n });\n opts.extensions = extensions;\n }\n\n // ==-- Parse \"overwrite\" extensions --== //\n if (pack.renderer) {\n const renderer = this.defaults.renderer || new _Renderer(this.defaults);\n for (const prop in pack.renderer) {\n if (!(prop in renderer)) {\n throw new Error(`renderer '${prop}' does not exist`);\n }\n if (['options', 'parser'].includes(prop)) {\n // ignore options property\n continue;\n }\n const rendererProp = prop as Exclude, 'options' | 'parser'>;\n const rendererFunc = pack.renderer[rendererProp] as GenericRendererFunction;\n const prevRenderer = renderer[rendererProp] as GenericRendererFunction;\n // Replace renderer with func to run extension, but fall back if false\n renderer[rendererProp] = (...args: unknown[]) => {\n let ret = rendererFunc.apply(renderer, args);\n if (ret === false) {\n ret = prevRenderer.apply(renderer, args);\n }\n return (ret || '') as RendererOutput;\n };\n }\n opts.renderer = renderer;\n }\n if (pack.tokenizer) {\n const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);\n for (const prop in pack.tokenizer) {\n if (!(prop in tokenizer)) {\n throw new Error(`tokenizer '${prop}' does not exist`);\n }\n if (['options', 'rules', 'lexer'].includes(prop)) {\n // ignore options, rules, and lexer properties\n continue;\n }\n const tokenizerProp = prop as Exclude, 'options' | 'rules' | 'lexer'>;\n const tokenizerFunc = pack.tokenizer[tokenizerProp] as UnknownFunction;\n const prevTokenizer = tokenizer[tokenizerProp] as UnknownFunction;\n // Replace tokenizer with func to run extension, but fall back if false\n // @ts-expect-error cannot type tokenizer function dynamically\n tokenizer[tokenizerProp] = (...args: unknown[]) => {\n let ret = tokenizerFunc.apply(tokenizer, args);\n if (ret === false) {\n ret = prevTokenizer.apply(tokenizer, args);\n }\n return ret;\n };\n }\n opts.tokenizer = tokenizer;\n }\n\n // ==-- Parse Hooks extensions --== //\n if (pack.hooks) {\n const hooks = this.defaults.hooks || new _Hooks();\n for (const prop in pack.hooks) {\n if (!(prop in hooks)) {\n throw new Error(`hook '${prop}' does not exist`);\n }\n if (['options', 'block'].includes(prop)) {\n // ignore options and block properties\n continue;\n }\n const hooksProp = prop as Exclude, 'options' | 'block'>;\n const hooksFunc = pack.hooks[hooksProp] as UnknownFunction;\n const prevHook = hooks[hooksProp] as UnknownFunction;\n if (_Hooks.passThroughHooks.has(prop)) {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (arg: unknown) => {\n if (this.defaults.async && _Hooks.passThroughHooksRespectAsync.has(prop)) {\n return (async() => {\n const ret = await hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n })();\n }\n\n const ret = hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n };\n } else {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (...args: unknown[]) => {\n if (this.defaults.async) {\n return (async() => {\n let ret = await hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = await prevHook.apply(hooks, args);\n }\n return ret;\n })();\n }\n\n let ret = hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = prevHook.apply(hooks, args);\n }\n return ret;\n };\n }\n }\n opts.hooks = hooks;\n }\n\n // ==-- Parse WalkTokens extensions --== //\n if (pack.walkTokens) {\n const walkTokens = this.defaults.walkTokens;\n const packWalktokens = pack.walkTokens;\n opts.walkTokens = function(token) {\n let values: MaybePromise[] = [];\n values.push(packWalktokens.call(this, token));\n if (walkTokens) {\n values = values.concat(walkTokens.call(this, token));\n }\n return values;\n };\n }\n\n this.defaults = { ...this.defaults, ...opts };\n });\n\n return this;\n }\n\n setOptions(opt: MarkedOptions) {\n this.defaults = { ...this.defaults, ...opt };\n return this;\n }\n\n lexer(src: string, options?: MarkedOptions) {\n return _Lexer.lex(src, options ?? this.defaults);\n }\n\n parser(tokens: Token[], options?: MarkedOptions) {\n return _Parser.parse(tokens, options ?? this.defaults);\n }\n\n private parseMarkdown(blockType: boolean) {\n type overloadedParse = {\n (src: string, options: MarkedOptions & { async: true }): Promise;\n (src: string, options: MarkedOptions & { async: false }): ParserOutput;\n (src: string, options?: MarkedOptions | null): ParserOutput | Promise;\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const parse: overloadedParse = (src: string, options?: MarkedOptions | null): any => {\n const origOpt = { ...options };\n const opt = { ...this.defaults, ...origOpt };\n\n const throwError = this.onError(!!opt.silent, !!opt.async);\n\n // throw error if an extension set async to true but parse was called with async: false\n if (this.defaults.async === true && origOpt.async === false) {\n return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.'));\n }\n\n // throw error in case of non string input\n if (typeof src === 'undefined' || src === null) {\n return throwError(new Error('marked(): input parameter is undefined or null'));\n }\n if (typeof src !== 'string') {\n return throwError(new Error('marked(): input parameter is of type '\n + Object.prototype.toString.call(src) + ', string expected'));\n }\n\n if (opt.hooks) {\n opt.hooks.options = opt;\n opt.hooks.block = blockType;\n }\n\n if (opt.async) {\n return (async() => {\n const processedSrc = opt.hooks ? await opt.hooks.preprocess(src) : src;\n const lexer = opt.hooks ? await opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline);\n const tokens = await lexer(processedSrc, opt);\n const processedTokens = opt.hooks ? await opt.hooks.processAllTokens(tokens) : tokens;\n if (opt.walkTokens) {\n await Promise.all(this.walkTokens(processedTokens, opt.walkTokens));\n }\n const parser = opt.hooks ? await opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline);\n const html = await parser(processedTokens, opt);\n return opt.hooks ? await opt.hooks.postprocess(html) : html;\n })().catch(throwError);\n }\n\n try {\n if (opt.hooks) {\n src = opt.hooks.preprocess(src) as string;\n }\n const lexer = opt.hooks ? opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline);\n let tokens = lexer(src, opt);\n if (opt.hooks) {\n tokens = opt.hooks.processAllTokens(tokens);\n }\n if (opt.walkTokens) {\n this.walkTokens(tokens, opt.walkTokens);\n }\n const parser = opt.hooks ? opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline);\n let html = parser(tokens, opt);\n if (opt.hooks) {\n html = opt.hooks.postprocess(html);\n }\n return html;\n } catch(e) {\n return throwError(e as Error);\n }\n };\n\n return parse;\n }\n\n private onError(silent: boolean, async: boolean) {\n return (e: Error): string | Promise => {\n e.message += '\\nPlease report this to https://github.com/markedjs/marked.';\n\n if (silent) {\n const msg = '

    An error occurred:

    '\n          + escape(e.message + '', true)\n          + '
    ';\n if (async) {\n return Promise.resolve(msg);\n }\n return msg;\n }\n\n if (async) {\n return Promise.reject(e);\n }\n throw e;\n };\n }\n}\n", "import { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { Marked } from './Instance.ts';\nimport {\n _getDefaults,\n changeDefaults,\n _defaults,\n} from './defaults.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\nimport type { MaybePromise } from './Instance.ts';\n\nconst markedInstance = new Marked();\n\n/**\n * Compiles markdown to HTML asynchronously.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options, having async: true\n * @return Promise of string of compiled HTML\n */\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise;\n\n/**\n * Compiles markdown to HTML.\n *\n * @param src String of markdown source to be compiled\n * @param options Optional hash of options\n * @return String of compiled HTML. Will be a Promise of string if async is set to true by any extensions.\n */\nexport function marked(src: string, options: MarkedOptions & { async: false }): string;\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise;\nexport function marked(src: string, options?: MarkedOptions | null): string | Promise;\nexport function marked(src: string, opt?: MarkedOptions | null): string | Promise {\n return markedInstance.parse(src, opt);\n}\n\n/**\n * Sets the default options.\n *\n * @param options Hash of options\n */\nmarked.options =\nmarked.setOptions = function(options: MarkedOptions) {\n markedInstance.setOptions(options);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\n\n/**\n * Gets the original marked default options.\n */\nmarked.getDefaults = _getDefaults;\n\nmarked.defaults = _defaults;\n\n/**\n * Use Extension\n */\n\nmarked.use = function(...args: MarkedExtension[]) {\n markedInstance.use(...args);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\n\n/**\n * Run callback for every token\n */\n\nmarked.walkTokens = function(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n return markedInstance.walkTokens(tokens, callback);\n};\n\n/**\n * Compiles markdown to HTML without enclosing `p` tag.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options\n * @return String of compiled HTML\n */\nmarked.parseInline = markedInstance.parseInline;\n\n/**\n * Expose\n */\nmarked.Parser = _Parser;\nmarked.parser = _Parser.parse;\nmarked.Renderer = _Renderer;\nmarked.TextRenderer = _TextRenderer;\nmarked.Lexer = _Lexer;\nmarked.lexer = _Lexer.lex;\nmarked.Tokenizer = _Tokenizer;\nmarked.Hooks = _Hooks;\nmarked.parse = marked;\n\nexport const options = marked.options;\nexport const setOptions = marked.setOptions;\nexport const use = marked.use;\nexport const walkTokens = marked.walkTokens;\nexport const parseInline = marked.parseInline;\nexport const parse = marked;\nexport const parser = _Parser.parse;\nexport const lexer = _Lexer.lex;\nexport { _defaults as defaults, _getDefaults as getDefaults } from './defaults.ts';\nexport { _Lexer as Lexer } from './Lexer.ts';\nexport { _Parser as Parser } from './Parser.ts';\nexport { _Tokenizer as Tokenizer } from './Tokenizer.ts';\nexport { _Renderer as Renderer } from './Renderer.ts';\nexport { _TextRenderer as TextRenderer } from './TextRenderer.ts';\nexport { _Hooks as Hooks } from './Hooks.ts';\nexport { Marked } from './Instance.ts';\nexport type * from './MarkedOptions.ts';\nexport type * from './Tokens.ts';\n"], - "mappings": ";;;;;;;;;;;;AAKO,SAASA,GAA4G,CAC1H,MAAO,CACL,MAAO,GACP,OAAQ,GACR,WAAY,KACZ,IAAK,GACL,MAAO,KACP,SAAU,GACV,SAAU,KACV,OAAQ,GACR,UAAW,KACX,WAAY,IACd,CACF,CAEO,IAAIC,EAAqCD,EAAa,EAEtD,SAASE,EAA+DC,EAA0D,CACvIF,EAAYE,CACd,CCxBA,IAAMC,EAAW,CAAE,KAAM,IAAM,IAAK,EAEpC,SAASC,EAAKC,EAAwBC,EAAM,GAAI,CAC9C,IAAIC,EAAS,OAAOF,GAAU,SAAWA,EAAQA,EAAM,OACjDG,EAAM,CACV,QAAS,CAACC,EAAuBC,IAAyB,CACxD,IAAIC,EAAY,OAAOD,GAAQ,SAAWA,EAAMA,EAAI,OACpD,OAAAC,EAAYA,EAAU,QAAQC,EAAM,MAAO,IAAI,EAC/CL,EAASA,EAAO,QAAQE,EAAME,CAAS,EAChCH,CACT,EACA,SAAU,IACD,IAAI,OAAOD,EAAQD,CA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O,WACpBiB,GAAMjB,EAAO,IACbkB,GAAalB,EAAO,WACpBmB,GAAcnB,EAAO,YACrBoB,GAAQpB,EACRqB,GAASX,EAAQ,MACjBY,GAAQT,EAAO", - "names": ["_getDefaults", "_defaults", "changeDefaults", "newDefaults", "noopTest", "edit", "regex", "opt", "source", "obj", "name", "val", "valSource", "other", "supportsLookbehind", "bull", "indent", "newline", "blockCode", "fences", "hr", "heading", "bullet", "lheadingCore", "lheading", "lheadingGfm", "_paragraph", "blockText", "_blockLabel", "def", "list", "_tag", "_comment", "html", "paragraph", "blockquote", "blockNormal", "gfmTable", "blockGfm", "blockPedantic", "escape", "inlineCode", "br", "inlineText", "_punctuation", "_punctuationOrSpace", "_notPunctuationOrSpace", "punctuation", "_punctuationGfmStrongEm", "_punctuationOrSpaceGfmStrongEm", "_notPunctuationOrSpaceGfmStrongEm", "blockSkip", "emStrongLDelimCore", "emStrongLDelim", "emStrongLDelimGfm", "emStrongRDelimAstCore", "emStrongRDelimAst", "emStrongRDelimAstGfm", "emStrongRDelimUnd", "anyPunctuation", "autolink", "_inlineComment", "tag", "_inlineLabel", "link", "reflink", "nolink", "reflinkSearch", "_caseInsensitiveProtocol", "inlineNormal", "inlinePedantic", "inlineGfm", "inlineBreaks", "block", "inline", "escapeReplacements", "getEscapeReplacement", "ch", "escape", "html", "encode", "other", "cleanUrl", "href", "other", "splitCells", "tableRow", "count", "row", "match", "offset", "str", "escaped", "curr", "cells", "i", "rtrim", "c", "invert", "l", "suffLen", "currChar", "findClosingBracket", "b", "level", "outputLink", "cap", "link", "raw", "lexer", "rules", "href", "title", "text", "token", "indentCodeCompensation", "matchIndentToCode", "indentToCode", "node", "matchIndentInNode", "indentInNode", "_Tokenizer", "options", "_defaults", "src", "rtrim", "trimmed", "lines", "tokens", "inBlockquote", "currentLines", "i", "currentRaw", "currentText", "top", "lastToken", "oldToken", "newText", "newToken", "bull", "isordered", "list", "itemRegex", "endsWithBlankLine", "endEarly", "itemContents", "line", "t", "nextLine", "blankLine", "indent", "nextBulletRegex", "hrRegex", "fencesBeginRegex", "headingBeginRegex", "htmlBeginRegex", "rawLine", "nextLineWithoutTabs", "istask", "ischecked", "lastItem", "spacers", "hasMultipleLineBreaks", "tag", "headers", "splitCells", "aligns", "rows", "item", "align", "row", "cell", "trimmedUrl", "rtrimSlash", "lastParenIndex", "findClosingBracket", "linkLen", "links", "linkString", "maskedSrc", "prevChar", "match", "lLength", "rDelim", "rLength", "delimTotal", "midDelimTotal", "endReg", "lastCharLength", "hasNonSpaceChars", "hasSpaceCharsOnBothEnds", "prevCapZero", "escaped", "_Lexer", "__Lexer", "options", "_defaults", "_Tokenizer", "rules", "other", "block", "inline", "src", "i", "next", "tokens", "lastParagraphClipped", "token", "extTokenizer", "lastToken", "cutSrc", "startIndex", "tempSrc", "tempStart", "getStartIndex", "errMsg", "maskedSrc", "match", "links", "offset", "keepPrevChar", "prevChar", "_Renderer", "options", "_defaults", "token", "text", "lang", "escaped", "langString", "other", "code", "escape", "tokens", "depth", "ordered", "start", "body", "j", "item", "type", "startAttr", "itemBody", "checkbox", "checked", "header", "cell", "row", "k", "content", "href", "title", "cleanHref", "cleanUrl", "out", "_TextRenderer", "text", "_Parser", "__Parser", "options", "_defaults", "_Renderer", "_TextRenderer", "tokens", "top", "out", "i", "anyToken", "genericToken", "ret", "token", "textToken", "body", "errMsg", "renderer", "_Hooks", "options", "_defaults", "markdown", "html", "tokens", "src", "_Lexer", "_Parser", "Marked", "_getDefaults", "_Parser", "_Renderer", "_TextRenderer", "_Lexer", "_Tokenizer", "_Hooks", "args", "tokens", "callback", "values", "token", "tableToken", "cell", "row", "listToken", "genericToken", "childTokens", "extensions", "pack", "opts", "ext", "prevRenderer", "ret", "extLevel", "renderer", "prop", "rendererProp", "rendererFunc", "tokenizer", "tokenizerProp", "tokenizerFunc", "prevTokenizer", "hooks", "hooksProp", "hooksFunc", "prevHook", "arg", "walkTokens", "packWalktokens", "opt", "src", "options", "blockType", "origOpt", "throwError", "processedSrc", "processedTokens", "html", "e", "silent", "async", "msg", "escape", "markedInstance", "Marked", "marked", "src", "opt", "options", "changeDefaults", "_getDefaults", "_defaults", "args", "tokens", "callback", "_Parser", "_Renderer", "_TextRenderer", "_Lexer", "_Tokenizer", "_Hooks", "setOptions", "use", "walkTokens", "parseInline", "parse", "parser", "lexer"] -} diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/lib/marked.umd.js b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/lib/marked.umd.js deleted file mode 100644 index 34b107400..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/lib/marked.umd.js +++ /dev/null @@ -1,75 +0,0 @@ -/** - * marked v16.4.2 - a markdown parser - * Copyright (c) 2018-2025, MarkedJS. (MIT License) - * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License) - * https://github.com/markedjs/marked - */ - -/** - * DO NOT EDIT THIS FILE - * The code in this file is generated from files in ./src/ - */ -(function(g,f){if(typeof exports=="object"&&typeof module<"u"){module.exports=f()}else if("function"==typeof define && define.amd){define("marked",f)}else {g["marked"]=f()}}(typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : this,function(){var exports={};var __exports=exports;var module={exports}; -"use strict";var G=Object.defineProperty;var Re=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var Oe=Object.prototype.hasOwnProperty;var we=(l,e)=>{for(var t in e)G(l,t,{get:e[t],enumerable:!0})},ye=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Te(e))!Oe.call(l,r)&&r!==t&&G(l,r,{get:()=>e[r],enumerable:!(n=Re(e,r))||n.enumerable});return l};var Pe=l=>ye(G({},"__esModule",{value:!0}),l);var gt={};we(gt,{Hooks:()=>S,Lexer:()=>x,Marked:()=>A,Parser:()=>b,Renderer:()=>P,TextRenderer:()=>$,Tokenizer:()=>y,defaults:()=>T,getDefaults:()=>_,lexer:()=>kt,marked:()=>k,options:()=>at,parse:()=>ht,parseInline:()=>ct,parser:()=>dt,setOptions:()=>lt,use:()=>ut,walkTokens:()=>pt});module.exports=Pe(gt);function _(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var T=_();function N(l){T=l}var I={exec:()=>null};function d(l,e=""){let t=typeof l=="string"?l:l.source,n={replace:(r,i)=>{let s=typeof i=="string"?i:i.source;return s=s.replace(m.caret,"$1"),t=t.replace(r,s),n},getRegex:()=>new RegExp(t,e)};return n}var Se=(()=>{try{return!!new RegExp("(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^
    /i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l=>new RegExp(`^( {0,3}${l})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}#`),htmlBeginRegex:l=>new RegExp(`^ {0,${Math.min(3,l-1)}}<(?:[a-z].*>|!--)`,"i")},$e=/^(?:[ \t]*(?:\n|$))+/,_e=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Le=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,C=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Me=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,j=/(?:[*+-]|\d{1,9}[.)])/,oe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ae=d(oe).replace(/bull/g,j).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),ze=d(oe).replace(/bull/g,j).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Q=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Ae=/^[^\n]+/,U=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Ee=d(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",U).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ie=d(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,j).getRegex(),v="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",K=/|$))/,Ce=d("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",K).replace("tag",v).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),le=d(Q).replace("hr",C).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex(),Be=d(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",le).getRegex(),W={blockquote:Be,code:_e,def:Ee,fences:Le,heading:Me,hr:C,html:Ce,lheading:ae,list:Ie,newline:$e,paragraph:le,table:I,text:Ae},se=d("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",C).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex(),qe={...W,lheading:ze,table:se,paragraph:d(Q).replace("hr",C).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",se).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",v).getRegex()},ve={...W,html:d(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",K).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:I,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:d(Q).replace("hr",C).replace("heading",` *#{1,6} *[^ -]`).replace("lheading",ae).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},De=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,He=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ue=/^( {2,}|\\)\n(?!\s*$)/,Ze=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Se?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),he=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,Qe=d(he,"u").replace(/punct/g,D).getRegex(),Ue=d(he,"u").replace(/punct/g,ce).getRegex(),de="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Ke=d(de,"gu").replace(/notPunctSpace/g,pe).replace(/punctSpace/g,X).replace(/punct/g,D).getRegex(),We=d(de,"gu").replace(/notPunctSpace/g,Fe).replace(/punctSpace/g,Ne).replace(/punct/g,ce).getRegex(),Xe=d("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,pe).replace(/punctSpace/g,X).replace(/punct/g,D).getRegex(),Je=d(/\\(punct)/,"gu").replace(/punct/g,D).getRegex(),Ve=d(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Ye=d(K).replace("(?:-->|$)","-->").getRegex(),et=d("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",Ye).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),q=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,tt=d(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",q).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ke=d(/^!?\[(label)\]\[(ref)\]/).replace("label",q).replace("ref",U).getRegex(),ge=d(/^!?\[(ref)\](?:\[\])?/).replace("ref",U).getRegex(),nt=d("reflink|nolink(?!\\()","g").replace("reflink",ke).replace("nolink",ge).getRegex(),ie=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,J={_backpedal:I,anyPunctuation:Je,autolink:Ve,blockSkip:je,br:ue,code:He,del:I,emStrongLDelim:Qe,emStrongRDelimAst:Ke,emStrongRDelimUnd:Xe,escape:De,link:tt,nolink:ge,punctuation:Ge,reflink:ke,reflinkSearch:nt,tag:et,text:Ze,url:I},rt={...J,link:d(/^!?\[(label)\]\((.*?)\)/).replace("label",q).getRegex(),reflink:d(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",q).getRegex()},F={...J,emStrongRDelimAst:We,emStrongLDelim:Ue,url:d(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",ie).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:d(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},fe=l=>it[l];function w(l,e){if(e){if(m.escapeTest.test(l))return l.replace(m.escapeReplace,fe)}else if(m.escapeTestNoEncode.test(l))return l.replace(m.escapeReplaceNoEncode,fe);return l}function V(l){try{l=encodeURI(l).replace(m.percentDecode,"%")}catch{return null}return l}function Y(l,e){let t=l.replace(m.findPipe,(i,s,a)=>{let o=!1,p=s;for(;--p>=0&&a[p]==="\\";)o=!o;return o?"|":" |"}),n=t.split(m.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length0?-2:-1}function xe(l,e,t,n,r){let i=e.href,s=e.title||null,a=l[1].replace(r.other.outputLinkReplace,"$1");n.state.inLink=!0;let o={type:l[0].charAt(0)==="!"?"image":"link",raw:t,href:i,title:s,text:a,tokens:n.inlineTokens(a)};return n.state.inLink=!1,o}function ot(l,e,t){let n=l.match(t.other.indentCodeCompensation);if(n===null)return e;let r=n[1];return e.split(` -`).map(i=>{let s=i.match(t.other.beginningSpace);if(s===null)return i;let[a]=s;return a.length>=r.length?i.slice(r.length):i}).join(` -`)}var y=class{options;rules;lexer;constructor(e){this.options=e||T}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:z(n,` -`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],r=ot(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let r=z(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:z(t[0],` -`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=z(t[0],` -`).split(` -`),r="",i="",s=[];for(;n.length>0;){let a=!1,o=[],p;for(p=0;p1,i={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let s=this.rules.other.listItemRegex(n),a=!1;for(;e;){let p=!1,u="",c="";if(!(t=s.exec(e))||this.rules.block.hr.test(e))break;u=t[0],e=e.substring(u.length);let g=t[2].split(` -`,1)[0].replace(this.rules.other.listReplaceTabs,H=>" ".repeat(3*H.length)),h=e.split(` -`,1)[0],R=!g.trim(),f=0;if(this.options.pedantic?(f=2,c=g.trimStart()):R?f=t[1].length+1:(f=t[2].search(this.rules.other.nonSpaceChar),f=f>4?1:f,c=g.slice(f),f+=t[1].length),R&&this.rules.other.blankLine.test(h)&&(u+=h+` -`,e=e.substring(h.length+1),p=!0),!p){let H=this.rules.other.nextBulletRegex(f),te=this.rules.other.hrRegex(f),ne=this.rules.other.fencesBeginRegex(f),re=this.rules.other.headingBeginRegex(f),be=this.rules.other.htmlBeginRegex(f);for(;e;){let Z=e.split(` -`,1)[0],E;if(h=Z,this.options.pedantic?(h=h.replace(this.rules.other.listReplaceNesting," "),E=h):E=h.replace(this.rules.other.tabCharGlobal," "),ne.test(h)||re.test(h)||be.test(h)||H.test(h)||te.test(h))break;if(E.search(this.rules.other.nonSpaceChar)>=f||!h.trim())c+=` -`+E.slice(f);else{if(R||g.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ne.test(g)||re.test(g)||te.test(g))break;c+=` -`+h}!R&&!h.trim()&&(R=!0),u+=Z+` -`,e=e.substring(Z.length+1),g=E.slice(f)}}i.loose||(a?i.loose=!0:this.rules.other.doubleBlankLine.test(u)&&(a=!0));let O=null,ee;this.options.gfm&&(O=this.rules.other.listIsTask.exec(c),O&&(ee=O[0]!=="[ ] ",c=c.replace(this.rules.other.listReplaceTask,""))),i.items.push({type:"list_item",raw:u,task:!!O,checked:ee,loose:!1,text:c,tokens:[]}),i.raw+=u}let o=i.items.at(-1);if(o)o.raw=o.raw.trimEnd(),o.text=o.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let p=0;pg.type==="space"),c=u.length>0&&u.some(g=>this.rules.other.anyLine.test(g.raw));i.loose=c}if(i.loose)for(let p=0;p({text:o,tokens:this.lexer.inline(o),header:!1,align:s.align[p]})));return s}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===` -`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let s=z(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=me(t[2],"()");if(s===-2)return;if(s>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+s;t[2]=t[2].substring(0,s),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let r=t[2],i="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(r);s&&(r=s[1],i=s[3])}else i=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),xe(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[r.toLowerCase()];if(!i){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return xe(n,i,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(!r||r[3]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(r[1]||r[2]||"")||!n||this.rules.inline.punctuation.exec(n)){let s=[...r[0]].length-1,a,o,p=s,u=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+s);(r=c.exec(t))!=null;){if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a)continue;if(o=[...a].length,r[3]||r[4]){p+=o;continue}else if((r[5]||r[6])&&s%3&&!((s+o)%3)){u+=o;continue}if(p-=o,p>0)continue;o=Math.min(o,o+p+u);let g=[...r[0]][0].length,h=e.slice(0,s+r.index+g+o);if(Math.min(s,o)%2){let f=h.slice(1,-1);return{type:"em",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}let R=h.slice(2,-2);return{type:"strong",raw:h,text:R,tokens:this.lexer.inlineTokens(R)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,r;return t[2]==="@"?(n=t[1],r="mailto:"+n):(n=t[1],r=n),{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,r;if(t[2]==="@")n=t[0],r="mailto:"+n;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);n=t[0],t[1]==="www."?r="http://"+t[0]:r=t[0]}return{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}};var x=class l{tokens;options;state;tokenizer;inlineQueue;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||T,this.options.tokenizer=this.options.tokenizer||new y,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:m,block:B.normal,inline:M.normal};this.options.pedantic?(t.block=B.pedantic,t.inline=M.pedantic):this.options.gfm&&(t.block=B.gfm,this.options.breaks?t.inline=M.breaks:t.inline=M.gfm),this.tokenizer.rules=t}static get rules(){return{block:B,inline:M}}static lex(e,t){return new l(t).lex(e)}static lexInline(e,t){return new l(t).inlineTokens(e)}lex(e){e=e.replace(m.carriageReturn,` -`),this.blockTokens(e,this.tokens);for(let t=0;t(r=s.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let s=t.at(-1);r.raw.length===1&&s!==void 0?s.raw+=` -`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(` -`)?"":` -`)+r.raw,s.text+=` -`+r.text,this.inlineQueue.at(-1).src=s.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(` -`)?"":` -`)+r.raw,s.text+=` -`+r.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startBlock){let s=1/0,a=e.slice(1),o;this.options.extensions.startBlock.forEach(p=>{o=p.call({lexer:this},a),typeof o=="number"&&o>=0&&(s=Math.min(s,o))}),s<1/0&&s>=0&&(i=e.substring(0,s+1))}if(this.state.top&&(r=this.tokenizer.paragraph(i))){let s=t.at(-1);n&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(` -`)?"":` -`)+r.raw,s.text+=` -`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):t.push(r),n=i.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let s=t.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(` -`)?"":` -`)+r.raw,s.text+=` -`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):t.push(r);continue}if(e){let s="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(s);break}else throw new Error(s)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n=e,r=null;if(this.tokens.links){let o=Object.keys(this.tokens.links);if(o.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!=null;)o.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(n=n.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!=null;)n=n.slice(0,r.index)+"++"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!=null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+"["+"a".repeat(r[0].length-i-2)+"]"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let s=!1,a="";for(;e;){s||(a=""),s=!1;let o;if(this.options.extensions?.inline?.some(u=>(o=u.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))continue;if(o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.tag(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);let u=t.at(-1);o.type==="text"&&u?.type==="text"?(u.raw+=o.raw,u.text+=o.text):t.push(o);continue}if(o=this.tokenizer.emStrong(e,n,a)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.br(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.del(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.autolink(e)){e=e.substring(o.raw.length),t.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),t.push(o);continue}let p=e;if(this.options.extensions?.startInline){let u=1/0,c=e.slice(1),g;this.options.extensions.startInline.forEach(h=>{g=h.call({lexer:this},c),typeof g=="number"&&g>=0&&(u=Math.min(u,g))}),u<1/0&&u>=0&&(p=e.substring(0,u+1))}if(o=this.tokenizer.inlineText(p)){e=e.substring(o.raw.length),o.raw.slice(-1)!=="_"&&(a=o.raw.slice(-1)),s=!0;let u=t.at(-1);u?.type==="text"?(u.raw+=o.raw,u.text+=o.text):t.push(o);continue}if(e){let u="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(u);break}else throw new Error(u)}}return t}};var P=class{options;parser;constructor(e){this.options=e||T}space(e){return""}code({text:e,lang:t,escaped:n}){let r=(t||"").match(m.notSpaceStart)?.[0],i=e.replace(m.endingNewline,"")+` -`;return r?'
    '+(n?i:w(i,!0))+`
    -`:"
    "+(n?i:w(i,!0))+`
    -`}blockquote({tokens:e}){return`
    -${this.parser.parse(e)}
    -`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} -`}hr(e){return`
    -`}list(e){let t=e.ordered,n=e.start,r="";for(let a=0;a -`+r+" -`}listitem(e){let t="";if(e.task){let n=this.checkbox({checked:!!e.checked});e.loose?e.tokens[0]?.type==="paragraph"?(e.tokens[0].text=n+" "+e.tokens[0].text,e.tokens[0].tokens&&e.tokens[0].tokens.length>0&&e.tokens[0].tokens[0].type==="text"&&(e.tokens[0].tokens[0].text=n+" "+w(e.tokens[0].tokens[0].text),e.tokens[0].tokens[0].escaped=!0)):e.tokens.unshift({type:"text",raw:n+" ",text:n+" ",escaped:!0}):t+=n+" "}return t+=this.parser.parse(e.tokens,!!e.loose),`
  • ${t}
  • -`}checkbox({checked:e}){return"'}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    -`}table(e){let t="",n="";for(let i=0;i${r}`),` - -`+t+` -`+r+`
    -`}tablerow({text:e}){return` -${e} -`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+` -`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${w(e,!0)}`}br(e){return"
    "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=V(e);if(i===null)return r;e=i;let s='
    ",s}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=V(e);if(i===null)return w(n);e=i;let s=`${n}{let a=i[s].flat(1/0);n=n.concat(this.walkTokens(a,t))}):i.tokens&&(n=n.concat(this.walkTokens(i.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let s=t.renderers[i.name];s?t.renderers[i.name]=function(...a){let o=i.renderer.apply(this,a);return o===!1&&(o=s.apply(this,a)),o}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=t[i.level];s?s.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),r.extensions=t),n.renderer){let i=this.defaults.renderer||new P(this.defaults);for(let s in n.renderer){if(!(s in i))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let a=s,o=n.renderer[a],p=i[a];i[a]=(...u)=>{let c=o.apply(i,u);return c===!1&&(c=p.apply(i,u)),c||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new y(this.defaults);for(let s in n.tokenizer){if(!(s in i))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let a=s,o=n.tokenizer[a],p=i[a];i[a]=(...u)=>{let c=o.apply(i,u);return c===!1&&(c=p.apply(i,u)),c}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new S;for(let s in n.hooks){if(!(s in i))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let a=s,o=n.hooks[a],p=i[a];S.passThroughHooks.has(s)?i[a]=u=>{if(this.defaults.async&&S.passThroughHooksRespectAsync.has(s))return(async()=>{let g=await o.call(i,u);return p.call(i,g)})();let c=o.call(i,u);return p.call(i,c)}:i[a]=(...u)=>{if(this.defaults.async)return(async()=>{let g=await o.apply(i,u);return g===!1&&(g=await p.apply(i,u)),g})();let c=o.apply(i,u);return c===!1&&(c=p.apply(i,u)),c}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,s=n.walkTokens;r.walkTokens=function(a){let o=[];return o.push(s.call(this,a)),i&&(o=o.concat(i.call(this,a))),o}}this.defaults={...this.defaults,...r}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(n,r)=>{let i={...r},s={...this.defaults,...i},a=this.onError(!!s.silent,!!s.async);if(this.defaults.async===!0&&i.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(s.hooks&&(s.hooks.options=s,s.hooks.block=e),s.async)return(async()=>{let o=s.hooks?await s.hooks.preprocess(n):n,u=await(s.hooks?await s.hooks.provideLexer():e?x.lex:x.lexInline)(o,s),c=s.hooks?await s.hooks.processAllTokens(u):u;s.walkTokens&&await Promise.all(this.walkTokens(c,s.walkTokens));let h=await(s.hooks?await s.hooks.provideParser():e?b.parse:b.parseInline)(c,s);return s.hooks?await s.hooks.postprocess(h):h})().catch(a);try{s.hooks&&(n=s.hooks.preprocess(n));let p=(s.hooks?s.hooks.provideLexer():e?x.lex:x.lexInline)(n,s);s.hooks&&(p=s.hooks.processAllTokens(p)),s.walkTokens&&this.walkTokens(p,s.walkTokens);let c=(s.hooks?s.hooks.provideParser():e?b.parse:b.parseInline)(p,s);return s.hooks&&(c=s.hooks.postprocess(c)),c}catch(o){return a(o)}}}onError(e,t){return n=>{if(n.message+=` -Please report this to https://github.com/markedjs/marked.`,e){let r="

    An error occurred:

    "+w(n.message+"",!0)+"
    ";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}};var L=new A;function k(l,e){return L.parse(l,e)}k.options=k.setOptions=function(l){return L.setOptions(l),k.defaults=L.defaults,N(k.defaults),k};k.getDefaults=_;k.defaults=T;k.use=function(...l){return L.use(...l),k.defaults=L.defaults,N(k.defaults),k};k.walkTokens=function(l,e){return L.walkTokens(l,e)};k.parseInline=L.parseInline;k.Parser=b;k.parser=b.parse;k.Renderer=P;k.TextRenderer=$;k.Lexer=x;k.lexer=x.lex;k.Tokenizer=y;k.Hooks=S;k.parse=k;var at=k.options,lt=k.setOptions,ut=k.use,pt=k.walkTokens,ct=k.parseInline,ht=k,dt=b.parse,kt=x.lex; - -if(__exports != exports)module.exports = exports;return module.exports})); -//# sourceMappingURL=marked.umd.js.map diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/lib/marked.umd.js.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/lib/marked.umd.js.map deleted file mode 100644 index 1caac9988..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/lib/marked.umd.js.map +++ /dev/null @@ -1,7 +0,0 @@ -{ - "version": 3, - "sources": ["../src/marked.ts", "../src/defaults.ts", "../src/rules.ts", "../src/helpers.ts", "../src/Tokenizer.ts", "../src/Lexer.ts", "../src/Renderer.ts", "../src/TextRenderer.ts", "../src/Parser.ts", "../src/Hooks.ts", "../src/Instance.ts"], - "sourcesContent": ["import { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { Marked } from './Instance.ts';\nimport {\n _getDefaults,\n changeDefaults,\n _defaults,\n} from './defaults.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\nimport type { MaybePromise } from './Instance.ts';\n\nconst markedInstance = new Marked();\n\n/**\n * Compiles markdown to HTML asynchronously.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options, having async: true\n * @return Promise of string of compiled HTML\n */\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise;\n\n/**\n * Compiles markdown to HTML.\n *\n * @param src String of markdown source to be compiled\n * @param options Optional hash of options\n * @return String of compiled HTML. Will be a Promise of string if async is set to true by any extensions.\n */\nexport function marked(src: string, options: MarkedOptions & { async: false }): string;\nexport function marked(src: string, options: MarkedOptions & { async: true }): Promise;\nexport function marked(src: string, options?: MarkedOptions | null): string | Promise;\nexport function marked(src: string, opt?: MarkedOptions | null): string | Promise {\n return markedInstance.parse(src, opt);\n}\n\n/**\n * Sets the default options.\n *\n * @param options Hash of options\n */\nmarked.options =\nmarked.setOptions = function(options: MarkedOptions) {\n markedInstance.setOptions(options);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\n\n/**\n * Gets the original marked default options.\n */\nmarked.getDefaults = _getDefaults;\n\nmarked.defaults = _defaults;\n\n/**\n * Use Extension\n */\n\nmarked.use = function(...args: MarkedExtension[]) {\n markedInstance.use(...args);\n marked.defaults = markedInstance.defaults;\n changeDefaults(marked.defaults);\n return marked;\n};\n\n/**\n * Run callback for every token\n */\n\nmarked.walkTokens = function(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n return markedInstance.walkTokens(tokens, callback);\n};\n\n/**\n * Compiles markdown to HTML without enclosing `p` tag.\n *\n * @param src String of markdown source to be compiled\n * @param options Hash of options\n * @return String of compiled HTML\n */\nmarked.parseInline = markedInstance.parseInline;\n\n/**\n * Expose\n */\nmarked.Parser = _Parser;\nmarked.parser = _Parser.parse;\nmarked.Renderer = _Renderer;\nmarked.TextRenderer = _TextRenderer;\nmarked.Lexer = _Lexer;\nmarked.lexer = _Lexer.lex;\nmarked.Tokenizer = _Tokenizer;\nmarked.Hooks = _Hooks;\nmarked.parse = marked;\n\nexport const options = marked.options;\nexport const setOptions = marked.setOptions;\nexport const use = marked.use;\nexport const walkTokens = marked.walkTokens;\nexport const parseInline = marked.parseInline;\nexport const parse = marked;\nexport const parser = _Parser.parse;\nexport const lexer = _Lexer.lex;\nexport { _defaults as defaults, _getDefaults as getDefaults } from './defaults.ts';\nexport { _Lexer as Lexer } from './Lexer.ts';\nexport { _Parser as Parser } from './Parser.ts';\nexport { _Tokenizer as Tokenizer } from './Tokenizer.ts';\nexport { _Renderer as Renderer } from './Renderer.ts';\nexport { _TextRenderer as TextRenderer } from './TextRenderer.ts';\nexport { _Hooks as Hooks } from './Hooks.ts';\nexport { Marked } from './Instance.ts';\nexport type * from './MarkedOptions.ts';\nexport type * from './Tokens.ts';\n", "import type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Gets the original marked default options.\n */\nexport function _getDefaults(): MarkedOptions {\n return {\n async: false,\n breaks: false,\n extensions: null,\n gfm: true,\n hooks: null,\n pedantic: false,\n renderer: null,\n silent: false,\n tokenizer: null,\n walkTokens: null,\n };\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport let _defaults: MarkedOptions = _getDefaults();\n\nexport function changeDefaults(newDefaults: MarkedOptions) {\n _defaults = newDefaults;\n}\n", "const noopTest = { exec: () => null } as unknown as RegExp;\n\nfunction edit(regex: string | RegExp, opt = '') {\n let source = typeof regex === 'string' ? regex : regex.source;\n const obj = {\n replace: (name: string | RegExp, val: string | RegExp) => {\n let valSource = typeof val === 'string' ? val : val.source;\n valSource = valSource.replace(other.caret, '$1');\n source = source.replace(name, valSource);\n return obj;\n },\n getRegex: () => {\n return new RegExp(source, opt);\n },\n };\n return obj;\n}\n\nconst supportsLookbehind = (() => {\ntry {\n // eslint-disable-next-line prefer-regex-literals\n return !!new RegExp('(?<=1)(?/,\n blockquoteSetextReplace: /\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g,\n blockquoteSetextReplace2: /^ {0,3}>[ \\t]?/gm,\n listReplaceTabs: /^\\t+/,\n listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g,\n listIsTask: /^\\[[ xX]\\] /,\n listReplaceTask: /^\\[[ xX]\\] +/,\n anyLine: /\\n.*\\n/,\n hrefBrackets: /^<(.*)>$/,\n tableDelimiter: /[:|]/,\n tableAlignChars: /^\\||\\| *$/g,\n tableRowBlankLine: /\\n[ \\t]*$/,\n tableAlignRight: /^ *-+: *$/,\n tableAlignCenter: /^ *:-+: *$/,\n tableAlignLeft: /^ *:-+ *$/,\n startATag: /^
    /i,\n startPreScriptTag: /^<(pre|code|kbd|script)(\\s|>)/i,\n endPreScriptTag: /^<\\/(pre|code|kbd|script)(\\s|>)/i,\n startAngleBracket: /^$/,\n pedanticHrefTitle: /^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/,\n unicodeAlphaNumeric: /[\\p{L}\\p{N}]/u,\n escapeTest: /[&<>\"']/,\n escapeReplace: /[&<>\"']/g,\n escapeTestNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/,\n escapeReplaceNoEncode: /[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,\n unescapeTest: /&(#(?:\\d+)|(?:#x[0-9A-Fa-f]+)|(?:\\w+));?/ig,\n caret: /(^|[^\\[])\\^/g,\n percentDecode: /%25/g,\n findPipe: /\\|/g,\n splitPipe: / \\|/,\n slashPipe: /\\\\\\|/g,\n carriageReturn: /\\r\\n|\\r/g,\n spaceLine: /^ +$/gm,\n notSpaceStart: /^\\S*/,\n endingNewline: /\\n$/,\n listItemRegex: (bull: string) => new RegExp(`^( {0,3}${bull})((?:[\\t ][^\\\\n]*)?(?:\\\\n|$))`),\n nextBulletRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \\t][^\\\\n]*)?(?:\\\\n|$))`),\n hrRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`),\n fencesBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}(?:\\`\\`\\`|~~~)`),\n headingBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}#`),\n htmlBeginRegex: (indent: number) => new RegExp(`^ {0,${Math.min(3, indent - 1)}}<(?:[a-z].*>|!--)`, 'i'),\n};\n\n/**\n * Block-Level Grammar\n */\n\nconst newline = /^(?:[ \\t]*(?:\\n|$))+/;\nconst blockCode = /^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\n|$))*)?)+/;\nconst fences = /^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/;\nconst hr = /^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/;\nconst heading = /^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/;\nconst bullet = /(?:[*+-]|\\d{1,9}[.)])/;\nconst lheadingCore = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/;\nconst lheading = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // indented code blocks can interrupt\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .replace(/\\|table/g, '') // table not in commonmark\n .getRegex();\nconst lheadingGfm = edit(lheadingCore)\n .replace(/bull/g, bullet) // lists can interrupt\n .replace(/blockCode/g, /(?: {4}| {0,3}\\t)/) // indented code blocks can interrupt\n .replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/) // fenced code blocks can interrupt\n .replace(/blockquote/g, / {0,3}>/) // blockquote can interrupt\n .replace(/heading/g, / {0,3}#{1,6}/) // ATX heading can interrupt\n .replace(/html/g, / {0,3}<[^\\n>]+>\\n/) // block html can interrupt\n .replace(/table/g, / {0,3}\\|?(?:[:\\- ]*\\|)+[\\:\\- ]*\\n/) // table can interrupt\n .getRegex();\nconst _paragraph = /^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\\n)[^\\n]+)*)/;\nconst blockText = /^[^\\n]+/;\nconst _blockLabel = /(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\])+/;\nconst def = edit(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/)\n .replace('label', _blockLabel)\n .replace('title', /(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/)\n .getRegex();\n\nconst list = edit(/^( {0,3}bull)([ \\t][^\\n]+?)?(?:\\n|$)/)\n .replace(/bull/g, bullet)\n .getRegex();\n\nconst _tag = 'address|article|aside|base|basefont|blockquote|body|caption'\n + '|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption'\n + '|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe'\n + '|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option'\n + '|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title'\n + '|tr|track|ul';\nconst _comment = /|$))/;\nconst html = edit(\n '^ {0,3}(?:' // optional indentation\n+ '<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:[^\\\\n]*\\\\n+|$)' // (1)\n+ '|comment[^\\\\n]*(\\\\n+|$)' // (2)\n+ '|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>\\\\n*|$)' // (3)\n+ '|\\\\n*|$)' // (4)\n+ '|\\\\n*|$)' // (5)\n+ '|)[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (6)\n+ '|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) open tag\n+ '|(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \\t]*)+\\\\n|$)' // (7) closing tag\n+ ')', 'i')\n .replace('comment', _comment)\n .replace('tag', _tag)\n .replace('attribute', / +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/)\n .getRegex();\n\nconst paragraph = edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex();\n\nconst blockquote = edit(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/)\n .replace('paragraph', paragraph)\n .getRegex();\n\n/**\n * Normal Block Grammar\n */\n\nconst blockNormal = {\n blockquote,\n code: blockCode,\n def,\n fences,\n heading,\n hr,\n html,\n lheading,\n list,\n newline,\n paragraph,\n table: noopTest,\n text: blockText,\n};\n\ntype BlockKeys = keyof typeof blockNormal;\n\n/**\n * GFM Block Grammar\n */\n\nconst gfmTable = edit(\n '^ *([^\\\\n ].*)\\\\n' // Header\n+ ' {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)' // Align\n+ '(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)') // Cells\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('blockquote', ' {0,3}>')\n .replace('code', '(?: {4}| {0,3}\\t)[^\\\\n]')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // tables can be interrupted by type (6) html blocks\n .getRegex();\n\nconst blockGfm: Record = {\n ...blockNormal,\n lheading: lheadingGfm,\n table: gfmTable,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' {0,3}#{1,6}(?:\\\\s|$)')\n .replace('|lheading', '') // setext headings don't interrupt commonmark paragraphs\n .replace('table', gfmTable) // interrupt paragraphs with table\n .replace('blockquote', ' {0,3}>')\n .replace('fences', ' {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n')\n .replace('list', ' {0,3}(?:[*+-]|1[.)]) ') // only lists starting from 1 can interrupt\n .replace('html', ')|<(?:script|pre|style|textarea|!--)')\n .replace('tag', _tag) // pars can be interrupted by type (6) html blocks\n .getRegex(),\n};\n\n/**\n * Pedantic grammar (original John Gruber's loose markdown specification)\n */\n\nconst blockPedantic: Record = {\n ...blockNormal,\n html: edit(\n '^ *(?:comment *(?:\\\\n|\\\\s*$)'\n + '|<(tag)[\\\\s\\\\S]+? *(?:\\\\n{2,}|\\\\s*$)' // closed tag\n + '|\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))')\n .replace('comment', _comment)\n .replace(/tag/g, '(?!(?:'\n + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub'\n + '|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)'\n + '\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b')\n .getRegex(),\n def: /^ *\\[([^\\]]+)\\]: *]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,\n heading: /^(#{1,6})(.*)(?:\\n+|$)/,\n fences: noopTest, // fences not supported\n lheading: /^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,\n paragraph: edit(_paragraph)\n .replace('hr', hr)\n .replace('heading', ' *#{1,6} *[^\\n]')\n .replace('lheading', lheading)\n .replace('|table', '')\n .replace('blockquote', ' {0,3}>')\n .replace('|fences', '')\n .replace('|list', '')\n .replace('|html', '')\n .replace('|tag', '')\n .getRegex(),\n};\n\n/**\n * Inline-Level Grammar\n */\n\nconst escape = /^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/;\nconst inlineCode = /^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/;\nconst br = /^( {2,}|\\\\)\\n(?!\\s*$)/;\nconst inlineText = /^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\\nconst blockSkip = edit(/link|precode-code|html/, 'g')\n .replace('link', /\\[(?:[^\\[\\]`]|(?`+)[^`]+\\k(?!`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)/)\n .replace('precode-', supportsLookbehind ? '(?`+)[^`]+\\k(?!`)/)\n .replace('html', /<(?! )[^<>]*?>/)\n .getRegex();\n\nconst emStrongLDelimCore = /^(?:\\*+(?:((?!\\*)punct)|[^\\s*]))|^_+(?:((?!_)punct)|([^\\s_]))/;\n\nconst emStrongLDelim = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongLDelimGfm = edit(emStrongLDelimCore, 'u')\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\nconst emStrongRDelimAstCore =\n '^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)' // Skip orphan inside strong\n+ '|[^*]+(?=[^*])' // Consume to delim\n+ '|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)' // (1) #*** can only be a Right Delimiter\n+ '|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)' // (2) a***#, a*** can only be a Right Delimiter\n+ '|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)' // (3) #***a, ***a can only be Left Delimiter\n+ '|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)' // (4) ***# can only be Left Delimiter\n+ '|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)' // (5) #***# can be either Left or Right Delimiter\n+ '|notPunctSpace(\\\\*+)(?=notPunctSpace)'; // (6) a***a can be either Left or Right Delimiter\n\nconst emStrongRDelimAst = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst emStrongRDelimAstGfm = edit(emStrongRDelimAstCore, 'gu')\n .replace(/notPunctSpace/g, _notPunctuationOrSpaceGfmStrongEm)\n .replace(/punctSpace/g, _punctuationOrSpaceGfmStrongEm)\n .replace(/punct/g, _punctuationGfmStrongEm)\n .getRegex();\n\n// (6) Not allowed for _\nconst emStrongRDelimUnd = edit(\n '^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)' // Skip orphan inside strong\n+ '|[^_]+(?=[^_])' // Consume to delim\n+ '|(?!_)punct(_+)(?=[\\\\s]|$)' // (1) #___ can only be a Right Delimiter\n+ '|notPunctSpace(_+)(?!_)(?=punctSpace|$)' // (2) a___#, a___ can only be a Right Delimiter\n+ '|(?!_)punctSpace(_+)(?=notPunctSpace)' // (3) #___a, ___a can only be Left Delimiter\n+ '|[\\\\s](_+)(?!_)(?=punct)' // (4) ___# can only be Left Delimiter\n+ '|(?!_)punct(_+)(?!_)(?=punct)', 'gu') // (5) #___# can be either Left or Right Delimiter\n .replace(/notPunctSpace/g, _notPunctuationOrSpace)\n .replace(/punctSpace/g, _punctuationOrSpace)\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst anyPunctuation = edit(/\\\\(punct)/, 'gu')\n .replace(/punct/g, _punctuation)\n .getRegex();\n\nconst autolink = edit(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/)\n .replace('scheme', /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/)\n .replace('email', /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/)\n .getRegex();\n\nconst _inlineComment = edit(_comment).replace('(?:-->|$)', '-->').getRegex();\nconst tag = edit(\n '^comment'\n + '|^' // self-closing tag\n + '|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>' // open tag\n + '|^<\\\\?[\\\\s\\\\S]*?\\\\?>' // processing instruction, e.g. \n + '|^' // declaration, e.g. \n + '|^') // CDATA section\n .replace('comment', _inlineComment)\n .replace('attribute', /\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/)\n .getRegex();\n\nconst _inlineLabel = /(?:\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+[^`]*?`+(?!`)|[^\\[\\]\\\\`])*?/;\n\nconst link = edit(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]*(?:\\n[ \\t]*)?)(title))?\\s*\\)/)\n .replace('label', _inlineLabel)\n .replace('href', /<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]*/)\n .replace('title', /\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/)\n .getRegex();\n\nconst reflink = edit(/^!?\\[(label)\\]\\[(ref)\\]/)\n .replace('label', _inlineLabel)\n .replace('ref', _blockLabel)\n .getRegex();\n\nconst nolink = edit(/^!?\\[(ref)\\](?:\\[\\])?/)\n .replace('ref', _blockLabel)\n .getRegex();\n\nconst reflinkSearch = edit('reflink|nolink(?!\\\\()', 'g')\n .replace('reflink', reflink)\n .replace('nolink', nolink)\n .getRegex();\n\nconst _caseInsensitiveProtocol = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/;\n\n/**\n * Normal Inline Grammar\n */\n\nconst inlineNormal = {\n _backpedal: noopTest, // only used for GFM url\n anyPunctuation,\n autolink,\n blockSkip,\n br,\n code: inlineCode,\n del: noopTest,\n emStrongLDelim,\n emStrongRDelimAst,\n emStrongRDelimUnd,\n escape,\n link,\n nolink,\n punctuation,\n reflink,\n reflinkSearch,\n tag,\n text: inlineText,\n url: noopTest,\n};\n\ntype InlineKeys = keyof typeof inlineNormal;\n\n/**\n * Pedantic Inline Grammar\n */\n\nconst inlinePedantic: Record = {\n ...inlineNormal,\n link: edit(/^!?\\[(label)\\]\\((.*?)\\)/)\n .replace('label', _inlineLabel)\n .getRegex(),\n reflink: edit(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/)\n .replace('label', _inlineLabel)\n .getRegex(),\n};\n\n/**\n * GFM Inline Grammar\n */\n\nconst inlineGfm: Record = {\n ...inlineNormal,\n emStrongRDelimAst: emStrongRDelimAstGfm,\n emStrongLDelim: emStrongLDelimGfm,\n url: edit(/^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/)\n .replace('protocol', _caseInsensitiveProtocol)\n .replace('email', /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/)\n .getRegex(),\n _backpedal: /(?:[^?!.,:;*_'\"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'\"~)]+(?!$))+/,\n del: /^(~~?)(?=[^\\s~])((?:\\\\[\\s\\S]|[^\\\\])*?(?:\\\\[\\s\\S]|[^\\s~\\\\]))\\1(?=[^~]|$)/,\n text: edit(/^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\ = {\n ...inlineGfm,\n br: edit(br).replace('{2,}', '*').getRegex(),\n text: edit(inlineGfm.text)\n .replace('\\\\b_', '\\\\b_| {2,}\\\\n')\n .replace(/\\{2,\\}/g, '*')\n .getRegex(),\n};\n\n/**\n * exports\n */\n\nexport const block = {\n normal: blockNormal,\n gfm: blockGfm,\n pedantic: blockPedantic,\n};\n\nexport const inline = {\n normal: inlineNormal,\n gfm: inlineGfm,\n breaks: inlineBreaks,\n pedantic: inlinePedantic,\n};\n\nexport interface Rules {\n other: typeof other\n block: Record\n inline: Record\n}\n", "import { other } from './rules.ts';\n\n/**\n * Helpers\n */\nconst escapeReplacements: { [index: string]: string } = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n};\nconst getEscapeReplacement = (ch: string) => escapeReplacements[ch];\n\nexport function escape(html: string, encode?: boolean) {\n if (encode) {\n if (other.escapeTest.test(html)) {\n return html.replace(other.escapeReplace, getEscapeReplacement);\n }\n } else {\n if (other.escapeTestNoEncode.test(html)) {\n return html.replace(other.escapeReplaceNoEncode, getEscapeReplacement);\n }\n }\n\n return html;\n}\n\nexport function unescape(html: string) {\n // explicitly match decimal, hex, and named HTML entities\n return html.replace(other.unescapeTest, (_, n) => {\n n = n.toLowerCase();\n if (n === 'colon') return ':';\n if (n.charAt(0) === '#') {\n return n.charAt(1) === 'x'\n ? String.fromCharCode(parseInt(n.substring(2), 16))\n : String.fromCharCode(+n.substring(1));\n }\n return '';\n });\n}\n\nexport function cleanUrl(href: string) {\n try {\n href = encodeURI(href).replace(other.percentDecode, '%');\n } catch {\n return null;\n }\n return href;\n}\n\nexport function splitCells(tableRow: string, count?: number) {\n // ensure that every cell-delimiting pipe has a space\n // before it to distinguish it from an escaped pipe\n const row = tableRow.replace(other.findPipe, (match, offset, str) => {\n let escaped = false;\n let curr = offset;\n while (--curr >= 0 && str[curr] === '\\\\') escaped = !escaped;\n if (escaped) {\n // odd number of slashes means | is escaped\n // so we leave it alone\n return '|';\n } else {\n // add space before unescaped |\n return ' |';\n }\n }),\n cells = row.split(other.splitPipe);\n let i = 0;\n\n // First/last cell in a row cannot be empty if it has no leading/trailing pipe\n if (!cells[0].trim()) {\n cells.shift();\n }\n if (cells.length > 0 && !cells.at(-1)?.trim()) {\n cells.pop();\n }\n\n if (count) {\n if (cells.length > count) {\n cells.splice(count);\n } else {\n while (cells.length < count) cells.push('');\n }\n }\n\n for (; i < cells.length; i++) {\n // leading or trailing whitespace is ignored per the gfm spec\n cells[i] = cells[i].trim().replace(other.slashPipe, '|');\n }\n return cells;\n}\n\n/**\n * Remove trailing 'c's. Equivalent to str.replace(/c*$/, '').\n * /c*$/ is vulnerable to REDOS.\n *\n * @param str\n * @param c\n * @param invert Remove suffix of non-c chars instead. Default falsey.\n */\nexport function rtrim(str: string, c: string, invert?: boolean) {\n const l = str.length;\n if (l === 0) {\n return '';\n }\n\n // Length of suffix matching the invert condition.\n let suffLen = 0;\n\n // Step left until we fail to match the invert condition.\n while (suffLen < l) {\n const currChar = str.charAt(l - suffLen - 1);\n if (currChar === c && !invert) {\n suffLen++;\n } else if (currChar !== c && invert) {\n suffLen++;\n } else {\n break;\n }\n }\n\n return str.slice(0, l - suffLen);\n}\n\nexport function findClosingBracket(str: string, b: string) {\n if (str.indexOf(b[1]) === -1) {\n return -1;\n }\n\n let level = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '\\\\') {\n i++;\n } else if (str[i] === b[0]) {\n level++;\n } else if (str[i] === b[1]) {\n level--;\n if (level < 0) {\n return i;\n }\n }\n }\n if (level > 0) {\n return -2;\n }\n\n return -1;\n}\n", "import { _defaults } from './defaults.ts';\nimport {\n rtrim,\n splitCells,\n findClosingBracket,\n} from './helpers.ts';\nimport type { Rules } from './rules.ts';\nimport type { _Lexer } from './Lexer.ts';\nimport type { Links, Tokens, Token } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\nfunction outputLink(cap: string[], link: Pick, raw: string, lexer: _Lexer, rules: Rules): Tokens.Link | Tokens.Image {\n const href = link.href;\n const title = link.title || null;\n const text = cap[1].replace(rules.other.outputLinkReplace, '$1');\n\n lexer.state.inLink = true;\n const token: Tokens.Link | Tokens.Image = {\n type: cap[0].charAt(0) === '!' ? 'image' : 'link',\n raw,\n href,\n title,\n text,\n tokens: lexer.inlineTokens(text),\n };\n lexer.state.inLink = false;\n return token;\n}\n\nfunction indentCodeCompensation(raw: string, text: string, rules: Rules) {\n const matchIndentToCode = raw.match(rules.other.indentCodeCompensation);\n\n if (matchIndentToCode === null) {\n return text;\n }\n\n const indentToCode = matchIndentToCode[1];\n\n return text\n .split('\\n')\n .map(node => {\n const matchIndentInNode = node.match(rules.other.beginningSpace);\n if (matchIndentInNode === null) {\n return node;\n }\n\n const [indentInNode] = matchIndentInNode;\n\n if (indentInNode.length >= indentToCode.length) {\n return node.slice(indentToCode.length);\n }\n\n return node;\n })\n .join('\\n');\n}\n\n/**\n * Tokenizer\n */\nexport class _Tokenizer {\n options: MarkedOptions;\n rules!: Rules; // set by the lexer\n lexer!: _Lexer; // set by the lexer\n\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n }\n\n space(src: string): Tokens.Space | undefined {\n const cap = this.rules.block.newline.exec(src);\n if (cap && cap[0].length > 0) {\n return {\n type: 'space',\n raw: cap[0],\n };\n }\n }\n\n code(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.code.exec(src);\n if (cap) {\n const text = cap[0].replace(this.rules.other.codeRemoveIndent, '');\n return {\n type: 'code',\n raw: cap[0],\n codeBlockStyle: 'indented',\n text: !this.options.pedantic\n ? rtrim(text, '\\n')\n : text,\n };\n }\n }\n\n fences(src: string): Tokens.Code | undefined {\n const cap = this.rules.block.fences.exec(src);\n if (cap) {\n const raw = cap[0];\n const text = indentCodeCompensation(raw, cap[3] || '', this.rules);\n\n return {\n type: 'code',\n raw,\n lang: cap[2] ? cap[2].trim().replace(this.rules.inline.anyPunctuation, '$1') : cap[2],\n text,\n };\n }\n }\n\n heading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.heading.exec(src);\n if (cap) {\n let text = cap[2].trim();\n\n // remove trailing #s\n if (this.rules.other.endingHash.test(text)) {\n const trimmed = rtrim(text, '#');\n if (this.options.pedantic) {\n text = trimmed.trim();\n } else if (!trimmed || this.rules.other.endingSpaceChar.test(trimmed)) {\n // CommonMark requires space before trailing #s\n text = trimmed.trim();\n }\n }\n\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[1].length,\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n hr(src: string): Tokens.Hr | undefined {\n const cap = this.rules.block.hr.exec(src);\n if (cap) {\n return {\n type: 'hr',\n raw: rtrim(cap[0], '\\n'),\n };\n }\n }\n\n blockquote(src: string): Tokens.Blockquote | undefined {\n const cap = this.rules.block.blockquote.exec(src);\n if (cap) {\n let lines = rtrim(cap[0], '\\n').split('\\n');\n let raw = '';\n let text = '';\n const tokens: Token[] = [];\n\n while (lines.length > 0) {\n let inBlockquote = false;\n const currentLines = [];\n\n let i;\n for (i = 0; i < lines.length; i++) {\n // get lines up to a continuation\n if (this.rules.other.blockquoteStart.test(lines[i])) {\n currentLines.push(lines[i]);\n inBlockquote = true;\n } else if (!inBlockquote) {\n currentLines.push(lines[i]);\n } else {\n break;\n }\n }\n lines = lines.slice(i);\n\n const currentRaw = currentLines.join('\\n');\n const currentText = currentRaw\n // precede setext continuation with 4 spaces so it isn't a setext\n .replace(this.rules.other.blockquoteSetextReplace, '\\n $1')\n .replace(this.rules.other.blockquoteSetextReplace2, '');\n raw = raw ? `${raw}\\n${currentRaw}` : currentRaw;\n text = text ? `${text}\\n${currentText}` : currentText;\n\n // parse blockquote lines as top level tokens\n // merge paragraphs if this is a continuation\n const top = this.lexer.state.top;\n this.lexer.state.top = true;\n this.lexer.blockTokens(currentText, tokens, true);\n this.lexer.state.top = top;\n\n // if there is no continuation then we are done\n if (lines.length === 0) {\n break;\n }\n\n const lastToken = tokens.at(-1);\n\n if (lastToken?.type === 'code') {\n // blockquote continuation cannot be preceded by a code block\n break;\n } else if (lastToken?.type === 'blockquote') {\n // include continuation in nested blockquote\n const oldToken = lastToken as Tokens.Blockquote;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.blockquote(newText)!;\n tokens[tokens.length - 1] = newToken;\n\n raw = raw.substring(0, raw.length - oldToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.text.length) + newToken.text;\n break;\n } else if (lastToken?.type === 'list') {\n // include continuation in nested list\n const oldToken = lastToken as Tokens.List;\n const newText = oldToken.raw + '\\n' + lines.join('\\n');\n const newToken = this.list(newText)!;\n tokens[tokens.length - 1] = newToken;\n\n raw = raw.substring(0, raw.length - lastToken.raw.length) + newToken.raw;\n text = text.substring(0, text.length - oldToken.raw.length) + newToken.raw;\n lines = newText.substring(tokens.at(-1)!.raw.length).split('\\n');\n continue;\n }\n }\n\n return {\n type: 'blockquote',\n raw,\n tokens,\n text,\n };\n }\n }\n\n list(src: string): Tokens.List | undefined {\n let cap = this.rules.block.list.exec(src);\n if (cap) {\n let bull = cap[1].trim();\n const isordered = bull.length > 1;\n\n const list: Tokens.List = {\n type: 'list',\n raw: '',\n ordered: isordered,\n start: isordered ? +bull.slice(0, -1) : '',\n loose: false,\n items: [],\n };\n\n bull = isordered ? `\\\\d{1,9}\\\\${bull.slice(-1)}` : `\\\\${bull}`;\n\n if (this.options.pedantic) {\n bull = isordered ? bull : '[*+-]';\n }\n\n // Get next list item\n const itemRegex = this.rules.other.listItemRegex(bull);\n let endsWithBlankLine = false;\n // Check if current bullet point can start a new List Item\n while (src) {\n let endEarly = false;\n let raw = '';\n let itemContents = '';\n if (!(cap = itemRegex.exec(src))) {\n break;\n }\n\n if (this.rules.block.hr.test(src)) { // End list if bullet was actually HR (possibly move into itemRegex?)\n break;\n }\n\n raw = cap[0];\n src = src.substring(raw.length);\n\n let line = cap[2].split('\\n', 1)[0].replace(this.rules.other.listReplaceTabs, (t: string) => ' '.repeat(3 * t.length));\n let nextLine = src.split('\\n', 1)[0];\n let blankLine = !line.trim();\n\n let indent = 0;\n if (this.options.pedantic) {\n indent = 2;\n itemContents = line.trimStart();\n } else if (blankLine) {\n indent = cap[1].length + 1;\n } else {\n indent = cap[2].search(this.rules.other.nonSpaceChar); // Find first non-space char\n indent = indent > 4 ? 1 : indent; // Treat indented code blocks (> 4 spaces) as having only 1 indent\n itemContents = line.slice(indent);\n indent += cap[1].length;\n }\n\n if (blankLine && this.rules.other.blankLine.test(nextLine)) { // Items begin with at most one blank line\n raw += nextLine + '\\n';\n src = src.substring(nextLine.length + 1);\n endEarly = true;\n }\n\n if (!endEarly) {\n const nextBulletRegex = this.rules.other.nextBulletRegex(indent);\n const hrRegex = this.rules.other.hrRegex(indent);\n const fencesBeginRegex = this.rules.other.fencesBeginRegex(indent);\n const headingBeginRegex = this.rules.other.headingBeginRegex(indent);\n const htmlBeginRegex = this.rules.other.htmlBeginRegex(indent);\n\n // Check if following lines should be included in List Item\n while (src) {\n const rawLine = src.split('\\n', 1)[0];\n let nextLineWithoutTabs;\n nextLine = rawLine;\n\n // Re-align to follow commonmark nesting rules\n if (this.options.pedantic) {\n nextLine = nextLine.replace(this.rules.other.listReplaceNesting, ' ');\n nextLineWithoutTabs = nextLine;\n } else {\n nextLineWithoutTabs = nextLine.replace(this.rules.other.tabCharGlobal, ' ');\n }\n\n // End list item if found code fences\n if (fencesBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new heading\n if (headingBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of html block\n if (htmlBeginRegex.test(nextLine)) {\n break;\n }\n\n // End list item if found start of new bullet\n if (nextBulletRegex.test(nextLine)) {\n break;\n }\n\n // Horizontal rule found\n if (hrRegex.test(nextLine)) {\n break;\n }\n\n if (nextLineWithoutTabs.search(this.rules.other.nonSpaceChar) >= indent || !nextLine.trim()) { // Dedent if possible\n itemContents += '\\n' + nextLineWithoutTabs.slice(indent);\n } else {\n // not enough indentation\n if (blankLine) {\n break;\n }\n\n // paragraph continuation unless last line was a different block level element\n if (line.replace(this.rules.other.tabCharGlobal, ' ').search(this.rules.other.nonSpaceChar) >= 4) { // indented code block\n break;\n }\n if (fencesBeginRegex.test(line)) {\n break;\n }\n if (headingBeginRegex.test(line)) {\n break;\n }\n if (hrRegex.test(line)) {\n break;\n }\n\n itemContents += '\\n' + nextLine;\n }\n\n if (!blankLine && !nextLine.trim()) { // Check if current line is blank\n blankLine = true;\n }\n\n raw += rawLine + '\\n';\n src = src.substring(rawLine.length + 1);\n line = nextLineWithoutTabs.slice(indent);\n }\n }\n\n if (!list.loose) {\n // If the previous item ended with a blank line, the list is loose\n if (endsWithBlankLine) {\n list.loose = true;\n } else if (this.rules.other.doubleBlankLine.test(raw)) {\n endsWithBlankLine = true;\n }\n }\n\n let istask: RegExpExecArray | null = null;\n let ischecked: boolean | undefined;\n // Check for task list items\n if (this.options.gfm) {\n istask = this.rules.other.listIsTask.exec(itemContents);\n if (istask) {\n ischecked = istask[0] !== '[ ] ';\n itemContents = itemContents.replace(this.rules.other.listReplaceTask, '');\n }\n }\n\n list.items.push({\n type: 'list_item',\n raw,\n task: !!istask,\n checked: ischecked,\n loose: false,\n text: itemContents,\n tokens: [],\n });\n\n list.raw += raw;\n }\n\n // Do not consume newlines at end of final item. Alternatively, make itemRegex *start* with any newlines to simplify/speed up endsWithBlankLine logic\n const lastItem = list.items.at(-1);\n if (lastItem) {\n lastItem.raw = lastItem.raw.trimEnd();\n lastItem.text = lastItem.text.trimEnd();\n } else {\n // not a list since there were no items\n return;\n }\n list.raw = list.raw.trimEnd();\n\n // Item child tokens handled here at end because we needed to have the final item to trim it first\n for (let i = 0; i < list.items.length; i++) {\n this.lexer.state.top = false;\n list.items[i].tokens = this.lexer.blockTokens(list.items[i].text, []);\n\n if (!list.loose) {\n // Check if list should be loose\n const spacers = list.items[i].tokens.filter(t => t.type === 'space');\n const hasMultipleLineBreaks = spacers.length > 0 && spacers.some(t => this.rules.other.anyLine.test(t.raw));\n\n list.loose = hasMultipleLineBreaks;\n }\n }\n\n // Set all items to loose if list is loose\n if (list.loose) {\n for (let i = 0; i < list.items.length; i++) {\n list.items[i].loose = true;\n }\n }\n\n return list;\n }\n }\n\n html(src: string): Tokens.HTML | undefined {\n const cap = this.rules.block.html.exec(src);\n if (cap) {\n const token: Tokens.HTML = {\n type: 'html',\n block: true,\n raw: cap[0],\n pre: cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style',\n text: cap[0],\n };\n return token;\n }\n }\n\n def(src: string): Tokens.Def | undefined {\n const cap = this.rules.block.def.exec(src);\n if (cap) {\n const tag = cap[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, ' ');\n const href = cap[2] ? cap[2].replace(this.rules.other.hrefBrackets, '$1').replace(this.rules.inline.anyPunctuation, '$1') : '';\n const title = cap[3] ? cap[3].substring(1, cap[3].length - 1).replace(this.rules.inline.anyPunctuation, '$1') : cap[3];\n return {\n type: 'def',\n tag,\n raw: cap[0],\n href,\n title,\n };\n }\n }\n\n table(src: string): Tokens.Table | undefined {\n const cap = this.rules.block.table.exec(src);\n if (!cap) {\n return;\n }\n\n if (!this.rules.other.tableDelimiter.test(cap[2])) {\n // delimiter row must have a pipe (|) or colon (:) otherwise it is a setext heading\n return;\n }\n\n const headers = splitCells(cap[1]);\n const aligns = cap[2].replace(this.rules.other.tableAlignChars, '').split('|');\n const rows = cap[3]?.trim() ? cap[3].replace(this.rules.other.tableRowBlankLine, '').split('\\n') : [];\n\n const item: Tokens.Table = {\n type: 'table',\n raw: cap[0],\n header: [],\n align: [],\n rows: [],\n };\n\n if (headers.length !== aligns.length) {\n // header and align columns must be equal, rows can be different.\n return;\n }\n\n for (const align of aligns) {\n if (this.rules.other.tableAlignRight.test(align)) {\n item.align.push('right');\n } else if (this.rules.other.tableAlignCenter.test(align)) {\n item.align.push('center');\n } else if (this.rules.other.tableAlignLeft.test(align)) {\n item.align.push('left');\n } else {\n item.align.push(null);\n }\n }\n\n for (let i = 0; i < headers.length; i++) {\n item.header.push({\n text: headers[i],\n tokens: this.lexer.inline(headers[i]),\n header: true,\n align: item.align[i],\n });\n }\n\n for (const row of rows) {\n item.rows.push(splitCells(row, item.header.length).map((cell, i) => {\n return {\n text: cell,\n tokens: this.lexer.inline(cell),\n header: false,\n align: item.align[i],\n };\n }));\n }\n\n return item;\n }\n\n lheading(src: string): Tokens.Heading | undefined {\n const cap = this.rules.block.lheading.exec(src);\n if (cap) {\n return {\n type: 'heading',\n raw: cap[0],\n depth: cap[2].charAt(0) === '=' ? 1 : 2,\n text: cap[1],\n tokens: this.lexer.inline(cap[1]),\n };\n }\n }\n\n paragraph(src: string): Tokens.Paragraph | undefined {\n const cap = this.rules.block.paragraph.exec(src);\n if (cap) {\n const text = cap[1].charAt(cap[1].length - 1) === '\\n'\n ? cap[1].slice(0, -1)\n : cap[1];\n return {\n type: 'paragraph',\n raw: cap[0],\n text,\n tokens: this.lexer.inline(text),\n };\n }\n }\n\n text(src: string): Tokens.Text | undefined {\n const cap = this.rules.block.text.exec(src);\n if (cap) {\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n tokens: this.lexer.inline(cap[0]),\n };\n }\n }\n\n escape(src: string): Tokens.Escape | undefined {\n const cap = this.rules.inline.escape.exec(src);\n if (cap) {\n return {\n type: 'escape',\n raw: cap[0],\n text: cap[1],\n };\n }\n }\n\n tag(src: string): Tokens.Tag | undefined {\n const cap = this.rules.inline.tag.exec(src);\n if (cap) {\n if (!this.lexer.state.inLink && this.rules.other.startATag.test(cap[0])) {\n this.lexer.state.inLink = true;\n } else if (this.lexer.state.inLink && this.rules.other.endATag.test(cap[0])) {\n this.lexer.state.inLink = false;\n }\n if (!this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = true;\n } else if (this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(cap[0])) {\n this.lexer.state.inRawBlock = false;\n }\n\n return {\n type: 'html',\n raw: cap[0],\n inLink: this.lexer.state.inLink,\n inRawBlock: this.lexer.state.inRawBlock,\n block: false,\n text: cap[0],\n };\n }\n }\n\n link(src: string): Tokens.Link | Tokens.Image | undefined {\n const cap = this.rules.inline.link.exec(src);\n if (cap) {\n const trimmedUrl = cap[2].trim();\n if (!this.options.pedantic && this.rules.other.startAngleBracket.test(trimmedUrl)) {\n // commonmark requires matching angle brackets\n if (!(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n return;\n }\n\n // ending angle bracket cannot be escaped\n const rtrimSlash = rtrim(trimmedUrl.slice(0, -1), '\\\\');\n if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {\n return;\n }\n } else {\n // find closing parenthesis\n const lastParenIndex = findClosingBracket(cap[2], '()');\n if (lastParenIndex === -2) {\n // more open parens than closed\n return;\n }\n\n if (lastParenIndex > -1) {\n const start = cap[0].indexOf('!') === 0 ? 5 : 4;\n const linkLen = start + cap[1].length + lastParenIndex;\n cap[2] = cap[2].substring(0, lastParenIndex);\n cap[0] = cap[0].substring(0, linkLen).trim();\n cap[3] = '';\n }\n }\n let href = cap[2];\n let title = '';\n if (this.options.pedantic) {\n // split pedantic href and title\n const link = this.rules.other.pedanticHrefTitle.exec(href);\n\n if (link) {\n href = link[1];\n title = link[3];\n }\n } else {\n title = cap[3] ? cap[3].slice(1, -1) : '';\n }\n\n href = href.trim();\n if (this.rules.other.startAngleBracket.test(href)) {\n if (this.options.pedantic && !(this.rules.other.endAngleBracket.test(trimmedUrl))) {\n // pedantic allows starting angle bracket without ending angle bracket\n href = href.slice(1);\n } else {\n href = href.slice(1, -1);\n }\n }\n return outputLink(cap, {\n href: href ? href.replace(this.rules.inline.anyPunctuation, '$1') : href,\n title: title ? title.replace(this.rules.inline.anyPunctuation, '$1') : title,\n }, cap[0], this.lexer, this.rules);\n }\n }\n\n reflink(src: string, links: Links): Tokens.Link | Tokens.Image | Tokens.Text | undefined {\n let cap;\n if ((cap = this.rules.inline.reflink.exec(src))\n || (cap = this.rules.inline.nolink.exec(src))) {\n const linkString = (cap[2] || cap[1]).replace(this.rules.other.multipleSpaceGlobal, ' ');\n const link = links[linkString.toLowerCase()];\n if (!link) {\n const text = cap[0].charAt(0);\n return {\n type: 'text',\n raw: text,\n text,\n };\n }\n return outputLink(cap, link, cap[0], this.lexer, this.rules);\n }\n }\n\n emStrong(src: string, maskedSrc: string, prevChar = ''): Tokens.Em | Tokens.Strong | undefined {\n let match = this.rules.inline.emStrongLDelim.exec(src);\n if (!match) return;\n\n // _ can't be between two alphanumerics. \\p{L}\\p{N} includes non-english alphabet/numbers as well\n if (match[3] && prevChar.match(this.rules.other.unicodeAlphaNumeric)) return;\n\n const nextChar = match[1] || match[2] || '';\n\n if (!nextChar || !prevChar || this.rules.inline.punctuation.exec(prevChar)) {\n // unicode Regex counts emoji as 1 char; spread into array for proper count (used multiple times below)\n const lLength = [...match[0]].length - 1;\n let rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;\n\n const endReg = match[0][0] === '*' ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;\n endReg.lastIndex = 0;\n\n // Clip maskedSrc to same section of string as src (move to lexer?)\n maskedSrc = maskedSrc.slice(-1 * src.length + lLength);\n\n while ((match = endReg.exec(maskedSrc)) != null) {\n rDelim = match[1] || match[2] || match[3] || match[4] || match[5] || match[6];\n\n if (!rDelim) continue; // skip single * in __abc*abc__\n\n rLength = [...rDelim].length;\n\n if (match[3] || match[4]) { // found another Left Delim\n delimTotal += rLength;\n continue;\n } else if (match[5] || match[6]) { // either Left or Right Delim\n if (lLength % 3 && !((lLength + rLength) % 3)) {\n midDelimTotal += rLength;\n continue; // CommonMark Emphasis Rules 9-10\n }\n }\n\n delimTotal -= rLength;\n\n if (delimTotal > 0) continue; // Haven't found enough closing delimiters\n\n // Remove extra characters. *a*** -> *a*\n rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);\n // char length can be >1 for unicode characters;\n const lastCharLength = [...match[0]][0].length;\n const raw = src.slice(0, lLength + match.index + lastCharLength + rLength);\n\n // Create `em` if smallest delimiter has odd char count. *a***\n if (Math.min(lLength, rLength) % 2) {\n const text = raw.slice(1, -1);\n return {\n type: 'em',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n\n // Create 'strong' if smallest delimiter has even char count. **a***\n const text = raw.slice(2, -2);\n return {\n type: 'strong',\n raw,\n text,\n tokens: this.lexer.inlineTokens(text),\n };\n }\n }\n }\n\n codespan(src: string): Tokens.Codespan | undefined {\n const cap = this.rules.inline.code.exec(src);\n if (cap) {\n let text = cap[2].replace(this.rules.other.newLineCharGlobal, ' ');\n const hasNonSpaceChars = this.rules.other.nonSpaceChar.test(text);\n const hasSpaceCharsOnBothEnds = this.rules.other.startingSpaceChar.test(text) && this.rules.other.endingSpaceChar.test(text);\n if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {\n text = text.substring(1, text.length - 1);\n }\n return {\n type: 'codespan',\n raw: cap[0],\n text,\n };\n }\n }\n\n br(src: string): Tokens.Br | undefined {\n const cap = this.rules.inline.br.exec(src);\n if (cap) {\n return {\n type: 'br',\n raw: cap[0],\n };\n }\n }\n\n del(src: string): Tokens.Del | undefined {\n const cap = this.rules.inline.del.exec(src);\n if (cap) {\n return {\n type: 'del',\n raw: cap[0],\n text: cap[2],\n tokens: this.lexer.inlineTokens(cap[2]),\n };\n }\n }\n\n autolink(src: string): Tokens.Link | undefined {\n const cap = this.rules.inline.autolink.exec(src);\n if (cap) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[1];\n href = 'mailto:' + text;\n } else {\n text = cap[1];\n href = text;\n }\n\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text,\n },\n ],\n };\n }\n }\n\n url(src: string): Tokens.Link | undefined {\n let cap;\n if (cap = this.rules.inline.url.exec(src)) {\n let text, href;\n if (cap[2] === '@') {\n text = cap[0];\n href = 'mailto:' + text;\n } else {\n // do extended autolink path validation\n let prevCapZero;\n do {\n prevCapZero = cap[0];\n cap[0] = this.rules.inline._backpedal.exec(cap[0])?.[0] ?? '';\n } while (prevCapZero !== cap[0]);\n text = cap[0];\n if (cap[1] === 'www.') {\n href = 'http://' + cap[0];\n } else {\n href = cap[0];\n }\n }\n return {\n type: 'link',\n raw: cap[0],\n text,\n href,\n tokens: [\n {\n type: 'text',\n raw: text,\n text,\n },\n ],\n };\n }\n }\n\n inlineText(src: string): Tokens.Text | undefined {\n const cap = this.rules.inline.text.exec(src);\n if (cap) {\n const escaped = this.lexer.state.inRawBlock;\n return {\n type: 'text',\n raw: cap[0],\n text: cap[0],\n escaped,\n };\n }\n }\n}\n", "import { _Tokenizer } from './Tokenizer.ts';\nimport { _defaults } from './defaults.ts';\nimport { other, block, inline } from './rules.ts';\nimport type { Token, TokensList, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Block Lexer\n */\nexport class _Lexer {\n tokens: TokensList;\n options: MarkedOptions;\n state: {\n inLink: boolean;\n inRawBlock: boolean;\n top: boolean;\n };\n\n private tokenizer: _Tokenizer;\n private inlineQueue: { src: string, tokens: Token[] }[];\n\n constructor(options?: MarkedOptions) {\n // TokenList cannot be created in one go\n this.tokens = [] as unknown as TokensList;\n this.tokens.links = Object.create(null);\n this.options = options || _defaults;\n this.options.tokenizer = this.options.tokenizer || new _Tokenizer();\n this.tokenizer = this.options.tokenizer;\n this.tokenizer.options = this.options;\n this.tokenizer.lexer = this;\n this.inlineQueue = [];\n this.state = {\n inLink: false,\n inRawBlock: false,\n top: true,\n };\n\n const rules = {\n other,\n block: block.normal,\n inline: inline.normal,\n };\n\n if (this.options.pedantic) {\n rules.block = block.pedantic;\n rules.inline = inline.pedantic;\n } else if (this.options.gfm) {\n rules.block = block.gfm;\n if (this.options.breaks) {\n rules.inline = inline.breaks;\n } else {\n rules.inline = inline.gfm;\n }\n }\n this.tokenizer.rules = rules;\n }\n\n /**\n * Expose Rules\n */\n static get rules() {\n return {\n block,\n inline,\n };\n }\n\n /**\n * Static Lex Method\n */\n static lex(src: string, options?: MarkedOptions) {\n const lexer = new _Lexer(options);\n return lexer.lex(src);\n }\n\n /**\n * Static Lex Inline Method\n */\n static lexInline(src: string, options?: MarkedOptions) {\n const lexer = new _Lexer(options);\n return lexer.inlineTokens(src);\n }\n\n /**\n * Preprocessing\n */\n lex(src: string) {\n src = src.replace(other.carriageReturn, '\\n');\n\n this.blockTokens(src, this.tokens);\n\n for (let i = 0; i < this.inlineQueue.length; i++) {\n const next = this.inlineQueue[i];\n this.inlineTokens(next.src, next.tokens);\n }\n this.inlineQueue = [];\n\n return this.tokens;\n }\n\n /**\n * Lexing\n */\n blockTokens(src: string, tokens?: Token[], lastParagraphClipped?: boolean): Token[];\n blockTokens(src: string, tokens?: TokensList, lastParagraphClipped?: boolean): TokensList;\n blockTokens(src: string, tokens: Token[] = [], lastParagraphClipped = false) {\n if (this.options.pedantic) {\n src = src.replace(other.tabCharGlobal, ' ').replace(other.spaceLine, '');\n }\n\n while (src) {\n let token: Tokens.Generic | undefined;\n\n if (this.options.extensions?.block?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n\n // newline\n if (token = this.tokenizer.space(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.raw.length === 1 && lastToken !== undefined) {\n // if there's a single \\n as a spacer, it's terminating the last line,\n // so move it there so that we don't get unnecessary paragraph tags\n lastToken.raw += '\\n';\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // code\n if (token = this.tokenizer.code(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n // An indented code block cannot interrupt a paragraph.\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // fences\n if (token = this.tokenizer.fences(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // heading\n if (token = this.tokenizer.heading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // hr\n if (token = this.tokenizer.hr(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // blockquote\n if (token = this.tokenizer.blockquote(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // list\n if (token = this.tokenizer.list(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // html\n if (token = this.tokenizer.html(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // def\n if (token = this.tokenizer.def(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'paragraph' || lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.raw;\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else if (!this.tokens.links[token.tag]) {\n this.tokens.links[token.tag] = {\n href: token.href,\n title: token.title,\n };\n tokens.push(token);\n }\n continue;\n }\n\n // table (gfm)\n if (token = this.tokenizer.table(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // lheading\n if (token = this.tokenizer.lheading(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // top-level paragraph\n // prevent paragraph consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (this.options.extensions?.startBlock) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startBlock.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {\n const lastToken = tokens.at(-1);\n if (lastParagraphClipped && lastToken?.type === 'paragraph') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n lastParagraphClipped = cutSrc.length !== src.length;\n src = src.substring(token.raw.length);\n continue;\n }\n\n // text\n if (token = this.tokenizer.text(src)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += (lastToken.raw.endsWith('\\n') ? '' : '\\n') + token.raw;\n lastToken.text += '\\n' + token.text;\n this.inlineQueue.pop();\n this.inlineQueue.at(-1)!.src = lastToken.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n\n this.state.top = true;\n return tokens;\n }\n\n inline(src: string, tokens: Token[] = []) {\n this.inlineQueue.push({ src, tokens });\n return tokens;\n }\n\n /**\n * Lexing/Compiling\n */\n inlineTokens(src: string, tokens: Token[] = []): Token[] {\n // String with links masked to avoid interference with em and strong\n let maskedSrc = src;\n let match: RegExpExecArray | null = null;\n\n // Mask out reflinks\n if (this.tokens.links) {\n const links = Object.keys(this.tokens.links);\n if (links.length > 0) {\n while ((match = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {\n if (links.includes(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {\n maskedSrc = maskedSrc.slice(0, match.index)\n + '[' + 'a'.repeat(match[0].length - 2) + ']'\n + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);\n }\n }\n }\n }\n\n // Mask out escaped characters\n while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) != null) {\n maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);\n }\n\n // Mask out other blocks\n let offset;\n while ((match = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {\n offset = match[2] ? match[2].length : 0;\n maskedSrc = maskedSrc.slice(0, match.index + offset) + '[' + 'a'.repeat(match[0].length - offset - 2) + ']' + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);\n }\n\n // Mask out blocks from extensions\n maskedSrc = this.options.hooks?.emStrongMask?.call({ lexer: this }, maskedSrc) ?? maskedSrc;\n\n let keepPrevChar = false;\n let prevChar = '';\n while (src) {\n if (!keepPrevChar) {\n prevChar = '';\n }\n keepPrevChar = false;\n\n let token: Tokens.Generic | undefined;\n\n // extensions\n if (this.options.extensions?.inline?.some((extTokenizer) => {\n if (token = extTokenizer.call({ lexer: this }, src, tokens)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n return true;\n }\n return false;\n })) {\n continue;\n }\n\n // escape\n if (token = this.tokenizer.escape(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // tag\n if (token = this.tokenizer.tag(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // link\n if (token = this.tokenizer.link(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // reflink, nolink\n if (token = this.tokenizer.reflink(src, this.tokens.links)) {\n src = src.substring(token.raw.length);\n const lastToken = tokens.at(-1);\n if (token.type === 'text' && lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n // em & strong\n if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // code\n if (token = this.tokenizer.codespan(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // br\n if (token = this.tokenizer.br(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // del (gfm)\n if (token = this.tokenizer.del(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // autolink\n if (token = this.tokenizer.autolink(src)) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // url (gfm)\n if (!this.state.inLink && (token = this.tokenizer.url(src))) {\n src = src.substring(token.raw.length);\n tokens.push(token);\n continue;\n }\n\n // text\n // prevent inlineText consuming extensions by clipping 'src' to extension start\n let cutSrc = src;\n if (this.options.extensions?.startInline) {\n let startIndex = Infinity;\n const tempSrc = src.slice(1);\n let tempStart;\n this.options.extensions.startInline.forEach((getStartIndex) => {\n tempStart = getStartIndex.call({ lexer: this }, tempSrc);\n if (typeof tempStart === 'number' && tempStart >= 0) {\n startIndex = Math.min(startIndex, tempStart);\n }\n });\n if (startIndex < Infinity && startIndex >= 0) {\n cutSrc = src.substring(0, startIndex + 1);\n }\n }\n if (token = this.tokenizer.inlineText(cutSrc)) {\n src = src.substring(token.raw.length);\n if (token.raw.slice(-1) !== '_') { // Track prevChar before string of ____ started\n prevChar = token.raw.slice(-1);\n }\n keepPrevChar = true;\n const lastToken = tokens.at(-1);\n if (lastToken?.type === 'text') {\n lastToken.raw += token.raw;\n lastToken.text += token.text;\n } else {\n tokens.push(token);\n }\n continue;\n }\n\n if (src) {\n const errMsg = 'Infinite loop on byte: ' + src.charCodeAt(0);\n if (this.options.silent) {\n console.error(errMsg);\n break;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n\n return tokens;\n }\n}\n", "import { _defaults } from './defaults.ts';\nimport {\n cleanUrl,\n escape,\n} from './helpers.ts';\nimport { other } from './rules.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Tokens } from './Tokens.ts';\nimport type { _Parser } from './Parser.ts';\n\n/**\n * Renderer\n */\nexport class _Renderer {\n options: MarkedOptions;\n parser!: _Parser; // set by the parser\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n }\n\n space(token: Tokens.Space): RendererOutput {\n return '' as RendererOutput;\n }\n\n code({ text, lang, escaped }: Tokens.Code): RendererOutput {\n const langString = (lang || '').match(other.notSpaceStart)?.[0];\n\n const code = text.replace(other.endingNewline, '') + '\\n';\n\n if (!langString) {\n return '
    '\n        + (escaped ? code : escape(code, true))\n        + '
    \\n' as RendererOutput;\n }\n\n return '
    '\n      + (escaped ? code : escape(code, true))\n      + '
    \\n' as RendererOutput;\n }\n\n blockquote({ tokens }: Tokens.Blockquote): RendererOutput {\n const body = this.parser.parse(tokens);\n return `
    \\n${body}
    \\n` as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n def(token: Tokens.Def): RendererOutput {\n return '' as RendererOutput;\n }\n\n heading({ tokens, depth }: Tokens.Heading): RendererOutput {\n return `${this.parser.parseInline(tokens)}\\n` as RendererOutput;\n }\n\n hr(token: Tokens.Hr): RendererOutput {\n return '
    \\n' as RendererOutput;\n }\n\n list(token: Tokens.List): RendererOutput {\n const ordered = token.ordered;\n const start = token.start;\n\n let body = '';\n for (let j = 0; j < token.items.length; j++) {\n const item = token.items[j];\n body += this.listitem(item);\n }\n\n const type = ordered ? 'ol' : 'ul';\n const startAttr = (ordered && start !== 1) ? (' start=\"' + start + '\"') : '';\n return '<' + type + startAttr + '>\\n' + body + '\\n' as RendererOutput;\n }\n\n listitem(item: Tokens.ListItem): RendererOutput {\n let itemBody = '';\n if (item.task) {\n const checkbox = this.checkbox({ checked: !!item.checked });\n if (item.loose) {\n if (item.tokens[0]?.type === 'paragraph') {\n item.tokens[0].text = checkbox + ' ' + item.tokens[0].text;\n if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {\n item.tokens[0].tokens[0].text = checkbox + ' ' + escape(item.tokens[0].tokens[0].text);\n item.tokens[0].tokens[0].escaped = true;\n }\n } else {\n item.tokens.unshift({\n type: 'text',\n raw: checkbox + ' ',\n text: checkbox + ' ',\n escaped: true,\n });\n }\n } else {\n itemBody += checkbox + ' ';\n }\n }\n\n itemBody += this.parser.parse(item.tokens, !!item.loose);\n\n return `
  • ${itemBody}
  • \\n` as RendererOutput;\n }\n\n checkbox({ checked }: Tokens.Checkbox): RendererOutput {\n return '' as RendererOutput;\n }\n\n paragraph({ tokens }: Tokens.Paragraph): RendererOutput {\n return `

    ${this.parser.parseInline(tokens)}

    \\n` as RendererOutput;\n }\n\n table(token: Tokens.Table): RendererOutput {\n let header = '';\n\n // header\n let cell = '';\n for (let j = 0; j < token.header.length; j++) {\n cell += this.tablecell(token.header[j]);\n }\n header += this.tablerow({ text: cell as ParserOutput });\n\n let body = '';\n for (let j = 0; j < token.rows.length; j++) {\n const row = token.rows[j];\n\n cell = '';\n for (let k = 0; k < row.length; k++) {\n cell += this.tablecell(row[k]);\n }\n\n body += this.tablerow({ text: cell as ParserOutput });\n }\n if (body) body = `${body}`;\n\n return '\\n'\n + '\\n'\n + header\n + '\\n'\n + body\n + '
    \\n' as RendererOutput;\n }\n\n tablerow({ text }: Tokens.TableRow): RendererOutput {\n return `\\n${text}\\n` as RendererOutput;\n }\n\n tablecell(token: Tokens.TableCell): RendererOutput {\n const content = this.parser.parseInline(token.tokens);\n const type = token.header ? 'th' : 'td';\n const tag = token.align\n ? `<${type} align=\"${token.align}\">`\n : `<${type}>`;\n return tag + content + `\\n` as RendererOutput;\n }\n\n /**\n * span level renderer\n */\n strong({ tokens }: Tokens.Strong): RendererOutput {\n return `${this.parser.parseInline(tokens)}` as RendererOutput;\n }\n\n em({ tokens }: Tokens.Em): RendererOutput {\n return `${this.parser.parseInline(tokens)}` as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return `${escape(text, true)}` as RendererOutput;\n }\n\n br(token: Tokens.Br): RendererOutput {\n return '
    ' as RendererOutput;\n }\n\n del({ tokens }: Tokens.Del): RendererOutput {\n return `${this.parser.parseInline(tokens)}` as RendererOutput;\n }\n\n link({ href, title, tokens }: Tokens.Link): RendererOutput {\n const text = this.parser.parseInline(tokens) as string;\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return text as RendererOutput;\n }\n href = cleanHref;\n let out = '
    ';\n return out as RendererOutput;\n }\n\n image({ href, title, text, tokens }: Tokens.Image): RendererOutput {\n if (tokens) {\n text = this.parser.parseInline(tokens, this.parser.textRenderer) as string;\n }\n const cleanHref = cleanUrl(href);\n if (cleanHref === null) {\n return escape(text) as RendererOutput;\n }\n href = cleanHref;\n\n let out = `\"${text}\"`;\n {\n // no need for block level renderers\n strong({ text }: Tokens.Strong): RendererOutput {\n return text as RendererOutput;\n }\n\n em({ text }: Tokens.Em): RendererOutput {\n return text as RendererOutput;\n }\n\n codespan({ text }: Tokens.Codespan): RendererOutput {\n return text as RendererOutput;\n }\n\n del({ text }: Tokens.Del): RendererOutput {\n return text as RendererOutput;\n }\n\n html({ text }: Tokens.HTML | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n text({ text }: Tokens.Text | Tokens.Escape | Tokens.Tag): RendererOutput {\n return text as RendererOutput;\n }\n\n link({ text }: Tokens.Link): RendererOutput {\n return '' + text as RendererOutput;\n }\n\n image({ text }: Tokens.Image): RendererOutput {\n return '' + text as RendererOutput;\n }\n\n br(): RendererOutput {\n return '' as RendererOutput;\n }\n}\n", "import { _Renderer } from './Renderer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { _defaults } from './defaults.ts';\nimport type { MarkedToken, Token, Tokens } from './Tokens.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\n\n/**\n * Parsing & Compiling\n */\nexport class _Parser {\n options: MarkedOptions;\n renderer: _Renderer;\n textRenderer: _TextRenderer;\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n this.options.renderer = this.options.renderer || new _Renderer();\n this.renderer = this.options.renderer;\n this.renderer.options = this.options;\n this.renderer.parser = this;\n this.textRenderer = new _TextRenderer();\n }\n\n /**\n * Static Parse Method\n */\n static parse(tokens: Token[], options?: MarkedOptions) {\n const parser = new _Parser(options);\n return parser.parse(tokens);\n }\n\n /**\n * Static Parse Inline Method\n */\n static parseInline(tokens: Token[], options?: MarkedOptions) {\n const parser = new _Parser(options);\n return parser.parseInline(tokens);\n }\n\n /**\n * Parse Loop\n */\n parse(tokens: Token[], top = true): ParserOutput {\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const genericToken = anyToken as Tokens.Generic;\n const ret = this.options.extensions.renderers[genericToken.type].call({ parser: this }, genericToken);\n if (ret !== false || !['space', 'hr', 'heading', 'code', 'table', 'blockquote', 'list', 'html', 'def', 'paragraph', 'text'].includes(genericToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'space': {\n out += this.renderer.space(token);\n continue;\n }\n case 'hr': {\n out += this.renderer.hr(token);\n continue;\n }\n case 'heading': {\n out += this.renderer.heading(token);\n continue;\n }\n case 'code': {\n out += this.renderer.code(token);\n continue;\n }\n case 'table': {\n out += this.renderer.table(token);\n continue;\n }\n case 'blockquote': {\n out += this.renderer.blockquote(token);\n continue;\n }\n case 'list': {\n out += this.renderer.list(token);\n continue;\n }\n case 'html': {\n out += this.renderer.html(token);\n continue;\n }\n case 'def': {\n out += this.renderer.def(token);\n continue;\n }\n case 'paragraph': {\n out += this.renderer.paragraph(token);\n continue;\n }\n case 'text': {\n let textToken = token;\n let body = this.renderer.text(textToken) as string;\n while (i + 1 < tokens.length && tokens[i + 1].type === 'text') {\n textToken = tokens[++i] as Tokens.Text;\n body += ('\\n' + this.renderer.text(textToken));\n }\n if (top) {\n out += this.renderer.paragraph({\n type: 'paragraph',\n raw: body,\n text: body,\n tokens: [{ type: 'text', raw: body, text: body, escaped: true }],\n });\n } else {\n out += body;\n }\n continue;\n }\n\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n\n return out as ParserOutput;\n }\n\n /**\n * Parse Inline Tokens\n */\n parseInline(tokens: Token[], renderer: _Renderer | _TextRenderer = this.renderer): ParserOutput {\n let out = '';\n\n for (let i = 0; i < tokens.length; i++) {\n const anyToken = tokens[i];\n\n // Run any renderer extensions\n if (this.options.extensions?.renderers?.[anyToken.type]) {\n const ret = this.options.extensions.renderers[anyToken.type].call({ parser: this }, anyToken);\n if (ret !== false || !['escape', 'html', 'link', 'image', 'strong', 'em', 'codespan', 'br', 'del', 'text'].includes(anyToken.type)) {\n out += ret || '';\n continue;\n }\n }\n\n const token = anyToken as MarkedToken;\n\n switch (token.type) {\n case 'escape': {\n out += renderer.text(token);\n break;\n }\n case 'html': {\n out += renderer.html(token);\n break;\n }\n case 'link': {\n out += renderer.link(token);\n break;\n }\n case 'image': {\n out += renderer.image(token);\n break;\n }\n case 'strong': {\n out += renderer.strong(token);\n break;\n }\n case 'em': {\n out += renderer.em(token);\n break;\n }\n case 'codespan': {\n out += renderer.codespan(token);\n break;\n }\n case 'br': {\n out += renderer.br(token);\n break;\n }\n case 'del': {\n out += renderer.del(token);\n break;\n }\n case 'text': {\n out += renderer.text(token);\n break;\n }\n default: {\n const errMsg = 'Token with \"' + token.type + '\" type was not found.';\n if (this.options.silent) {\n console.error(errMsg);\n return '' as ParserOutput;\n } else {\n throw new Error(errMsg);\n }\n }\n }\n }\n return out as ParserOutput;\n }\n}\n", "import { _defaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport type { MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, TokensList } from './Tokens.ts';\n\nexport class _Hooks {\n options: MarkedOptions;\n block?: boolean;\n\n constructor(options?: MarkedOptions) {\n this.options = options || _defaults;\n }\n\n static passThroughHooks = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n 'emStrongMask',\n ]);\n\n static passThroughHooksRespectAsync = new Set([\n 'preprocess',\n 'postprocess',\n 'processAllTokens',\n ]);\n\n /**\n * Process markdown before marked\n */\n preprocess(markdown: string) {\n return markdown;\n }\n\n /**\n * Process HTML after marked is finished\n */\n postprocess(html: ParserOutput) {\n return html;\n }\n\n /**\n * Process all tokens before walk tokens\n */\n processAllTokens(tokens: Token[] | TokensList) {\n return tokens;\n }\n\n /**\n * Mask contents that should not be interpreted as em/strong delimiters\n */\n emStrongMask(src: string) {\n return src;\n }\n\n /**\n * Provide function to tokenize markdown\n */\n provideLexer() {\n return this.block ? _Lexer.lex : _Lexer.lexInline;\n }\n\n /**\n * Provide function to parse tokens\n */\n provideParser() {\n return this.block ? _Parser.parse : _Parser.parseInline;\n }\n}\n", "import { _getDefaults } from './defaults.ts';\nimport { _Lexer } from './Lexer.ts';\nimport { _Parser } from './Parser.ts';\nimport { _Hooks } from './Hooks.ts';\nimport { _Renderer } from './Renderer.ts';\nimport { _Tokenizer } from './Tokenizer.ts';\nimport { _TextRenderer } from './TextRenderer.ts';\nimport { escape } from './helpers.ts';\nimport type { MarkedExtension, MarkedOptions } from './MarkedOptions.ts';\nimport type { Token, Tokens, TokensList } from './Tokens.ts';\n\nexport type MaybePromise = void | Promise;\n\ntype UnknownFunction = (...args: unknown[]) => unknown;\ntype GenericRendererFunction = (...args: unknown[]) => string | false;\n\nexport class Marked {\n defaults = _getDefaults();\n options = this.setOptions;\n\n parse = this.parseMarkdown(true);\n parseInline = this.parseMarkdown(false);\n\n Parser = _Parser;\n Renderer = _Renderer;\n TextRenderer = _TextRenderer;\n Lexer = _Lexer;\n Tokenizer = _Tokenizer;\n Hooks = _Hooks;\n\n constructor(...args: MarkedExtension[]) {\n this.use(...args);\n }\n\n /**\n * Run callback for every token\n */\n walkTokens(tokens: Token[] | TokensList, callback: (token: Token) => MaybePromise | MaybePromise[]) {\n let values: MaybePromise[] = [];\n for (const token of tokens) {\n values = values.concat(callback.call(this, token));\n switch (token.type) {\n case 'table': {\n const tableToken = token as Tokens.Table;\n for (const cell of tableToken.header) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n for (const row of tableToken.rows) {\n for (const cell of row) {\n values = values.concat(this.walkTokens(cell.tokens, callback));\n }\n }\n break;\n }\n case 'list': {\n const listToken = token as Tokens.List;\n values = values.concat(this.walkTokens(listToken.items, callback));\n break;\n }\n default: {\n const genericToken = token as Tokens.Generic;\n if (this.defaults.extensions?.childTokens?.[genericToken.type]) {\n this.defaults.extensions.childTokens[genericToken.type].forEach((childTokens) => {\n const tokens = genericToken[childTokens].flat(Infinity) as Token[] | TokensList;\n values = values.concat(this.walkTokens(tokens, callback));\n });\n } else if (genericToken.tokens) {\n values = values.concat(this.walkTokens(genericToken.tokens, callback));\n }\n }\n }\n }\n return values;\n }\n\n use(...args: MarkedExtension[]) {\n const extensions: MarkedOptions['extensions'] = this.defaults.extensions || { renderers: {}, childTokens: {} };\n\n args.forEach((pack) => {\n // copy options to new object\n const opts = { ...pack } as MarkedOptions;\n\n // set async to true if it was set to true before\n opts.async = this.defaults.async || opts.async || false;\n\n // ==-- Parse \"addon\" extensions --== //\n if (pack.extensions) {\n pack.extensions.forEach((ext) => {\n if (!ext.name) {\n throw new Error('extension name required');\n }\n if ('renderer' in ext) { // Renderer extensions\n const prevRenderer = extensions.renderers[ext.name];\n if (prevRenderer) {\n // Replace extension with func to run new extension but fall back if false\n extensions.renderers[ext.name] = function(...args) {\n let ret = ext.renderer.apply(this, args);\n if (ret === false) {\n ret = prevRenderer.apply(this, args);\n }\n return ret;\n };\n } else {\n extensions.renderers[ext.name] = ext.renderer;\n }\n }\n if ('tokenizer' in ext) { // Tokenizer Extensions\n if (!ext.level || (ext.level !== 'block' && ext.level !== 'inline')) {\n throw new Error(\"extension level must be 'block' or 'inline'\");\n }\n const extLevel = extensions[ext.level];\n if (extLevel) {\n extLevel.unshift(ext.tokenizer);\n } else {\n extensions[ext.level] = [ext.tokenizer];\n }\n if (ext.start) { // Function to check for start of token\n if (ext.level === 'block') {\n if (extensions.startBlock) {\n extensions.startBlock.push(ext.start);\n } else {\n extensions.startBlock = [ext.start];\n }\n } else if (ext.level === 'inline') {\n if (extensions.startInline) {\n extensions.startInline.push(ext.start);\n } else {\n extensions.startInline = [ext.start];\n }\n }\n }\n }\n if ('childTokens' in ext && ext.childTokens) { // Child tokens to be visited by walkTokens\n extensions.childTokens[ext.name] = ext.childTokens;\n }\n });\n opts.extensions = extensions;\n }\n\n // ==-- Parse \"overwrite\" extensions --== //\n if (pack.renderer) {\n const renderer = this.defaults.renderer || new _Renderer(this.defaults);\n for (const prop in pack.renderer) {\n if (!(prop in renderer)) {\n throw new Error(`renderer '${prop}' does not exist`);\n }\n if (['options', 'parser'].includes(prop)) {\n // ignore options property\n continue;\n }\n const rendererProp = prop as Exclude, 'options' | 'parser'>;\n const rendererFunc = pack.renderer[rendererProp] as GenericRendererFunction;\n const prevRenderer = renderer[rendererProp] as GenericRendererFunction;\n // Replace renderer with func to run extension, but fall back if false\n renderer[rendererProp] = (...args: unknown[]) => {\n let ret = rendererFunc.apply(renderer, args);\n if (ret === false) {\n ret = prevRenderer.apply(renderer, args);\n }\n return (ret || '') as RendererOutput;\n };\n }\n opts.renderer = renderer;\n }\n if (pack.tokenizer) {\n const tokenizer = this.defaults.tokenizer || new _Tokenizer(this.defaults);\n for (const prop in pack.tokenizer) {\n if (!(prop in tokenizer)) {\n throw new Error(`tokenizer '${prop}' does not exist`);\n }\n if (['options', 'rules', 'lexer'].includes(prop)) {\n // ignore options, rules, and lexer properties\n continue;\n }\n const tokenizerProp = prop as Exclude, 'options' | 'rules' | 'lexer'>;\n const tokenizerFunc = pack.tokenizer[tokenizerProp] as UnknownFunction;\n const prevTokenizer = tokenizer[tokenizerProp] as UnknownFunction;\n // Replace tokenizer with func to run extension, but fall back if false\n // @ts-expect-error cannot type tokenizer function dynamically\n tokenizer[tokenizerProp] = (...args: unknown[]) => {\n let ret = tokenizerFunc.apply(tokenizer, args);\n if (ret === false) {\n ret = prevTokenizer.apply(tokenizer, args);\n }\n return ret;\n };\n }\n opts.tokenizer = tokenizer;\n }\n\n // ==-- Parse Hooks extensions --== //\n if (pack.hooks) {\n const hooks = this.defaults.hooks || new _Hooks();\n for (const prop in pack.hooks) {\n if (!(prop in hooks)) {\n throw new Error(`hook '${prop}' does not exist`);\n }\n if (['options', 'block'].includes(prop)) {\n // ignore options and block properties\n continue;\n }\n const hooksProp = prop as Exclude, 'options' | 'block'>;\n const hooksFunc = pack.hooks[hooksProp] as UnknownFunction;\n const prevHook = hooks[hooksProp] as UnknownFunction;\n if (_Hooks.passThroughHooks.has(prop)) {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (arg: unknown) => {\n if (this.defaults.async && _Hooks.passThroughHooksRespectAsync.has(prop)) {\n return (async() => {\n const ret = await hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n })();\n }\n\n const ret = hooksFunc.call(hooks, arg);\n return prevHook.call(hooks, ret);\n };\n } else {\n // @ts-expect-error cannot type hook function dynamically\n hooks[hooksProp] = (...args: unknown[]) => {\n if (this.defaults.async) {\n return (async() => {\n let ret = await hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = await prevHook.apply(hooks, args);\n }\n return ret;\n })();\n }\n\n let ret = hooksFunc.apply(hooks, args);\n if (ret === false) {\n ret = prevHook.apply(hooks, args);\n }\n return ret;\n };\n }\n }\n opts.hooks = hooks;\n }\n\n // ==-- Parse WalkTokens extensions --== //\n if (pack.walkTokens) {\n const walkTokens = this.defaults.walkTokens;\n const packWalktokens = pack.walkTokens;\n opts.walkTokens = function(token) {\n let values: MaybePromise[] = [];\n values.push(packWalktokens.call(this, token));\n if (walkTokens) {\n values = values.concat(walkTokens.call(this, token));\n }\n return values;\n };\n }\n\n this.defaults = { ...this.defaults, ...opts };\n });\n\n return this;\n }\n\n setOptions(opt: MarkedOptions) {\n this.defaults = { ...this.defaults, ...opt };\n return this;\n }\n\n lexer(src: string, options?: MarkedOptions) {\n return _Lexer.lex(src, options ?? this.defaults);\n }\n\n parser(tokens: Token[], options?: MarkedOptions) {\n return _Parser.parse(tokens, options ?? this.defaults);\n }\n\n private parseMarkdown(blockType: boolean) {\n type overloadedParse = {\n (src: string, options: MarkedOptions & { async: true }): Promise;\n (src: string, options: MarkedOptions & { async: false }): ParserOutput;\n (src: string, options?: MarkedOptions | null): ParserOutput | Promise;\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const parse: overloadedParse = (src: string, options?: MarkedOptions | null): any => {\n const origOpt = { ...options };\n const opt = { ...this.defaults, ...origOpt };\n\n const throwError = this.onError(!!opt.silent, !!opt.async);\n\n // throw error if an extension set async to true but parse was called with async: false\n if (this.defaults.async === true && origOpt.async === false) {\n return throwError(new Error('marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.'));\n }\n\n // throw error in case of non string input\n if (typeof src === 'undefined' || src === null) {\n return throwError(new Error('marked(): input parameter is undefined or null'));\n }\n if (typeof src !== 'string') {\n return throwError(new Error('marked(): input parameter is of type '\n + Object.prototype.toString.call(src) + ', string expected'));\n }\n\n if (opt.hooks) {\n opt.hooks.options = opt;\n opt.hooks.block = blockType;\n }\n\n if (opt.async) {\n return (async() => {\n const processedSrc = opt.hooks ? await opt.hooks.preprocess(src) : src;\n const lexer = opt.hooks ? await opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline);\n const tokens = await lexer(processedSrc, opt);\n const processedTokens = opt.hooks ? await opt.hooks.processAllTokens(tokens) : tokens;\n if (opt.walkTokens) {\n await Promise.all(this.walkTokens(processedTokens, opt.walkTokens));\n }\n const parser = opt.hooks ? await opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline);\n const html = await parser(processedTokens, opt);\n return opt.hooks ? await opt.hooks.postprocess(html) : html;\n })().catch(throwError);\n }\n\n try {\n if (opt.hooks) {\n src = opt.hooks.preprocess(src) as string;\n }\n const lexer = opt.hooks ? opt.hooks.provideLexer() : (blockType ? _Lexer.lex : _Lexer.lexInline);\n let tokens = lexer(src, opt);\n if (opt.hooks) {\n tokens = opt.hooks.processAllTokens(tokens);\n }\n if (opt.walkTokens) {\n this.walkTokens(tokens, opt.walkTokens);\n }\n const parser = opt.hooks ? opt.hooks.provideParser() : (blockType ? _Parser.parse : _Parser.parseInline);\n let html = parser(tokens, opt);\n if (opt.hooks) {\n html = opt.hooks.postprocess(html);\n }\n return html;\n } catch(e) {\n return throwError(e as Error);\n }\n };\n\n return parse;\n }\n\n private onError(silent: boolean, async: boolean) {\n return (e: Error): string | Promise => {\n e.message += '\\nPlease report this to https://github.com/markedjs/marked.';\n\n if (silent) {\n const msg = '

    An error occurred:

    '\n          + escape(e.message + '', true)\n          + '
    ';\n if (async) {\n return Promise.resolve(msg);\n }\n return msg;\n }\n\n if (async) {\n return Promise.reject(e);\n }\n throw e;\n };\n }\n}\n"], - "mappings": ";;;;;;;;;;;;mbAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,WAAAE,EAAA,UAAAC,EAAA,WAAAC,EAAA,WAAAC,EAAA,aAAAC,EAAA,iBAAAC,EAAA,cAAAC,EAAA,aAAAC,EAAA,gBAAAC,EAAA,UAAAC,GAAA,WAAAC,EAAA,YAAAC,GAAA,UAAAC,GAAA,gBAAAC,GAAA,WAAAC,GAAA,eAAAC,GAAA,QAAAC,GAAA,eAAAC,KAAA,eAAA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,EAAe,WAAWK,CAAO,EACjCH,EAAO,SAAWF,EAAe,SACjCM,EAAeJ,EAAO,QAAQ,EACvBA,CACT,EAKAA,EAAO,YAAcK,EAErBL,EAAO,SAAWM,EAMlBN,EAAO,IAAM,YAAYO,EAAyB,CAChD,OAAAT,EAAe,IAAI,GAAGS,CAAI,EAC1BP,EAAO,SAAWF,EAAe,SACjCM,EAAeJ,EAAO,QAAQ,EACvBA,CACT,EAMAA,EAAO,WAAa,SAASQ,EAA8BC,EAA2D,CACpH,OAAOX,EAAe,WAAWU,EAAQC,CAAQ,CACnD,EASAT,EAAO,YAAcF,EAAe,YAKpCE,EAAO,OAASU,EAChBV,EAAO,OAASU,EAAQ,MACxBV,EAAO,SAAWW,EAClBX,EAAO,aAAeY,EACtBZ,EAAO,MAAQa,EACfb,EAAO,MAAQa,EAAO,IACtBb,EAAO,UAAYc,EACnBd,EAAO,MAAQe,EACff,EAAO,MAAQA,EAER,IAAMG,GAAUH,EAAO,QACjBgB,GAAahB,EAAO,WACpBiB,GAAMjB,EAAO,IACbkB,GAAalB,EAAO,WACpBmB,GAAcnB,EAAO,YACrBoB,GAAQpB,EACRqB,GAASX,EAAQ,MACjBY,GAAQT,EAAO", - "names": ["marked_exports", "__export", "_Hooks", "_Lexer", "Marked", "_Parser", "_Renderer", "_TextRenderer", "_Tokenizer", "_defaults", "_getDefaults", "lexer", "marked", "options", "parse", "parseInline", "parser", "setOptions", "use", "walkTokens", "__toCommonJS", "_getDefaults", "_defaults", "changeDefaults", "newDefaults", "noopTest", "edit", "regex", "opt", "source", "obj", "name", "val", "valSource", "other", "supportsLookbehind", "bull", "indent", "newline", "blockCode", "fences", "hr", "heading", "bullet", "lheadingCore", "lheading", "lheadingGfm", "_paragraph", "blockText", "_blockLabel", "def", "list", "_tag", "_comment", "html", "paragraph", "blockquote", "blockNormal", "gfmTable", "blockGfm", "blockPedantic", "escape", "inlineCode", "br", "inlineText", "_punctuation", "_punctuationOrSpace", "_notPunctuationOrSpace", "punctuation", "_punctuationGfmStrongEm", "_punctuationOrSpaceGfmStrongEm", "_notPunctuationOrSpaceGfmStrongEm", "blockSkip", "emStrongLDelimCore", "emStrongLDelim", "emStrongLDelimGfm", "emStrongRDelimAstCore", "emStrongRDelimAst", "emStrongRDelimAstGfm", "emStrongRDelimUnd", "anyPunctuation", "autolink", "_inlineComment", "tag", "_inlineLabel", "link", "reflink", "nolink", "reflinkSearch", "_caseInsensitiveProtocol", "inlineNormal", "inlinePedantic", "inlineGfm", "inlineBreaks", "block", "inline", "escapeReplacements", "getEscapeReplacement", "ch", "escape", "html", "encode", "other", "cleanUrl", "href", "other", "splitCells", "tableRow", "count", "row", "match", "offset", "str", "escaped", "curr", "cells", "i", "rtrim", "c", "invert", "l", "suffLen", "currChar", "findClosingBracket", "b", "level", "outputLink", "cap", "link", "raw", "lexer", "rules", "href", "title", "text", "token", "indentCodeCompensation", "matchIndentToCode", "indentToCode", "node", "matchIndentInNode", "indentInNode", "_Tokenizer", "options", "_defaults", "src", "rtrim", "trimmed", "lines", "tokens", "inBlockquote", "currentLines", "i", "currentRaw", "currentText", "top", "lastToken", "oldToken", "newText", "newToken", "bull", "isordered", "list", "itemRegex", "endsWithBlankLine", "endEarly", "itemContents", "line", "t", "nextLine", "blankLine", "indent", "nextBulletRegex", "hrRegex", "fencesBeginRegex", "headingBeginRegex", "htmlBeginRegex", "rawLine", "nextLineWithoutTabs", "istask", "ischecked", "lastItem", "spacers", "hasMultipleLineBreaks", "tag", "headers", "splitCells", "aligns", "rows", "item", "align", "row", "cell", "trimmedUrl", "rtrimSlash", "lastParenIndex", "findClosingBracket", "linkLen", "links", "linkString", "maskedSrc", "prevChar", "match", "lLength", "rDelim", "rLength", "delimTotal", "midDelimTotal", "endReg", "lastCharLength", "hasNonSpaceChars", "hasSpaceCharsOnBothEnds", "prevCapZero", "escaped", "_Lexer", "__Lexer", "options", "_defaults", "_Tokenizer", "rules", "other", "block", "inline", "src", "i", "next", "tokens", "lastParagraphClipped", "token", "extTokenizer", "lastToken", "cutSrc", "startIndex", "tempSrc", "tempStart", "getStartIndex", "errMsg", "maskedSrc", "match", "links", "offset", "keepPrevChar", "prevChar", "_Renderer", "options", "_defaults", "token", "text", "lang", "escaped", "langString", "other", "code", "escape", "tokens", "depth", "ordered", "start", "body", "j", "item", "type", "startAttr", "itemBody", "checkbox", "checked", "header", "cell", "row", "k", "content", "href", "title", "cleanHref", "cleanUrl", "out", "_TextRenderer", "text", "_Parser", "__Parser", "options", "_defaults", "_Renderer", "_TextRenderer", "tokens", "top", "out", "i", "anyToken", "genericToken", "ret", "token", "textToken", "body", "errMsg", "renderer", "_Hooks", "options", "_defaults", "markdown", "html", "tokens", "src", "_Lexer", "_Parser", "Marked", "_getDefaults", "_Parser", "_Renderer", "_TextRenderer", "_Lexer", "_Tokenizer", "_Hooks", "args", "tokens", "callback", "values", "token", "tableToken", "cell", "row", "listToken", "genericToken", "childTokens", "extensions", "pack", "opts", "ext", "prevRenderer", "ret", "extLevel", "renderer", "prop", "rendererProp", "rendererFunc", "tokenizer", "tokenizerProp", "tokenizerFunc", "prevTokenizer", "hooks", "hooksProp", "hooksFunc", "prevHook", "arg", "walkTokens", "packWalktokens", "opt", "src", "options", "blockType", "origOpt", "throwError", "processedSrc", "processedTokens", "html", "e", "silent", "async", "msg", "escape", "markedInstance", "Marked", "marked", "src", "opt", "options", "changeDefaults", "_getDefaults", "_defaults", "args", "tokens", "callback", "_Parser", "_Renderer", "_TextRenderer", "_Lexer", "_Tokenizer", "_Hooks", "setOptions", "use", "walkTokens", "parseInline", "parse", "parser", "lexer"] -} diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/man/marked.1 b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/man/marked.1 deleted file mode 100644 index 10b3a2911..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/man/marked.1 +++ /dev/null @@ -1,113 +0,0 @@ -.TH "MARKED" "1" "November 2025" "16.4.1" -.SH "NAME" -\fBmarked\fR \- a javascript markdown parser -.SH SYNOPSIS -.P -\fBmarked\fP [\fB\-o\fP ] [\fB\-i\fP ] [\fB\-s\fP ] [\fB\-c\fP ] [\fB\-\-help\fP] [\fB\-\-version\fP] [\fB\-\-tokens\fP] [\fB\-\-no\-clobber\fP] [\fB\-\-pedantic\fP] [\fB\-\-gfm\fP] [\fB\-\-breaks\fP] [\fB\-\-no\-etc\.\.\.\fP] [\fB\-\-silent\fP] [filename] -.SH DESCRIPTION -.P -marked is a full\-featured javascript markdown parser, built for speed\. -.br -It also includes multiple GFM features\. -.SH EXAMPLES -.RS 2 -.nf -cat in\.md | marked > out\.html -.fi -.RE -.RS 2 -.nf -echo "hello *world*" | marked -.fi -.RE -.RS 2 -.nf -marked \-o out\.html \-i in\.md \-\-gfm -.fi -.RE -.RS 2 -.nf -marked \-\-output="hello world\.html" \-i in\.md \-\-no\-breaks -.fi -.RE -.SH OPTIONS - -.RS 1 -.IP \(bu 2 -\-o, \-\-output [output file] -.br -Specify file output\. If none is specified, write to stdout\. -.IP \(bu 2 -\-i, \-\-input [input file] -.br -Specify file input, otherwise use last argument as input file\. -.br -If no input file is specified, read from stdin\. -.IP \(bu 2 -\-s, \-\-string [markdown string] -.br -Specify string input instead of a file\. -.IP \(bu 2 -\-c, \-\-config [config file] -.br -Specify config file to use instead of the default \fB~/\.marked\.json\fP or \fB~/\.marked\.js\fP or \fB~/\.marked/index\.js\fP\|\. -.IP \(bu 2 -\-t, \-\-tokens -.br -Output a token list instead of html\. -.IP \(bu 2 -\-n, \-\-no\-clobber -.br -Do not overwrite \fBoutput\fP if it exists\. -.IP \(bu 2 -\-\-pedantic -.br -Conform to obscure parts of markdown\.pl as much as possible\. -.br -Don't fix original markdown bugs\. -.IP \(bu 2 -\-\-gfm -.br -Enable github flavored markdown\. -.IP \(bu 2 -\-\-breaks -.br -Enable GFM line breaks\. Only works with the gfm option\. -.IP \(bu 2 -\-\-no\-breaks, \-no\-etc\.\.\. -.br -The inverse of any of the marked options above\. -.IP \(bu 2 -\-\-silent -.br -Silence error output\. -.IP \(bu 2 -\-h, \-\-help -.br -Display help information\. - -.RE -.SH CONFIGURATION -.P -For configuring and running programmatically\. -.P -Example -.RS 2 -.nf -import { Marked } from 'marked'; -const marked = new Marked({ gfm: true }); -marked\.parse('*foo*'); -.fi -.RE -.SH BUGS -.P -Please report any bugs to https://github.com/markedjs/marked -.SH LICENSE -.P -Copyright (c) 2018+, MarkedJS\. (MIT License) -.br -Copyright (c) 2011\-2018, Christopher Jeffrey\. (MIT License) -.SH SEE ALSO -.P -markdown(1), nodejs(1) - diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/man/marked.1.md b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/man/marked.1.md deleted file mode 100644 index 027551122..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/man/marked.1.md +++ /dev/null @@ -1,93 +0,0 @@ -# marked(1) -- a javascript markdown parser - -## SYNOPSIS - -`marked` [`-o` ] [`-i` ] [`-s` ] [`-c` ] [`--help`] [`--version`] [`--tokens`] [`--no-clobber`] [`--pedantic`] [`--gfm`] [`--breaks`] [`--no-etc...`] [`--silent`] [filename] - -## DESCRIPTION - -marked is a full-featured javascript markdown parser, built for speed. -It also includes multiple GFM features. - -## EXAMPLES - -```sh -cat in.md | marked > out.html -``` - -```sh -echo "hello *world*" | marked -``` - -```sh -marked -o out.html -i in.md --gfm -``` - -```sh -marked --output="hello world.html" -i in.md --no-breaks -``` - -## OPTIONS - -* -o, --output [output file] -Specify file output. If none is specified, write to stdout. - -* -i, --input [input file] -Specify file input, otherwise use last argument as input file. -If no input file is specified, read from stdin. - -* -s, --string [markdown string] -Specify string input instead of a file. - -* -c, --config [config file] -Specify config file to use instead of the default `~/.marked.json` or `~/.marked.js` or `~/.marked/index.js`. - -* -t, --tokens -Output a token list instead of html. - -* -n, --no-clobber -Do not overwrite `output` if it exists. - -* --pedantic -Conform to obscure parts of markdown.pl as much as possible. -Don't fix original markdown bugs. - -* --gfm -Enable github flavored markdown. - -* --breaks -Enable GFM line breaks. Only works with the gfm option. - -* --no-breaks, -no-etc... -The inverse of any of the marked options above. - -* --silent -Silence error output. - -* -h, --help -Display help information. - -## CONFIGURATION - -For configuring and running programmatically. - -Example - -```js -import { Marked } from 'marked'; -const marked = new Marked({ gfm: true }); -marked.parse('*foo*'); -``` - -## BUGS - -Please report any bugs to . - -## LICENSE - -Copyright (c) 2018+, MarkedJS. (MIT License) -Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License) - -## SEE ALSO - -markdown(1), nodejs(1) diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/package.json b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/package.json deleted file mode 100644 index 9c3ba4619..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/@mariozechner/mini-lit/node_modules/marked/package.json +++ /dev/null @@ -1,103 +0,0 @@ -{ - "name": "marked", - "description": "A markdown parser built for speed", - "author": "Christopher Jeffrey", - "version": "16.4.2", - "type": "module", - "main": "./lib/marked.esm.js", - "module": "./lib/marked.esm.js", - "browser": "./lib/marked.umd.js", - "types": "./lib/marked.d.ts", - "bin": { - "marked": "bin/marked.js" - }, - "man": "./man/marked.1", - "files": [ - "bin/", - "lib/", - "man/" - ], - "exports": { - ".": { - "types": "./lib/marked.d.ts", - "default": "./lib/marked.esm.js" - }, - "./bin/marked": "./bin/marked.js", - "./package.json": "./package.json" - }, - "publishConfig": { - "provenance": true - }, - "repository": { - "type": "git", - "url": "git://github.com/markedjs/marked.git" - }, - "homepage": "https://marked.js.org", - "bugs": { - "url": "http://github.com/markedjs/marked/issues" - }, - "license": "MIT", - "keywords": [ - "markdown", - "markup", - "html" - ], - "tags": [ - "markdown", - "markup", - "html" - ], - "devDependencies": { - "@arethetypeswrong/cli": "^0.18.2", - "@markedjs/eslint-config": "^1.0.12", - "@markedjs/testutils": "15.0.11-0", - "@semantic-release/commit-analyzer": "^13.0.1", - "@semantic-release/git": "^10.0.1", - "@semantic-release/github": "^12.0.1", - "@semantic-release/npm": "^13.1.1", - "@semantic-release/release-notes-generator": "^14.1.0", - "cheerio": "1.1.2", - "commonmark": "0.31.2", - "cross-env": "^10.1.0", - "dts-bundle-generator": "^9.5.1", - "esbuild": "^0.25.12", - "esbuild-plugin-umd-wrapper": "^3.0.0", - "eslint": "^9.39.0", - "highlight.js": "^11.11.1", - "markdown-it": "14.1.0", - "marked-highlight": "^2.2.2", - "marked-man": "^2.1.0", - "recheck": "^4.5.0", - "rimraf": "^6.1.0", - "semantic-release": "^25.0.1", - "titleize": "^4.0.0", - "tslib": "^2.8.1", - "typescript": "5.9.3" - }, - "scripts": { - "bench": "npm run build && node test/bench.js", - "build": "npm run build:esbuild && npm run build:types && npm run build:man", - "build:docs": "npm run build && node docs/build.js", - "build:esbuild": "node esbuild.config.js", - "build:man": "marked-man man/marked.1.md > man/marked.1", - "build:reset": "rimraf ./lib ./public", - "build:types": "tsc && dts-bundle-generator --export-referenced-types --project tsconfig.json -o lib/marked.d.ts src/marked.ts", - "lint": "eslint --fix", - "rules": "node test/rules.js", - "test": "npm run build:reset && npm run build:docs && npm run test:specs && npm run test:unit && npm run test:umd && npm run test:cjs && npm run test:types && npm run test:lint", - "test:cjs": "node test/cjs-test.cjs", - "test:lint": "eslint", - "test:only": "npm run build && npm run test:specs:only && npm run test:unit:only", - "test:redos": "node test/recheck.js > vuln.js", - "test:specs:only": "node --test --test-only --test-reporter=spec test/run-spec-tests.js", - "test:specs": "node --test --test-reporter=spec test/run-spec-tests.js", - "test:types": "tsc --project tsconfig-type-test.json && attw -P --entrypoints . --profile esm-only", - "test:umd": "node test/umd-test.js", - "test:unit:only": "node --test --test-only --test-reporter=spec test/unit/*.test.js", - "test:unit": "node --test --test-reporter=spec test/unit/*.test.js", - "test:update": "node test/update-specs.js" - }, - "engines": { - "node": ">= 20" - } -} diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.d.ts b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.d.ts deleted file mode 100644 index 2c2af63a6..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -/* - * @license - * docx-preview - * Released under Apache License 2.0 - * Copyright Volodymyr Baydalka - */ -export interface Options { - inWrapper: boolean; - hideWrapperOnPrint: boolean; - ignoreWidth: boolean; - ignoreHeight: boolean; - ignoreFonts: boolean; - breakPages: boolean; - debug: boolean; - experimental: boolean; - className: string; - trimXmlDeclaration: boolean; - renderHeaders: boolean; - renderFooters: boolean; - renderFootnotes: boolean; - renderEndnotes: boolean; - ignoreLastRenderedPageBreak: boolean; - useBase64URL: boolean; - renderChanges: boolean; - renderComments: boolean; - renderAltChunks: boolean; -} -//stub -export type WordDocument = any; -export declare const defaultOptions: Options; -export declare function parseAsync(data: Blob | any, userOptions?: Partial): Promise; -export declare function renderDocument(document: WordDocument, bodyContainer: HTMLElement, styleContainer?: HTMLElement, userOptions?: Partial): Promise; -export declare function renderAsync(data: Blob | any, bodyContainer: HTMLElement, styleContainer?: HTMLElement, userOptions?: Partial): Promise; diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.js b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.js deleted file mode 100644 index b7a26e98e..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.js +++ /dev/null @@ -1,4000 +0,0 @@ -/* - * @license - * docx-preview - * Released under Apache License 2.0 - * Copyright Volodymyr Baydalka - */ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('jszip')) : - typeof define === 'function' && define.amd ? define(['exports', 'jszip'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.docx = {}, global.JSZip)); -})(this, (function (exports, JSZip) { 'use strict'; - - var RelationshipTypes; - (function (RelationshipTypes) { - RelationshipTypes["OfficeDocument"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"; - RelationshipTypes["FontTable"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable"; - RelationshipTypes["Image"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"; - RelationshipTypes["Numbering"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering"; - RelationshipTypes["Styles"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"; - RelationshipTypes["StylesWithEffects"] = "http://schemas.microsoft.com/office/2007/relationships/stylesWithEffects"; - RelationshipTypes["Theme"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme"; - RelationshipTypes["Settings"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings"; - RelationshipTypes["WebSettings"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings"; - RelationshipTypes["Hyperlink"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"; - RelationshipTypes["Footnotes"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes"; - RelationshipTypes["Endnotes"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes"; - RelationshipTypes["Footer"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer"; - RelationshipTypes["Header"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header"; - RelationshipTypes["ExtendedProperties"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"; - RelationshipTypes["CoreProperties"] = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"; - RelationshipTypes["CustomProperties"] = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/custom-properties"; - RelationshipTypes["Comments"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"; - RelationshipTypes["CommentsExtended"] = "http://schemas.microsoft.com/office/2011/relationships/commentsExtended"; - RelationshipTypes["AltChunk"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk"; - })(RelationshipTypes || (RelationshipTypes = {})); - function parseRelationships(root, xml) { - return xml.elements(root).map(e => ({ - id: xml.attr(e, "Id"), - type: xml.attr(e, "Type"), - target: xml.attr(e, "Target"), - targetMode: xml.attr(e, "TargetMode") - })); - } - - function escapeClassName(className) { - return className?.replace(/[ .]+/g, '-').replace(/[&]+/g, 'and').toLowerCase(); - } - function encloseFontFamily(fontFamily) { - return /^[^"'].*\s.*[^"']$/.test(fontFamily) ? `'${fontFamily}'` : fontFamily; - } - function splitPath(path) { - let si = path.lastIndexOf('/') + 1; - let folder = si == 0 ? "" : path.substring(0, si); - let fileName = si == 0 ? path : path.substring(si); - return [folder, fileName]; - } - function resolvePath(path, base) { - try { - const prefix = "http://docx/"; - const url = new URL(path, prefix + base).toString(); - return url.substring(prefix.length); - } - catch { - return `${base}${path}`; - } - } - function keyBy(array, by) { - return array.reduce((a, x) => { - a[by(x)] = x; - return a; - }, {}); - } - function blobToBase64(blob) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onloadend = () => resolve(reader.result); - reader.onerror = () => reject(); - reader.readAsDataURL(blob); - }); - } - function isObject(item) { - return item && typeof item === 'object' && !Array.isArray(item); - } - function isString(item) { - return typeof item === 'string' || item instanceof String; - } - function mergeDeep(target, ...sources) { - if (!sources.length) - return target; - const source = sources.shift(); - if (isObject(target) && isObject(source)) { - for (const key in source) { - if (isObject(source[key])) { - const val = target[key] ?? (target[key] = {}); - mergeDeep(val, source[key]); - } - else { - target[key] = source[key]; - } - } - } - return mergeDeep(target, ...sources); - } - function asArray(val) { - return Array.isArray(val) ? val : [val]; - } - function clamp(val, min, max) { - return min > val ? min : (max < val ? max : val); - } - - const ns$1 = { - wordml: "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}; - const LengthUsage = { - Dxa: { mul: 0.05, unit: "pt" }, - Emu: { mul: 1 / 12700, unit: "pt" }, - FontSize: { mul: 0.5, unit: "pt" }, - Border: { mul: 0.125, unit: "pt", min: 0.25, max: 12 }, - Point: { mul: 1, unit: "pt" }, - Percent: { mul: 0.02, unit: "%" }}; - function convertLength(val, usage = LengthUsage.Dxa) { - if (val == null || /.+(p[xt]|[%])$/.test(val)) { - return val; - } - var num = parseInt(val) * usage.mul; - if (usage.min && usage.max) - num = clamp(num, usage.min, usage.max); - return `${num.toFixed(2)}${usage.unit}`; - } - function convertBoolean(v, defaultValue = false) { - switch (v) { - case "1": return true; - case "0": return false; - case "on": return true; - case "off": return false; - case "true": return true; - case "false": return false; - default: return defaultValue; - } - } - function parseCommonProperty(elem, props, xml) { - if (elem.namespaceURI != ns$1.wordml) - return false; - switch (elem.localName) { - case "color": - props.color = xml.attr(elem, "val"); - break; - case "sz": - props.fontSize = xml.lengthAttr(elem, "val", LengthUsage.FontSize); - break; - default: - return false; - } - return true; - } - - function parseXmlString(xmlString, trimXmlDeclaration = false) { - if (trimXmlDeclaration) - xmlString = xmlString.replace(/<[?].*[?]>/, ""); - xmlString = removeUTF8BOM(xmlString); - const result = new DOMParser().parseFromString(xmlString, "application/xml"); - const errorText = hasXmlParserError(result); - if (errorText) - throw new Error(errorText); - return result; - } - function hasXmlParserError(doc) { - return doc.getElementsByTagName("parsererror")[0]?.textContent; - } - function removeUTF8BOM(data) { - return data.charCodeAt(0) === 0xFEFF ? data.substring(1) : data; - } - function serializeXmlString(elem) { - return new XMLSerializer().serializeToString(elem); - } - class XmlParser { - elements(elem, localName = null) { - const result = []; - for (let i = 0, l = elem.childNodes.length; i < l; i++) { - let c = elem.childNodes.item(i); - if (c.nodeType == Node.ELEMENT_NODE && (localName == null || c.localName == localName)) - result.push(c); - } - return result; - } - element(elem, localName) { - for (let i = 0, l = elem.childNodes.length; i < l; i++) { - let c = elem.childNodes.item(i); - if (c.nodeType == 1 && c.localName == localName) - return c; - } - return null; - } - elementAttr(elem, localName, attrLocalName) { - var el = this.element(elem, localName); - return el ? this.attr(el, attrLocalName) : undefined; - } - attrs(elem) { - return Array.from(elem.attributes); - } - attr(elem, localName) { - for (let i = 0, l = elem.attributes.length; i < l; i++) { - let a = elem.attributes.item(i); - if (a.localName == localName) - return a.value; - } - return null; - } - intAttr(node, attrName, defaultValue = null) { - var val = this.attr(node, attrName); - return val ? parseInt(val) : defaultValue; - } - hexAttr(node, attrName, defaultValue = null) { - var val = this.attr(node, attrName); - return val ? parseInt(val, 16) : defaultValue; - } - floatAttr(node, attrName, defaultValue = null) { - var val = this.attr(node, attrName); - return val ? parseFloat(val) : defaultValue; - } - boolAttr(node, attrName, defaultValue = null) { - return convertBoolean(this.attr(node, attrName), defaultValue); - } - lengthAttr(node, attrName, usage = LengthUsage.Dxa) { - return convertLength(this.attr(node, attrName), usage); - } - } - const globalXmlParser = new XmlParser(); - - class Part { - constructor(_package, path) { - this._package = _package; - this.path = path; - } - async load() { - this.rels = await this._package.loadRelationships(this.path); - const xmlText = await this._package.load(this.path); - const xmlDoc = this._package.parseXmlDocument(xmlText); - if (this._package.options.keepOrigin) { - this._xmlDocument = xmlDoc; - } - this.parseXml(xmlDoc.firstElementChild); - } - save() { - this._package.update(this.path, serializeXmlString(this._xmlDocument)); - } - parseXml(root) { - } - } - - const embedFontTypeMap = { - embedRegular: 'regular', - embedBold: 'bold', - embedItalic: 'italic', - embedBoldItalic: 'boldItalic', - }; - function parseFonts(root, xml) { - return xml.elements(root).map(el => parseFont(el, xml)); - } - function parseFont(elem, xml) { - let result = { - name: xml.attr(elem, "name"), - embedFontRefs: [] - }; - for (let el of xml.elements(elem)) { - switch (el.localName) { - case "family": - result.family = xml.attr(el, "val"); - break; - case "altName": - result.altName = xml.attr(el, "val"); - break; - case "embedRegular": - case "embedBold": - case "embedItalic": - case "embedBoldItalic": - result.embedFontRefs.push(parseEmbedFontRef(el, xml)); - break; - } - } - return result; - } - function parseEmbedFontRef(elem, xml) { - return { - id: xml.attr(elem, "id"), - key: xml.attr(elem, "fontKey"), - type: embedFontTypeMap[elem.localName] - }; - } - - class FontTablePart extends Part { - parseXml(root) { - this.fonts = parseFonts(root, this._package.xmlParser); - } - } - - class OpenXmlPackage { - constructor(_zip, options) { - this._zip = _zip; - this.options = options; - this.xmlParser = new XmlParser(); - } - get(path) { - const p = normalizePath(path); - return this._zip.files[p] ?? this._zip.files[p.replace(/\//g, '\\')]; - } - update(path, content) { - this._zip.file(path, content); - } - static async load(input, options) { - const zip = await JSZip.loadAsync(input); - return new OpenXmlPackage(zip, options); - } - save(type = "blob") { - return this._zip.generateAsync({ type }); - } - load(path, type = "string") { - return this.get(path)?.async(type) ?? Promise.resolve(null); - } - async loadRelationships(path = null) { - let relsPath = `_rels/.rels`; - if (path != null) { - const [f, fn] = splitPath(path); - relsPath = `${f}_rels/${fn}.rels`; - } - const txt = await this.load(relsPath); - return txt ? parseRelationships(this.parseXmlDocument(txt).firstElementChild, this.xmlParser) : null; - } - parseXmlDocument(txt) { - return parseXmlString(txt, this.options.trimXmlDeclaration); - } - } - function normalizePath(path) { - return path.startsWith('/') ? path.substr(1) : path; - } - - class DocumentPart extends Part { - constructor(pkg, path, parser) { - super(pkg, path); - this._documentParser = parser; - } - parseXml(root) { - this.body = this._documentParser.parseDocumentFile(root); - } - } - - function parseBorder(elem, xml) { - return { - type: xml.attr(elem, "val"), - color: xml.attr(elem, "color"), - size: xml.lengthAttr(elem, "sz", LengthUsage.Border), - offset: xml.lengthAttr(elem, "space", LengthUsage.Point), - frame: xml.boolAttr(elem, 'frame'), - shadow: xml.boolAttr(elem, 'shadow') - }; - } - function parseBorders(elem, xml) { - var result = {}; - for (let e of xml.elements(elem)) { - switch (e.localName) { - case "left": - result.left = parseBorder(e, xml); - break; - case "top": - result.top = parseBorder(e, xml); - break; - case "right": - result.right = parseBorder(e, xml); - break; - case "bottom": - result.bottom = parseBorder(e, xml); - break; - } - } - return result; - } - - var SectionType; - (function (SectionType) { - SectionType["Continuous"] = "continuous"; - SectionType["NextPage"] = "nextPage"; - SectionType["NextColumn"] = "nextColumn"; - SectionType["EvenPage"] = "evenPage"; - SectionType["OddPage"] = "oddPage"; - })(SectionType || (SectionType = {})); - function parseSectionProperties(elem, xml = globalXmlParser) { - var section = {}; - for (let e of xml.elements(elem)) { - switch (e.localName) { - case "pgSz": - section.pageSize = { - width: xml.lengthAttr(e, "w"), - height: xml.lengthAttr(e, "h"), - orientation: xml.attr(e, "orient") - }; - break; - case "type": - section.type = xml.attr(e, "val"); - break; - case "pgMar": - section.pageMargins = { - left: xml.lengthAttr(e, "left"), - right: xml.lengthAttr(e, "right"), - top: xml.lengthAttr(e, "top"), - bottom: xml.lengthAttr(e, "bottom"), - header: xml.lengthAttr(e, "header"), - footer: xml.lengthAttr(e, "footer"), - gutter: xml.lengthAttr(e, "gutter"), - }; - break; - case "cols": - section.columns = parseColumns(e, xml); - break; - case "headerReference": - (section.headerRefs ?? (section.headerRefs = [])).push(parseFooterHeaderReference(e, xml)); - break; - case "footerReference": - (section.footerRefs ?? (section.footerRefs = [])).push(parseFooterHeaderReference(e, xml)); - break; - case "titlePg": - section.titlePage = xml.boolAttr(e, "val", true); - break; - case "pgBorders": - section.pageBorders = parseBorders(e, xml); - break; - case "pgNumType": - section.pageNumber = parsePageNumber(e, xml); - break; - } - } - return section; - } - function parseColumns(elem, xml) { - return { - numberOfColumns: xml.intAttr(elem, "num"), - space: xml.lengthAttr(elem, "space"), - separator: xml.boolAttr(elem, "sep"), - equalWidth: xml.boolAttr(elem, "equalWidth", true), - columns: xml.elements(elem, "col") - .map(e => ({ - width: xml.lengthAttr(e, "w"), - space: xml.lengthAttr(e, "space") - })) - }; - } - function parsePageNumber(elem, xml) { - return { - chapSep: xml.attr(elem, "chapSep"), - chapStyle: xml.attr(elem, "chapStyle"), - format: xml.attr(elem, "fmt"), - start: xml.intAttr(elem, "start") - }; - } - function parseFooterHeaderReference(elem, xml) { - return { - id: xml.attr(elem, "id"), - type: xml.attr(elem, "type"), - }; - } - - function parseLineSpacing(elem, xml) { - return { - before: xml.lengthAttr(elem, "before"), - after: xml.lengthAttr(elem, "after"), - line: xml.intAttr(elem, "line"), - lineRule: xml.attr(elem, "lineRule") - }; - } - - function parseRunProperties(elem, xml) { - let result = {}; - for (let el of xml.elements(elem)) { - parseRunProperty(el, result, xml); - } - return result; - } - function parseRunProperty(elem, props, xml) { - if (parseCommonProperty(elem, props, xml)) - return true; - return false; - } - - function parseParagraphProperties(elem, xml) { - let result = {}; - for (let el of xml.elements(elem)) { - parseParagraphProperty(el, result, xml); - } - return result; - } - function parseParagraphProperty(elem, props, xml) { - if (elem.namespaceURI != ns$1.wordml) - return false; - if (parseCommonProperty(elem, props, xml)) - return true; - switch (elem.localName) { - case "tabs": - props.tabs = parseTabs(elem, xml); - break; - case "sectPr": - props.sectionProps = parseSectionProperties(elem, xml); - break; - case "numPr": - props.numbering = parseNumbering$1(elem, xml); - break; - case "spacing": - props.lineSpacing = parseLineSpacing(elem, xml); - return false; - case "textAlignment": - props.textAlignment = xml.attr(elem, "val"); - return false; - case "keepLines": - props.keepLines = xml.boolAttr(elem, "val", true); - break; - case "keepNext": - props.keepNext = xml.boolAttr(elem, "val", true); - break; - case "pageBreakBefore": - props.pageBreakBefore = xml.boolAttr(elem, "val", true); - break; - case "outlineLvl": - props.outlineLevel = xml.intAttr(elem, "val"); - break; - case "pStyle": - props.styleName = xml.attr(elem, "val"); - break; - case "rPr": - props.runProps = parseRunProperties(elem, xml); - break; - default: - return false; - } - return true; - } - function parseTabs(elem, xml) { - return xml.elements(elem, "tab") - .map(e => ({ - position: xml.lengthAttr(e, "pos"), - leader: xml.attr(e, "leader"), - style: xml.attr(e, "val") - })); - } - function parseNumbering$1(elem, xml) { - var result = {}; - for (let e of xml.elements(elem)) { - switch (e.localName) { - case "numId": - result.id = xml.attr(e, "val"); - break; - case "ilvl": - result.level = xml.intAttr(e, "val"); - break; - } - } - return result; - } - - function parseNumberingPart(elem, xml) { - let result = { - numberings: [], - abstractNumberings: [], - bulletPictures: [] - }; - for (let e of xml.elements(elem)) { - switch (e.localName) { - case "num": - result.numberings.push(parseNumbering(e, xml)); - break; - case "abstractNum": - result.abstractNumberings.push(parseAbstractNumbering(e, xml)); - break; - case "numPicBullet": - result.bulletPictures.push(parseNumberingBulletPicture(e, xml)); - break; - } - } - return result; - } - function parseNumbering(elem, xml) { - let result = { - id: xml.attr(elem, 'numId'), - overrides: [] - }; - for (let e of xml.elements(elem)) { - switch (e.localName) { - case "abstractNumId": - result.abstractId = xml.attr(e, "val"); - break; - case "lvlOverride": - result.overrides.push(parseNumberingLevelOverrride(e, xml)); - break; - } - } - return result; - } - function parseAbstractNumbering(elem, xml) { - let result = { - id: xml.attr(elem, 'abstractNumId'), - levels: [] - }; - for (let e of xml.elements(elem)) { - switch (e.localName) { - case "name": - result.name = xml.attr(e, "val"); - break; - case "multiLevelType": - result.multiLevelType = xml.attr(e, "val"); - break; - case "numStyleLink": - result.numberingStyleLink = xml.attr(e, "val"); - break; - case "styleLink": - result.styleLink = xml.attr(e, "val"); - break; - case "lvl": - result.levels.push(parseNumberingLevel(e, xml)); - break; - } - } - return result; - } - function parseNumberingLevel(elem, xml) { - let result = { - level: xml.intAttr(elem, 'ilvl') - }; - for (let e of xml.elements(elem)) { - switch (e.localName) { - case "start": - result.start = xml.attr(e, "val"); - break; - case "lvlRestart": - result.restart = xml.intAttr(e, "val"); - break; - case "numFmt": - result.format = xml.attr(e, "val"); - break; - case "lvlText": - result.text = xml.attr(e, "val"); - break; - case "lvlJc": - result.justification = xml.attr(e, "val"); - break; - case "lvlPicBulletId": - result.bulletPictureId = xml.attr(e, "val"); - break; - case "pStyle": - result.paragraphStyle = xml.attr(e, "val"); - break; - case "pPr": - result.paragraphProps = parseParagraphProperties(e, xml); - break; - case "rPr": - result.runProps = parseRunProperties(e, xml); - break; - } - } - return result; - } - function parseNumberingLevelOverrride(elem, xml) { - let result = { - level: xml.intAttr(elem, 'ilvl') - }; - for (let e of xml.elements(elem)) { - switch (e.localName) { - case "startOverride": - result.start = xml.intAttr(e, "val"); - break; - case "lvl": - result.numberingLevel = parseNumberingLevel(e, xml); - break; - } - } - return result; - } - function parseNumberingBulletPicture(elem, xml) { - var pict = xml.element(elem, "pict"); - var shape = pict && xml.element(pict, "shape"); - var imagedata = shape && xml.element(shape, "imagedata"); - return imagedata ? { - id: xml.attr(elem, "numPicBulletId"), - referenceId: xml.attr(imagedata, "id"), - style: xml.attr(shape, "style") - } : null; - } - - class NumberingPart extends Part { - constructor(pkg, path, parser) { - super(pkg, path); - this._documentParser = parser; - } - parseXml(root) { - Object.assign(this, parseNumberingPart(root, this._package.xmlParser)); - this.domNumberings = this._documentParser.parseNumberingFile(root); - } - } - - class StylesPart extends Part { - constructor(pkg, path, parser) { - super(pkg, path); - this._documentParser = parser; - } - parseXml(root) { - this.styles = this._documentParser.parseStylesFile(root); - } - } - - var DomType; - (function (DomType) { - DomType["Document"] = "document"; - DomType["Paragraph"] = "paragraph"; - DomType["Run"] = "run"; - DomType["Break"] = "break"; - DomType["NoBreakHyphen"] = "noBreakHyphen"; - DomType["Table"] = "table"; - DomType["Row"] = "row"; - DomType["Cell"] = "cell"; - DomType["Hyperlink"] = "hyperlink"; - DomType["SmartTag"] = "smartTag"; - DomType["Drawing"] = "drawing"; - DomType["Image"] = "image"; - DomType["Text"] = "text"; - DomType["Tab"] = "tab"; - DomType["Symbol"] = "symbol"; - DomType["BookmarkStart"] = "bookmarkStart"; - DomType["BookmarkEnd"] = "bookmarkEnd"; - DomType["Footer"] = "footer"; - DomType["Header"] = "header"; - DomType["FootnoteReference"] = "footnoteReference"; - DomType["EndnoteReference"] = "endnoteReference"; - DomType["Footnote"] = "footnote"; - DomType["Endnote"] = "endnote"; - DomType["SimpleField"] = "simpleField"; - DomType["ComplexField"] = "complexField"; - DomType["Instruction"] = "instruction"; - DomType["VmlPicture"] = "vmlPicture"; - DomType["MmlMath"] = "mmlMath"; - DomType["MmlMathParagraph"] = "mmlMathParagraph"; - DomType["MmlFraction"] = "mmlFraction"; - DomType["MmlFunction"] = "mmlFunction"; - DomType["MmlFunctionName"] = "mmlFunctionName"; - DomType["MmlNumerator"] = "mmlNumerator"; - DomType["MmlDenominator"] = "mmlDenominator"; - DomType["MmlRadical"] = "mmlRadical"; - DomType["MmlBase"] = "mmlBase"; - DomType["MmlDegree"] = "mmlDegree"; - DomType["MmlSuperscript"] = "mmlSuperscript"; - DomType["MmlSubscript"] = "mmlSubscript"; - DomType["MmlPreSubSuper"] = "mmlPreSubSuper"; - DomType["MmlSubArgument"] = "mmlSubArgument"; - DomType["MmlSuperArgument"] = "mmlSuperArgument"; - DomType["MmlNary"] = "mmlNary"; - DomType["MmlDelimiter"] = "mmlDelimiter"; - DomType["MmlRun"] = "mmlRun"; - DomType["MmlEquationArray"] = "mmlEquationArray"; - DomType["MmlLimit"] = "mmlLimit"; - DomType["MmlLimitLower"] = "mmlLimitLower"; - DomType["MmlMatrix"] = "mmlMatrix"; - DomType["MmlMatrixRow"] = "mmlMatrixRow"; - DomType["MmlBox"] = "mmlBox"; - DomType["MmlBar"] = "mmlBar"; - DomType["MmlGroupChar"] = "mmlGroupChar"; - DomType["VmlElement"] = "vmlElement"; - DomType["Inserted"] = "inserted"; - DomType["Deleted"] = "deleted"; - DomType["DeletedText"] = "deletedText"; - DomType["Comment"] = "comment"; - DomType["CommentReference"] = "commentReference"; - DomType["CommentRangeStart"] = "commentRangeStart"; - DomType["CommentRangeEnd"] = "commentRangeEnd"; - DomType["AltChunk"] = "altChunk"; - })(DomType || (DomType = {})); - class OpenXmlElementBase { - constructor() { - this.children = []; - this.cssStyle = {}; - } - } - - class WmlHeader extends OpenXmlElementBase { - constructor() { - super(...arguments); - this.type = DomType.Header; - } - } - class WmlFooter extends OpenXmlElementBase { - constructor() { - super(...arguments); - this.type = DomType.Footer; - } - } - - class BaseHeaderFooterPart extends Part { - constructor(pkg, path, parser) { - super(pkg, path); - this._documentParser = parser; - } - parseXml(root) { - this.rootElement = this.createRootElement(); - this.rootElement.children = this._documentParser.parseBodyElements(root); - } - } - class HeaderPart extends BaseHeaderFooterPart { - createRootElement() { - return new WmlHeader(); - } - } - class FooterPart extends BaseHeaderFooterPart { - createRootElement() { - return new WmlFooter(); - } - } - - function parseExtendedProps(root, xmlParser) { - const result = {}; - for (let el of xmlParser.elements(root)) { - switch (el.localName) { - case "Template": - result.template = el.textContent; - break; - case "Pages": - result.pages = safeParseToInt(el.textContent); - break; - case "Words": - result.words = safeParseToInt(el.textContent); - break; - case "Characters": - result.characters = safeParseToInt(el.textContent); - break; - case "Application": - result.application = el.textContent; - break; - case "Lines": - result.lines = safeParseToInt(el.textContent); - break; - case "Paragraphs": - result.paragraphs = safeParseToInt(el.textContent); - break; - case "Company": - result.company = el.textContent; - break; - case "AppVersion": - result.appVersion = el.textContent; - break; - } - } - return result; - } - function safeParseToInt(value) { - if (typeof value === 'undefined') - return; - return parseInt(value); - } - - class ExtendedPropsPart extends Part { - parseXml(root) { - this.props = parseExtendedProps(root, this._package.xmlParser); - } - } - - function parseCoreProps(root, xmlParser) { - const result = {}; - for (let el of xmlParser.elements(root)) { - switch (el.localName) { - case "title": - result.title = el.textContent; - break; - case "description": - result.description = el.textContent; - break; - case "subject": - result.subject = el.textContent; - break; - case "creator": - result.creator = el.textContent; - break; - case "keywords": - result.keywords = el.textContent; - break; - case "language": - result.language = el.textContent; - break; - case "lastModifiedBy": - result.lastModifiedBy = el.textContent; - break; - case "revision": - el.textContent && (result.revision = parseInt(el.textContent)); - break; - } - } - return result; - } - - class CorePropsPart extends Part { - parseXml(root) { - this.props = parseCoreProps(root, this._package.xmlParser); - } - } - - class DmlTheme { - } - function parseTheme(elem, xml) { - var result = new DmlTheme(); - var themeElements = xml.element(elem, "themeElements"); - for (let el of xml.elements(themeElements)) { - switch (el.localName) { - case "clrScheme": - result.colorScheme = parseColorScheme(el, xml); - break; - case "fontScheme": - result.fontScheme = parseFontScheme(el, xml); - break; - } - } - return result; - } - function parseColorScheme(elem, xml) { - var result = { - name: xml.attr(elem, "name"), - colors: {} - }; - for (let el of xml.elements(elem)) { - var srgbClr = xml.element(el, "srgbClr"); - var sysClr = xml.element(el, "sysClr"); - if (srgbClr) { - result.colors[el.localName] = xml.attr(srgbClr, "val"); - } - else if (sysClr) { - result.colors[el.localName] = xml.attr(sysClr, "lastClr"); - } - } - return result; - } - function parseFontScheme(elem, xml) { - var result = { - name: xml.attr(elem, "name"), - }; - for (let el of xml.elements(elem)) { - switch (el.localName) { - case "majorFont": - result.majorFont = parseFontInfo(el, xml); - break; - case "minorFont": - result.minorFont = parseFontInfo(el, xml); - break; - } - } - return result; - } - function parseFontInfo(elem, xml) { - return { - latinTypeface: xml.elementAttr(elem, "latin", "typeface"), - eaTypeface: xml.elementAttr(elem, "ea", "typeface"), - csTypeface: xml.elementAttr(elem, "cs", "typeface"), - }; - } - - class ThemePart extends Part { - constructor(pkg, path) { - super(pkg, path); - } - parseXml(root) { - this.theme = parseTheme(root, this._package.xmlParser); - } - } - - class WmlBaseNote { - } - class WmlFootnote extends WmlBaseNote { - constructor() { - super(...arguments); - this.type = DomType.Footnote; - } - } - class WmlEndnote extends WmlBaseNote { - constructor() { - super(...arguments); - this.type = DomType.Endnote; - } - } - - class BaseNotePart extends Part { - constructor(pkg, path, parser) { - super(pkg, path); - this._documentParser = parser; - } - } - class FootnotesPart extends BaseNotePart { - constructor(pkg, path, parser) { - super(pkg, path, parser); - } - parseXml(root) { - this.notes = this._documentParser.parseNotes(root, "footnote", WmlFootnote); - } - } - class EndnotesPart extends BaseNotePart { - constructor(pkg, path, parser) { - super(pkg, path, parser); - } - parseXml(root) { - this.notes = this._documentParser.parseNotes(root, "endnote", WmlEndnote); - } - } - - function parseSettings(elem, xml) { - var result = {}; - for (let el of xml.elements(elem)) { - switch (el.localName) { - case "defaultTabStop": - result.defaultTabStop = xml.lengthAttr(el, "val"); - break; - case "footnotePr": - result.footnoteProps = parseNoteProperties(el, xml); - break; - case "endnotePr": - result.endnoteProps = parseNoteProperties(el, xml); - break; - case "autoHyphenation": - result.autoHyphenation = xml.boolAttr(el, "val"); - break; - } - } - return result; - } - function parseNoteProperties(elem, xml) { - var result = { - defaultNoteIds: [] - }; - for (let el of xml.elements(elem)) { - switch (el.localName) { - case "numFmt": - result.nummeringFormat = xml.attr(el, "val"); - break; - case "footnote": - case "endnote": - result.defaultNoteIds.push(xml.attr(el, "id")); - break; - } - } - return result; - } - - class SettingsPart extends Part { - constructor(pkg, path) { - super(pkg, path); - } - parseXml(root) { - this.settings = parseSettings(root, this._package.xmlParser); - } - } - - function parseCustomProps(root, xml) { - return xml.elements(root, "property").map(e => { - const firstChild = e.firstChild; - return { - formatId: xml.attr(e, "fmtid"), - name: xml.attr(e, "name"), - type: firstChild.nodeName, - value: firstChild.textContent - }; - }); - } - - class CustomPropsPart extends Part { - parseXml(root) { - this.props = parseCustomProps(root, this._package.xmlParser); - } - } - - class CommentsPart extends Part { - constructor(pkg, path, parser) { - super(pkg, path); - this._documentParser = parser; - } - parseXml(root) { - this.comments = this._documentParser.parseComments(root); - this.commentMap = keyBy(this.comments, x => x.id); - } - } - - class CommentsExtendedPart extends Part { - constructor(pkg, path) { - super(pkg, path); - this.comments = []; - } - parseXml(root) { - const xml = this._package.xmlParser; - for (let el of xml.elements(root, "commentEx")) { - this.comments.push({ - paraId: xml.attr(el, 'paraId'), - paraIdParent: xml.attr(el, 'paraIdParent'), - done: xml.boolAttr(el, 'done') - }); - } - this.commentMap = keyBy(this.comments, x => x.paraId); - } - } - - const topLevelRels = [ - { type: RelationshipTypes.OfficeDocument, target: "word/document.xml" }, - { type: RelationshipTypes.ExtendedProperties, target: "docProps/app.xml" }, - { type: RelationshipTypes.CoreProperties, target: "docProps/core.xml" }, - { type: RelationshipTypes.CustomProperties, target: "docProps/custom.xml" }, - ]; - class WordDocument { - constructor() { - this.parts = []; - this.partsMap = {}; - } - static async load(blob, parser, options) { - var d = new WordDocument(); - d._options = options; - d._parser = parser; - d._package = await OpenXmlPackage.load(blob, options); - d.rels = await d._package.loadRelationships(); - await Promise.all(topLevelRels.map(rel => { - const r = d.rels.find(x => x.type === rel.type) ?? rel; - return d.loadRelationshipPart(r.target, r.type); - })); - return d; - } - save(type = "blob") { - return this._package.save(type); - } - async loadRelationshipPart(path, type) { - if (this.partsMap[path]) - return this.partsMap[path]; - if (!this._package.get(path)) - return null; - let part = null; - switch (type) { - case RelationshipTypes.OfficeDocument: - this.documentPart = part = new DocumentPart(this._package, path, this._parser); - break; - case RelationshipTypes.FontTable: - this.fontTablePart = part = new FontTablePart(this._package, path); - break; - case RelationshipTypes.Numbering: - this.numberingPart = part = new NumberingPart(this._package, path, this._parser); - break; - case RelationshipTypes.Styles: - this.stylesPart = part = new StylesPart(this._package, path, this._parser); - break; - case RelationshipTypes.Theme: - this.themePart = part = new ThemePart(this._package, path); - break; - case RelationshipTypes.Footnotes: - this.footnotesPart = part = new FootnotesPart(this._package, path, this._parser); - break; - case RelationshipTypes.Endnotes: - this.endnotesPart = part = new EndnotesPart(this._package, path, this._parser); - break; - case RelationshipTypes.Footer: - part = new FooterPart(this._package, path, this._parser); - break; - case RelationshipTypes.Header: - part = new HeaderPart(this._package, path, this._parser); - break; - case RelationshipTypes.CoreProperties: - this.corePropsPart = part = new CorePropsPart(this._package, path); - break; - case RelationshipTypes.ExtendedProperties: - this.extendedPropsPart = part = new ExtendedPropsPart(this._package, path); - break; - case RelationshipTypes.CustomProperties: - part = new CustomPropsPart(this._package, path); - break; - case RelationshipTypes.Settings: - this.settingsPart = part = new SettingsPart(this._package, path); - break; - case RelationshipTypes.Comments: - this.commentsPart = part = new CommentsPart(this._package, path, this._parser); - break; - case RelationshipTypes.CommentsExtended: - this.commentsExtendedPart = part = new CommentsExtendedPart(this._package, path); - break; - } - if (part == null) - return Promise.resolve(null); - this.partsMap[path] = part; - this.parts.push(part); - await part.load(); - if (part.rels?.length > 0) { - const [folder] = splitPath(part.path); - await Promise.all(part.rels.map(rel => this.loadRelationshipPart(resolvePath(rel.target, folder), rel.type))); - } - return part; - } - async loadDocumentImage(id, part) { - const x = await this.loadResource(part ?? this.documentPart, id, "blob"); - return this.blobToURL(x); - } - async loadNumberingImage(id) { - const x = await this.loadResource(this.numberingPart, id, "blob"); - return this.blobToURL(x); - } - async loadFont(id, key) { - const x = await this.loadResource(this.fontTablePart, id, "uint8array"); - return x ? this.blobToURL(new Blob([deobfuscate(x, key)])) : x; - } - async loadAltChunk(id, part) { - return await this.loadResource(part ?? this.documentPart, id, "string"); - } - blobToURL(blob) { - if (!blob) - return null; - if (this._options.useBase64URL) { - return blobToBase64(blob); - } - return URL.createObjectURL(blob); - } - findPartByRelId(id, basePart = null) { - var rel = (basePart.rels ?? this.rels).find(r => r.id == id); - const folder = basePart ? splitPath(basePart.path)[0] : ''; - return rel ? this.partsMap[resolvePath(rel.target, folder)] : null; - } - getPathById(part, id) { - const rel = part.rels.find(x => x.id == id); - const [folder] = splitPath(part.path); - return rel ? resolvePath(rel.target, folder) : null; - } - loadResource(part, id, outputType) { - const path = this.getPathById(part, id); - return path ? this._package.load(path, outputType) : Promise.resolve(null); - } - } - function deobfuscate(data, guidKey) { - const len = 16; - const trimmed = guidKey.replace(/{|}|-/g, ""); - const numbers = new Array(len); - for (let i = 0; i < len; i++) - numbers[len - i - 1] = parseInt(trimmed.substring(i * 2, i * 2 + 2), 16); - for (let i = 0; i < 32; i++) - data[i] = data[i] ^ numbers[i % len]; - return data; - } - - function parseBookmarkStart(elem, xml) { - return { - type: DomType.BookmarkStart, - id: xml.attr(elem, "id"), - name: xml.attr(elem, "name"), - colFirst: xml.intAttr(elem, "colFirst"), - colLast: xml.intAttr(elem, "colLast") - }; - } - function parseBookmarkEnd(elem, xml) { - return { - type: DomType.BookmarkEnd, - id: xml.attr(elem, "id") - }; - } - - class VmlElement extends OpenXmlElementBase { - constructor() { - super(...arguments); - this.type = DomType.VmlElement; - this.attrs = {}; - } - } - function parseVmlElement(elem, parser) { - var result = new VmlElement(); - switch (elem.localName) { - case "rect": - result.tagName = "rect"; - Object.assign(result.attrs, { width: '100%', height: '100%' }); - break; - case "oval": - result.tagName = "ellipse"; - Object.assign(result.attrs, { cx: "50%", cy: "50%", rx: "50%", ry: "50%" }); - break; - case "line": - result.tagName = "line"; - break; - case "shape": - result.tagName = "g"; - break; - case "textbox": - result.tagName = "foreignObject"; - Object.assign(result.attrs, { width: '100%', height: '100%' }); - break; - default: - return null; - } - for (const at of globalXmlParser.attrs(elem)) { - switch (at.localName) { - case "style": - result.cssStyleText = at.value; - break; - case "fillcolor": - result.attrs.fill = at.value; - break; - case "from": - const [x1, y1] = parsePoint(at.value); - Object.assign(result.attrs, { x1, y1 }); - break; - case "to": - const [x2, y2] = parsePoint(at.value); - Object.assign(result.attrs, { x2, y2 }); - break; - } - } - for (const el of globalXmlParser.elements(elem)) { - switch (el.localName) { - case "stroke": - Object.assign(result.attrs, parseStroke(el)); - break; - case "fill": - Object.assign(result.attrs, parseFill()); - break; - case "imagedata": - result.tagName = "image"; - Object.assign(result.attrs, { width: '100%', height: '100%' }); - result.imageHref = { - id: globalXmlParser.attr(el, "id"), - title: globalXmlParser.attr(el, "title"), - }; - break; - case "txbxContent": - result.children.push(...parser.parseBodyElements(el)); - break; - default: - const child = parseVmlElement(el, parser); - child && result.children.push(child); - break; - } - } - return result; - } - function parseStroke(el) { - return { - 'stroke': globalXmlParser.attr(el, "color"), - 'stroke-width': globalXmlParser.lengthAttr(el, "weight", LengthUsage.Emu) ?? '1px' - }; - } - function parseFill(el) { - return {}; - } - function parsePoint(val) { - return val.split(","); - } - - class WmlComment extends OpenXmlElementBase { - constructor() { - super(...arguments); - this.type = DomType.Comment; - } - } - class WmlCommentReference extends OpenXmlElementBase { - constructor(id) { - super(); - this.id = id; - this.type = DomType.CommentReference; - } - } - class WmlCommentRangeStart extends OpenXmlElementBase { - constructor(id) { - super(); - this.id = id; - this.type = DomType.CommentRangeStart; - } - } - class WmlCommentRangeEnd extends OpenXmlElementBase { - constructor(id) { - super(); - this.id = id; - this.type = DomType.CommentRangeEnd; - } - } - - var autos = { - shd: "inherit", - color: "black", - borderColor: "black", - highlight: "transparent" - }; - const supportedNamespaceURIs = []; - const mmlTagMap = { - "oMath": DomType.MmlMath, - "oMathPara": DomType.MmlMathParagraph, - "f": DomType.MmlFraction, - "func": DomType.MmlFunction, - "fName": DomType.MmlFunctionName, - "num": DomType.MmlNumerator, - "den": DomType.MmlDenominator, - "rad": DomType.MmlRadical, - "deg": DomType.MmlDegree, - "e": DomType.MmlBase, - "sSup": DomType.MmlSuperscript, - "sSub": DomType.MmlSubscript, - "sPre": DomType.MmlPreSubSuper, - "sup": DomType.MmlSuperArgument, - "sub": DomType.MmlSubArgument, - "d": DomType.MmlDelimiter, - "nary": DomType.MmlNary, - "eqArr": DomType.MmlEquationArray, - "lim": DomType.MmlLimit, - "limLow": DomType.MmlLimitLower, - "m": DomType.MmlMatrix, - "mr": DomType.MmlMatrixRow, - "box": DomType.MmlBox, - "bar": DomType.MmlBar, - "groupChr": DomType.MmlGroupChar - }; - class DocumentParser { - constructor(options) { - this.options = { - ignoreWidth: false, - debug: false, - ...options - }; - } - parseNotes(xmlDoc, elemName, elemClass) { - var result = []; - for (let el of globalXmlParser.elements(xmlDoc, elemName)) { - const node = new elemClass(); - node.id = globalXmlParser.attr(el, "id"); - node.noteType = globalXmlParser.attr(el, "type"); - node.children = this.parseBodyElements(el); - result.push(node); - } - return result; - } - parseComments(xmlDoc) { - var result = []; - for (let el of globalXmlParser.elements(xmlDoc, "comment")) { - const item = new WmlComment(); - item.id = globalXmlParser.attr(el, "id"); - item.author = globalXmlParser.attr(el, "author"); - item.initials = globalXmlParser.attr(el, "initials"); - item.date = globalXmlParser.attr(el, "date"); - item.children = this.parseBodyElements(el); - result.push(item); - } - return result; - } - parseDocumentFile(xmlDoc) { - var xbody = globalXmlParser.element(xmlDoc, "body"); - var background = globalXmlParser.element(xmlDoc, "background"); - var sectPr = globalXmlParser.element(xbody, "sectPr"); - return { - type: DomType.Document, - children: this.parseBodyElements(xbody), - props: sectPr ? parseSectionProperties(sectPr, globalXmlParser) : {}, - cssStyle: background ? this.parseBackground(background) : {}, - }; - } - parseBackground(elem) { - var result = {}; - var color = xmlUtil.colorAttr(elem, "color"); - if (color) { - result["background-color"] = color; - } - return result; - } - parseBodyElements(element) { - var children = []; - for (const elem of globalXmlParser.elements(element)) { - switch (elem.localName) { - case "p": - children.push(this.parseParagraph(elem)); - break; - case "altChunk": - children.push(this.parseAltChunk(elem)); - break; - case "tbl": - children.push(this.parseTable(elem)); - break; - case "sdt": - children.push(...this.parseSdt(elem, e => this.parseBodyElements(e))); - break; - } - } - return children; - } - parseStylesFile(xstyles) { - var result = []; - for (const n of globalXmlParser.elements(xstyles)) { - switch (n.localName) { - case "style": - result.push(this.parseStyle(n)); - break; - case "docDefaults": - result.push(this.parseDefaultStyles(n)); - break; - } - } - return result; - } - parseDefaultStyles(node) { - var result = { - id: null, - name: null, - target: null, - basedOn: null, - styles: [] - }; - for (const c of globalXmlParser.elements(node)) { - switch (c.localName) { - case "rPrDefault": - var rPr = globalXmlParser.element(c, "rPr"); - if (rPr) - result.styles.push({ - target: "span", - values: this.parseDefaultProperties(rPr, {}) - }); - break; - case "pPrDefault": - var pPr = globalXmlParser.element(c, "pPr"); - if (pPr) - result.styles.push({ - target: "p", - values: this.parseDefaultProperties(pPr, {}) - }); - break; - } - } - return result; - } - parseStyle(node) { - var result = { - id: globalXmlParser.attr(node, "styleId"), - isDefault: globalXmlParser.boolAttr(node, "default"), - name: null, - target: null, - basedOn: null, - styles: [], - linked: null - }; - switch (globalXmlParser.attr(node, "type")) { - case "paragraph": - result.target = "p"; - break; - case "table": - result.target = "table"; - break; - case "character": - result.target = "span"; - break; - } - for (const n of globalXmlParser.elements(node)) { - switch (n.localName) { - case "basedOn": - result.basedOn = globalXmlParser.attr(n, "val"); - break; - case "name": - result.name = globalXmlParser.attr(n, "val"); - break; - case "link": - result.linked = globalXmlParser.attr(n, "val"); - break; - case "next": - result.next = globalXmlParser.attr(n, "val"); - break; - case "aliases": - result.aliases = globalXmlParser.attr(n, "val").split(","); - break; - case "pPr": - result.styles.push({ - target: "p", - values: this.parseDefaultProperties(n, {}) - }); - result.paragraphProps = parseParagraphProperties(n, globalXmlParser); - break; - case "rPr": - result.styles.push({ - target: "span", - values: this.parseDefaultProperties(n, {}) - }); - result.runProps = parseRunProperties(n, globalXmlParser); - break; - case "tblPr": - case "tcPr": - result.styles.push({ - target: "td", - values: this.parseDefaultProperties(n, {}) - }); - break; - case "tblStylePr": - for (let s of this.parseTableStyle(n)) - result.styles.push(s); - break; - case "rsid": - case "qFormat": - case "hidden": - case "semiHidden": - case "unhideWhenUsed": - case "autoRedefine": - case "uiPriority": - break; - default: - this.options.debug && console.warn(`DOCX: Unknown style element: ${n.localName}`); - } - } - return result; - } - parseTableStyle(node) { - var result = []; - var type = globalXmlParser.attr(node, "type"); - var selector = ""; - var modificator = ""; - switch (type) { - case "firstRow": - modificator = ".first-row"; - selector = "tr.first-row td"; - break; - case "lastRow": - modificator = ".last-row"; - selector = "tr.last-row td"; - break; - case "firstCol": - modificator = ".first-col"; - selector = "td.first-col"; - break; - case "lastCol": - modificator = ".last-col"; - selector = "td.last-col"; - break; - case "band1Vert": - modificator = ":not(.no-vband)"; - selector = "td.odd-col"; - break; - case "band2Vert": - modificator = ":not(.no-vband)"; - selector = "td.even-col"; - break; - case "band1Horz": - modificator = ":not(.no-hband)"; - selector = "tr.odd-row"; - break; - case "band2Horz": - modificator = ":not(.no-hband)"; - selector = "tr.even-row"; - break; - default: return []; - } - for (const n of globalXmlParser.elements(node)) { - switch (n.localName) { - case "pPr": - result.push({ - target: `${selector} p`, - mod: modificator, - values: this.parseDefaultProperties(n, {}) - }); - break; - case "rPr": - result.push({ - target: `${selector} span`, - mod: modificator, - values: this.parseDefaultProperties(n, {}) - }); - break; - case "tblPr": - case "tcPr": - result.push({ - target: selector, - mod: modificator, - values: this.parseDefaultProperties(n, {}) - }); - break; - } - } - return result; - } - parseNumberingFile(node) { - var result = []; - var mapping = {}; - var bullets = []; - for (const n of globalXmlParser.elements(node)) { - switch (n.localName) { - case "abstractNum": - this.parseAbstractNumbering(n, bullets) - .forEach(x => result.push(x)); - break; - case "numPicBullet": - bullets.push(this.parseNumberingPicBullet(n)); - break; - case "num": - var numId = globalXmlParser.attr(n, "numId"); - var abstractNumId = globalXmlParser.elementAttr(n, "abstractNumId", "val"); - mapping[abstractNumId] = numId; - break; - } - } - result.forEach(x => x.id = mapping[x.id]); - return result; - } - parseNumberingPicBullet(elem) { - var pict = globalXmlParser.element(elem, "pict"); - var shape = pict && globalXmlParser.element(pict, "shape"); - var imagedata = shape && globalXmlParser.element(shape, "imagedata"); - return imagedata ? { - id: globalXmlParser.intAttr(elem, "numPicBulletId"), - src: globalXmlParser.attr(imagedata, "id"), - style: globalXmlParser.attr(shape, "style") - } : null; - } - parseAbstractNumbering(node, bullets) { - var result = []; - var id = globalXmlParser.attr(node, "abstractNumId"); - for (const n of globalXmlParser.elements(node)) { - switch (n.localName) { - case "lvl": - result.push(this.parseNumberingLevel(id, n, bullets)); - break; - } - } - return result; - } - parseNumberingLevel(id, node, bullets) { - var result = { - id: id, - level: globalXmlParser.intAttr(node, "ilvl"), - start: 1, - pStyleName: undefined, - pStyle: {}, - rStyle: {}, - suff: "tab" - }; - for (const n of globalXmlParser.elements(node)) { - switch (n.localName) { - case "start": - result.start = globalXmlParser.intAttr(n, "val"); - break; - case "pPr": - this.parseDefaultProperties(n, result.pStyle); - break; - case "rPr": - this.parseDefaultProperties(n, result.rStyle); - break; - case "lvlPicBulletId": - var bulletId = globalXmlParser.intAttr(n, "val"); - result.bullet = bullets.find(x => x?.id == bulletId); - break; - case "lvlText": - result.levelText = globalXmlParser.attr(n, "val"); - break; - case "pStyle": - result.pStyleName = globalXmlParser.attr(n, "val"); - break; - case "numFmt": - result.format = globalXmlParser.attr(n, "val"); - break; - case "suff": - result.suff = globalXmlParser.attr(n, "val"); - break; - } - } - return result; - } - parseSdt(node, parser) { - const sdtContent = globalXmlParser.element(node, "sdtContent"); - return sdtContent ? parser(sdtContent) : []; - } - parseInserted(node, parentParser) { - return { - type: DomType.Inserted, - children: parentParser(node)?.children ?? [] - }; - } - parseDeleted(node, parentParser) { - return { - type: DomType.Deleted, - children: parentParser(node)?.children ?? [] - }; - } - parseAltChunk(node) { - return { type: DomType.AltChunk, children: [], id: globalXmlParser.attr(node, "id") }; - } - parseParagraph(node) { - var result = { type: DomType.Paragraph, children: [] }; - for (let el of globalXmlParser.elements(node)) { - switch (el.localName) { - case "pPr": - this.parseParagraphProperties(el, result); - break; - case "r": - result.children.push(this.parseRun(el, result)); - break; - case "hyperlink": - result.children.push(this.parseHyperlink(el, result)); - break; - case "smartTag": - result.children.push(this.parseSmartTag(el, result)); - break; - case "bookmarkStart": - result.children.push(parseBookmarkStart(el, globalXmlParser)); - break; - case "bookmarkEnd": - result.children.push(parseBookmarkEnd(el, globalXmlParser)); - break; - case "commentRangeStart": - result.children.push(new WmlCommentRangeStart(globalXmlParser.attr(el, "id"))); - break; - case "commentRangeEnd": - result.children.push(new WmlCommentRangeEnd(globalXmlParser.attr(el, "id"))); - break; - case "oMath": - case "oMathPara": - result.children.push(this.parseMathElement(el)); - break; - case "sdt": - result.children.push(...this.parseSdt(el, e => this.parseParagraph(e).children)); - break; - case "ins": - result.children.push(this.parseInserted(el, e => this.parseParagraph(e))); - break; - case "del": - result.children.push(this.parseDeleted(el, e => this.parseParagraph(e))); - break; - } - } - return result; - } - parseParagraphProperties(elem, paragraph) { - this.parseDefaultProperties(elem, paragraph.cssStyle = {}, null, c => { - if (parseParagraphProperty(c, paragraph, globalXmlParser)) - return true; - switch (c.localName) { - case "pStyle": - paragraph.styleName = globalXmlParser.attr(c, "val"); - break; - case "cnfStyle": - paragraph.className = values.classNameOfCnfStyle(c); - break; - case "framePr": - this.parseFrame(c, paragraph); - break; - case "rPr": - break; - default: - return false; - } - return true; - }); - } - parseFrame(node, paragraph) { - var dropCap = globalXmlParser.attr(node, "dropCap"); - if (dropCap == "drop") - paragraph.cssStyle["float"] = "left"; - } - parseHyperlink(node, parent) { - var result = { type: DomType.Hyperlink, parent: parent, children: [] }; - result.anchor = globalXmlParser.attr(node, "anchor"); - result.id = globalXmlParser.attr(node, "id"); - for (const c of globalXmlParser.elements(node)) { - switch (c.localName) { - case "r": - result.children.push(this.parseRun(c, result)); - break; - } - } - return result; - } - parseSmartTag(node, parent) { - var result = { type: DomType.SmartTag, parent, children: [] }; - var uri = globalXmlParser.attr(node, "uri"); - var element = globalXmlParser.attr(node, "element"); - if (uri) - result.uri = uri; - if (element) - result.element = element; - for (const c of globalXmlParser.elements(node)) { - switch (c.localName) { - case "r": - result.children.push(this.parseRun(c, result)); - break; - } - } - return result; - } - parseRun(node, parent) { - var result = { type: DomType.Run, parent: parent, children: [] }; - for (let c of globalXmlParser.elements(node)) { - c = this.checkAlternateContent(c); - switch (c.localName) { - case "t": - result.children.push({ - type: DomType.Text, - text: c.textContent - }); - break; - case "delText": - result.children.push({ - type: DomType.DeletedText, - text: c.textContent - }); - break; - case "commentReference": - result.children.push(new WmlCommentReference(globalXmlParser.attr(c, "id"))); - break; - case "fldSimple": - result.children.push({ - type: DomType.SimpleField, - instruction: globalXmlParser.attr(c, "instr"), - lock: globalXmlParser.boolAttr(c, "lock", false), - dirty: globalXmlParser.boolAttr(c, "dirty", false) - }); - break; - case "instrText": - result.fieldRun = true; - result.children.push({ - type: DomType.Instruction, - text: c.textContent - }); - break; - case "fldChar": - result.fieldRun = true; - result.children.push({ - type: DomType.ComplexField, - charType: globalXmlParser.attr(c, "fldCharType"), - lock: globalXmlParser.boolAttr(c, "lock", false), - dirty: globalXmlParser.boolAttr(c, "dirty", false) - }); - break; - case "noBreakHyphen": - result.children.push({ type: DomType.NoBreakHyphen }); - break; - case "br": - result.children.push({ - type: DomType.Break, - break: globalXmlParser.attr(c, "type") || "textWrapping" - }); - break; - case "lastRenderedPageBreak": - result.children.push({ - type: DomType.Break, - break: "lastRenderedPageBreak" - }); - break; - case "sym": - result.children.push({ - type: DomType.Symbol, - font: encloseFontFamily(globalXmlParser.attr(c, "font")), - char: globalXmlParser.attr(c, "char") - }); - break; - case "tab": - result.children.push({ type: DomType.Tab }); - break; - case "footnoteReference": - result.children.push({ - type: DomType.FootnoteReference, - id: globalXmlParser.attr(c, "id") - }); - break; - case "endnoteReference": - result.children.push({ - type: DomType.EndnoteReference, - id: globalXmlParser.attr(c, "id") - }); - break; - case "drawing": - let d = this.parseDrawing(c); - if (d) - result.children = [d]; - break; - case "pict": - result.children.push(this.parseVmlPicture(c)); - break; - case "rPr": - this.parseRunProperties(c, result); - break; - } - } - return result; - } - parseMathElement(elem) { - const propsTag = `${elem.localName}Pr`; - const result = { type: mmlTagMap[elem.localName], children: [] }; - for (const el of globalXmlParser.elements(elem)) { - const childType = mmlTagMap[el.localName]; - if (childType) { - result.children.push(this.parseMathElement(el)); - } - else if (el.localName == "r") { - var run = this.parseRun(el); - run.type = DomType.MmlRun; - result.children.push(run); - } - else if (el.localName == propsTag) { - result.props = this.parseMathProperies(el); - } - } - return result; - } - parseMathProperies(elem) { - const result = {}; - for (const el of globalXmlParser.elements(elem)) { - switch (el.localName) { - case "chr": - result.char = globalXmlParser.attr(el, "val"); - break; - case "vertJc": - result.verticalJustification = globalXmlParser.attr(el, "val"); - break; - case "pos": - result.position = globalXmlParser.attr(el, "val"); - break; - case "degHide": - result.hideDegree = globalXmlParser.boolAttr(el, "val"); - break; - case "begChr": - result.beginChar = globalXmlParser.attr(el, "val"); - break; - case "endChr": - result.endChar = globalXmlParser.attr(el, "val"); - break; - } - } - return result; - } - parseRunProperties(elem, run) { - this.parseDefaultProperties(elem, run.cssStyle = {}, null, c => { - switch (c.localName) { - case "rStyle": - run.styleName = globalXmlParser.attr(c, "val"); - break; - case "vertAlign": - run.verticalAlign = values.valueOfVertAlign(c, true); - break; - default: - return false; - } - return true; - }); - } - parseVmlPicture(elem) { - const result = { type: DomType.VmlPicture, children: [] }; - for (const el of globalXmlParser.elements(elem)) { - const child = parseVmlElement(el, this); - child && result.children.push(child); - } - return result; - } - checkAlternateContent(elem) { - if (elem.localName != 'AlternateContent') - return elem; - var choice = globalXmlParser.element(elem, "Choice"); - if (choice) { - var requires = globalXmlParser.attr(choice, "Requires"); - var namespaceURI = elem.lookupNamespaceURI(requires); - if (supportedNamespaceURIs.includes(namespaceURI)) - return choice.firstElementChild; - } - return globalXmlParser.element(elem, "Fallback")?.firstElementChild; - } - parseDrawing(node) { - for (var n of globalXmlParser.elements(node)) { - switch (n.localName) { - case "inline": - case "anchor": - return this.parseDrawingWrapper(n); - } - } - } - parseDrawingWrapper(node) { - var result = { type: DomType.Drawing, children: [], cssStyle: {} }; - var isAnchor = node.localName == "anchor"; - let wrapType = null; - let simplePos = globalXmlParser.boolAttr(node, "simplePos"); - globalXmlParser.boolAttr(node, "behindDoc"); - let posX = { relative: "page", align: "left", offset: "0" }; - let posY = { relative: "page", align: "top", offset: "0" }; - for (var n of globalXmlParser.elements(node)) { - switch (n.localName) { - case "simplePos": - if (simplePos) { - posX.offset = globalXmlParser.lengthAttr(n, "x", LengthUsage.Emu); - posY.offset = globalXmlParser.lengthAttr(n, "y", LengthUsage.Emu); - } - break; - case "extent": - result.cssStyle["width"] = globalXmlParser.lengthAttr(n, "cx", LengthUsage.Emu); - result.cssStyle["height"] = globalXmlParser.lengthAttr(n, "cy", LengthUsage.Emu); - break; - case "positionH": - case "positionV": - if (!simplePos) { - let pos = n.localName == "positionH" ? posX : posY; - var alignNode = globalXmlParser.element(n, "align"); - var offsetNode = globalXmlParser.element(n, "posOffset"); - pos.relative = globalXmlParser.attr(n, "relativeFrom") ?? pos.relative; - if (alignNode) - pos.align = alignNode.textContent; - if (offsetNode) - pos.offset = convertLength(offsetNode.textContent, LengthUsage.Emu); - } - break; - case "wrapTopAndBottom": - wrapType = "wrapTopAndBottom"; - break; - case "wrapNone": - wrapType = "wrapNone"; - break; - case "graphic": - var g = this.parseGraphic(n); - if (g) - result.children.push(g); - break; - } - } - if (wrapType == "wrapTopAndBottom") { - result.cssStyle['display'] = 'block'; - if (posX.align) { - result.cssStyle['text-align'] = posX.align; - result.cssStyle['width'] = "100%"; - } - } - else if (wrapType == "wrapNone") { - result.cssStyle['display'] = 'block'; - result.cssStyle['position'] = 'relative'; - result.cssStyle["width"] = "0px"; - result.cssStyle["height"] = "0px"; - if (posX.offset) - result.cssStyle["left"] = posX.offset; - if (posY.offset) - result.cssStyle["top"] = posY.offset; - } - else if (isAnchor && (posX.align == 'left' || posX.align == 'right')) { - result.cssStyle["float"] = posX.align; - } - return result; - } - parseGraphic(elem) { - var graphicData = globalXmlParser.element(elem, "graphicData"); - for (let n of globalXmlParser.elements(graphicData)) { - switch (n.localName) { - case "pic": - return this.parsePicture(n); - } - } - return null; - } - parsePicture(elem) { - var result = { type: DomType.Image, src: "", cssStyle: {} }; - var blipFill = globalXmlParser.element(elem, "blipFill"); - var blip = globalXmlParser.element(blipFill, "blip"); - var srcRect = globalXmlParser.element(blipFill, "srcRect"); - result.src = globalXmlParser.attr(blip, "embed"); - if (srcRect) { - result.srcRect = [ - globalXmlParser.intAttr(srcRect, "l", 0) / 100000, - globalXmlParser.intAttr(srcRect, "t", 0) / 100000, - globalXmlParser.intAttr(srcRect, "r", 0) / 100000, - globalXmlParser.intAttr(srcRect, "b", 0) / 100000, - ]; - } - var spPr = globalXmlParser.element(elem, "spPr"); - var xfrm = globalXmlParser.element(spPr, "xfrm"); - result.cssStyle["position"] = "relative"; - if (xfrm) { - result.rotation = globalXmlParser.intAttr(xfrm, "rot", 0) / 60000; - for (var n of globalXmlParser.elements(xfrm)) { - switch (n.localName) { - case "ext": - result.cssStyle["width"] = globalXmlParser.lengthAttr(n, "cx", LengthUsage.Emu); - result.cssStyle["height"] = globalXmlParser.lengthAttr(n, "cy", LengthUsage.Emu); - break; - case "off": - result.cssStyle["left"] = globalXmlParser.lengthAttr(n, "x", LengthUsage.Emu); - result.cssStyle["top"] = globalXmlParser.lengthAttr(n, "y", LengthUsage.Emu); - break; - } - } - } - return result; - } - parseTable(node) { - var result = { type: DomType.Table, children: [] }; - for (const c of globalXmlParser.elements(node)) { - switch (c.localName) { - case "tr": - result.children.push(this.parseTableRow(c)); - break; - case "tblGrid": - result.columns = this.parseTableColumns(c); - break; - case "tblPr": - this.parseTableProperties(c, result); - break; - } - } - return result; - } - parseTableColumns(node) { - var result = []; - for (const n of globalXmlParser.elements(node)) { - switch (n.localName) { - case "gridCol": - result.push({ width: globalXmlParser.lengthAttr(n, "w") }); - break; - } - } - return result; - } - parseTableProperties(elem, table) { - table.cssStyle = {}; - table.cellStyle = {}; - this.parseDefaultProperties(elem, table.cssStyle, table.cellStyle, c => { - switch (c.localName) { - case "tblStyle": - table.styleName = globalXmlParser.attr(c, "val"); - break; - case "tblLook": - table.className = values.classNameOftblLook(c); - break; - case "tblpPr": - this.parseTablePosition(c, table); - break; - case "tblStyleColBandSize": - table.colBandSize = globalXmlParser.intAttr(c, "val"); - break; - case "tblStyleRowBandSize": - table.rowBandSize = globalXmlParser.intAttr(c, "val"); - break; - case "hidden": - table.cssStyle["display"] = "none"; - break; - default: - return false; - } - return true; - }); - switch (table.cssStyle["text-align"]) { - case "center": - delete table.cssStyle["text-align"]; - table.cssStyle["margin-left"] = "auto"; - table.cssStyle["margin-right"] = "auto"; - break; - case "right": - delete table.cssStyle["text-align"]; - table.cssStyle["margin-left"] = "auto"; - break; - } - } - parseTablePosition(node, table) { - var topFromText = globalXmlParser.lengthAttr(node, "topFromText"); - var bottomFromText = globalXmlParser.lengthAttr(node, "bottomFromText"); - var rightFromText = globalXmlParser.lengthAttr(node, "rightFromText"); - var leftFromText = globalXmlParser.lengthAttr(node, "leftFromText"); - table.cssStyle["float"] = 'left'; - table.cssStyle["margin-bottom"] = values.addSize(table.cssStyle["margin-bottom"], bottomFromText); - table.cssStyle["margin-left"] = values.addSize(table.cssStyle["margin-left"], leftFromText); - table.cssStyle["margin-right"] = values.addSize(table.cssStyle["margin-right"], rightFromText); - table.cssStyle["margin-top"] = values.addSize(table.cssStyle["margin-top"], topFromText); - } - parseTableRow(node) { - var result = { type: DomType.Row, children: [] }; - for (const c of globalXmlParser.elements(node)) { - switch (c.localName) { - case "tc": - result.children.push(this.parseTableCell(c)); - break; - case "trPr": - case "tblPrEx": - this.parseTableRowProperties(c, result); - break; - } - } - return result; - } - parseTableRowProperties(elem, row) { - row.cssStyle = this.parseDefaultProperties(elem, {}, null, c => { - switch (c.localName) { - case "cnfStyle": - row.className = values.classNameOfCnfStyle(c); - break; - case "tblHeader": - row.isHeader = globalXmlParser.boolAttr(c, "val"); - break; - case "gridBefore": - row.gridBefore = globalXmlParser.intAttr(c, "val"); - break; - case "gridAfter": - row.gridAfter = globalXmlParser.intAttr(c, "val"); - break; - default: - return false; - } - return true; - }); - } - parseTableCell(node) { - var result = { type: DomType.Cell, children: [] }; - for (const c of globalXmlParser.elements(node)) { - switch (c.localName) { - case "tbl": - result.children.push(this.parseTable(c)); - break; - case "p": - result.children.push(this.parseParagraph(c)); - break; - case "tcPr": - this.parseTableCellProperties(c, result); - break; - } - } - return result; - } - parseTableCellProperties(elem, cell) { - cell.cssStyle = this.parseDefaultProperties(elem, {}, null, c => { - switch (c.localName) { - case "gridSpan": - cell.span = globalXmlParser.intAttr(c, "val", null); - break; - case "vMerge": - cell.verticalMerge = globalXmlParser.attr(c, "val") ?? "continue"; - break; - case "cnfStyle": - cell.className = values.classNameOfCnfStyle(c); - break; - default: - return false; - } - return true; - }); - this.parseTableCellVerticalText(elem, cell); - } - parseTableCellVerticalText(elem, cell) { - const directionMap = { - "btLr": { - writingMode: "vertical-rl", - transform: "rotate(180deg)" - }, - "lrTb": { - writingMode: "vertical-lr", - transform: "none" - }, - "tbRl": { - writingMode: "vertical-rl", - transform: "none" - } - }; - for (const c of globalXmlParser.elements(elem)) { - if (c.localName === "textDirection") { - const direction = globalXmlParser.attr(c, "val"); - const style = directionMap[direction] || { writingMode: "horizontal-tb" }; - cell.cssStyle["writing-mode"] = style.writingMode; - cell.cssStyle["transform"] = style.transform; - } - } - } - parseDefaultProperties(elem, style = null, childStyle = null, handler = null) { - style = style || {}; - for (const c of globalXmlParser.elements(elem)) { - if (handler?.(c)) - continue; - switch (c.localName) { - case "jc": - style["text-align"] = values.valueOfJc(c); - break; - case "textAlignment": - style["vertical-align"] = values.valueOfTextAlignment(c); - break; - case "color": - style["color"] = xmlUtil.colorAttr(c, "val", null, autos.color); - break; - case "sz": - style["font-size"] = style["min-height"] = globalXmlParser.lengthAttr(c, "val", LengthUsage.FontSize); - break; - case "shd": - style["background-color"] = xmlUtil.colorAttr(c, "fill", null, autos.shd); - break; - case "highlight": - style["background-color"] = xmlUtil.colorAttr(c, "val", null, autos.highlight); - break; - case "vertAlign": - break; - case "position": - style.verticalAlign = globalXmlParser.lengthAttr(c, "val", LengthUsage.FontSize); - break; - case "tcW": - if (this.options.ignoreWidth) - break; - case "tblW": - style["width"] = values.valueOfSize(c, "w"); - break; - case "trHeight": - this.parseTrHeight(c, style); - break; - case "strike": - style["text-decoration"] = globalXmlParser.boolAttr(c, "val", true) ? "line-through" : "none"; - break; - case "b": - style["font-weight"] = globalXmlParser.boolAttr(c, "val", true) ? "bold" : "normal"; - break; - case "i": - style["font-style"] = globalXmlParser.boolAttr(c, "val", true) ? "italic" : "normal"; - break; - case "caps": - style["text-transform"] = globalXmlParser.boolAttr(c, "val", true) ? "uppercase" : "none"; - break; - case "smallCaps": - style["font-variant"] = globalXmlParser.boolAttr(c, "val", true) ? "small-caps" : "none"; - break; - case "u": - this.parseUnderline(c, style); - break; - case "ind": - case "tblInd": - this.parseIndentation(c, style); - break; - case "rFonts": - this.parseFont(c, style); - break; - case "tblBorders": - this.parseBorderProperties(c, childStyle || style); - break; - case "tblCellSpacing": - style["border-spacing"] = values.valueOfMargin(c); - style["border-collapse"] = "separate"; - break; - case "pBdr": - this.parseBorderProperties(c, style); - break; - case "bdr": - style["border"] = values.valueOfBorder(c); - break; - case "tcBorders": - this.parseBorderProperties(c, style); - break; - case "vanish": - if (globalXmlParser.boolAttr(c, "val", true)) - style["display"] = "none"; - break; - case "kern": - break; - case "noWrap": - break; - case "tblCellMar": - case "tcMar": - this.parseMarginProperties(c, childStyle || style); - break; - case "tblLayout": - style["table-layout"] = values.valueOfTblLayout(c); - break; - case "vAlign": - style["vertical-align"] = values.valueOfTextAlignment(c); - break; - case "spacing": - if (elem.localName == "pPr") - this.parseSpacing(c, style); - break; - case "wordWrap": - if (globalXmlParser.boolAttr(c, "val")) - style["overflow-wrap"] = "break-word"; - break; - case "suppressAutoHyphens": - style["hyphens"] = globalXmlParser.boolAttr(c, "val", true) ? "none" : "auto"; - break; - case "lang": - style["$lang"] = globalXmlParser.attr(c, "val"); - break; - case "rtl": - case "bidi": - if (globalXmlParser.boolAttr(c, "val", true)) - style["direction"] = "rtl"; - break; - case "bCs": - case "iCs": - case "szCs": - case "tabs": - case "outlineLvl": - case "contextualSpacing": - case "tblStyleColBandSize": - case "tblStyleRowBandSize": - case "webHidden": - case "pageBreakBefore": - case "suppressLineNumbers": - case "keepLines": - case "keepNext": - case "widowControl": - case "bidi": - case "rtl": - case "noProof": - break; - default: - if (this.options.debug) - console.warn(`DOCX: Unknown document element: ${elem.localName}.${c.localName}`); - break; - } - } - return style; - } - parseUnderline(node, style) { - var val = globalXmlParser.attr(node, "val"); - if (val == null) - return; - switch (val) { - case "dash": - case "dashDotDotHeavy": - case "dashDotHeavy": - case "dashedHeavy": - case "dashLong": - case "dashLongHeavy": - case "dotDash": - case "dotDotDash": - style["text-decoration"] = "underline dashed"; - break; - case "dotted": - case "dottedHeavy": - style["text-decoration"] = "underline dotted"; - break; - case "double": - style["text-decoration"] = "underline double"; - break; - case "single": - case "thick": - style["text-decoration"] = "underline"; - break; - case "wave": - case "wavyDouble": - case "wavyHeavy": - style["text-decoration"] = "underline wavy"; - break; - case "words": - style["text-decoration"] = "underline"; - break; - case "none": - style["text-decoration"] = "none"; - break; - } - var col = xmlUtil.colorAttr(node, "color"); - if (col) - style["text-decoration-color"] = col; - } - parseFont(node, style) { - var ascii = globalXmlParser.attr(node, "ascii"); - var asciiTheme = values.themeValue(node, "asciiTheme"); - var eastAsia = globalXmlParser.attr(node, "eastAsia"); - var fonts = [ascii, asciiTheme, eastAsia].filter(x => x).map(x => encloseFontFamily(x)); - if (fonts.length > 0) - style["font-family"] = [...new Set(fonts)].join(', '); - } - parseIndentation(node, style) { - var firstLine = globalXmlParser.lengthAttr(node, "firstLine"); - var hanging = globalXmlParser.lengthAttr(node, "hanging"); - var left = globalXmlParser.lengthAttr(node, "left"); - var start = globalXmlParser.lengthAttr(node, "start"); - var right = globalXmlParser.lengthAttr(node, "right"); - var end = globalXmlParser.lengthAttr(node, "end"); - if (firstLine) - style["text-indent"] = firstLine; - if (hanging) - style["text-indent"] = `-${hanging}`; - if (left || start) - style["margin-inline-start"] = left || start; - if (right || end) - style["margin-inline-end"] = right || end; - } - parseSpacing(node, style) { - var before = globalXmlParser.lengthAttr(node, "before"); - var after = globalXmlParser.lengthAttr(node, "after"); - var line = globalXmlParser.intAttr(node, "line", null); - var lineRule = globalXmlParser.attr(node, "lineRule"); - if (before) - style["margin-top"] = before; - if (after) - style["margin-bottom"] = after; - if (line !== null) { - switch (lineRule) { - case "auto": - style["line-height"] = `${(line / 240).toFixed(2)}`; - break; - case "atLeast": - style["line-height"] = `calc(100% + ${line / 20}pt)`; - break; - default: - style["line-height"] = style["min-height"] = `${line / 20}pt`; - break; - } - } - } - parseMarginProperties(node, output) { - for (const c of globalXmlParser.elements(node)) { - switch (c.localName) { - case "left": - output["padding-left"] = values.valueOfMargin(c); - break; - case "right": - output["padding-right"] = values.valueOfMargin(c); - break; - case "top": - output["padding-top"] = values.valueOfMargin(c); - break; - case "bottom": - output["padding-bottom"] = values.valueOfMargin(c); - break; - } - } - } - parseTrHeight(node, output) { - switch (globalXmlParser.attr(node, "hRule")) { - case "exact": - output["height"] = globalXmlParser.lengthAttr(node, "val"); - break; - case "atLeast": - default: - output["height"] = globalXmlParser.lengthAttr(node, "val"); - break; - } - } - parseBorderProperties(node, output) { - for (const c of globalXmlParser.elements(node)) { - switch (c.localName) { - case "start": - case "left": - output["border-left"] = values.valueOfBorder(c); - break; - case "end": - case "right": - output["border-right"] = values.valueOfBorder(c); - break; - case "top": - output["border-top"] = values.valueOfBorder(c); - break; - case "bottom": - output["border-bottom"] = values.valueOfBorder(c); - break; - } - } - } - } - const knownColors = ['black', 'blue', 'cyan', 'darkBlue', 'darkCyan', 'darkGray', 'darkGreen', 'darkMagenta', 'darkRed', 'darkYellow', 'green', 'lightGray', 'magenta', 'none', 'red', 'white', 'yellow']; - class xmlUtil { - static colorAttr(node, attrName, defValue = null, autoColor = 'black') { - var v = globalXmlParser.attr(node, attrName); - if (v) { - if (v == "auto") { - return autoColor; - } - else if (knownColors.includes(v)) { - return v; - } - return `#${v}`; - } - var themeColor = globalXmlParser.attr(node, "themeColor"); - return themeColor ? `var(--docx-${themeColor}-color)` : defValue; - } - } - class values { - static themeValue(c, attr) { - var val = globalXmlParser.attr(c, attr); - return val ? `var(--docx-${val}-font)` : null; - } - static valueOfSize(c, attr) { - var type = LengthUsage.Dxa; - switch (globalXmlParser.attr(c, "type")) { - case "dxa": break; - case "pct": - type = LengthUsage.Percent; - break; - case "auto": return "auto"; - } - return globalXmlParser.lengthAttr(c, attr, type); - } - static valueOfMargin(c) { - return globalXmlParser.lengthAttr(c, "w"); - } - static valueOfBorder(c) { - var type = values.parseBorderType(globalXmlParser.attr(c, "val")); - if (type == "none") - return "none"; - var color = xmlUtil.colorAttr(c, "color"); - var size = globalXmlParser.lengthAttr(c, "sz", LengthUsage.Border); - return `${size} ${type} ${color == "auto" ? autos.borderColor : color}`; - } - static parseBorderType(type) { - switch (type) { - case "single": return "solid"; - case "dashDotStroked": return "solid"; - case "dashed": return "dashed"; - case "dashSmallGap": return "dashed"; - case "dotDash": return "dotted"; - case "dotDotDash": return "dotted"; - case "dotted": return "dotted"; - case "double": return "double"; - case "doubleWave": return "double"; - case "inset": return "inset"; - case "nil": return "none"; - case "none": return "none"; - case "outset": return "outset"; - case "thick": return "solid"; - case "thickThinLargeGap": return "solid"; - case "thickThinMediumGap": return "solid"; - case "thickThinSmallGap": return "solid"; - case "thinThickLargeGap": return "solid"; - case "thinThickMediumGap": return "solid"; - case "thinThickSmallGap": return "solid"; - case "thinThickThinLargeGap": return "solid"; - case "thinThickThinMediumGap": return "solid"; - case "thinThickThinSmallGap": return "solid"; - case "threeDEmboss": return "solid"; - case "threeDEngrave": return "solid"; - case "triple": return "double"; - case "wave": return "solid"; - } - return 'solid'; - } - static valueOfTblLayout(c) { - var type = globalXmlParser.attr(c, "val"); - return type == "fixed" ? "fixed" : "auto"; - } - static classNameOfCnfStyle(c) { - const val = globalXmlParser.attr(c, "val"); - const classes = [ - 'first-row', 'last-row', 'first-col', 'last-col', - 'odd-col', 'even-col', 'odd-row', 'even-row', - 'ne-cell', 'nw-cell', 'se-cell', 'sw-cell' - ]; - return classes.filter((_, i) => val[i] == '1').join(' '); - } - static valueOfJc(c) { - var type = globalXmlParser.attr(c, "val"); - switch (type) { - case "start": - case "left": return "left"; - case "center": return "center"; - case "end": - case "right": return "right"; - case "both": return "justify"; - } - return type; - } - static valueOfVertAlign(c, asTagName = false) { - var type = globalXmlParser.attr(c, "val"); - switch (type) { - case "subscript": return "sub"; - case "superscript": return asTagName ? "sup" : "super"; - } - return asTagName ? null : type; - } - static valueOfTextAlignment(c) { - var type = globalXmlParser.attr(c, "val"); - switch (type) { - case "auto": - case "baseline": return "baseline"; - case "top": return "top"; - case "center": return "middle"; - case "bottom": return "bottom"; - } - return type; - } - static addSize(a, b) { - if (a == null) - return b; - if (b == null) - return a; - return `calc(${a} + ${b})`; - } - static classNameOftblLook(c) { - const val = globalXmlParser.hexAttr(c, "val", 0); - let className = ""; - if (globalXmlParser.boolAttr(c, "firstRow") || (val & 0x0020)) - className += " first-row"; - if (globalXmlParser.boolAttr(c, "lastRow") || (val & 0x0040)) - className += " last-row"; - if (globalXmlParser.boolAttr(c, "firstColumn") || (val & 0x0080)) - className += " first-col"; - if (globalXmlParser.boolAttr(c, "lastColumn") || (val & 0x0100)) - className += " last-col"; - if (globalXmlParser.boolAttr(c, "noHBand") || (val & 0x0200)) - className += " no-hband"; - if (globalXmlParser.boolAttr(c, "noVBand") || (val & 0x0400)) - className += " no-vband"; - return className.trim(); - } - } - - const defaultTab = { pos: 0, leader: "none", style: "left" }; - const maxTabs = 50; - function computePixelToPoint(container = document.body) { - const temp = document.createElement("div"); - temp.style.width = '100pt'; - container.appendChild(temp); - const result = 100 / temp.offsetWidth; - container.removeChild(temp); - return result; - } - function updateTabStop(elem, tabs, defaultTabSize, pixelToPoint = 72 / 96) { - const p = elem.closest("p"); - const ebb = elem.getBoundingClientRect(); - const pbb = p.getBoundingClientRect(); - const pcs = getComputedStyle(p); - const tabStops = tabs?.length > 0 ? tabs.map(t => ({ - pos: lengthToPoint(t.position), - leader: t.leader, - style: t.style - })).sort((a, b) => a.pos - b.pos) : [defaultTab]; - const lastTab = tabStops[tabStops.length - 1]; - const pWidthPt = pbb.width * pixelToPoint; - const size = lengthToPoint(defaultTabSize); - let pos = lastTab.pos + size; - if (pos < pWidthPt) { - for (; pos < pWidthPt && tabStops.length < maxTabs; pos += size) { - tabStops.push({ ...defaultTab, pos: pos }); - } - } - const marginLeft = parseFloat(pcs.marginLeft); - const pOffset = pbb.left + marginLeft; - const left = (ebb.left - pOffset) * pixelToPoint; - const tab = tabStops.find(t => t.style != "clear" && t.pos > left); - if (tab == null) - return; - let width = 1; - if (tab.style == "right" || tab.style == "center") { - const tabStops = Array.from(p.querySelectorAll(`.${elem.className}`)); - const nextIdx = tabStops.indexOf(elem) + 1; - const range = document.createRange(); - range.setStart(elem, 1); - if (nextIdx < tabStops.length) { - range.setEndBefore(tabStops[nextIdx]); - } - else { - range.setEndAfter(p); - } - const mul = tab.style == "center" ? 0.5 : 1; - const nextBB = range.getBoundingClientRect(); - const offset = nextBB.left + mul * nextBB.width - (pbb.left - marginLeft); - width = tab.pos - offset * pixelToPoint; - } - else { - width = tab.pos - left; - } - elem.innerHTML = " "; - elem.style.textDecoration = "inherit"; - elem.style.wordSpacing = `${width.toFixed(0)}pt`; - switch (tab.leader) { - case "dot": - case "middleDot": - elem.style.textDecoration = "underline"; - elem.style.textDecorationStyle = "dotted"; - break; - case "hyphen": - case "heavy": - case "underscore": - elem.style.textDecoration = "underline"; - break; - } - } - function lengthToPoint(length) { - return parseFloat(length); - } - - const ns = { - svg: "http://www.w3.org/2000/svg", - mathML: "http://www.w3.org/1998/Math/MathML" - }; - class HtmlRenderer { - constructor(htmlDocument) { - this.htmlDocument = htmlDocument; - this.className = "docx"; - this.styleMap = {}; - this.currentPart = null; - this.tableVerticalMerges = []; - this.currentVerticalMerge = null; - this.tableCellPositions = []; - this.currentCellPosition = null; - this.footnoteMap = {}; - this.endnoteMap = {}; - this.currentEndnoteIds = []; - this.usedHederFooterParts = []; - this.currentTabs = []; - this.commentMap = {}; - this.tasks = []; - this.postRenderTasks = []; - } - async render(document, bodyContainer, styleContainer = null, options) { - this.document = document; - this.options = options; - this.className = options.className; - this.rootSelector = options.inWrapper ? `.${this.className}-wrapper` : ':root'; - this.styleMap = null; - this.tasks = []; - if (this.options.renderComments && globalThis.Highlight) { - this.commentHighlight = new Highlight(); - } - styleContainer = styleContainer || bodyContainer; - removeAllElements(styleContainer); - removeAllElements(bodyContainer); - styleContainer.appendChild(this.createComment("docxjs library predefined styles")); - styleContainer.appendChild(this.renderDefaultStyle()); - if (document.themePart) { - styleContainer.appendChild(this.createComment("docxjs document theme values")); - this.renderTheme(document.themePart, styleContainer); - } - if (document.stylesPart != null) { - this.styleMap = this.processStyles(document.stylesPart.styles); - styleContainer.appendChild(this.createComment("docxjs document styles")); - styleContainer.appendChild(this.renderStyles(document.stylesPart.styles)); - } - if (document.numberingPart) { - this.prodessNumberings(document.numberingPart.domNumberings); - styleContainer.appendChild(this.createComment("docxjs document numbering styles")); - styleContainer.appendChild(this.renderNumbering(document.numberingPart.domNumberings, styleContainer)); - } - if (document.footnotesPart) { - this.footnoteMap = keyBy(document.footnotesPart.notes, x => x.id); - } - if (document.endnotesPart) { - this.endnoteMap = keyBy(document.endnotesPart.notes, x => x.id); - } - if (document.settingsPart) { - this.defaultTabSize = document.settingsPart.settings?.defaultTabStop; - } - if (!options.ignoreFonts && document.fontTablePart) - this.renderFontTable(document.fontTablePart, styleContainer); - var sectionElements = this.renderSections(document.documentPart.body); - if (this.options.inWrapper) { - bodyContainer.appendChild(this.renderWrapper(sectionElements)); - } - else { - appendChildren(bodyContainer, sectionElements); - } - if (this.commentHighlight && options.renderComments) { - CSS.highlights.set(`${this.className}-comments`, this.commentHighlight); - } - this.postRenderTasks.forEach(t => t()); - await Promise.allSettled(this.tasks); - this.refreshTabStops(); - } - renderTheme(themePart, styleContainer) { - const variables = {}; - const fontScheme = themePart.theme?.fontScheme; - if (fontScheme) { - if (fontScheme.majorFont) { - variables['--docx-majorHAnsi-font'] = fontScheme.majorFont.latinTypeface; - } - if (fontScheme.minorFont) { - variables['--docx-minorHAnsi-font'] = fontScheme.minorFont.latinTypeface; - } - } - const colorScheme = themePart.theme?.colorScheme; - if (colorScheme) { - for (let [k, v] of Object.entries(colorScheme.colors)) { - variables[`--docx-${k}-color`] = `#${v}`; - } - } - const cssText = this.styleToString(`.${this.className}`, variables); - styleContainer.appendChild(this.createStyleElement(cssText)); - } - renderFontTable(fontsPart, styleContainer) { - for (let f of fontsPart.fonts) { - for (let ref of f.embedFontRefs) { - this.tasks.push(this.document.loadFont(ref.id, ref.key).then(fontData => { - const cssValues = { - 'font-family': encloseFontFamily(f.name), - 'src': `url(${fontData})` - }; - if (ref.type == "bold" || ref.type == "boldItalic") { - cssValues['font-weight'] = 'bold'; - } - if (ref.type == "italic" || ref.type == "boldItalic") { - cssValues['font-style'] = 'italic'; - } - const cssText = this.styleToString("@font-face", cssValues); - styleContainer.appendChild(this.createComment(`docxjs ${f.name} font`)); - styleContainer.appendChild(this.createStyleElement(cssText)); - })); - } - } - } - processStyleName(className) { - return className ? `${this.className}_${escapeClassName(className)}` : this.className; - } - processStyles(styles) { - const stylesMap = keyBy(styles.filter(x => x.id != null), x => x.id); - for (const style of styles.filter(x => x.basedOn)) { - var baseStyle = stylesMap[style.basedOn]; - if (baseStyle) { - style.paragraphProps = mergeDeep(style.paragraphProps, baseStyle.paragraphProps); - style.runProps = mergeDeep(style.runProps, baseStyle.runProps); - for (const baseValues of baseStyle.styles) { - const styleValues = style.styles.find(x => x.target == baseValues.target); - if (styleValues) { - this.copyStyleProperties(baseValues.values, styleValues.values); - } - else { - style.styles.push({ ...baseValues, values: { ...baseValues.values } }); - } - } - } - else if (this.options.debug) - console.warn(`Can't find base style ${style.basedOn}`); - } - for (let style of styles) { - style.cssName = this.processStyleName(style.id); - } - return stylesMap; - } - prodessNumberings(numberings) { - for (let num of numberings.filter(n => n.pStyleName)) { - const style = this.findStyle(num.pStyleName); - if (style?.paragraphProps?.numbering) { - style.paragraphProps.numbering.level = num.level; - } - } - } - processElement(element) { - if (element.children) { - for (var e of element.children) { - e.parent = element; - if (e.type == DomType.Table) { - this.processTable(e); - } - else { - this.processElement(e); - } - } - } - } - processTable(table) { - for (var r of table.children) { - for (var c of r.children) { - c.cssStyle = this.copyStyleProperties(table.cellStyle, c.cssStyle, [ - "border-left", "border-right", "border-top", "border-bottom", - "padding-left", "padding-right", "padding-top", "padding-bottom" - ]); - this.processElement(c); - } - } - } - copyStyleProperties(input, output, attrs = null) { - if (!input) - return output; - if (output == null) - output = {}; - if (attrs == null) - attrs = Object.getOwnPropertyNames(input); - for (var key of attrs) { - if (input.hasOwnProperty(key) && !output.hasOwnProperty(key)) - output[key] = input[key]; - } - return output; - } - createPageElement(className, props) { - var elem = this.createElement("section", { className }); - if (props) { - if (props.pageMargins) { - elem.style.paddingLeft = props.pageMargins.left; - elem.style.paddingRight = props.pageMargins.right; - elem.style.paddingTop = props.pageMargins.top; - elem.style.paddingBottom = props.pageMargins.bottom; - } - if (props.pageSize) { - if (!this.options.ignoreWidth) - elem.style.width = props.pageSize.width; - if (!this.options.ignoreHeight) - elem.style.minHeight = props.pageSize.height; - } - } - return elem; - } - createSectionContent(props) { - var elem = this.createElement("article"); - if (props.columns && props.columns.numberOfColumns) { - elem.style.columnCount = `${props.columns.numberOfColumns}`; - elem.style.columnGap = props.columns.space; - if (props.columns.separator) { - elem.style.columnRule = "1px solid black"; - } - } - return elem; - } - renderSections(document) { - const result = []; - this.processElement(document); - const sections = this.splitBySection(document.children, document.props); - const pages = this.groupByPageBreaks(sections); - let prevProps = null; - for (let i = 0, l = pages.length; i < l; i++) { - this.currentFootnoteIds = []; - const section = pages[i][0]; - let props = section.sectProps; - const pageElement = this.createPageElement(this.className, props); - this.renderStyleValues(document.cssStyle, pageElement); - this.options.renderHeaders && this.renderHeaderFooter(props.headerRefs, props, result.length, prevProps != props, pageElement); - for (const sect of pages[i]) { - var contentElement = this.createSectionContent(sect.sectProps); - this.renderElements(sect.elements, contentElement); - pageElement.appendChild(contentElement); - props = sect.sectProps; - } - if (this.options.renderFootnotes) { - this.renderNotes(this.currentFootnoteIds, this.footnoteMap, pageElement); - } - if (this.options.renderEndnotes && i == l - 1) { - this.renderNotes(this.currentEndnoteIds, this.endnoteMap, pageElement); - } - this.options.renderFooters && this.renderHeaderFooter(props.footerRefs, props, result.length, prevProps != props, pageElement); - result.push(pageElement); - prevProps = props; - } - return result; - } - renderHeaderFooter(refs, props, page, firstOfSection, into) { - if (!refs) - return; - var ref = (props.titlePage && firstOfSection ? refs.find(x => x.type == "first") : null) - ?? (page % 2 == 1 ? refs.find(x => x.type == "even") : null) - ?? refs.find(x => x.type == "default"); - var part = ref && this.document.findPartByRelId(ref.id, this.document.documentPart); - if (part) { - this.currentPart = part; - if (!this.usedHederFooterParts.includes(part.path)) { - this.processElement(part.rootElement); - this.usedHederFooterParts.push(part.path); - } - const [el] = this.renderElements([part.rootElement], into); - if (props?.pageMargins) { - if (part.rootElement.type === DomType.Header) { - el.style.marginTop = `calc(${props.pageMargins.header} - ${props.pageMargins.top})`; - el.style.minHeight = `calc(${props.pageMargins.top} - ${props.pageMargins.header})`; - } - else if (part.rootElement.type === DomType.Footer) { - el.style.marginBottom = `calc(${props.pageMargins.footer} - ${props.pageMargins.bottom})`; - el.style.minHeight = `calc(${props.pageMargins.bottom} - ${props.pageMargins.footer})`; - } - } - this.currentPart = null; - } - } - isPageBreakElement(elem) { - if (elem.type != DomType.Break) - return false; - if (elem.break == "lastRenderedPageBreak") - return !this.options.ignoreLastRenderedPageBreak; - return elem.break == "page"; - } - isPageBreakSection(prev, next) { - if (!prev) - return false; - if (!next) - return false; - return prev.pageSize?.orientation != next.pageSize?.orientation - || prev.pageSize?.width != next.pageSize?.width - || prev.pageSize?.height != next.pageSize?.height; - } - splitBySection(elements, defaultProps) { - var current = { sectProps: null, elements: [], pageBreak: false }; - var result = [current]; - for (let elem of elements) { - if (elem.type == DomType.Paragraph) { - const s = this.findStyle(elem.styleName); - if (s?.paragraphProps?.pageBreakBefore) { - current.sectProps = sectProps; - current.pageBreak = true; - current = { sectProps: null, elements: [], pageBreak: false }; - result.push(current); - } - } - current.elements.push(elem); - if (elem.type == DomType.Paragraph) { - const p = elem; - var sectProps = p.sectionProps; - var pBreakIndex = -1; - var rBreakIndex = -1; - if (this.options.breakPages && p.children) { - pBreakIndex = p.children.findIndex(r => { - rBreakIndex = r.children?.findIndex(this.isPageBreakElement.bind(this)) ?? -1; - return rBreakIndex != -1; - }); - } - if (sectProps || pBreakIndex != -1) { - current.sectProps = sectProps; - current.pageBreak = pBreakIndex != -1; - current = { sectProps: null, elements: [], pageBreak: false }; - result.push(current); - } - if (pBreakIndex != -1) { - let breakRun = p.children[pBreakIndex]; - let splitRun = rBreakIndex < breakRun.children.length - 1; - if (pBreakIndex < p.children.length - 1 || splitRun) { - var children = elem.children; - var newParagraph = { ...elem, children: children.slice(pBreakIndex) }; - elem.children = children.slice(0, pBreakIndex); - current.elements.push(newParagraph); - if (splitRun) { - let runChildren = breakRun.children; - let newRun = { ...breakRun, children: runChildren.slice(0, rBreakIndex) }; - elem.children.push(newRun); - breakRun.children = runChildren.slice(rBreakIndex); - } - } - } - } - } - let currentSectProps = null; - for (let i = result.length - 1; i >= 0; i--) { - if (result[i].sectProps == null) { - result[i].sectProps = currentSectProps ?? defaultProps; - } - else { - currentSectProps = result[i].sectProps; - } - } - return result; - } - groupByPageBreaks(sections) { - let current = []; - let prev; - const result = [current]; - for (let s of sections) { - current.push(s); - if (this.options.ignoreLastRenderedPageBreak || s.pageBreak || this.isPageBreakSection(prev, s.sectProps)) - result.push(current = []); - prev = s.sectProps; - } - return result.filter(x => x.length > 0); - } - renderWrapper(children) { - return this.createElement("div", { className: `${this.className}-wrapper` }, children); - } - renderDefaultStyle() { - var c = this.className; - var wrapperStyle = ` -.${c}-wrapper { background: gray; padding: 30px; padding-bottom: 0px; display: flex; flex-flow: column; align-items: center; } -.${c}-wrapper>section.${c} { background: white; box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); margin-bottom: 30px; }`; - if (this.options.hideWrapperOnPrint) { - wrapperStyle = `@media not print { ${wrapperStyle} }`; - } - var styleText = `${wrapperStyle} -.${c} { color: black; hyphens: auto; text-underline-position: from-font; } -section.${c} { box-sizing: border-box; display: flex; flex-flow: column nowrap; position: relative; overflow: hidden; } -section.${c}>article { margin-bottom: auto; z-index: 1; } -section.${c}>footer { z-index: 1; } -.${c} table { border-collapse: collapse; } -.${c} table td, .${c} table th { vertical-align: top; } -.${c} p { margin: 0pt; min-height: 1em; } -.${c} span { white-space: pre-wrap; overflow-wrap: break-word; } -.${c} a { color: inherit; text-decoration: inherit; } -.${c} svg { fill: transparent; } -`; - if (this.options.renderComments) { - styleText += ` -.${c}-comment-ref { cursor: default; } -.${c}-comment-popover { display: none; z-index: 1000; padding: 0.5rem; background: white; position: absolute; box-shadow: 0 0 0.25rem rgba(0, 0, 0, 0.25); width: 30ch; } -.${c}-comment-ref:hover~.${c}-comment-popover { display: block; } -.${c}-comment-author,.${c}-comment-date { font-size: 0.875rem; color: #888; } -`; - } - return this.createStyleElement(styleText); - } - renderNumbering(numberings, styleContainer) { - var styleText = ""; - var resetCounters = []; - for (var num of numberings) { - var selector = `p.${this.numberingClass(num.id, num.level)}`; - var listStyleType = "none"; - if (num.bullet) { - let valiable = `--${this.className}-${num.bullet.src}`.toLowerCase(); - styleText += this.styleToString(`${selector}:before`, { - "content": "' '", - "display": "inline-block", - "background": `var(${valiable})` - }, num.bullet.style); - this.tasks.push(this.document.loadNumberingImage(num.bullet.src).then(data => { - var text = `${this.rootSelector} { ${valiable}: url(${data}) }`; - styleContainer.appendChild(this.createStyleElement(text)); - })); - } - else if (num.levelText) { - let counter = this.numberingCounter(num.id, num.level); - const counterReset = counter + " " + (num.start - 1); - if (num.level > 0) { - styleText += this.styleToString(`p.${this.numberingClass(num.id, num.level - 1)}`, { - "counter-set": counterReset - }); - } - resetCounters.push(counterReset); - styleText += this.styleToString(`${selector}:before`, { - "content": this.levelTextToContent(num.levelText, num.suff, num.id, this.numFormatToCssValue(num.format)), - "counter-increment": counter, - ...num.rStyle, - }); - } - else { - listStyleType = this.numFormatToCssValue(num.format); - } - styleText += this.styleToString(selector, { - "display": "list-item", - "list-style-position": "inside", - "list-style-type": listStyleType, - ...num.pStyle - }); - } - if (resetCounters.length > 0) { - styleText += this.styleToString(this.rootSelector, { - "counter-reset": resetCounters.join(" ") - }); - } - return this.createStyleElement(styleText); - } - renderStyles(styles) { - var styleText = ""; - const stylesMap = this.styleMap; - const defautStyles = keyBy(styles.filter(s => s.isDefault), s => s.target); - for (const style of styles) { - var subStyles = style.styles; - if (style.linked) { - var linkedStyle = style.linked && stylesMap[style.linked]; - if (linkedStyle) - subStyles = subStyles.concat(linkedStyle.styles); - else if (this.options.debug) - console.warn(`Can't find linked style ${style.linked}`); - } - for (const subStyle of subStyles) { - var selector = `${style.target ?? ''}.${style.cssName}`; - if (style.target != subStyle.target) - selector += ` ${subStyle.target}`; - if (defautStyles[style.target] == style) - selector = `.${this.className} ${style.target}, ` + selector; - styleText += this.styleToString(selector, subStyle.values); - } - } - return this.createStyleElement(styleText); - } - renderNotes(noteIds, notesMap, into) { - var notes = noteIds.map(id => notesMap[id]).filter(x => x); - if (notes.length > 0) { - var result = this.createElement("ol", null, this.renderElements(notes)); - into.appendChild(result); - } - } - renderElement(elem) { - switch (elem.type) { - case DomType.Paragraph: - return this.renderParagraph(elem); - case DomType.BookmarkStart: - return this.renderBookmarkStart(elem); - case DomType.BookmarkEnd: - return null; - case DomType.Run: - return this.renderRun(elem); - case DomType.Table: - return this.renderTable(elem); - case DomType.Row: - return this.renderTableRow(elem); - case DomType.Cell: - return this.renderTableCell(elem); - case DomType.Hyperlink: - return this.renderHyperlink(elem); - case DomType.SmartTag: - return this.renderSmartTag(elem); - case DomType.Drawing: - return this.renderDrawing(elem); - case DomType.Image: - return this.renderImage(elem); - case DomType.Text: - return this.renderText(elem); - case DomType.Text: - return this.renderText(elem); - case DomType.DeletedText: - return this.renderDeletedText(elem); - case DomType.Tab: - return this.renderTab(elem); - case DomType.Symbol: - return this.renderSymbol(elem); - case DomType.Break: - return this.renderBreak(elem); - case DomType.Footer: - return this.renderContainer(elem, "footer"); - case DomType.Header: - return this.renderContainer(elem, "header"); - case DomType.Footnote: - case DomType.Endnote: - return this.renderContainer(elem, "li"); - case DomType.FootnoteReference: - return this.renderFootnoteReference(elem); - case DomType.EndnoteReference: - return this.renderEndnoteReference(elem); - case DomType.NoBreakHyphen: - return this.createElement("wbr"); - case DomType.VmlPicture: - return this.renderVmlPicture(elem); - case DomType.VmlElement: - return this.renderVmlElement(elem); - case DomType.MmlMath: - return this.renderContainerNS(elem, ns.mathML, "math", { xmlns: ns.mathML }); - case DomType.MmlMathParagraph: - return this.renderContainer(elem, "span"); - case DomType.MmlFraction: - return this.renderContainerNS(elem, ns.mathML, "mfrac"); - case DomType.MmlBase: - return this.renderContainerNS(elem, ns.mathML, elem.parent.type == DomType.MmlMatrixRow ? "mtd" : "mrow"); - case DomType.MmlNumerator: - case DomType.MmlDenominator: - case DomType.MmlFunction: - case DomType.MmlLimit: - case DomType.MmlBox: - return this.renderContainerNS(elem, ns.mathML, "mrow"); - case DomType.MmlGroupChar: - return this.renderMmlGroupChar(elem); - case DomType.MmlLimitLower: - return this.renderContainerNS(elem, ns.mathML, "munder"); - case DomType.MmlMatrix: - return this.renderContainerNS(elem, ns.mathML, "mtable"); - case DomType.MmlMatrixRow: - return this.renderContainerNS(elem, ns.mathML, "mtr"); - case DomType.MmlRadical: - return this.renderMmlRadical(elem); - case DomType.MmlSuperscript: - return this.renderContainerNS(elem, ns.mathML, "msup"); - case DomType.MmlSubscript: - return this.renderContainerNS(elem, ns.mathML, "msub"); - case DomType.MmlDegree: - case DomType.MmlSuperArgument: - case DomType.MmlSubArgument: - return this.renderContainerNS(elem, ns.mathML, "mn"); - case DomType.MmlFunctionName: - return this.renderContainerNS(elem, ns.mathML, "ms"); - case DomType.MmlDelimiter: - return this.renderMmlDelimiter(elem); - case DomType.MmlRun: - return this.renderMmlRun(elem); - case DomType.MmlNary: - return this.renderMmlNary(elem); - case DomType.MmlPreSubSuper: - return this.renderMmlPreSubSuper(elem); - case DomType.MmlBar: - return this.renderMmlBar(elem); - case DomType.MmlEquationArray: - return this.renderMllList(elem); - case DomType.Inserted: - return this.renderInserted(elem); - case DomType.Deleted: - return this.renderDeleted(elem); - case DomType.CommentRangeStart: - return this.renderCommentRangeStart(elem); - case DomType.CommentRangeEnd: - return this.renderCommentRangeEnd(elem); - case DomType.CommentReference: - return this.renderCommentReference(elem); - case DomType.AltChunk: - return this.renderAltChunk(elem); - } - return null; - } - renderElements(elems, into) { - if (elems == null) - return null; - var result = elems.flatMap(e => this.renderElement(e)).filter(e => e != null); - if (into) - appendChildren(into, result); - return result; - } - renderContainer(elem, tagName, props) { - return this.createElement(tagName, props, this.renderElements(elem.children)); - } - renderContainerNS(elem, ns, tagName, props) { - return this.createElementNS(ns, tagName, props, this.renderElements(elem.children)); - } - renderParagraph(elem) { - var result = this.renderContainer(elem, "p"); - const style = this.findStyle(elem.styleName); - elem.tabs ?? (elem.tabs = style?.paragraphProps?.tabs); - this.renderClass(elem, result); - this.renderStyleValues(elem.cssStyle, result); - this.renderCommonProperties(result.style, elem); - const numbering = elem.numbering ?? style?.paragraphProps?.numbering; - if (numbering) { - result.classList.add(this.numberingClass(numbering.id, numbering.level)); - } - return result; - } - renderRunProperties(style, props) { - this.renderCommonProperties(style, props); - } - renderCommonProperties(style, props) { - if (props == null) - return; - if (props.color) { - style["color"] = props.color; - } - if (props.fontSize) { - style["font-size"] = props.fontSize; - } - } - renderHyperlink(elem) { - var result = this.renderContainer(elem, "a"); - this.renderStyleValues(elem.cssStyle, result); - let href = ''; - if (elem.id) { - const rel = this.document.documentPart.rels.find(it => it.id == elem.id && it.targetMode === "External"); - href = rel?.target ?? href; - } - if (elem.anchor) { - href += `#${elem.anchor}`; - } - result.href = href; - return result; - } - renderSmartTag(elem) { - return this.renderContainer(elem, "span"); - } - renderCommentRangeStart(commentStart) { - if (!this.options.renderComments) - return null; - const rng = new Range(); - this.commentHighlight?.add(rng); - const result = this.createComment(`start of comment #${commentStart.id}`); - this.later(() => rng.setStart(result, 0)); - this.commentMap[commentStart.id] = rng; - return result; - } - renderCommentRangeEnd(commentEnd) { - if (!this.options.renderComments) - return null; - const rng = this.commentMap[commentEnd.id]; - const result = this.createComment(`end of comment #${commentEnd.id}`); - this.later(() => rng?.setEnd(result, 0)); - return result; - } - renderCommentReference(commentRef) { - if (!this.options.renderComments) - return null; - var comment = this.document.commentsPart?.commentMap[commentRef.id]; - if (!comment) - return null; - const frg = new DocumentFragment(); - const commentRefEl = this.createElement("span", { className: `${this.className}-comment-ref` }, ['💬']); - const commentsContainerEl = this.createElement("div", { className: `${this.className}-comment-popover` }); - this.renderCommentContent(comment, commentsContainerEl); - frg.appendChild(this.createComment(`comment #${comment.id} by ${comment.author} on ${comment.date}`)); - frg.appendChild(commentRefEl); - frg.appendChild(commentsContainerEl); - return frg; - } - renderAltChunk(elem) { - if (!this.options.renderAltChunks) - return null; - var result = this.createElement("iframe"); - this.tasks.push(this.document.loadAltChunk(elem.id, this.currentPart).then(x => { - result.srcdoc = x; - })); - return result; - } - renderCommentContent(comment, container) { - container.appendChild(this.createElement('div', { className: `${this.className}-comment-author` }, [comment.author])); - container.appendChild(this.createElement('div', { className: `${this.className}-comment-date` }, [new Date(comment.date).toLocaleString()])); - this.renderElements(comment.children, container); - } - renderDrawing(elem) { - var result = this.renderContainer(elem, "div"); - result.style.display = "inline-block"; - result.style.position = "relative"; - result.style.textIndent = "0px"; - this.renderStyleValues(elem.cssStyle, result); - return result; - } - renderImage(elem) { - let result = this.createElement("img"); - let transform = elem.cssStyle?.transform; - this.renderStyleValues(elem.cssStyle, result); - if (elem.srcRect && elem.srcRect.some(x => x != 0)) { - var [left, top, right, bottom] = elem.srcRect; - transform = `scale(${1 / (1 - left - right)}, ${1 / (1 - top - bottom)})`; - result.style['clip-path'] = `rect(${(100 * top).toFixed(2)}% ${(100 * (1 - right)).toFixed(2)}% ${(100 * (1 - bottom)).toFixed(2)}% ${(100 * left).toFixed(2)}%)`; - } - if (elem.rotation) - transform = `rotate(${elem.rotation}deg) ${transform ?? ''}`; - result.style.transform = transform?.trim(); - if (this.document) { - this.tasks.push(this.document.loadDocumentImage(elem.src, this.currentPart).then(x => { - result.src = x; - })); - } - return result; - } - renderText(elem) { - return this.htmlDocument.createTextNode(elem.text); - } - renderDeletedText(elem) { - return this.options.renderChanges ? this.renderText(elem) : null; - } - renderBreak(elem) { - if (elem.break == "textWrapping") { - return this.createElement("br"); - } - return null; - } - renderInserted(elem) { - if (this.options.renderChanges) - return this.renderContainer(elem, "ins"); - return this.renderElements(elem.children); - } - renderDeleted(elem) { - if (this.options.renderChanges) - return this.renderContainer(elem, "del"); - return null; - } - renderSymbol(elem) { - var span = this.createElement("span"); - span.style.fontFamily = elem.font; - span.innerHTML = `&#x${elem.char};`; - return span; - } - renderFootnoteReference(elem) { - var result = this.createElement("sup"); - this.currentFootnoteIds.push(elem.id); - result.textContent = `${this.currentFootnoteIds.length}`; - return result; - } - renderEndnoteReference(elem) { - var result = this.createElement("sup"); - this.currentEndnoteIds.push(elem.id); - result.textContent = `${this.currentEndnoteIds.length}`; - return result; - } - renderTab(elem) { - var tabSpan = this.createElement("span"); - tabSpan.innerHTML = " "; - if (this.options.experimental) { - tabSpan.className = this.tabStopClass(); - var stops = findParent(elem, DomType.Paragraph)?.tabs; - this.currentTabs.push({ stops, span: tabSpan }); - } - return tabSpan; - } - renderBookmarkStart(elem) { - return this.createElement("span", { id: elem.name }); - } - renderRun(elem) { - if (elem.fieldRun) - return null; - const result = this.createElement("span"); - if (elem.id) - result.id = elem.id; - this.renderClass(elem, result); - this.renderStyleValues(elem.cssStyle, result); - if (elem.verticalAlign) { - const wrapper = this.createElement(elem.verticalAlign); - this.renderElements(elem.children, wrapper); - result.appendChild(wrapper); - } - else { - this.renderElements(elem.children, result); - } - return result; - } - renderTable(elem) { - let result = this.createElement("table"); - this.tableCellPositions.push(this.currentCellPosition); - this.tableVerticalMerges.push(this.currentVerticalMerge); - this.currentVerticalMerge = {}; - this.currentCellPosition = { col: 0, row: 0 }; - if (elem.columns) - result.appendChild(this.renderTableColumns(elem.columns)); - this.renderClass(elem, result); - this.renderElements(elem.children, result); - this.renderStyleValues(elem.cssStyle, result); - this.currentVerticalMerge = this.tableVerticalMerges.pop(); - this.currentCellPosition = this.tableCellPositions.pop(); - return result; - } - renderTableColumns(columns) { - let result = this.createElement("colgroup"); - for (let col of columns) { - let colElem = this.createElement("col"); - if (col.width) - colElem.style.width = col.width; - result.appendChild(colElem); - } - return result; - } - renderTableRow(elem) { - let result = this.createElement("tr"); - this.currentCellPosition.col = 0; - if (elem.gridBefore) - result.appendChild(this.renderTableCellPlaceholder(elem.gridBefore)); - this.renderClass(elem, result); - this.renderElements(elem.children, result); - this.renderStyleValues(elem.cssStyle, result); - if (elem.gridAfter) - result.appendChild(this.renderTableCellPlaceholder(elem.gridAfter)); - this.currentCellPosition.row++; - return result; - } - renderTableCellPlaceholder(colSpan) { - const result = this.createElement("td", { colSpan }); - result.style['border'] = 'none'; - return result; - } - renderTableCell(elem) { - let result = this.renderContainer(elem, "td"); - const key = this.currentCellPosition.col; - if (elem.verticalMerge) { - if (elem.verticalMerge == "restart") { - this.currentVerticalMerge[key] = result; - result.rowSpan = 1; - } - else if (this.currentVerticalMerge[key]) { - this.currentVerticalMerge[key].rowSpan += 1; - result.style.display = "none"; - } - } - else { - this.currentVerticalMerge[key] = null; - } - this.renderClass(elem, result); - this.renderStyleValues(elem.cssStyle, result); - if (elem.span) - result.colSpan = elem.span; - this.currentCellPosition.col += result.colSpan; - return result; - } - renderVmlPicture(elem) { - return this.renderContainer(elem, "div"); - } - renderVmlElement(elem) { - var container = this.createSvgElement("svg"); - container.setAttribute("style", elem.cssStyleText); - const result = this.renderVmlChildElement(elem); - if (elem.imageHref?.id) { - this.tasks.push(this.document?.loadDocumentImage(elem.imageHref.id, this.currentPart) - .then(x => result.setAttribute("href", x))); - } - container.appendChild(result); - requestAnimationFrame(() => { - const bb = container.firstElementChild.getBBox(); - container.setAttribute("width", `${Math.ceil(bb.x + bb.width)}`); - container.setAttribute("height", `${Math.ceil(bb.y + bb.height)}`); - }); - return container; - } - renderVmlChildElement(elem) { - const result = this.createSvgElement(elem.tagName); - Object.entries(elem.attrs).forEach(([k, v]) => result.setAttribute(k, v)); - for (let child of elem.children) { - if (child.type == DomType.VmlElement) { - result.appendChild(this.renderVmlChildElement(child)); - } - else { - result.appendChild(...asArray(this.renderElement(child))); - } - } - return result; - } - renderMmlRadical(elem) { - const base = elem.children.find(el => el.type == DomType.MmlBase); - if (elem.props?.hideDegree) { - return this.createElementNS(ns.mathML, "msqrt", null, this.renderElements([base])); - } - const degree = elem.children.find(el => el.type == DomType.MmlDegree); - return this.createElementNS(ns.mathML, "mroot", null, this.renderElements([base, degree])); - } - renderMmlDelimiter(elem) { - const children = []; - children.push(this.createElementNS(ns.mathML, "mo", null, [elem.props.beginChar ?? '('])); - children.push(...this.renderElements(elem.children)); - children.push(this.createElementNS(ns.mathML, "mo", null, [elem.props.endChar ?? ')'])); - return this.createElementNS(ns.mathML, "mrow", null, children); - } - renderMmlNary(elem) { - const children = []; - const grouped = keyBy(elem.children, x => x.type); - const sup = grouped[DomType.MmlSuperArgument]; - const sub = grouped[DomType.MmlSubArgument]; - const supElem = sup ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sup))) : null; - const subElem = sub ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sub))) : null; - const charElem = this.createElementNS(ns.mathML, "mo", null, [elem.props?.char ?? '\u222B']); - if (supElem || subElem) { - children.push(this.createElementNS(ns.mathML, "munderover", null, [charElem, subElem, supElem])); - } - else if (supElem) { - children.push(this.createElementNS(ns.mathML, "mover", null, [charElem, supElem])); - } - else if (subElem) { - children.push(this.createElementNS(ns.mathML, "munder", null, [charElem, subElem])); - } - else { - children.push(charElem); - } - children.push(...this.renderElements(grouped[DomType.MmlBase].children)); - return this.createElementNS(ns.mathML, "mrow", null, children); - } - renderMmlPreSubSuper(elem) { - const children = []; - const grouped = keyBy(elem.children, x => x.type); - const sup = grouped[DomType.MmlSuperArgument]; - const sub = grouped[DomType.MmlSubArgument]; - const supElem = sup ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sup))) : null; - const subElem = sub ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sub))) : null; - const stubElem = this.createElementNS(ns.mathML, "mo", null); - children.push(this.createElementNS(ns.mathML, "msubsup", null, [stubElem, subElem, supElem])); - children.push(...this.renderElements(grouped[DomType.MmlBase].children)); - return this.createElementNS(ns.mathML, "mrow", null, children); - } - renderMmlGroupChar(elem) { - const tagName = elem.props.verticalJustification === "bot" ? "mover" : "munder"; - const result = this.renderContainerNS(elem, ns.mathML, tagName); - if (elem.props.char) { - result.appendChild(this.createElementNS(ns.mathML, "mo", null, [elem.props.char])); - } - return result; - } - renderMmlBar(elem) { - const result = this.renderContainerNS(elem, ns.mathML, "mrow"); - switch (elem.props.position) { - case "top": - result.style.textDecoration = "overline"; - break; - case "bottom": - result.style.textDecoration = "underline"; - break; - } - return result; - } - renderMmlRun(elem) { - const result = this.createElementNS(ns.mathML, "ms", null, this.renderElements(elem.children)); - this.renderClass(elem, result); - this.renderStyleValues(elem.cssStyle, result); - return result; - } - renderMllList(elem) { - const result = this.createElementNS(ns.mathML, "mtable"); - this.renderClass(elem, result); - this.renderStyleValues(elem.cssStyle, result); - for (let child of this.renderElements(elem.children)) { - result.appendChild(this.createElementNS(ns.mathML, "mtr", null, [ - this.createElementNS(ns.mathML, "mtd", null, [child]) - ])); - } - return result; - } - renderStyleValues(style, ouput) { - for (let k in style) { - if (k.startsWith("$")) { - ouput.setAttribute(k.slice(1), style[k]); - } - else { - ouput.style[k] = style[k]; - } - } - } - renderClass(input, ouput) { - if (input.className) - ouput.className = input.className; - if (input.styleName) - ouput.classList.add(this.processStyleName(input.styleName)); - } - findStyle(styleName) { - return styleName && this.styleMap?.[styleName]; - } - numberingClass(id, lvl) { - return `${this.className}-num-${id}-${lvl}`; - } - tabStopClass() { - return `${this.className}-tab-stop`; - } - styleToString(selectors, values, cssText = null) { - let result = `${selectors} {\r\n`; - for (const key in values) { - if (key.startsWith('$')) - continue; - result += ` ${key}: ${values[key]};\r\n`; - } - if (cssText) - result += cssText; - return result + "}\r\n"; - } - numberingCounter(id, lvl) { - return `${this.className}-num-${id}-${lvl}`; - } - levelTextToContent(text, suff, id, numformat) { - const suffMap = { - "tab": "\\9", - "space": "\\a0", - }; - var result = text.replace(/%\d*/g, s => { - let lvl = parseInt(s.substring(1), 10) - 1; - return `"counter(${this.numberingCounter(id, lvl)}, ${numformat})"`; - }); - return `"${result}${suffMap[suff] ?? ""}"`; - } - numFormatToCssValue(format) { - var mapping = { - none: "none", - bullet: "disc", - decimal: "decimal", - lowerLetter: "lower-alpha", - upperLetter: "upper-alpha", - lowerRoman: "lower-roman", - upperRoman: "upper-roman", - decimalZero: "decimal-leading-zero", - aiueo: "katakana", - aiueoFullWidth: "katakana", - chineseCounting: "simp-chinese-informal", - chineseCountingThousand: "simp-chinese-informal", - chineseLegalSimplified: "simp-chinese-formal", - chosung: "hangul-consonant", - ideographDigital: "cjk-ideographic", - ideographTraditional: "cjk-heavenly-stem", - ideographLegalTraditional: "trad-chinese-formal", - ideographZodiac: "cjk-earthly-branch", - iroha: "katakana-iroha", - irohaFullWidth: "katakana-iroha", - japaneseCounting: "japanese-informal", - japaneseDigitalTenThousand: "cjk-decimal", - japaneseLegal: "japanese-formal", - thaiNumbers: "thai", - koreanCounting: "korean-hangul-formal", - koreanDigital: "korean-hangul-formal", - koreanDigital2: "korean-hanja-informal", - hebrew1: "hebrew", - hebrew2: "hebrew", - hindiNumbers: "devanagari", - ganada: "hangul", - taiwaneseCounting: "cjk-ideographic", - taiwaneseCountingThousand: "cjk-ideographic", - taiwaneseDigital: "cjk-decimal", - }; - return mapping[format] ?? format; - } - refreshTabStops() { - if (!this.options.experimental) - return; - setTimeout(() => { - const pixelToPoint = computePixelToPoint(); - for (let tab of this.currentTabs) { - updateTabStop(tab.span, tab.stops, this.defaultTabSize, pixelToPoint); - } - }, 500); - } - createElementNS(ns, tagName, props, children) { - var result = ns ? this.htmlDocument.createElementNS(ns, tagName) : this.htmlDocument.createElement(tagName); - Object.assign(result, props); - children && appendChildren(result, children); - return result; - } - createElement(tagName, props, children) { - return this.createElementNS(undefined, tagName, props, children); - } - createSvgElement(tagName, props, children) { - return this.createElementNS(ns.svg, tagName, props, children); - } - createStyleElement(cssText) { - return this.createElement("style", { innerHTML: cssText }); - } - createComment(text) { - return this.htmlDocument.createComment(text); - } - later(func) { - this.postRenderTasks.push(func); - } - } - function removeAllElements(elem) { - elem.innerHTML = ''; - } - function appendChildren(elem, children) { - children.forEach(c => elem.appendChild(isString(c) ? document.createTextNode(c) : c)); - } - function findParent(elem, type) { - var parent = elem.parent; - while (parent != null && parent.type != type) - parent = parent.parent; - return parent; - } - - const defaultOptions = { - ignoreHeight: false, - ignoreWidth: false, - ignoreFonts: false, - breakPages: true, - debug: false, - experimental: false, - className: "docx", - inWrapper: true, - hideWrapperOnPrint: false, - trimXmlDeclaration: true, - ignoreLastRenderedPageBreak: true, - renderHeaders: true, - renderFooters: true, - renderFootnotes: true, - renderEndnotes: true, - useBase64URL: false, - renderChanges: false, - renderComments: false, - renderAltChunks: true - }; - function parseAsync(data, userOptions) { - const ops = { ...defaultOptions, ...userOptions }; - return WordDocument.load(data, new DocumentParser(ops), ops); - } - async function renderDocument(document, bodyContainer, styleContainer, userOptions) { - const ops = { ...defaultOptions, ...userOptions }; - const renderer = new HtmlRenderer(window.document); - return await renderer.render(document, bodyContainer, styleContainer, ops); - } - async function renderAsync(data, bodyContainer, styleContainer, userOptions) { - const doc = await parseAsync(data, userOptions); - await renderDocument(doc, bodyContainer, styleContainer, userOptions); - return doc; - } - - exports.defaultOptions = defaultOptions; - exports.parseAsync = parseAsync; - exports.renderAsync = renderAsync; - exports.renderDocument = renderDocument; - -})); -//# sourceMappingURL=docx-preview.js.map diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.js.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.js.map deleted file mode 100644 index d315f350c..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"docx-preview.js","sources":["../src/common/relationship.ts","../src/utils.ts","../src/document/common.ts","../src/parser/xml-parser.ts","../src/common/part.ts","../src/font-table/fonts.ts","../src/font-table/font-table.ts","../src/common/open-xml-package.ts","../src/document/document-part.ts","../src/document/border.ts","../src/document/section.ts","../src/document/line-spacing.ts","../src/document/run.ts","../src/document/paragraph.ts","../src/numbering/numbering.ts","../src/numbering/numbering-part.ts","../src/styles/styles-part.ts","../src/document/dom.ts","../src/header-footer/elements.ts","../src/header-footer/parts.ts","../src/document-props/extended-props.ts","../src/document-props/extended-props-part.ts","../src/document-props/core-props.ts","../src/document-props/core-props-part.ts","../src/theme/theme.ts","../src/theme/theme-part.ts","../src/notes/elements.ts","../src/notes/parts.ts","../src/settings/settings.ts","../src/settings/settings-part.ts","../src/document-props/custom-props.ts","../src/document-props/custom-props-part.ts","../src/comments/comments-part.ts","../src/comments/comments-extended-part.ts","../src/word-document.ts","../src/document/bookmarks.ts","../src/vml/vml.ts","../src/comments/elements.ts","../src/document-parser.ts","../src/javascript.ts","../src/html-renderer.ts","../src/docx-preview.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["ns","parseNumbering","xml"],"mappings":";;;;;;;;;;;;IASA,IAAY,iBAqBX;IArBD,CAAA,UAAY,iBAAiB,EAAA;IACzB,IAAA,iBAAA,CAAA,gBAAA,CAAA,GAAA,oFAAqG;IACrG,IAAA,iBAAA,CAAA,WAAA,CAAA,GAAA,+EAA2F;IAC3F,IAAA,iBAAA,CAAA,OAAA,CAAA,GAAA,2EAAmF;IACnF,IAAA,iBAAA,CAAA,WAAA,CAAA,GAAA,+EAA2F;IAC3F,IAAA,iBAAA,CAAA,QAAA,CAAA,GAAA,4EAAqF;IACrF,IAAA,iBAAA,CAAA,mBAAA,CAAA,GAAA,0EAA8F;IAC9F,IAAA,iBAAA,CAAA,OAAA,CAAA,GAAA,2EAAmF;IACnF,IAAA,iBAAA,CAAA,UAAA,CAAA,GAAA,8EAAyF;IACzF,IAAA,iBAAA,CAAA,aAAA,CAAA,GAAA,iFAA+F;IAC/F,IAAA,iBAAA,CAA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E,IAAI;IACnB,IAAA,aAAa,EAAE,IAAI;IACnB,IAAA,eAAe,EAAE,IAAI;IACxB,IAAA,cAAc,EAAE,IAAI;IACpB,IAAA,YAAY,EAAE,KAAK;IACnB,IAAA,aAAa,EAAE,KAAK;IACjB,IAAA,cAAc,EAAE,KAAK;IACrB,IAAA,eAAe,EAAE;;IAGf,SAAU,UAAU,CAAC,IAAgB,EAAE,WAA8B,EAAA;QACvE,MAAM,GAAG,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,WAAW,EAAE;IACjD,IAAA,OAAO,YAAY,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,cAAc,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC;IAChE;IAEO,eAAe,cAAc,CAAC,QAAa,EAAE,aAA0B,EAAE,cAA4B,EAAE,WAA8B,EAAA;QACxI,MAAM,GAAG,GAAG,EAAE,GAAG,cAAc,EAAE,GAAG,WAAW,EAAE;QACjD,MAAM,QAAQ,GAAG,IAAI,YAAY,CAAC,MAAM,CAAC,QAAQ,CAAC;IACrD,IAAA,OAAO,MAAM,QAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,aAAa,EAAE,cAAc,EAAE,GAAG,CAAC;IAC3E;IAEO,eAAe,WAAW,CAAC,IAAgB,EAAE,aAA0B,EAAE,cAA4B,EAAE,WAA8B,EAAA;QAC3I,MAAM,GAAG,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,WAAW,CAAC;QAC/C,MAAM,cAAc,CAAC,GAAG,EAAE,aAAa,EAAE,cAAc,EAAE,WAAW,CAAC;IAClE,IAAA,OAAO,GAAG;IACd;;;;;;;;;;;"} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.min.js b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.min.js deleted file mode 100644 index 230faf368..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.min.js +++ /dev/null @@ -1,8 +0,0 @@ -/* - * @license - * docx-preview - * Released under Apache License 2.0 - * Copyright Volodymyr Baydalka - */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("jszip")):"function"==typeof define&&define.amd?define(["exports","jszip"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).docx={},e.JSZip)}(this,function(e,t){"use strict";var r;function a(e){return/^[^"'].*\s.*[^"']$/.test(e)?`'${e}'`:e}function s(e){let t=e.lastIndexOf("/")+1;return[0==t?"":e.substring(0,t),0==t?e:e.substring(t)]}function n(e,t){try{const r="http://docx/";return new URL(e,r+t).toString().substring(r.length)}catch{return`${t}${e}`}}function l(e,t){return e.reduce((e,r)=>(e[t(r)]=r,e),{})}function o(e){return e&&"object"==typeof e&&!Array.isArray(e)}function i(e,...t){if(!t.length)return e;const r=t.shift();if(o(e)&&o(r))for(const t in r)if(o(r[t])){i(e[t]??(e[t]={}),r[t])}else e[t]=r[t];return i(e,...t)}function c(e){return Array.isArray(e)?e:[e]}!function(e){e.OfficeDocument="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",e.FontTable="http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable",e.Image="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",e.Numbering="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",e.Styles="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",e.StylesWithEffects="http://schemas.microsoft.com/office/2007/relationships/stylesWithEffects",e.Theme="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",e.Settings="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings",e.WebSettings="http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings",e.Hyperlink="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",e.Footnotes="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes",e.Endnotes="http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes",e.Footer="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer",e.Header="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header",e.ExtendedProperties="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties",e.CoreProperties="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties",e.CustomProperties="http://schemas.openxmlformats.org/package/2006/relationships/metadata/custom-properties",e.Comments="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",e.CommentsExtended="http://schemas.microsoft.com/office/2011/relationships/commentsExtended",e.AltChunk="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk"}(r||(r={}));const h="http://schemas.openxmlformats.org/wordprocessingml/2006/main",m={mul:.05,unit:"pt"},p={mul:1/12700,unit:"pt"},u={mul:.5,unit:"pt"},d={mul:.125,unit:"pt",min:.25,max:12},f={mul:1,unit:"pt"},g={mul:.02,unit:"%"};function b(e,t=m){if(null==e||/.+(p[xt]|[%])$/.test(e))return e;var r=parseInt(e)*t.mul;return t.min&&t.max&&(r=function(e,t,r){return t>e?t:rfunction(e,t){let r={name:t.attr(e,"name"),embedFontRefs:[]};for(let a of t.elements(e))switch(a.localName){case"family":r.family=t.attr(a,"val");break;case"altName":r.altName=t.attr(a,"val");break;case"embedRegular":case"embedBold":case"embedItalic":case"embedBoldItalic":r.embedFontRefs.push(C(a,t))}return r}(e,t))}function C(e,t){return{id:t.attr(e,"id"),key:t.attr(e,"fontKey"),type:P[e.localName]}}class x extends S{parseXml(e){this.fonts=w(e,this._package.xmlParser)}}class N{constructor(e,t){this._zip=e,this.options=t,this.xmlParser=new k}get(e){const t=function(e){return e.startsWith("/")?e.substr(1):e}(e);return this._zip.files[t]??this._zip.files[t.replace(/\//g,"\\")]}update(e,t){this._zip.file(e,t)}static async load(e,r){const a=await t.loadAsync(e);return new N(a,r)}save(e="blob"){return this._zip.generateAsync({type:e})}load(e,t="string"){return this.get(e)?.async(t)??Promise.resolve(null)}async loadRelationships(e=null){let t="_rels/.rels";if(null!=e){const[r,a]=s(e);t=`${r}_rels/${a}.rels`}const r=await this.load(t);return r?(a=this.parseXmlDocument(r).firstElementChild,(n=this.xmlParser).elements(a).map(e=>({id:n.attr(e,"Id"),type:n.attr(e,"Type"),target:n.attr(e,"Target"),targetMode:n.attr(e,"TargetMode")}))):null;var a,n}parseXmlDocument(e){return function(e,t=!1){var r;t&&(e=e.replace(/<[?].*[?]>/,"")),e=65279===(r=e).charCodeAt(0)?r.substring(1):r;const a=(new DOMParser).parseFromString(e,"application/xml"),s=(n=a,n.getElementsByTagName("parsererror")[0]?.textContent);var n;if(s)throw new Error(s);return a}(e,this.options.trimXmlDeclaration)}}class M extends S{constructor(e,t,r){super(e,t),this._documentParser=r}parseXml(e){this.body=this._documentParser.parseDocumentFile(e)}}function A(e,t){return{type:t.attr(e,"val"),color:t.attr(e,"color"),size:t.lengthAttr(e,"sz",d),offset:t.lengthAttr(e,"space",f),frame:t.boolAttr(e,"frame"),shadow:t.boolAttr(e,"shadow")}}function E(e,t){var r={};for(let a of t.elements(e))switch(a.localName){case"left":r.left=A(a,t);break;case"top":r.top=A(a,t);break;case"right":r.right=A(a,t);break;case"bottom":r.bottom=A(a,t)}return r}var T,R;function B(e,t=v){var r={};for(let a of t.elements(e))switch(a.localName){case"pgSz":r.pageSize={width:t.lengthAttr(a,"w"),height:t.lengthAttr(a,"h"),orientation:t.attr(a,"orient")};break;case"type":r.type=t.attr(a,"val");break;case"pgMar":r.pageMargins={left:t.lengthAttr(a,"left"),right:t.lengthAttr(a,"right"),top:t.lengthAttr(a,"top"),bottom:t.lengthAttr(a,"bottom"),header:t.lengthAttr(a,"header"),footer:t.lengthAttr(a,"footer"),gutter:t.lengthAttr(a,"gutter")};break;case"cols":r.columns=D(a,t);break;case"headerReference":(r.headerRefs??(r.headerRefs=[])).push(F(a,t));break;case"footerReference":(r.footerRefs??(r.footerRefs=[])).push(F(a,t));break;case"titlePg":r.titlePage=t.boolAttr(a,"val",!0);break;case"pgBorders":r.pageBorders=E(a,t);break;case"pgNumType":r.pageNumber=$(a,t)}return r}function D(e,t){return{numberOfColumns:t.intAttr(e,"num"),space:t.lengthAttr(e,"space"),separator:t.boolAttr(e,"sep"),equalWidth:t.boolAttr(e,"equalWidth",!0),columns:t.elements(e,"col").map(e=>({width:t.lengthAttr(e,"w"),space:t.lengthAttr(e,"space")}))}}function $(e,t){return{chapSep:t.attr(e,"chapSep"),chapStyle:t.attr(e,"chapStyle"),format:t.attr(e,"fmt"),start:t.intAttr(e,"start")}}function F(e,t){return{id:t.attr(e,"id"),type:t.attr(e,"type")}}function L(e,t){let r={};for(let a of t.elements(e))I(a,r,t);return r}function I(e,t,r){return!!y(e,t,r)}function O(e,t){let r={};for(let a of t.elements(e))H(a,r,t);return r}function H(e,t,r){if(e.namespaceURI!=h)return!1;if(y(e,t,r))return!0;switch(e.localName){case"tabs":t.tabs=function(e,t){return t.elements(e,"tab").map(e=>({position:t.lengthAttr(e,"pos"),leader:t.attr(e,"leader"),style:t.attr(e,"val")}))}(e,r);break;case"sectPr":t.sectionProps=B(e,r);break;case"numPr":t.numbering=function(e,t){var r={};for(let a of t.elements(e))switch(a.localName){case"numId":r.id=t.attr(a,"val");break;case"ilvl":r.level=t.intAttr(a,"val")}return r}(e,r);break;case"spacing":return t.lineSpacing=function(e,t){return{before:t.lengthAttr(e,"before"),after:t.lengthAttr(e,"after"),line:t.intAttr(e,"line"),lineRule:t.attr(e,"lineRule")}}(e,r),!1;case"textAlignment":return t.textAlignment=r.attr(e,"val"),!1;case"keepLines":t.keepLines=r.boolAttr(e,"val",!0);break;case"keepNext":t.keepNext=r.boolAttr(e,"val",!0);break;case"pageBreakBefore":t.pageBreakBefore=r.boolAttr(e,"val",!0);break;case"outlineLvl":t.outlineLevel=r.intAttr(e,"val");break;case"pStyle":t.styleName=r.attr(e,"val");break;case"rPr":t.runProps=L(e,r);break;default:return!1}return!0}function _(e,t){let r={id:t.attr(e,"numId"),overrides:[]};for(let a of t.elements(e))switch(a.localName){case"abstractNumId":r.abstractId=t.attr(a,"val");break;case"lvlOverride":r.overrides.push(j(a,t))}return r}function z(e,t){let r={id:t.attr(e,"abstractNumId"),levels:[]};for(let a of t.elements(e))switch(a.localName){case"name":r.name=t.attr(a,"val");break;case"multiLevelType":r.multiLevelType=t.attr(a,"val");break;case"numStyleLink":r.numberingStyleLink=t.attr(a,"val");break;case"styleLink":r.styleLink=t.attr(a,"val");break;case"lvl":r.levels.push(V(a,t))}return r}function V(e,t){let r={level:t.intAttr(e,"ilvl")};for(let a of t.elements(e))switch(a.localName){case"start":r.start=t.attr(a,"val");break;case"lvlRestart":r.restart=t.intAttr(a,"val");break;case"numFmt":r.format=t.attr(a,"val");break;case"lvlText":r.text=t.attr(a,"val");break;case"lvlJc":r.justification=t.attr(a,"val");break;case"lvlPicBulletId":r.bulletPictureId=t.attr(a,"val");break;case"pStyle":r.paragraphStyle=t.attr(a,"val");break;case"pPr":r.paragraphProps=O(a,t);break;case"rPr":r.runProps=L(a,t)}return r}function j(e,t){let r={level:t.intAttr(e,"ilvl")};for(let a of t.elements(e))switch(a.localName){case"startOverride":r.start=t.intAttr(a,"val");break;case"lvl":r.numberingLevel=V(a,t)}return r}function W(e,t){var r=t.element(e,"pict"),a=r&&t.element(r,"shape"),s=a&&t.element(a,"imagedata");return s?{id:t.attr(e,"numPicBulletId"),referenceId:t.attr(s,"id"),style:t.attr(a,"style")}:null}!function(e){e.Continuous="continuous",e.NextPage="nextPage",e.NextColumn="nextColumn",e.EvenPage="evenPage",e.OddPage="oddPage"}(T||(T={}));class X extends S{constructor(e,t,r){super(e,t),this._documentParser=r}parseXml(e){Object.assign(this,function(e,t){let r={numberings:[],abstractNumberings:[],bulletPictures:[]};for(let a of t.elements(e))switch(a.localName){case"num":r.numberings.push(_(a,t));break;case"abstractNum":r.abstractNumberings.push(z(a,t));break;case"numPicBullet":r.bulletPictures.push(W(a,t))}return r}(e,this._package.xmlParser)),this.domNumberings=this._documentParser.parseNumberingFile(e)}}class G extends S{constructor(e,t,r){super(e,t),this._documentParser=r}parseXml(e){this.styles=this._documentParser.parseStylesFile(e)}}!function(e){e.Document="document",e.Paragraph="paragraph",e.Run="run",e.Break="break",e.NoBreakHyphen="noBreakHyphen",e.Table="table",e.Row="row",e.Cell="cell",e.Hyperlink="hyperlink",e.SmartTag="smartTag",e.Drawing="drawing",e.Image="image",e.Text="text",e.Tab="tab",e.Symbol="symbol",e.BookmarkStart="bookmarkStart",e.BookmarkEnd="bookmarkEnd",e.Footer="footer",e.Header="header",e.FootnoteReference="footnoteReference",e.EndnoteReference="endnoteReference",e.Footnote="footnote",e.Endnote="endnote",e.SimpleField="simpleField",e.ComplexField="complexField",e.Instruction="instruction",e.VmlPicture="vmlPicture",e.MmlMath="mmlMath",e.MmlMathParagraph="mmlMathParagraph",e.MmlFraction="mmlFraction",e.MmlFunction="mmlFunction",e.MmlFunctionName="mmlFunctionName",e.MmlNumerator="mmlNumerator",e.MmlDenominator="mmlDenominator",e.MmlRadical="mmlRadical",e.MmlBase="mmlBase",e.MmlDegree="mmlDegree",e.MmlSuperscript="mmlSuperscript",e.MmlSubscript="mmlSubscript",e.MmlPreSubSuper="mmlPreSubSuper",e.MmlSubArgument="mmlSubArgument",e.MmlSuperArgument="mmlSuperArgument",e.MmlNary="mmlNary",e.MmlDelimiter="mmlDelimiter",e.MmlRun="mmlRun",e.MmlEquationArray="mmlEquationArray",e.MmlLimit="mmlLimit",e.MmlLimitLower="mmlLimitLower",e.MmlMatrix="mmlMatrix",e.MmlMatrixRow="mmlMatrixRow",e.MmlBox="mmlBox",e.MmlBar="mmlBar",e.MmlGroupChar="mmlGroupChar",e.VmlElement="vmlElement",e.Inserted="inserted",e.Deleted="deleted",e.DeletedText="deletedText",e.Comment="comment",e.CommentReference="commentReference",e.CommentRangeStart="commentRangeStart",e.CommentRangeEnd="commentRangeEnd",e.AltChunk="altChunk"}(R||(R={}));class U{constructor(){this.children=[],this.cssStyle={}}}class q extends U{constructor(){super(...arguments),this.type=R.Header}}class J extends U{constructor(){super(...arguments),this.type=R.Footer}}class Z extends S{constructor(e,t,r){super(e,t),this._documentParser=r}parseXml(e){this.rootElement=this.createRootElement(),this.rootElement.children=this._documentParser.parseBodyElements(e)}}class K extends Z{createRootElement(){return new q}}class Y extends Z{createRootElement(){return new J}}function Q(e){if(void 0!==e)return parseInt(e)}class ee extends S{parseXml(e){this.props=function(e,t){const r={};for(let a of t.elements(e))switch(a.localName){case"Template":r.template=a.textContent;break;case"Pages":r.pages=Q(a.textContent);break;case"Words":r.words=Q(a.textContent);break;case"Characters":r.characters=Q(a.textContent);break;case"Application":r.application=a.textContent;break;case"Lines":r.lines=Q(a.textContent);break;case"Paragraphs":r.paragraphs=Q(a.textContent);break;case"Company":r.company=a.textContent;break;case"AppVersion":r.appVersion=a.textContent}return r}(e,this._package.xmlParser)}}class te extends S{parseXml(e){this.props=function(e,t){const r={};for(let a of t.elements(e))switch(a.localName){case"title":r.title=a.textContent;break;case"description":r.description=a.textContent;break;case"subject":r.subject=a.textContent;break;case"creator":r.creator=a.textContent;break;case"keywords":r.keywords=a.textContent;break;case"language":r.language=a.textContent;break;case"lastModifiedBy":r.lastModifiedBy=a.textContent;break;case"revision":a.textContent&&(r.revision=parseInt(a.textContent))}return r}(e,this._package.xmlParser)}}class re{}function ae(e,t){var r={name:t.attr(e,"name"),colors:{}};for(let n of t.elements(e)){var a=t.element(n,"srgbClr"),s=t.element(n,"sysClr");a?r.colors[n.localName]=t.attr(a,"val"):s&&(r.colors[n.localName]=t.attr(s,"lastClr"))}return r}function se(e,t){var r={name:t.attr(e,"name")};for(let a of t.elements(e))switch(a.localName){case"majorFont":r.majorFont=ne(a,t);break;case"minorFont":r.minorFont=ne(a,t)}return r}function ne(e,t){return{latinTypeface:t.elementAttr(e,"latin","typeface"),eaTypeface:t.elementAttr(e,"ea","typeface"),csTypeface:t.elementAttr(e,"cs","typeface")}}class le extends S{constructor(e,t){super(e,t)}parseXml(e){this.theme=function(e,t){var r=new re,a=t.element(e,"themeElements");for(let e of t.elements(a))switch(e.localName){case"clrScheme":r.colorScheme=ae(e,t);break;case"fontScheme":r.fontScheme=se(e,t)}return r}(e,this._package.xmlParser)}}class oe{}class ie extends oe{constructor(){super(...arguments),this.type=R.Footnote}}class ce extends oe{constructor(){super(...arguments),this.type=R.Endnote}}class he extends S{constructor(e,t,r){super(e,t),this._documentParser=r}}class me extends he{constructor(e,t,r){super(e,t,r)}parseXml(e){this.notes=this._documentParser.parseNotes(e,"footnote",ie)}}class pe extends he{constructor(e,t,r){super(e,t,r)}parseXml(e){this.notes=this._documentParser.parseNotes(e,"endnote",ce)}}function ue(e,t){var r={defaultNoteIds:[]};for(let a of t.elements(e))switch(a.localName){case"numFmt":r.nummeringFormat=t.attr(a,"val");break;case"footnote":case"endnote":r.defaultNoteIds.push(t.attr(a,"id"))}return r}class de extends S{constructor(e,t){super(e,t)}parseXml(e){this.settings=function(e,t){var r={};for(let a of t.elements(e))switch(a.localName){case"defaultTabStop":r.defaultTabStop=t.lengthAttr(a,"val");break;case"footnotePr":r.footnoteProps=ue(a,t);break;case"endnotePr":r.endnoteProps=ue(a,t);break;case"autoHyphenation":r.autoHyphenation=t.boolAttr(a,"val")}return r}(e,this._package.xmlParser)}}class fe extends S{parseXml(e){this.props=function(e,t){return t.elements(e,"property").map(e=>{const r=e.firstChild;return{formatId:t.attr(e,"fmtid"),name:t.attr(e,"name"),type:r.nodeName,value:r.textContent}})}(e,this._package.xmlParser)}}class ge extends S{constructor(e,t,r){super(e,t),this._documentParser=r}parseXml(e){this.comments=this._documentParser.parseComments(e),this.commentMap=l(this.comments,e=>e.id)}}class be extends S{constructor(e,t){super(e,t),this.comments=[]}parseXml(e){const t=this._package.xmlParser;for(let r of t.elements(e,"commentEx"))this.comments.push({paraId:t.attr(r,"paraId"),paraIdParent:t.attr(r,"paraIdParent"),done:t.boolAttr(r,"done")});this.commentMap=l(this.comments,e=>e.paraId)}}const ye=[{type:r.OfficeDocument,target:"word/document.xml"},{type:r.ExtendedProperties,target:"docProps/app.xml"},{type:r.CoreProperties,target:"docProps/core.xml"},{type:r.CustomProperties,target:"docProps/custom.xml"}];class ke{constructor(){this.parts=[],this.partsMap={}}static async load(e,t,r){var a=new ke;return a._options=r,a._parser=t,a._package=await N.load(e,r),a.rels=await a._package.loadRelationships(),await Promise.all(ye.map(e=>{const t=a.rels.find(t=>t.type===e.type)??e;return a.loadRelationshipPart(t.target,t.type)})),a}save(e="blob"){return this._package.save(e)}async loadRelationshipPart(e,t){if(this.partsMap[e])return this.partsMap[e];if(!this._package.get(e))return null;let a=null;switch(t){case r.OfficeDocument:this.documentPart=a=new M(this._package,e,this._parser);break;case r.FontTable:this.fontTablePart=a=new x(this._package,e);break;case r.Numbering:this.numberingPart=a=new X(this._package,e,this._parser);break;case r.Styles:this.stylesPart=a=new G(this._package,e,this._parser);break;case r.Theme:this.themePart=a=new le(this._package,e);break;case r.Footnotes:this.footnotesPart=a=new me(this._package,e,this._parser);break;case r.Endnotes:this.endnotesPart=a=new pe(this._package,e,this._parser);break;case r.Footer:a=new Y(this._package,e,this._parser);break;case r.Header:a=new K(this._package,e,this._parser);break;case r.CoreProperties:this.corePropsPart=a=new te(this._package,e);break;case r.ExtendedProperties:this.extendedPropsPart=a=new ee(this._package,e);break;case r.CustomProperties:a=new fe(this._package,e);break;case r.Settings:this.settingsPart=a=new de(this._package,e);break;case r.Comments:this.commentsPart=a=new ge(this._package,e,this._parser);break;case r.CommentsExtended:this.commentsExtendedPart=a=new be(this._package,e)}if(null==a)return Promise.resolve(null);if(this.partsMap[e]=a,this.parts.push(a),await a.load(),a.rels?.length>0){const[e]=s(a.path);await Promise.all(a.rels.map(t=>this.loadRelationshipPart(n(t.target,e),t.type)))}return a}async loadDocumentImage(e,t){const r=await this.loadResource(t??this.documentPart,e,"blob");return this.blobToURL(r)}async loadNumberingImage(e){const t=await this.loadResource(this.numberingPart,e,"blob");return this.blobToURL(t)}async loadFont(e,t){const r=await this.loadResource(this.fontTablePart,e,"uint8array");return r?this.blobToURL(new Blob([ve(r,t)])):r}async loadAltChunk(e,t){return await this.loadResource(t??this.documentPart,e,"string")}blobToURL(e){return e?this._options.useBase64URL?function(e){return new Promise((t,r)=>{const a=new FileReader;a.onloadend=()=>t(a.result),a.onerror=()=>r(),a.readAsDataURL(e)})}(e):URL.createObjectURL(e):null}findPartByRelId(e,t=null){var r=(t.rels??this.rels).find(t=>t.id==e);const a=t?s(t.path)[0]:"";return r?this.partsMap[n(r.target,a)]:null}getPathById(e,t){const r=e.rels.find(e=>e.id==t),[a]=s(e.path);return r?n(r.target,a):null}loadResource(e,t,r){const a=this.getPathById(e,t);return a?this._package.load(a,r):Promise.resolve(null)}}function ve(e,t){const r=t.replace(/{|}|-/g,""),a=new Array(16);for(let e=0;e<16;e++)a[16-e-1]=parseInt(r.substring(2*e,2*e+2),16);for(let t=0;t<32;t++)e[t]=e[t]^a[t%16];return e}function Se(e,t){return{type:R.BookmarkStart,id:t.attr(e,"id"),name:t.attr(e,"name"),colFirst:t.intAttr(e,"colFirst"),colLast:t.intAttr(e,"colLast")}}function Pe(e,t){return{type:R.BookmarkEnd,id:t.attr(e,"id")}}class we extends U{constructor(){super(...arguments),this.type=R.VmlElement,this.attrs={}}}function Ce(e,t){var r=new we;switch(e.localName){case"rect":r.tagName="rect",Object.assign(r.attrs,{width:"100%",height:"100%"});break;case"oval":r.tagName="ellipse",Object.assign(r.attrs,{cx:"50%",cy:"50%",rx:"50%",ry:"50%"});break;case"line":r.tagName="line";break;case"shape":r.tagName="g";break;case"textbox":r.tagName="foreignObject",Object.assign(r.attrs,{width:"100%",height:"100%"});break;default:return null}for(const t of v.attrs(e))switch(t.localName){case"style":r.cssStyleText=t.value;break;case"fillcolor":r.attrs.fill=t.value;break;case"from":const[e,a]=Me(t.value);Object.assign(r.attrs,{x1:e,y1:a});break;case"to":const[s,n]=Me(t.value);Object.assign(r.attrs,{x2:s,y2:n})}for(const a of v.elements(e))switch(a.localName){case"stroke":Object.assign(r.attrs,xe(a));break;case"fill":Object.assign(r.attrs,Ne());break;case"imagedata":r.tagName="image",Object.assign(r.attrs,{width:"100%",height:"100%"}),r.imageHref={id:v.attr(a,"id"),title:v.attr(a,"title")};break;case"txbxContent":r.children.push(...t.parseBodyElements(a));break;default:const e=Ce(a,t);e&&r.children.push(e)}return r}function xe(e){return{stroke:v.attr(e,"color"),"stroke-width":v.lengthAttr(e,"weight",p)??"1px"}}function Ne(e){return{}}function Me(e){return e.split(",")}class Ae extends U{constructor(){super(...arguments),this.type=R.Comment}}class Ee extends U{constructor(e){super(),this.id=e,this.type=R.CommentReference}}class Te extends U{constructor(e){super(),this.id=e,this.type=R.CommentRangeStart}}class Re extends U{constructor(e){super(),this.id=e,this.type=R.CommentRangeEnd}}var Be="inherit",De="black",$e="black",Fe="transparent";const Le=[],Ie={oMath:R.MmlMath,oMathPara:R.MmlMathParagraph,f:R.MmlFraction,func:R.MmlFunction,fName:R.MmlFunctionName,num:R.MmlNumerator,den:R.MmlDenominator,rad:R.MmlRadical,deg:R.MmlDegree,e:R.MmlBase,sSup:R.MmlSuperscript,sSub:R.MmlSubscript,sPre:R.MmlPreSubSuper,sup:R.MmlSuperArgument,sub:R.MmlSubArgument,d:R.MmlDelimiter,nary:R.MmlNary,eqArr:R.MmlEquationArray,lim:R.MmlLimit,limLow:R.MmlLimitLower,m:R.MmlMatrix,mr:R.MmlMatrixRow,box:R.MmlBox,bar:R.MmlBar,groupChr:R.MmlGroupChar};class Oe{constructor(e){this.options={ignoreWidth:!1,debug:!1,...e}}parseNotes(e,t,r){var a=[];for(let s of v.elements(e,t)){const e=new r;e.id=v.attr(s,"id"),e.noteType=v.attr(s,"type"),e.children=this.parseBodyElements(s),a.push(e)}return a}parseComments(e){var t=[];for(let r of v.elements(e,"comment")){const e=new Ae;e.id=v.attr(r,"id"),e.author=v.attr(r,"author"),e.initials=v.attr(r,"initials"),e.date=v.attr(r,"date"),e.children=this.parseBodyElements(r),t.push(e)}return t}parseDocumentFile(e){var t=v.element(e,"body"),r=v.element(e,"background"),a=v.element(t,"sectPr");return{type:R.Document,children:this.parseBodyElements(t),props:a?B(a,v):{},cssStyle:r?this.parseBackground(r):{}}}parseBackground(e){var t={},r=_e.colorAttr(e,"color");return r&&(t["background-color"]=r),t}parseBodyElements(e){var t=[];for(const r of v.elements(e))switch(r.localName){case"p":t.push(this.parseParagraph(r));break;case"altChunk":t.push(this.parseAltChunk(r));break;case"tbl":t.push(this.parseTable(r));break;case"sdt":t.push(...this.parseSdt(r,e=>this.parseBodyElements(e)))}return t}parseStylesFile(e){var t=[];for(const r of v.elements(e))switch(r.localName){case"style":t.push(this.parseStyle(r));break;case"docDefaults":t.push(this.parseDefaultStyles(r))}return t}parseDefaultStyles(e){var t={id:null,name:null,target:null,basedOn:null,styles:[]};for(const s of v.elements(e))switch(s.localName){case"rPrDefault":var r=v.element(s,"rPr");r&&t.styles.push({target:"span",values:this.parseDefaultProperties(r,{})});break;case"pPrDefault":var a=v.element(s,"pPr");a&&t.styles.push({target:"p",values:this.parseDefaultProperties(a,{})})}return t}parseStyle(e){var t={id:v.attr(e,"styleId"),isDefault:v.boolAttr(e,"default"),name:null,target:null,basedOn:null,styles:[],linked:null};switch(v.attr(e,"type")){case"paragraph":t.target="p";break;case"table":t.target="table";break;case"character":t.target="span"}for(const r of v.elements(e))switch(r.localName){case"basedOn":t.basedOn=v.attr(r,"val");break;case"name":t.name=v.attr(r,"val");break;case"link":t.linked=v.attr(r,"val");break;case"next":t.next=v.attr(r,"val");break;case"aliases":t.aliases=v.attr(r,"val").split(",");break;case"pPr":t.styles.push({target:"p",values:this.parseDefaultProperties(r,{})}),t.paragraphProps=O(r,v);break;case"rPr":t.styles.push({target:"span",values:this.parseDefaultProperties(r,{})}),t.runProps=L(r,v);break;case"tblPr":case"tcPr":t.styles.push({target:"td",values:this.parseDefaultProperties(r,{})});break;case"tblStylePr":for(let e of this.parseTableStyle(r))t.styles.push(e);break;case"rsid":case"qFormat":case"hidden":case"semiHidden":case"unhideWhenUsed":case"autoRedefine":case"uiPriority":break;default:this.options.debug&&console.warn(`DOCX: Unknown style element: ${r.localName}`)}return t}parseTableStyle(e){var t=[],r="",a="";switch(v.attr(e,"type")){case"firstRow":a=".first-row",r="tr.first-row td";break;case"lastRow":a=".last-row",r="tr.last-row td";break;case"firstCol":a=".first-col",r="td.first-col";break;case"lastCol":a=".last-col",r="td.last-col";break;case"band1Vert":a=":not(.no-vband)",r="td.odd-col";break;case"band2Vert":a=":not(.no-vband)",r="td.even-col";break;case"band1Horz":a=":not(.no-hband)",r="tr.odd-row";break;case"band2Horz":a=":not(.no-hband)",r="tr.even-row";break;default:return[]}for(const s of v.elements(e))switch(s.localName){case"pPr":t.push({target:`${r} p`,mod:a,values:this.parseDefaultProperties(s,{})});break;case"rPr":t.push({target:`${r} span`,mod:a,values:this.parseDefaultProperties(s,{})});break;case"tblPr":case"tcPr":t.push({target:r,mod:a,values:this.parseDefaultProperties(s,{})})}return t}parseNumberingFile(e){var t=[],r={},a=[];for(const l of v.elements(e))switch(l.localName){case"abstractNum":this.parseAbstractNumbering(l,a).forEach(e=>t.push(e));break;case"numPicBullet":a.push(this.parseNumberingPicBullet(l));break;case"num":var s=v.attr(l,"numId"),n=v.elementAttr(l,"abstractNumId","val");r[n]=s}return t.forEach(e=>e.id=r[e.id]),t}parseNumberingPicBullet(e){var t=v.element(e,"pict"),r=t&&v.element(t,"shape"),a=r&&v.element(r,"imagedata");return a?{id:v.intAttr(e,"numPicBulletId"),src:v.attr(a,"id"),style:v.attr(r,"style")}:null}parseAbstractNumbering(e,t){var r=[],a=v.attr(e,"abstractNumId");for(const s of v.elements(e))if("lvl"===s.localName)r.push(this.parseNumberingLevel(a,s,t));return r}parseNumberingLevel(e,t,r){var a={id:e,level:v.intAttr(t,"ilvl"),start:1,pStyleName:void 0,pStyle:{},rStyle:{},suff:"tab"};for(const e of v.elements(t))switch(e.localName){case"start":a.start=v.intAttr(e,"val");break;case"pPr":this.parseDefaultProperties(e,a.pStyle);break;case"rPr":this.parseDefaultProperties(e,a.rStyle);break;case"lvlPicBulletId":var s=v.intAttr(e,"val");a.bullet=r.find(e=>e?.id==s);break;case"lvlText":a.levelText=v.attr(e,"val");break;case"pStyle":a.pStyleName=v.attr(e,"val");break;case"numFmt":a.format=v.attr(e,"val");break;case"suff":a.suff=v.attr(e,"val")}return a}parseSdt(e,t){const r=v.element(e,"sdtContent");return r?t(r):[]}parseInserted(e,t){return{type:R.Inserted,children:t(e)?.children??[]}}parseDeleted(e,t){return{type:R.Deleted,children:t(e)?.children??[]}}parseAltChunk(e){return{type:R.AltChunk,children:[],id:v.attr(e,"id")}}parseParagraph(e){var t={type:R.Paragraph,children:[]};for(let r of v.elements(e))switch(r.localName){case"pPr":this.parseParagraphProperties(r,t);break;case"r":t.children.push(this.parseRun(r,t));break;case"hyperlink":t.children.push(this.parseHyperlink(r,t));break;case"smartTag":t.children.push(this.parseSmartTag(r,t));break;case"bookmarkStart":t.children.push(Se(r,v));break;case"bookmarkEnd":t.children.push(Pe(r,v));break;case"commentRangeStart":t.children.push(new Te(v.attr(r,"id")));break;case"commentRangeEnd":t.children.push(new Re(v.attr(r,"id")));break;case"oMath":case"oMathPara":t.children.push(this.parseMathElement(r));break;case"sdt":t.children.push(...this.parseSdt(r,e=>this.parseParagraph(e).children));break;case"ins":t.children.push(this.parseInserted(r,e=>this.parseParagraph(e)));break;case"del":t.children.push(this.parseDeleted(r,e=>this.parseParagraph(e)))}return t}parseParagraphProperties(e,t){this.parseDefaultProperties(e,t.cssStyle={},null,e=>{if(H(e,t,v))return!0;switch(e.localName){case"pStyle":t.styleName=v.attr(e,"val");break;case"cnfStyle":t.className=ze.classNameOfCnfStyle(e);break;case"framePr":this.parseFrame(e,t);break;case"rPr":break;default:return!1}return!0})}parseFrame(e,t){"drop"==v.attr(e,"dropCap")&&(t.cssStyle.float="left")}parseHyperlink(e,t){var r={type:R.Hyperlink,parent:t,children:[]};r.anchor=v.attr(e,"anchor"),r.id=v.attr(e,"id");for(const t of v.elements(e))if("r"===t.localName)r.children.push(this.parseRun(t,r));return r}parseSmartTag(e,t){var r={type:R.SmartTag,parent:t,children:[]},a=v.attr(e,"uri"),s=v.attr(e,"element");a&&(r.uri=a),s&&(r.element=s);for(const t of v.elements(e))if("r"===t.localName)r.children.push(this.parseRun(t,r));return r}parseRun(e,t){var r={type:R.Run,parent:t,children:[]};for(let t of v.elements(e))switch(t=this.checkAlternateContent(t),t.localName){case"t":r.children.push({type:R.Text,text:t.textContent});break;case"delText":r.children.push({type:R.DeletedText,text:t.textContent});break;case"commentReference":r.children.push(new Ee(v.attr(t,"id")));break;case"fldSimple":r.children.push({type:R.SimpleField,instruction:v.attr(t,"instr"),lock:v.boolAttr(t,"lock",!1),dirty:v.boolAttr(t,"dirty",!1)});break;case"instrText":r.fieldRun=!0,r.children.push({type:R.Instruction,text:t.textContent});break;case"fldChar":r.fieldRun=!0,r.children.push({type:R.ComplexField,charType:v.attr(t,"fldCharType"),lock:v.boolAttr(t,"lock",!1),dirty:v.boolAttr(t,"dirty",!1)});break;case"noBreakHyphen":r.children.push({type:R.NoBreakHyphen});break;case"br":r.children.push({type:R.Break,break:v.attr(t,"type")||"textWrapping"});break;case"lastRenderedPageBreak":r.children.push({type:R.Break,break:"lastRenderedPageBreak"});break;case"sym":r.children.push({type:R.Symbol,font:a(v.attr(t,"font")),char:v.attr(t,"char")});break;case"tab":r.children.push({type:R.Tab});break;case"footnoteReference":r.children.push({type:R.FootnoteReference,id:v.attr(t,"id")});break;case"endnoteReference":r.children.push({type:R.EndnoteReference,id:v.attr(t,"id")});break;case"drawing":let e=this.parseDrawing(t);e&&(r.children=[e]);break;case"pict":r.children.push(this.parseVmlPicture(t));break;case"rPr":this.parseRunProperties(t,r)}return r}parseMathElement(e){const t=`${e.localName}Pr`,r={type:Ie[e.localName],children:[]};for(const s of v.elements(e)){if(Ie[s.localName])r.children.push(this.parseMathElement(s));else if("r"==s.localName){var a=this.parseRun(s);a.type=R.MmlRun,r.children.push(a)}else s.localName==t&&(r.props=this.parseMathProperies(s))}return r}parseMathProperies(e){const t={};for(const r of v.elements(e))switch(r.localName){case"chr":t.char=v.attr(r,"val");break;case"vertJc":t.verticalJustification=v.attr(r,"val");break;case"pos":t.position=v.attr(r,"val");break;case"degHide":t.hideDegree=v.boolAttr(r,"val");break;case"begChr":t.beginChar=v.attr(r,"val");break;case"endChr":t.endChar=v.attr(r,"val")}return t}parseRunProperties(e,t){this.parseDefaultProperties(e,t.cssStyle={},null,e=>{switch(e.localName){case"rStyle":t.styleName=v.attr(e,"val");break;case"vertAlign":t.verticalAlign=ze.valueOfVertAlign(e,!0);break;default:return!1}return!0})}parseVmlPicture(e){const t={type:R.VmlPicture,children:[]};for(const r of v.elements(e)){const e=Ce(r,this);e&&t.children.push(e)}return t}checkAlternateContent(e){if("AlternateContent"!=e.localName)return e;var t=v.element(e,"Choice");if(t){var r=v.attr(t,"Requires"),a=e.lookupNamespaceURI(r);if(Le.includes(a))return t.firstElementChild}return v.element(e,"Fallback")?.firstElementChild}parseDrawing(e){for(var t of v.elements(e))switch(t.localName){case"inline":case"anchor":return this.parseDrawingWrapper(t)}}parseDrawingWrapper(e){var t={type:R.Drawing,children:[],cssStyle:{}},r="anchor"==e.localName;let a=null,s=v.boolAttr(e,"simplePos");v.boolAttr(e,"behindDoc");let n={relative:"page",align:"left",offset:"0"},l={relative:"page",align:"top",offset:"0"};for(var o of v.elements(e))switch(o.localName){case"simplePos":s&&(n.offset=v.lengthAttr(o,"x",p),l.offset=v.lengthAttr(o,"y",p));break;case"extent":t.cssStyle.width=v.lengthAttr(o,"cx",p),t.cssStyle.height=v.lengthAttr(o,"cy",p);break;case"positionH":case"positionV":if(!s){let e="positionH"==o.localName?n:l;var i=v.element(o,"align"),c=v.element(o,"posOffset");e.relative=v.attr(o,"relativeFrom")??e.relative,i&&(e.align=i.textContent),c&&(e.offset=b(c.textContent,p))}break;case"wrapTopAndBottom":a="wrapTopAndBottom";break;case"wrapNone":a="wrapNone";break;case"graphic":var h=this.parseGraphic(o);h&&t.children.push(h)}return"wrapTopAndBottom"==a?(t.cssStyle.display="block",n.align&&(t.cssStyle["text-align"]=n.align,t.cssStyle.width="100%")):"wrapNone"==a?(t.cssStyle.display="block",t.cssStyle.position="relative",t.cssStyle.width="0px",t.cssStyle.height="0px",n.offset&&(t.cssStyle.left=n.offset),l.offset&&(t.cssStyle.top=l.offset)):!r||"left"!=n.align&&"right"!=n.align||(t.cssStyle.float=n.align),t}parseGraphic(e){var t=v.element(e,"graphicData");for(let e of v.elements(t))if("pic"===e.localName)return this.parsePicture(e);return null}parsePicture(e){var t={type:R.Image,src:"",cssStyle:{}},r=v.element(e,"blipFill"),a=v.element(r,"blip"),s=v.element(r,"srcRect");t.src=v.attr(a,"embed"),s&&(t.srcRect=[v.intAttr(s,"l",0)/1e5,v.intAttr(s,"t",0)/1e5,v.intAttr(s,"r",0)/1e5,v.intAttr(s,"b",0)/1e5]);var n=v.element(e,"spPr"),l=v.element(n,"xfrm");if(t.cssStyle.position="relative",l)for(var o of(t.rotation=v.intAttr(l,"rot",0)/6e4,v.elements(l)))switch(o.localName){case"ext":t.cssStyle.width=v.lengthAttr(o,"cx",p),t.cssStyle.height=v.lengthAttr(o,"cy",p);break;case"off":t.cssStyle.left=v.lengthAttr(o,"x",p),t.cssStyle.top=v.lengthAttr(o,"y",p)}return t}parseTable(e){var t={type:R.Table,children:[]};for(const r of v.elements(e))switch(r.localName){case"tr":t.children.push(this.parseTableRow(r));break;case"tblGrid":t.columns=this.parseTableColumns(r);break;case"tblPr":this.parseTableProperties(r,t)}return t}parseTableColumns(e){var t=[];for(const r of v.elements(e))if("gridCol"===r.localName)t.push({width:v.lengthAttr(r,"w")});return t}parseTableProperties(e,t){switch(t.cssStyle={},t.cellStyle={},this.parseDefaultProperties(e,t.cssStyle,t.cellStyle,e=>{switch(e.localName){case"tblStyle":t.styleName=v.attr(e,"val");break;case"tblLook":t.className=ze.classNameOftblLook(e);break;case"tblpPr":this.parseTablePosition(e,t);break;case"tblStyleColBandSize":t.colBandSize=v.intAttr(e,"val");break;case"tblStyleRowBandSize":t.rowBandSize=v.intAttr(e,"val");break;case"hidden":t.cssStyle.display="none";break;default:return!1}return!0}),t.cssStyle["text-align"]){case"center":delete t.cssStyle["text-align"],t.cssStyle["margin-left"]="auto",t.cssStyle["margin-right"]="auto";break;case"right":delete t.cssStyle["text-align"],t.cssStyle["margin-left"]="auto"}}parseTablePosition(e,t){var r=v.lengthAttr(e,"topFromText"),a=v.lengthAttr(e,"bottomFromText"),s=v.lengthAttr(e,"rightFromText"),n=v.lengthAttr(e,"leftFromText");t.cssStyle.float="left",t.cssStyle["margin-bottom"]=ze.addSize(t.cssStyle["margin-bottom"],a),t.cssStyle["margin-left"]=ze.addSize(t.cssStyle["margin-left"],n),t.cssStyle["margin-right"]=ze.addSize(t.cssStyle["margin-right"],s),t.cssStyle["margin-top"]=ze.addSize(t.cssStyle["margin-top"],r)}parseTableRow(e){var t={type:R.Row,children:[]};for(const r of v.elements(e))switch(r.localName){case"tc":t.children.push(this.parseTableCell(r));break;case"trPr":case"tblPrEx":this.parseTableRowProperties(r,t)}return t}parseTableRowProperties(e,t){t.cssStyle=this.parseDefaultProperties(e,{},null,e=>{switch(e.localName){case"cnfStyle":t.className=ze.classNameOfCnfStyle(e);break;case"tblHeader":t.isHeader=v.boolAttr(e,"val");break;case"gridBefore":t.gridBefore=v.intAttr(e,"val");break;case"gridAfter":t.gridAfter=v.intAttr(e,"val");break;default:return!1}return!0})}parseTableCell(e){var t={type:R.Cell,children:[]};for(const r of v.elements(e))switch(r.localName){case"tbl":t.children.push(this.parseTable(r));break;case"p":t.children.push(this.parseParagraph(r));break;case"tcPr":this.parseTableCellProperties(r,t)}return t}parseTableCellProperties(e,t){t.cssStyle=this.parseDefaultProperties(e,{},null,e=>{switch(e.localName){case"gridSpan":t.span=v.intAttr(e,"val",null);break;case"vMerge":t.verticalMerge=v.attr(e,"val")??"continue";break;case"cnfStyle":t.className=ze.classNameOfCnfStyle(e);break;default:return!1}return!0}),this.parseTableCellVerticalText(e,t)}parseTableCellVerticalText(e,t){const r={btLr:{writingMode:"vertical-rl",transform:"rotate(180deg)"},lrTb:{writingMode:"vertical-lr",transform:"none"},tbRl:{writingMode:"vertical-rl",transform:"none"}};for(const a of v.elements(e))if("textDirection"===a.localName){const e=r[v.attr(a,"val")]||{writingMode:"horizontal-tb"};t.cssStyle["writing-mode"]=e.writingMode,t.cssStyle.transform=e.transform}}parseDefaultProperties(e,t=null,r=null,a=null){t=t||{};for(const s of v.elements(e))if(!a?.(s))switch(s.localName){case"jc":t["text-align"]=ze.valueOfJc(s);break;case"textAlignment":t["vertical-align"]=ze.valueOfTextAlignment(s);break;case"color":t.color=_e.colorAttr(s,"val",null,De);break;case"sz":t["font-size"]=t["min-height"]=v.lengthAttr(s,"val",u);break;case"shd":t["background-color"]=_e.colorAttr(s,"fill",null,Be);break;case"highlight":t["background-color"]=_e.colorAttr(s,"val",null,Fe);break;case"vertAlign":break;case"position":t.verticalAlign=v.lengthAttr(s,"val",u);break;case"tcW":if(this.options.ignoreWidth)break;case"tblW":t.width=ze.valueOfSize(s,"w");break;case"trHeight":this.parseTrHeight(s,t);break;case"strike":t["text-decoration"]=v.boolAttr(s,"val",!0)?"line-through":"none";break;case"b":t["font-weight"]=v.boolAttr(s,"val",!0)?"bold":"normal";break;case"i":t["font-style"]=v.boolAttr(s,"val",!0)?"italic":"normal";break;case"caps":t["text-transform"]=v.boolAttr(s,"val",!0)?"uppercase":"none";break;case"smallCaps":t["font-variant"]=v.boolAttr(s,"val",!0)?"small-caps":"none";break;case"u":this.parseUnderline(s,t);break;case"ind":case"tblInd":this.parseIndentation(s,t);break;case"rFonts":this.parseFont(s,t);break;case"tblBorders":this.parseBorderProperties(s,r||t);break;case"tblCellSpacing":t["border-spacing"]=ze.valueOfMargin(s),t["border-collapse"]="separate";break;case"pBdr":this.parseBorderProperties(s,t);break;case"bdr":t.border=ze.valueOfBorder(s);break;case"tcBorders":this.parseBorderProperties(s,t);break;case"vanish":v.boolAttr(s,"val",!0)&&(t.display="none");break;case"kern":case"noWrap":break;case"tblCellMar":case"tcMar":this.parseMarginProperties(s,r||t);break;case"tblLayout":t["table-layout"]=ze.valueOfTblLayout(s);break;case"vAlign":t["vertical-align"]=ze.valueOfTextAlignment(s);break;case"spacing":"pPr"==e.localName&&this.parseSpacing(s,t);break;case"wordWrap":v.boolAttr(s,"val")&&(t["overflow-wrap"]="break-word");break;case"suppressAutoHyphens":t.hyphens=v.boolAttr(s,"val",!0)?"none":"auto";break;case"lang":t.$lang=v.attr(s,"val");break;case"rtl":case"bidi":v.boolAttr(s,"val",!0)&&(t.direction="rtl");break;case"bCs":case"iCs":case"szCs":case"tabs":case"outlineLvl":case"contextualSpacing":case"tblStyleColBandSize":case"tblStyleRowBandSize":case"webHidden":case"pageBreakBefore":case"suppressLineNumbers":case"keepLines":case"keepNext":case"widowControl":case"bidi":case"rtl":case"noProof":break;default:this.options.debug&&console.warn(`DOCX: Unknown document element: ${e.localName}.${s.localName}`)}return t}parseUnderline(e,t){var r=v.attr(e,"val");if(null!=r){switch(r){case"dash":case"dashDotDotHeavy":case"dashDotHeavy":case"dashedHeavy":case"dashLong":case"dashLongHeavy":case"dotDash":case"dotDotDash":t["text-decoration"]="underline dashed";break;case"dotted":case"dottedHeavy":t["text-decoration"]="underline dotted";break;case"double":t["text-decoration"]="underline double";break;case"single":case"thick":case"words":t["text-decoration"]="underline";break;case"wave":case"wavyDouble":case"wavyHeavy":t["text-decoration"]="underline wavy";break;case"none":t["text-decoration"]="none"}var a=_e.colorAttr(e,"color");a&&(t["text-decoration-color"]=a)}}parseFont(e,t){var r=[v.attr(e,"ascii"),ze.themeValue(e,"asciiTheme"),v.attr(e,"eastAsia")].filter(e=>e).map(e=>a(e));r.length>0&&(t["font-family"]=[...new Set(r)].join(", "))}parseIndentation(e,t){var r=v.lengthAttr(e,"firstLine"),a=v.lengthAttr(e,"hanging"),s=v.lengthAttr(e,"left"),n=v.lengthAttr(e,"start"),l=v.lengthAttr(e,"right"),o=v.lengthAttr(e,"end");r&&(t["text-indent"]=r),a&&(t["text-indent"]=`-${a}`),(s||n)&&(t["margin-inline-start"]=s||n),(l||o)&&(t["margin-inline-end"]=l||o)}parseSpacing(e,t){var r=v.lengthAttr(e,"before"),a=v.lengthAttr(e,"after"),s=v.intAttr(e,"line",null),n=v.attr(e,"lineRule");if(r&&(t["margin-top"]=r),a&&(t["margin-bottom"]=a),null!==s)switch(n){case"auto":t["line-height"]=`${(s/240).toFixed(2)}`;break;case"atLeast":t["line-height"]=`calc(100% + ${s/20}pt)`;break;default:t["line-height"]=t["min-height"]=s/20+"pt"}}parseMarginProperties(e,t){for(const r of v.elements(e))switch(r.localName){case"left":t["padding-left"]=ze.valueOfMargin(r);break;case"right":t["padding-right"]=ze.valueOfMargin(r);break;case"top":t["padding-top"]=ze.valueOfMargin(r);break;case"bottom":t["padding-bottom"]=ze.valueOfMargin(r)}}parseTrHeight(e,t){v.attr(e,"hRule"),t.height=v.lengthAttr(e,"val")}parseBorderProperties(e,t){for(const r of v.elements(e))switch(r.localName){case"start":case"left":t["border-left"]=ze.valueOfBorder(r);break;case"end":case"right":t["border-right"]=ze.valueOfBorder(r);break;case"top":t["border-top"]=ze.valueOfBorder(r);break;case"bottom":t["border-bottom"]=ze.valueOfBorder(r)}}}const He=["black","blue","cyan","darkBlue","darkCyan","darkGray","darkGreen","darkMagenta","darkRed","darkYellow","green","lightGray","magenta","none","red","white","yellow"];class _e{static colorAttr(e,t,r=null,a="black"){var s=v.attr(e,t);if(s)return"auto"==s?a:He.includes(s)?s:`#${s}`;var n=v.attr(e,"themeColor");return n?`var(--docx-${n}-color)`:r}}class ze{static themeValue(e,t){var r=v.attr(e,t);return r?`var(--docx-${r}-font)`:null}static valueOfSize(e,t){var r=m;switch(v.attr(e,"type")){case"dxa":break;case"pct":r=g;break;case"auto":return"auto"}return v.lengthAttr(e,t,r)}static valueOfMargin(e){return v.lengthAttr(e,"w")}static valueOfBorder(e){var t=ze.parseBorderType(v.attr(e,"val"));if("none"==t)return"none";var r=_e.colorAttr(e,"color");return`${v.lengthAttr(e,"sz",d)} ${t} ${"auto"==r?$e:r}`}static parseBorderType(e){switch(e){case"single":case"dashDotStroked":case"thick":case"thickThinLargeGap":case"thickThinMediumGap":case"thickThinSmallGap":case"thinThickLargeGap":case"thinThickMediumGap":case"thinThickSmallGap":case"thinThickThinLargeGap":case"thinThickThinMediumGap":case"thinThickThinSmallGap":case"threeDEmboss":case"threeDEngrave":case"wave":return"solid";case"dashed":case"dashSmallGap":return"dashed";case"dotDash":case"dotDotDash":case"dotted":return"dotted";case"double":case"doubleWave":case"triple":return"double";case"inset":return"inset";case"nil":case"none":return"none";case"outset":return"outset"}return"solid"}static valueOfTblLayout(e){return"fixed"==v.attr(e,"val")?"fixed":"auto"}static classNameOfCnfStyle(e){const t=v.attr(e,"val");return["first-row","last-row","first-col","last-col","odd-col","even-col","odd-row","even-row","ne-cell","nw-cell","se-cell","sw-cell"].filter((e,r)=>"1"==t[r]).join(" ")}static valueOfJc(e){var t=v.attr(e,"val");switch(t){case"start":case"left":return"left";case"center":return"center";case"end":case"right":return"right";case"both":return"justify"}return t}static valueOfVertAlign(e,t=!1){var r=v.attr(e,"val");switch(r){case"subscript":return"sub";case"superscript":return t?"sup":"super"}return t?null:r}static valueOfTextAlignment(e){var t=v.attr(e,"val");switch(t){case"auto":case"baseline":return"baseline";case"top":return"top";case"center":return"middle";case"bottom":return"bottom"}return t}static addSize(e,t){return null==e?t:null==t?e:`calc(${e} + ${t})`}static classNameOftblLook(e){const t=v.hexAttr(e,"val",0);let r="";return(v.boolAttr(e,"firstRow")||32&t)&&(r+=" first-row"),(v.boolAttr(e,"lastRow")||64&t)&&(r+=" last-row"),(v.boolAttr(e,"firstColumn")||128&t)&&(r+=" first-col"),(v.boolAttr(e,"lastColumn")||256&t)&&(r+=" last-col"),(v.boolAttr(e,"noHBand")||512&t)&&(r+=" no-hband"),(v.boolAttr(e,"noVBand")||1024&t)&&(r+=" no-vband"),r.trim()}}const Ve={pos:0,leader:"none",style:"left"};function je(e,t,r,a=.75){const s=e.closest("p"),n=e.getBoundingClientRect(),l=s.getBoundingClientRect(),o=getComputedStyle(s),i=t?.length>0?t.map(e=>({pos:We(e.position),leader:e.leader,style:e.style})).sort((e,t)=>e.pos-t.pos):[Ve],c=i[i.length-1],h=l.width*a,m=We(r);let p=c.pos+m;if(p"clear"!=e.style&&e.pos>f);if(null==g)return;let b=1;if("right"==g.style||"center"==g.style){const t=Array.from(s.querySelectorAll(`.${e.className}`)),r=t.indexOf(e)+1,n=document.createRange();n.setStart(e,1),re.id)),e.endnotesPart&&(this.endnoteMap=l(e.endnotesPart.notes,e=>e.id)),e.settingsPart&&(this.defaultTabSize=e.settingsPart.settings?.defaultTabStop),!a.ignoreFonts&&e.fontTablePart&&this.renderFontTable(e.fontTablePart,r);var s=this.renderSections(e.documentPart.body);this.options.inWrapper?t.appendChild(this.renderWrapper(s)):Je(t,s),this.commentHighlight&&a.renderComments&&CSS.highlights.set(`${this.className}-comments`,this.commentHighlight),this.postRenderTasks.forEach(e=>e()),await Promise.allSettled(this.tasks),this.refreshTabStops()}renderTheme(e,t){const r={},a=e.theme?.fontScheme;a&&(a.majorFont&&(r["--docx-majorHAnsi-font"]=a.majorFont.latinTypeface),a.minorFont&&(r["--docx-minorHAnsi-font"]=a.minorFont.latinTypeface));const s=e.theme?.colorScheme;if(s)for(let[e,t]of Object.entries(s.colors))r[`--docx-${e}-color`]=`#${t}`;const n=this.styleToString(`.${this.className}`,r);t.appendChild(this.createStyleElement(n))}renderFontTable(e,t){for(let r of e.fonts)for(let e of r.embedFontRefs)this.tasks.push(this.document.loadFont(e.id,e.key).then(s=>{const n={"font-family":a(r.name),src:`url(${s})`};"bold"!=e.type&&"boldItalic"!=e.type||(n["font-weight"]="bold"),"italic"!=e.type&&"boldItalic"!=e.type||(n["font-style"]="italic");const l=this.styleToString("@font-face",n);t.appendChild(this.createComment(`docxjs ${r.name} font`)),t.appendChild(this.createStyleElement(l))}))}processStyleName(e){return e?`${this.className}_${function(e){return e?.replace(/[ .]+/g,"-").replace(/[&]+/g,"and").toLowerCase()}(e)}`:this.className}processStyles(e){const t=l(e.filter(e=>null!=e.id),e=>e.id);for(const a of e.filter(e=>e.basedOn)){var r=t[a.basedOn];if(r){a.paragraphProps=i(a.paragraphProps,r.paragraphProps),a.runProps=i(a.runProps,r.runProps);for(const e of r.styles){const t=a.styles.find(t=>t.target==e.target);t?this.copyStyleProperties(e.values,t.values):a.styles.push({...e,values:{...e.values}})}}else this.options.debug&&console.warn(`Can't find base style ${a.basedOn}`)}for(let t of e)t.cssName=this.processStyleName(t.id);return t}prodessNumberings(e){for(let t of e.filter(e=>e.pStyleName)){const e=this.findStyle(t.pStyleName);e?.paragraphProps?.numbering&&(e.paragraphProps.numbering.level=t.level)}}processElement(e){if(e.children)for(var t of e.children)t.parent=e,t.type==R.Table?this.processTable(t):this.processElement(t)}processTable(e){for(var t of e.children)for(var r of t.children)r.cssStyle=this.copyStyleProperties(e.cellStyle,r.cssStyle,["border-left","border-right","border-top","border-bottom","padding-left","padding-right","padding-top","padding-bottom"]),this.processElement(r)}copyStyleProperties(e,t,r=null){if(!e)return t;for(var a of(null==t&&(t={}),null==r&&(r=Object.getOwnPropertyNames(e)),r))e.hasOwnProperty(a)&&!t.hasOwnProperty(a)&&(t[a]=e[a]);return t}createPageElement(e,t){var r=this.createElement("section",{className:e});return t&&(t.pageMargins&&(r.style.paddingLeft=t.pageMargins.left,r.style.paddingRight=t.pageMargins.right,r.style.paddingTop=t.pageMargins.top,r.style.paddingBottom=t.pageMargins.bottom),t.pageSize&&(this.options.ignoreWidth||(r.style.width=t.pageSize.width),this.options.ignoreHeight||(r.style.minHeight=t.pageSize.height))),r}createSectionContent(e){var t=this.createElement("article");return e.columns&&e.columns.numberOfColumns&&(t.style.columnCount=`${e.columns.numberOfColumns}`,t.style.columnGap=e.columns.space,e.columns.separator&&(t.style.columnRule="1px solid black")),t}renderSections(e){const t=[];this.processElement(e);const r=this.splitBySection(e.children,e.props),a=this.groupByPageBreaks(r);let s=null;for(let r=0,l=a.length;r"first"==e.type):null)??(r%2==1?e.find(e=>"even"==e.type):null)??e.find(e=>"default"==e.type),l=n&&this.document.findPartByRelId(n.id,this.document.documentPart);if(l){this.currentPart=l,this.usedHederFooterParts.includes(l.path)||(this.processElement(l.rootElement),this.usedHederFooterParts.push(l.path));const[e]=this.renderElements([l.rootElement],s);t?.pageMargins&&(l.rootElement.type===R.Header?(e.style.marginTop=`calc(${t.pageMargins.header} - ${t.pageMargins.top})`,e.style.minHeight=`calc(${t.pageMargins.top} - ${t.pageMargins.header})`):l.rootElement.type===R.Footer&&(e.style.marginBottom=`calc(${t.pageMargins.footer} - ${t.pageMargins.bottom})`,e.style.minHeight=`calc(${t.pageMargins.bottom} - ${t.pageMargins.footer})`)),this.currentPart=null}}}isPageBreakElement(e){return e.type==R.Break&&("lastRenderedPageBreak"==e.break?!this.options.ignoreLastRenderedPageBreak:"page"==e.break)}isPageBreakSection(e,t){return!!e&&(!!t&&(e.pageSize?.orientation!=t.pageSize?.orientation||e.pageSize?.width!=t.pageSize?.width||e.pageSize?.height!=t.pageSize?.height))}splitBySection(e,t){var r={sectProps:null,elements:[],pageBreak:!1},a=[r];for(let t of e){if(t.type==R.Paragraph){const e=this.findStyle(t.styleName);e?.paragraphProps?.pageBreakBefore&&(r.sectProps=s,r.pageBreak=!0,r={sectProps:null,elements:[],pageBreak:!1},a.push(r))}if(r.elements.push(t),t.type==R.Paragraph){const e=t;var s=e.sectionProps,n=-1,l=-1;if(this.options.breakPages&&e.children&&(n=e.children.findIndex(e=>-1!=(l=e.children?.findIndex(this.isPageBreakElement.bind(this))??-1))),(s||-1!=n)&&(r.sectProps=s,r.pageBreak=-1!=n,r={sectProps:null,elements:[],pageBreak:!1},a.push(r)),-1!=n){let a=e.children[n],s=l=0;e--)null==a[e].sectProps?a[e].sectProps=c??t:c=a[e].sectProps;return a}groupByPageBreaks(e){let t,r=[];const a=[r];for(let s of e)r.push(s),(this.options.ignoreLastRenderedPageBreak||s.pageBreak||this.isPageBreakSection(t,s.sectProps))&&a.push(r=[]),t=s.sectProps;return a.filter(e=>e.length>0)}renderWrapper(e){return this.createElement("div",{className:`${this.className}-wrapper`},e)}renderDefaultStyle(){var e=this.className,t=`\n.${e}-wrapper { background: gray; padding: 30px; padding-bottom: 0px; display: flex; flex-flow: column; align-items: center; } \n.${e}-wrapper>section.${e} { background: white; box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); margin-bottom: 30px; }`;this.options.hideWrapperOnPrint&&(t=`@media not print { ${t} }`);var r=`${t}\n.${e} { color: black; hyphens: auto; text-underline-position: from-font; }\nsection.${e} { box-sizing: border-box; display: flex; flex-flow: column nowrap; position: relative; overflow: hidden; }\nsection.${e}>article { margin-bottom: auto; z-index: 1; }\nsection.${e}>footer { z-index: 1; }\n.${e} table { border-collapse: collapse; }\n.${e} table td, .${e} table th { vertical-align: top; }\n.${e} p { margin: 0pt; min-height: 1em; }\n.${e} span { white-space: pre-wrap; overflow-wrap: break-word; }\n.${e} a { color: inherit; text-decoration: inherit; }\n.${e} svg { fill: transparent; }\n`;return this.options.renderComments&&(r+=`\n.${e}-comment-ref { cursor: default; }\n.${e}-comment-popover { display: none; z-index: 1000; padding: 0.5rem; background: white; position: absolute; box-shadow: 0 0 0.25rem rgba(0, 0, 0, 0.25); width: 30ch; }\n.${e}-comment-ref:hover~.${e}-comment-popover { display: block; }\n.${e}-comment-author,.${e}-comment-date { font-size: 0.875rem; color: #888; }\n`),this.createStyleElement(r)}renderNumbering(e,t){var r="",a=[];for(var s of e){var n=`p.${this.numberingClass(s.id,s.level)}`,l="none";if(s.bullet){let e=`--${this.className}-${s.bullet.src}`.toLowerCase();r+=this.styleToString(`${n}:before`,{content:"' '",display:"inline-block",background:`var(${e})`},s.bullet.style),this.tasks.push(this.document.loadNumberingImage(s.bullet.src).then(r=>{var a=`${this.rootSelector} { ${e}: url(${r}) }`;t.appendChild(this.createStyleElement(a))}))}else if(s.levelText){let e=this.numberingCounter(s.id,s.level);const t=e+" "+(s.start-1);s.level>0&&(r+=this.styleToString(`p.${this.numberingClass(s.id,s.level-1)}`,{"counter-set":t})),a.push(t),r+=this.styleToString(`${n}:before`,{content:this.levelTextToContent(s.levelText,s.suff,s.id,this.numFormatToCssValue(s.format)),"counter-increment":e,...s.rStyle})}else l=this.numFormatToCssValue(s.format);r+=this.styleToString(n,{display:"list-item","list-style-position":"inside","list-style-type":l,...s.pStyle})}return a.length>0&&(r+=this.styleToString(this.rootSelector,{"counter-reset":a.join(" ")})),this.createStyleElement(r)}renderStyles(e){var t="";const r=this.styleMap,a=l(e.filter(e=>e.isDefault),e=>e.target);for(const l of e){var s=l.styles;if(l.linked){var n=l.linked&&r[l.linked];n?s=s.concat(n.styles):this.options.debug&&console.warn(`Can't find linked style ${l.linked}`)}for(const e of s){var o=`${l.target??""}.${l.cssName}`;l.target!=e.target&&(o+=` ${e.target}`),a[l.target]==l&&(o=`.${this.className} ${l.target}, `+o),t+=this.styleToString(o,e.values)}}return this.createStyleElement(t)}renderNotes(e,t,r){var a=e.map(e=>t[e]).filter(e=>e);if(a.length>0){var s=this.createElement("ol",null,this.renderElements(a));r.appendChild(s)}}renderElement(e){switch(e.type){case R.Paragraph:return this.renderParagraph(e);case R.BookmarkStart:return this.renderBookmarkStart(e);case R.BookmarkEnd:return null;case R.Run:return this.renderRun(e);case R.Table:return this.renderTable(e);case R.Row:return this.renderTableRow(e);case R.Cell:return this.renderTableCell(e);case R.Hyperlink:return this.renderHyperlink(e);case R.SmartTag:return this.renderSmartTag(e);case R.Drawing:return this.renderDrawing(e);case R.Image:return this.renderImage(e);case R.Text:case R.Text:return this.renderText(e);case R.DeletedText:return this.renderDeletedText(e);case R.Tab:return this.renderTab(e);case R.Symbol:return this.renderSymbol(e);case R.Break:return this.renderBreak(e);case R.Footer:return this.renderContainer(e,"footer");case R.Header:return this.renderContainer(e,"header");case R.Footnote:case R.Endnote:return this.renderContainer(e,"li");case R.FootnoteReference:return this.renderFootnoteReference(e);case R.EndnoteReference:return this.renderEndnoteReference(e);case R.NoBreakHyphen:return this.createElement("wbr");case R.VmlPicture:return this.renderVmlPicture(e);case R.VmlElement:return this.renderVmlElement(e);case R.MmlMath:return this.renderContainerNS(e,Ge,"math",{xmlns:Ge});case R.MmlMathParagraph:return this.renderContainer(e,"span");case R.MmlFraction:return this.renderContainerNS(e,Ge,"mfrac");case R.MmlBase:return this.renderContainerNS(e,Ge,e.parent.type==R.MmlMatrixRow?"mtd":"mrow");case R.MmlNumerator:case R.MmlDenominator:case R.MmlFunction:case R.MmlLimit:case R.MmlBox:return this.renderContainerNS(e,Ge,"mrow");case R.MmlGroupChar:return this.renderMmlGroupChar(e);case R.MmlLimitLower:return this.renderContainerNS(e,Ge,"munder");case R.MmlMatrix:return this.renderContainerNS(e,Ge,"mtable");case R.MmlMatrixRow:return this.renderContainerNS(e,Ge,"mtr");case R.MmlRadical:return this.renderMmlRadical(e);case R.MmlSuperscript:return this.renderContainerNS(e,Ge,"msup");case R.MmlSubscript:return this.renderContainerNS(e,Ge,"msub");case R.MmlDegree:case R.MmlSuperArgument:case R.MmlSubArgument:return this.renderContainerNS(e,Ge,"mn");case R.MmlFunctionName:return this.renderContainerNS(e,Ge,"ms");case R.MmlDelimiter:return this.renderMmlDelimiter(e);case R.MmlRun:return this.renderMmlRun(e);case R.MmlNary:return this.renderMmlNary(e);case R.MmlPreSubSuper:return this.renderMmlPreSubSuper(e);case R.MmlBar:return this.renderMmlBar(e);case R.MmlEquationArray:return this.renderMllList(e);case R.Inserted:return this.renderInserted(e);case R.Deleted:return this.renderDeleted(e);case R.CommentRangeStart:return this.renderCommentRangeStart(e);case R.CommentRangeEnd:return this.renderCommentRangeEnd(e);case R.CommentReference:return this.renderCommentReference(e);case R.AltChunk:return this.renderAltChunk(e)}return null}renderElements(e,t){if(null==e)return null;var r=e.flatMap(e=>this.renderElement(e)).filter(e=>null!=e);return t&&Je(t,r),r}renderContainer(e,t,r){return this.createElement(t,r,this.renderElements(e.children))}renderContainerNS(e,t,r,a){return this.createElementNS(t,r,a,this.renderElements(e.children))}renderParagraph(e){var t=this.renderContainer(e,"p");const r=this.findStyle(e.styleName);e.tabs??(e.tabs=r?.paragraphProps?.tabs),this.renderClass(e,t),this.renderStyleValues(e.cssStyle,t),this.renderCommonProperties(t.style,e);const a=e.numbering??r?.paragraphProps?.numbering;return a&&t.classList.add(this.numberingClass(a.id,a.level)),t}renderRunProperties(e,t){this.renderCommonProperties(e,t)}renderCommonProperties(e,t){null!=t&&(t.color&&(e.color=t.color),t.fontSize&&(e["font-size"]=t.fontSize))}renderHyperlink(e){var t=this.renderContainer(e,"a");this.renderStyleValues(e.cssStyle,t);let r="";if(e.id){const t=this.document.documentPart.rels.find(t=>t.id==e.id&&"External"===t.targetMode);r=t?.target??r}return e.anchor&&(r+=`#${e.anchor}`),t.href=r,t}renderSmartTag(e){return this.renderContainer(e,"span")}renderCommentRangeStart(e){if(!this.options.renderComments)return null;const t=new Range;this.commentHighlight?.add(t);const r=this.createComment(`start of comment #${e.id}`);return this.later(()=>t.setStart(r,0)),this.commentMap[e.id]=t,r}renderCommentRangeEnd(e){if(!this.options.renderComments)return null;const t=this.commentMap[e.id],r=this.createComment(`end of comment #${e.id}`);return this.later(()=>t?.setEnd(r,0)),r}renderCommentReference(e){if(!this.options.renderComments)return null;var t=this.document.commentsPart?.commentMap[e.id];if(!t)return null;const r=new DocumentFragment,a=this.createElement("span",{className:`${this.className}-comment-ref`},["💬"]),s=this.createElement("div",{className:`${this.className}-comment-popover`});return this.renderCommentContent(t,s),r.appendChild(this.createComment(`comment #${t.id} by ${t.author} on ${t.date}`)),r.appendChild(a),r.appendChild(s),r}renderAltChunk(e){if(!this.options.renderAltChunks)return null;var t=this.createElement("iframe");return this.tasks.push(this.document.loadAltChunk(e.id,this.currentPart).then(e=>{t.srcdoc=e})),t}renderCommentContent(e,t){t.appendChild(this.createElement("div",{className:`${this.className}-comment-author`},[e.author])),t.appendChild(this.createElement("div",{className:`${this.className}-comment-date`},[new Date(e.date).toLocaleString()])),this.renderElements(e.children,t)}renderDrawing(e){var t=this.renderContainer(e,"div");return t.style.display="inline-block",t.style.position="relative",t.style.textIndent="0px",this.renderStyleValues(e.cssStyle,t),t}renderImage(e){let t=this.createElement("img"),r=e.cssStyle?.transform;if(this.renderStyleValues(e.cssStyle,t),e.srcRect&&e.srcRect.some(e=>0!=e)){var[a,s,n,l]=e.srcRect;r=`scale(${1/(1-a-n)}, ${1/(1-s-l)})`,t.style["clip-path"]=`rect(${(100*s).toFixed(2)}% ${(100*(1-n)).toFixed(2)}% ${(100*(1-l)).toFixed(2)}% ${(100*a).toFixed(2)}%)`}return e.rotation&&(r=`rotate(${e.rotation}deg) ${r??""}`),t.style.transform=r?.trim(),this.document&&this.tasks.push(this.document.loadDocumentImage(e.src,this.currentPart).then(e=>{t.src=e})),t}renderText(e){return this.htmlDocument.createTextNode(e.text)}renderDeletedText(e){return this.options.renderChanges?this.renderText(e):null}renderBreak(e){return"textWrapping"==e.break?this.createElement("br"):null}renderInserted(e){return this.options.renderChanges?this.renderContainer(e,"ins"):this.renderElements(e.children)}renderDeleted(e){return this.options.renderChanges?this.renderContainer(e,"del"):null}renderSymbol(e){var t=this.createElement("span");return t.style.fontFamily=e.font,t.innerHTML=`&#x${e.char};`,t}renderFootnoteReference(e){var t=this.createElement("sup");return this.currentFootnoteIds.push(e.id),t.textContent=`${this.currentFootnoteIds.length}`,t}renderEndnoteReference(e){var t=this.createElement("sup");return this.currentEndnoteIds.push(e.id),t.textContent=`${this.currentEndnoteIds.length}`,t}renderTab(e){var t=this.createElement("span");if(t.innerHTML=" ",this.options.experimental){t.className=this.tabStopClass();var r=function(e,t){var r=e.parent;for(;null!=r&&r.type!=t;)r=r.parent;return r}(e,R.Paragraph)?.tabs;this.currentTabs.push({stops:r,span:t})}return t}renderBookmarkStart(e){return this.createElement("span",{id:e.name})}renderRun(e){if(e.fieldRun)return null;const t=this.createElement("span");if(e.id&&(t.id=e.id),this.renderClass(e,t),this.renderStyleValues(e.cssStyle,t),e.verticalAlign){const r=this.createElement(e.verticalAlign);this.renderElements(e.children,r),t.appendChild(r)}else this.renderElements(e.children,t);return t}renderTable(e){let t=this.createElement("table");return this.tableCellPositions.push(this.currentCellPosition),this.tableVerticalMerges.push(this.currentVerticalMerge),this.currentVerticalMerge={},this.currentCellPosition={col:0,row:0},e.columns&&t.appendChild(this.renderTableColumns(e.columns)),this.renderClass(e,t),this.renderElements(e.children,t),this.renderStyleValues(e.cssStyle,t),this.currentVerticalMerge=this.tableVerticalMerges.pop(),this.currentCellPosition=this.tableCellPositions.pop(),t}renderTableColumns(e){let t=this.createElement("colgroup");for(let r of e){let e=this.createElement("col");r.width&&(e.style.width=r.width),t.appendChild(e)}return t}renderTableRow(e){let t=this.createElement("tr");return this.currentCellPosition.col=0,e.gridBefore&&t.appendChild(this.renderTableCellPlaceholder(e.gridBefore)),this.renderClass(e,t),this.renderElements(e.children,t),this.renderStyleValues(e.cssStyle,t),e.gridAfter&&t.appendChild(this.renderTableCellPlaceholder(e.gridAfter)),this.currentCellPosition.row++,t}renderTableCellPlaceholder(e){const t=this.createElement("td",{colSpan:e});return t.style.border="none",t}renderTableCell(e){let t=this.renderContainer(e,"td");const r=this.currentCellPosition.col;return e.verticalMerge?"restart"==e.verticalMerge?(this.currentVerticalMerge[r]=t,t.rowSpan=1):this.currentVerticalMerge[r]&&(this.currentVerticalMerge[r].rowSpan+=1,t.style.display="none"):this.currentVerticalMerge[r]=null,this.renderClass(e,t),this.renderStyleValues(e.cssStyle,t),e.span&&(t.colSpan=e.span),this.currentCellPosition.col+=t.colSpan,t}renderVmlPicture(e){return this.renderContainer(e,"div")}renderVmlElement(e){var t=this.createSvgElement("svg");t.setAttribute("style",e.cssStyleText);const r=this.renderVmlChildElement(e);return e.imageHref?.id&&this.tasks.push(this.document?.loadDocumentImage(e.imageHref.id,this.currentPart).then(e=>r.setAttribute("href",e))),t.appendChild(r),requestAnimationFrame(()=>{const e=t.firstElementChild.getBBox();t.setAttribute("width",`${Math.ceil(e.x+e.width)}`),t.setAttribute("height",`${Math.ceil(e.y+e.height)}`)}),t}renderVmlChildElement(e){const t=this.createSvgElement(e.tagName);Object.entries(e.attrs).forEach(([e,r])=>t.setAttribute(e,r));for(let r of e.children)r.type==R.VmlElement?t.appendChild(this.renderVmlChildElement(r)):t.appendChild(...c(this.renderElement(r)));return t}renderMmlRadical(e){const t=e.children.find(e=>e.type==R.MmlBase);if(e.props?.hideDegree)return this.createElementNS(Ge,"msqrt",null,this.renderElements([t]));const r=e.children.find(e=>e.type==R.MmlDegree);return this.createElementNS(Ge,"mroot",null,this.renderElements([t,r]))}renderMmlDelimiter(e){const t=[];return t.push(this.createElementNS(Ge,"mo",null,[e.props.beginChar??"("])),t.push(...this.renderElements(e.children)),t.push(this.createElementNS(Ge,"mo",null,[e.props.endChar??")"])),this.createElementNS(Ge,"mrow",null,t)}renderMmlNary(e){const t=[],r=l(e.children,e=>e.type),a=r[R.MmlSuperArgument],s=r[R.MmlSubArgument],n=a?this.createElementNS(Ge,"mo",null,c(this.renderElement(a))):null,o=s?this.createElementNS(Ge,"mo",null,c(this.renderElement(s))):null,i=this.createElementNS(Ge,"mo",null,[e.props?.char??"∫"]);return n||o?t.push(this.createElementNS(Ge,"munderover",null,[i,o,n])):n?t.push(this.createElementNS(Ge,"mover",null,[i,n])):o?t.push(this.createElementNS(Ge,"munder",null,[i,o])):t.push(i),t.push(...this.renderElements(r[R.MmlBase].children)),this.createElementNS(Ge,"mrow",null,t)}renderMmlPreSubSuper(e){const t=[],r=l(e.children,e=>e.type),a=r[R.MmlSuperArgument],s=r[R.MmlSubArgument],n=a?this.createElementNS(Ge,"mo",null,c(this.renderElement(a))):null,o=s?this.createElementNS(Ge,"mo",null,c(this.renderElement(s))):null,i=this.createElementNS(Ge,"mo",null);return t.push(this.createElementNS(Ge,"msubsup",null,[i,o,n])),t.push(...this.renderElements(r[R.MmlBase].children)),this.createElementNS(Ge,"mrow",null,t)}renderMmlGroupChar(e){const t="bot"===e.props.verticalJustification?"mover":"munder",r=this.renderContainerNS(e,Ge,t);return e.props.char&&r.appendChild(this.createElementNS(Ge,"mo",null,[e.props.char])),r}renderMmlBar(e){const t=this.renderContainerNS(e,Ge,"mrow");switch(e.props.position){case"top":t.style.textDecoration="overline";break;case"bottom":t.style.textDecoration="underline"}return t}renderMmlRun(e){const t=this.createElementNS(Ge,"ms",null,this.renderElements(e.children));return this.renderClass(e,t),this.renderStyleValues(e.cssStyle,t),t}renderMllList(e){const t=this.createElementNS(Ge,"mtable");this.renderClass(e,t),this.renderStyleValues(e.cssStyle,t);for(let r of this.renderElements(e.children))t.appendChild(this.createElementNS(Ge,"mtr",null,[this.createElementNS(Ge,"mtd",null,[r])]));return t}renderStyleValues(e,t){for(let r in e)r.startsWith("$")?t.setAttribute(r.slice(1),e[r]):t.style[r]=e[r]}renderClass(e,t){e.className&&(t.className=e.className),e.styleName&&t.classList.add(this.processStyleName(e.styleName))}findStyle(e){return e&&this.styleMap?.[e]}numberingClass(e,t){return`${this.className}-num-${e}-${t}`}tabStopClass(){return`${this.className}-tab-stop`}styleToString(e,t,r=null){let a=`${e} {\r\n`;for(const e in t)e.startsWith("$")||(a+=` ${e}: ${t[e]};\r\n`);return r&&(a+=r),a+"}\r\n"}numberingCounter(e,t){return`${this.className}-num-${e}-${t}`}levelTextToContent(e,t,r,a){return`"${e.replace(/%\d*/g,e=>{let t=parseInt(e.substring(1),10)-1;return`"counter(${this.numberingCounter(r,t)}, ${a})"`})}${{tab:"\\9",space:"\\a0"}[t]??""}"`}numFormatToCssValue(e){return{none:"none",bullet:"disc",decimal:"decimal",lowerLetter:"lower-alpha",upperLetter:"upper-alpha",lowerRoman:"lower-roman",upperRoman:"upper-roman",decimalZero:"decimal-leading-zero",aiueo:"katakana",aiueoFullWidth:"katakana",chineseCounting:"simp-chinese-informal",chineseCountingThousand:"simp-chinese-informal",chineseLegalSimplified:"simp-chinese-formal",chosung:"hangul-consonant",ideographDigital:"cjk-ideographic",ideographTraditional:"cjk-heavenly-stem",ideographLegalTraditional:"trad-chinese-formal",ideographZodiac:"cjk-earthly-branch",iroha:"katakana-iroha",irohaFullWidth:"katakana-iroha",japaneseCounting:"japanese-informal",japaneseDigitalTenThousand:"cjk-decimal",japaneseLegal:"japanese-formal",thaiNumbers:"thai",koreanCounting:"korean-hangul-formal",koreanDigital:"korean-hangul-formal",koreanDigital2:"korean-hanja-informal",hebrew1:"hebrew",hebrew2:"hebrew",hindiNumbers:"devanagari",ganada:"hangul",taiwaneseCounting:"cjk-ideographic",taiwaneseCountingThousand:"cjk-ideographic",taiwaneseDigital:"cjk-decimal"}[e]??e}refreshTabStops(){this.options.experimental&&setTimeout(()=>{const e=function(e=document.body){const t=document.createElement("div");t.style.width="100pt",e.appendChild(t);const r=100/t.offsetWidth;return e.removeChild(t),r}();for(let t of this.currentTabs)je(t.span,t.stops,this.defaultTabSize,e)},500)}createElementNS(e,t,r,a){var s=e?this.htmlDocument.createElementNS(e,t):this.htmlDocument.createElement(t);return Object.assign(s,r),a&&Je(s,a),s}createElement(e,t,r){return this.createElementNS(void 0,e,t,r)}createSvgElement(e,t,r){return this.createElementNS(Xe,e,t,r)}createStyleElement(e){return this.createElement("style",{innerHTML:e})}createComment(e){return this.htmlDocument.createComment(e)}later(e){this.postRenderTasks.push(e)}}function qe(e){e.innerHTML=""}function Je(e,t){t.forEach(t=>{return e.appendChild("string"==typeof(r=t)||r instanceof String?document.createTextNode(t):t);var r})}const Ze={ignoreHeight:!1,ignoreWidth:!1,ignoreFonts:!1,breakPages:!0,debug:!1,experimental:!1,className:"docx",inWrapper:!0,hideWrapperOnPrint:!1,trimXmlDeclaration:!0,ignoreLastRenderedPageBreak:!0,renderHeaders:!0,renderFooters:!0,renderFootnotes:!0,renderEndnotes:!0,useBase64URL:!1,renderChanges:!1,renderComments:!1,renderAltChunks:!0};function Ke(e,t){const r={...Ze,...t};return ke.load(e,new Oe(r),r)}async function Ye(e,t,r,a){const s={...Ze,...a},n=new Ue(window.document);return await n.render(e,t,r,s)}e.defaultOptions=Ze,e.parseAsync=Ke,e.renderAsync=async function(e,t,r,a){const s=await Ke(e,a);return await Ye(s,t,r,a),s},e.renderDocument=Ye}); -//# sourceMappingURL=docx-preview.min.js.map diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.min.js.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.min.js.map deleted file mode 100644 index 07186188a..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.min.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"docx-preview.min.js","sources":["../src/common/relationship.ts","../src/utils.ts","../src/document/common.ts","../src/parser/xml-parser.ts","../src/common/part.ts","../src/font-table/fonts.ts","../src/font-table/font-table.ts","../src/common/open-xml-package.ts","../src/document/document-part.ts","../src/document/border.ts","../src/document/section.ts","../src/document/dom.ts","../src/document/run.ts","../src/document/paragraph.ts","../src/document/line-spacing.ts","../src/numbering/numbering.ts","../src/numbering/numbering-part.ts","../src/styles/styles-part.ts","../src/header-footer/elements.ts","../src/header-footer/parts.ts","../src/document-props/extended-props.ts","../src/document-props/extended-props-part.ts","../src/document-props/core-props-part.ts","../src/document-props/core-props.ts","../src/theme/theme.ts","../src/theme/theme-part.ts","../src/notes/elements.ts","../src/notes/parts.ts","../src/settings/settings.ts","../src/settings/settings-part.ts","../src/document-props/custom-props-part.ts","../src/document-props/custom-props.ts","../src/comments/comments-part.ts","../src/comments/comments-extended-part.ts","../src/word-document.ts","../src/document/bookmarks.ts","../src/vml/vml.ts","../src/comments/elements.ts","../src/document-parser.ts","../src/javascript.ts","../src/html-renderer.ts","../src/docx-preview.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["RelationshipTypes","encloseFontFamily","fontFamily","test","splitPath","path","si","lastIndexOf","substring","resolvePath","base","prefix","URL","toString","length","keyBy","array","by","reduce","a","x","isObject","item","Array","isArray","mergeDeep","target","sources","source","shift","key","asArray","val","ns","LengthUsage","mul","unit","min","max","convertLength","usage","num","parseInt","clamp","toFixed","parseCommonProperty","elem","props","xml","namespaceURI","localName","color","attr","fontSize","lengthAttr","XmlParser","elements","result","i","l","childNodes","c","nodeType","Node","ELEMENT_NODE","push","element","elementAttr","attrLocalName","el","this","undefined","attrs","from","attributes","value","intAttr","node","attrName","defaultValue","hexAttr","floatAttr","parseFloat","boolAttr","v","convertBoolean","globalXmlParser","Part","constructor","_package","load","rels","loadRelationships","xmlText","xmlDoc","parseXmlDocument","options","keepOrigin","_xmlDocument","parseXml","firstElementChild","save","update","XMLSerializer","serializeToString","root","embedFontTypeMap","embedRegular","embedBold","embedItalic","embedBoldItalic","parseFonts","map","name","embedFontRefs","family","altName","parseEmbedFontRef","parseFont","id","type","FontTablePart","fonts","xmlParser","OpenXmlPackage","_zip","get","p","startsWith","substr","normalizePath","files","replace","content","file","input","zip","JSZip","loadAsync","generateAsync","async","Promise","resolve","relsPath","f","fn","txt","e","targetMode","xmlString","trimXmlDeclaration","data","charCodeAt","DOMParser","parseFromString","errorText","doc","getElementsByTagName","textContent","Error","parseXmlString","DocumentPart","pkg","parser","super","_documentParser","body","parseDocumentFile","parseBorder","size","offset","frame","shadow","parseBorders","left","top","right","bottom","SectionType","DomType","parseSectionProperties","section","pageSize","width","height","orientation","pageMargins","header","footer","gutter","columns","parseColumns","headerRefs","parseFooterHeaderReference","footerRefs","titlePage","pageBorders","pageNumber","parsePageNumber","numberOfColumns","space","separator","equalWidth","chapSep","chapStyle","format","start","parseRunProperties","parseRunProperty","parseParagraphProperties","parseParagraphProperty","tabs","position","leader","style","parseTabs","sectionProps","numbering","level","parseNumbering","lineSpacing","before","after","line","lineRule","parseLineSpacing","textAlignment","keepLines","keepNext","pageBreakBefore","outlineLevel","styleName","runProps","overrides","abstractId","parseNumberingLevelOverrride","parseAbstractNumbering","levels","multiLevelType","numberingStyleLink","styleLink","parseNumberingLevel","restart","text","justification","bulletPictureId","paragraphStyle","paragraphProps","numberingLevel","parseNumberingBulletPicture","pict","shape","imagedata","referenceId","NumberingPart","Object","assign","numberings","abstractNumberings","bulletPictures","parseNumberingPart","domNumberings","parseNumberingFile","StylesPart","styles","parseStylesFile","OpenXmlElementBase","children","cssStyle","WmlHeader","Header","WmlFooter","Footer","BaseHeaderFooterPart","rootElement","createRootElement","parseBodyElements","HeaderPart","FooterPart","safeParseToInt","ExtendedPropsPart","template","pages","words","characters","application","lines","paragraphs","company","appVersion","parseExtendedProps","CorePropsPart","title","description","subject","creator","keywords","language","lastModifiedBy","revision","parseCoreProps","DmlTheme","parseColorScheme","colors","srgbClr","sysClr","parseFontScheme","majorFont","parseFontInfo","minorFont","latinTypeface","eaTypeface","csTypeface","ThemePart","theme","themeElements","colorScheme","fontScheme","parseTheme","WmlBaseNote","WmlFootnote","Footnote","WmlEndnote","Endnote","BaseNotePart","FootnotesPart","notes","parseNotes","EndnotesPart","parseNoteProperties","defaultNoteIds","nummeringFormat","SettingsPart","settings","defaultTabStop","footnoteProps","endnoteProps","autoHyphenation","parseSettings","CustomPropsPart","firstChild","formatId","nodeName","parseCustomProps","CommentsPart","comments","parseComments","commentMap","CommentsExtendedPart","paraId","paraIdParent","done","topLevelRels","OfficeDocument","ExtendedProperties","CoreProperties","CustomProperties","WordDocument","parts","partsMap","blob","d","_options","_parser","all","rel","r","find","loadRelationshipPart","part","documentPart","FontTable","fontTablePart","Numbering","numberingPart","Styles","stylesPart","Theme","themePart","Footnotes","footnotesPart","Endnotes","endnotesPart","corePropsPart","extendedPropsPart","Settings","settingsPart","Comments","commentsPart","CommentsExtended","commentsExtendedPart","folder","loadDocumentImage","loadResource","blobToURL","loadNumberingImage","loadFont","Blob","deobfuscate","loadAltChunk","useBase64URL","reject","reader","FileReader","onloadend","onerror","readAsDataURL","blobToBase64","createObjectURL","findPartByRelId","basePart","getPathById","outputType","guidKey","trimmed","numbers","parseBookmarkStart","BookmarkStart","colFirst","colLast","parseBookmarkEnd","BookmarkEnd","VmlElement","parseVmlElement","tagName","cx","cy","rx","ry","at","cssStyleText","fill","x1","y1","parsePoint","x2","y2","parseStroke","parseFill","imageHref","child","stroke","split","WmlComment","Comment","WmlCommentReference","CommentReference","WmlCommentRangeStart","CommentRangeStart","WmlCommentRangeEnd","CommentRangeEnd","autos","supportedNamespaceURIs","mmlTagMap","oMath","MmlMath","oMathPara","MmlMathParagraph","MmlFraction","func","MmlFunction","fName","MmlFunctionName","MmlNumerator","den","MmlDenominator","rad","MmlRadical","deg","MmlDegree","MmlBase","sSup","MmlSuperscript","sSub","MmlSubscript","sPre","MmlPreSubSuper","sup","MmlSuperArgument","sub","MmlSubArgument","MmlDelimiter","nary","MmlNary","eqArr","MmlEquationArray","lim","MmlLimit","limLow","MmlLimitLower","m","MmlMatrix","mr","MmlMatrixRow","box","MmlBox","bar","MmlBar","groupChr","MmlGroupChar","DocumentParser","ignoreWidth","debug","elemName","elemClass","noteType","author","initials","date","xbody","background","sectPr","Document","parseBackground","xmlUtil","colorAttr","parseParagraph","parseAltChunk","parseTable","parseSdt","xstyles","n","parseStyle","parseDefaultStyles","basedOn","rPr","values","parseDefaultProperties","pPr","isDefault","linked","next","aliases","s","parseTableStyle","console","warn","selector","modificator","mod","mapping","bullets","forEach","parseNumberingPicBullet","numId","abstractNumId","src","pStyleName","pStyle","rStyle","suff","bulletId","bullet","levelText","sdtContent","parseInserted","parentParser","Inserted","parseDeleted","Deleted","AltChunk","Paragraph","parseRun","parseHyperlink","parseSmartTag","parseMathElement","paragraph","className","classNameOfCnfStyle","parseFrame","parent","Hyperlink","anchor","SmartTag","uri","Run","checkAlternateContent","Text","DeletedText","SimpleField","instruction","lock","dirty","fieldRun","Instruction","ComplexField","charType","NoBreakHyphen","Break","break","Symbol","font","char","Tab","FootnoteReference","EndnoteReference","parseDrawing","parseVmlPicture","propsTag","run","MmlRun","parseMathProperies","verticalJustification","hideDegree","beginChar","endChar","verticalAlign","valueOfVertAlign","VmlPicture","choice","requires","lookupNamespaceURI","includes","parseDrawingWrapper","Drawing","isAnchor","wrapType","simplePos","posX","relative","align","posY","pos","alignNode","offsetNode","g","parseGraphic","graphicData","parsePicture","Image","blipFill","blip","srcRect","spPr","xfrm","rotation","Table","parseTableRow","parseTableColumns","parseTableProperties","table","cellStyle","classNameOftblLook","parseTablePosition","colBandSize","rowBandSize","topFromText","bottomFromText","rightFromText","leftFromText","addSize","Row","parseTableCell","parseTableRowProperties","row","isHeader","gridBefore","gridAfter","Cell","parseTableCellProperties","cell","span","verticalMerge","parseTableCellVerticalText","directionMap","btLr","writingMode","transform","lrTb","tbRl","childStyle","handler","valueOfJc","valueOfTextAlignment","valueOfSize","parseTrHeight","parseUnderline","parseIndentation","parseBorderProperties","valueOfMargin","valueOfBorder","parseMarginProperties","valueOfTblLayout","parseSpacing","col","themeValue","filter","Set","join","firstLine","hanging","end","output","knownColors","defValue","autoColor","themeColor","parseBorderType","_","asTagName","b","trim","defaultTab","updateTabStop","defaultTabSize","pixelToPoint","closest","ebb","getBoundingClientRect","pbb","pcs","getComputedStyle","tabStops","t","lengthToPoint","sort","lastTab","pWidthPt","marginLeft","pOffset","tab","querySelectorAll","nextIdx","indexOf","range","document","createRange","setStart","setEndBefore","setEndAfter","nextBB","innerHTML","textDecoration","wordSpacing","textDecorationStyle","HtmlRenderer","htmlDocument","styleMap","currentPart","tableVerticalMerges","currentVerticalMerge","tableCellPositions","currentCellPosition","footnoteMap","endnoteMap","currentEndnoteIds","usedHederFooterParts","currentTabs","tasks","postRenderTasks","render","bodyContainer","styleContainer","rootSelector","inWrapper","renderComments","globalThis","Highlight","commentHighlight","removeAllElements","appendChild","createComment","renderDefaultStyle","renderTheme","processStyles","renderStyles","prodessNumberings","renderNumbering","ignoreFonts","renderFontTable","sectionElements","renderSections","renderWrapper","appendChildren","CSS","highlights","set","allSettled","refreshTabStops","variables","k","entries","cssText","styleToString","createStyleElement","fontsPart","ref","then","fontData","cssValues","processStyleName","toLowerCase","escapeClassName","stylesMap","baseStyle","baseValues","styleValues","copyStyleProperties","cssName","findStyle","processElement","processTable","getOwnPropertyNames","hasOwnProperty","createPageElement","createElement","paddingLeft","paddingRight","paddingTop","paddingBottom","ignoreHeight","minHeight","createSectionContent","columnCount","columnGap","columnRule","sections","splitBySection","groupByPageBreaks","prevProps","currentFootnoteIds","sectProps","pageElement","renderStyleValues","renderHeaders","renderHeaderFooter","sect","contentElement","renderElements","renderFootnotes","renderNotes","renderEndnotes","renderFooters","refs","page","firstOfSection","into","marginTop","marginBottom","isPageBreakElement","ignoreLastRenderedPageBreak","isPageBreakSection","prev","defaultProps","current","pageBreak","pBreakIndex","rBreakIndex","breakPages","findIndex","bind","breakRun","splitRun","newParagraph","slice","runChildren","newRun","currentSectProps","wrapperStyle","hideWrapperOnPrint","styleText","resetCounters","numberingClass","listStyleType","valiable","display","counter","numberingCounter","counterReset","levelTextToContent","numFormatToCssValue","defautStyles","subStyles","linkedStyle","concat","subStyle","noteIds","notesMap","renderElement","renderParagraph","renderBookmarkStart","renderRun","renderTable","renderTableRow","renderTableCell","renderHyperlink","renderSmartTag","renderDrawing","renderImage","renderText","renderDeletedText","renderTab","renderSymbol","renderBreak","renderContainer","renderFootnoteReference","renderEndnoteReference","renderVmlPicture","renderVmlElement","renderContainerNS","xmlns","renderMmlGroupChar","renderMmlRadical","renderMmlDelimiter","renderMmlRun","renderMmlNary","renderMmlPreSubSuper","renderMmlBar","renderMllList","renderInserted","renderDeleted","renderCommentRangeStart","renderCommentRangeEnd","renderCommentReference","renderAltChunk","elems","flatMap","createElementNS","renderClass","renderCommonProperties","classList","add","renderRunProperties","href","it","commentStart","rng","Range","later","commentEnd","setEnd","commentRef","comment","frg","DocumentFragment","commentRefEl","commentsContainerEl","renderCommentContent","renderAltChunks","srcdoc","container","Date","toLocaleString","textIndent","some","createTextNode","renderChanges","tabSpan","experimental","tabStopClass","stops","findParent","wrapper","renderTableColumns","pop","colElem","renderTableCellPlaceholder","colSpan","rowSpan","createSvgElement","setAttribute","renderVmlChildElement","requestAnimationFrame","bb","getBBox","Math","ceil","y","degree","grouped","supElem","subElem","charElem","stubElem","ouput","lvl","selectors","numformat","none","decimal","lowerLetter","upperLetter","lowerRoman","upperRoman","decimalZero","aiueo","aiueoFullWidth","chineseCounting","chineseCountingThousand","chineseLegalSimplified","chosung","ideographDigital","ideographTraditional","ideographLegalTraditional","ideographZodiac","iroha","irohaFullWidth","japaneseCounting","japaneseDigitalTenThousand","japaneseLegal","thaiNumbers","koreanCounting","koreanDigital","koreanDigital2","hebrew1","hebrew2","hindiNumbers","ganada","taiwaneseCounting","taiwaneseCountingThousand","taiwaneseDigital","setTimeout","temp","offsetWidth","removeChild","computePixelToPoint","String","defaultOptions","parseAsync","userOptions","ops","renderDocument","renderer","window"],"mappings":";;;;;;8QASA,IAAYA,ECLN,SAAUC,EAAkBC,GAC9B,MAAO,qBAAqBC,KAAKD,GAAc,IAAIA,KAAgBA,CACvE,CAEM,SAAUE,EAAUC,GACtB,IAAIC,EAAKD,EAAKE,YAAY,KAAO,EAIjC,MAAO,CAHY,GAAND,EAAU,GAAKD,EAAKG,UAAU,EAAGF,GACzB,GAANA,EAAUD,EAAOA,EAAKG,UAAUF,GAGnD,CAEM,SAAUG,EAAYJ,EAAcK,GACtC,IACI,MAAMC,EAAS,eAEf,OADY,IAAIC,IAAIP,EAAMM,EAASD,GAAMG,WAC9BL,UAAUG,EAAOG,OAChC,CAAE,MACE,MAAO,GAAGJ,IAAOL,GACrB,CACJ,CAEM,SAAUU,EAAeC,EAAYC,GACvC,OAAOD,EAAME,OAAO,CAACC,EAAGC,KACpBD,EAAEF,EAAGG,IAAMA,EACJD,GACR,CAAA,EACP,CAWM,SAAUE,EAASC,GACrB,OAAOA,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B,YvC7+CD,iBADFluB,EuC8+CwBuC,IvC7+CVvC,aAAgBk+B,OuC6+CDnS,SAAS4N,eAAep3B,GAAKA,GvC9+C7E,IAAmBvC,GuC++CzB,CCngDO,MAAMm+B,GAA0B,CACnC/M,cAAc,EACdrT,aAAa,EACb2Q,aAAa,EACbgF,YAAY,EACZ1V,OAAO,EACP8b,cAAc,EACd7X,UAAW,OACX2L,WAAW,EACXyG,oBAAoB,EACpBrsB,oBAAoB,EACpBkrB,6BAA6B,EAC7BhB,eAAe,EACfQ,eAAe,EACfH,iBAAiB,EACpBE,gBAAgB,EAChB/a,cAAc,EACdkiB,eAAe,EACZ/L,gBAAgB,EAChBuL,iBAAiB,GAGf,SAAUgF,GAAWn2B,EAAkBo2B,GACzC,MAAMC,EAAM,IAAKH,MAAmBE,GACpC,OAAOtpB,GAAa3Q,KAAK6D,EAAM,IAAI6V,GAAewgB,GAAMA,EAC5D,CAEOh3B,eAAei3B,GAAexS,EAAe0B,EAA4BC,EAA8B2Q,GAC1G,MAAMC,EAAM,IAAKH,MAAmBE,GAC9BG,EAAW,IAAI/R,GAAagS,OAAO1S,UAC5C,aAAayS,EAAShR,OAAOzB,EAAU0B,EAAeC,EAAgB4Q,EACvE,mDAEOh3B,eAA2BW,EAAkBwlB,EAA4BC,EAA8B2Q,GAC7G,MAAM/1B,QAAY81B,GAAWn2B,EAAMo2B,GAEhC,aADGE,GAAej2B,EAAKmlB,EAAeC,EAAgB2Q,GAC/C/1B,CACX"} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.min.mjs b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.min.mjs deleted file mode 100644 index 39e7832db..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.min.mjs +++ /dev/null @@ -1,8 +0,0 @@ -/* - * @license - * docx-preview - * Released under Apache License 2.0 - * Copyright Volodymyr Baydalka - */ -import e from"jszip";var t;function r(e){return/^[^"'].*\s.*[^"']$/.test(e)?`'${e}'`:e}function a(e){let t=e.lastIndexOf("/")+1;return[0==t?"":e.substring(0,t),0==t?e:e.substring(t)]}function s(e,t){try{const r="http://docx/";return new URL(e,r+t).toString().substring(r.length)}catch{return`${t}${e}`}}function n(e,t){return e.reduce((e,r)=>(e[t(r)]=r,e),{})}function l(e){return e&&"object"==typeof e&&!Array.isArray(e)}function o(e,...t){if(!t.length)return e;const r=t.shift();if(l(e)&&l(r))for(const t in r)if(l(r[t])){o(e[t]??(e[t]={}),r[t])}else e[t]=r[t];return o(e,...t)}function i(e){return Array.isArray(e)?e:[e]}!function(e){e.OfficeDocument="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",e.FontTable="http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable",e.Image="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",e.Numbering="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",e.Styles="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",e.StylesWithEffects="http://schemas.microsoft.com/office/2007/relationships/stylesWithEffects",e.Theme="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",e.Settings="http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings",e.WebSettings="http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings",e.Hyperlink="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",e.Footnotes="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes",e.Endnotes="http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes",e.Footer="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer",e.Header="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header",e.ExtendedProperties="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties",e.CoreProperties="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties",e.CustomProperties="http://schemas.openxmlformats.org/package/2006/relationships/metadata/custom-properties",e.Comments="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",e.CommentsExtended="http://schemas.microsoft.com/office/2011/relationships/commentsExtended",e.AltChunk="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk"}(t||(t={}));const c="http://schemas.openxmlformats.org/wordprocessingml/2006/main",h={mul:.05,unit:"pt"},m={mul:1/12700,unit:"pt"},p={mul:.5,unit:"pt"},u={mul:.125,unit:"pt",min:.25,max:12},d={mul:1,unit:"pt"},f={mul:.02,unit:"%"};function g(e,t=h){if(null==e||/.+(p[xt]|[%])$/.test(e))return e;var r=parseInt(e)*t.mul;return t.min&&t.max&&(r=function(e,t,r){return t>e?t:rfunction(e,t){let r={name:t.attr(e,"name"),embedFontRefs:[]};for(let a of t.elements(e))switch(a.localName){case"family":r.family=t.attr(a,"val");break;case"altName":r.altName=t.attr(a,"val");break;case"embedRegular":case"embedBold":case"embedItalic":case"embedBoldItalic":r.embedFontRefs.push(w(a,t))}return r}(e,t))}function w(e,t){return{id:t.attr(e,"id"),key:t.attr(e,"fontKey"),type:S[e.localName]}}class C extends v{parseXml(e){this.fonts=P(e,this._package.xmlParser)}}class x{constructor(e,t){this._zip=e,this.options=t,this.xmlParser=new y}get(e){const t=function(e){return e.startsWith("/")?e.substr(1):e}(e);return this._zip.files[t]??this._zip.files[t.replace(/\//g,"\\")]}update(e,t){this._zip.file(e,t)}static async load(t,r){const a=await e.loadAsync(t);return new x(a,r)}save(e="blob"){return this._zip.generateAsync({type:e})}load(e,t="string"){return this.get(e)?.async(t)??Promise.resolve(null)}async loadRelationships(e=null){let t="_rels/.rels";if(null!=e){const[r,s]=a(e);t=`${r}_rels/${s}.rels`}const r=await this.load(t);return r?(s=this.parseXmlDocument(r).firstElementChild,(n=this.xmlParser).elements(s).map(e=>({id:n.attr(e,"Id"),type:n.attr(e,"Type"),target:n.attr(e,"Target"),targetMode:n.attr(e,"TargetMode")}))):null;var s,n}parseXmlDocument(e){return function(e,t=!1){var r;t&&(e=e.replace(/<[?].*[?]>/,"")),e=65279===(r=e).charCodeAt(0)?r.substring(1):r;const a=(new DOMParser).parseFromString(e,"application/xml"),s=(n=a,n.getElementsByTagName("parsererror")[0]?.textContent);var n;if(s)throw new Error(s);return a}(e,this.options.trimXmlDeclaration)}}class N extends v{constructor(e,t,r){super(e,t),this._documentParser=r}parseXml(e){this.body=this._documentParser.parseDocumentFile(e)}}function M(e,t){return{type:t.attr(e,"val"),color:t.attr(e,"color"),size:t.lengthAttr(e,"sz",u),offset:t.lengthAttr(e,"space",d),frame:t.boolAttr(e,"frame"),shadow:t.boolAttr(e,"shadow")}}function A(e,t){var r={};for(let a of t.elements(e))switch(a.localName){case"left":r.left=M(a,t);break;case"top":r.top=M(a,t);break;case"right":r.right=M(a,t);break;case"bottom":r.bottom=M(a,t)}return r}var E,T;function R(e,t=k){var r={};for(let a of t.elements(e))switch(a.localName){case"pgSz":r.pageSize={width:t.lengthAttr(a,"w"),height:t.lengthAttr(a,"h"),orientation:t.attr(a,"orient")};break;case"type":r.type=t.attr(a,"val");break;case"pgMar":r.pageMargins={left:t.lengthAttr(a,"left"),right:t.lengthAttr(a,"right"),top:t.lengthAttr(a,"top"),bottom:t.lengthAttr(a,"bottom"),header:t.lengthAttr(a,"header"),footer:t.lengthAttr(a,"footer"),gutter:t.lengthAttr(a,"gutter")};break;case"cols":r.columns=B(a,t);break;case"headerReference":(r.headerRefs??(r.headerRefs=[])).push($(a,t));break;case"footerReference":(r.footerRefs??(r.footerRefs=[])).push($(a,t));break;case"titlePg":r.titlePage=t.boolAttr(a,"val",!0);break;case"pgBorders":r.pageBorders=A(a,t);break;case"pgNumType":r.pageNumber=D(a,t)}return r}function B(e,t){return{numberOfColumns:t.intAttr(e,"num"),space:t.lengthAttr(e,"space"),separator:t.boolAttr(e,"sep"),equalWidth:t.boolAttr(e,"equalWidth",!0),columns:t.elements(e,"col").map(e=>({width:t.lengthAttr(e,"w"),space:t.lengthAttr(e,"space")}))}}function D(e,t){return{chapSep:t.attr(e,"chapSep"),chapStyle:t.attr(e,"chapStyle"),format:t.attr(e,"fmt"),start:t.intAttr(e,"start")}}function $(e,t){return{id:t.attr(e,"id"),type:t.attr(e,"type")}}function F(e,t){let r={};for(let a of t.elements(e))L(a,r,t);return r}function L(e,t,r){return!!b(e,t,r)}function I(e,t){let r={};for(let a of t.elements(e))O(a,r,t);return r}function O(e,t,r){if(e.namespaceURI!=c)return!1;if(b(e,t,r))return!0;switch(e.localName){case"tabs":t.tabs=function(e,t){return t.elements(e,"tab").map(e=>({position:t.lengthAttr(e,"pos"),leader:t.attr(e,"leader"),style:t.attr(e,"val")}))}(e,r);break;case"sectPr":t.sectionProps=R(e,r);break;case"numPr":t.numbering=function(e,t){var r={};for(let a of t.elements(e))switch(a.localName){case"numId":r.id=t.attr(a,"val");break;case"ilvl":r.level=t.intAttr(a,"val")}return r}(e,r);break;case"spacing":return t.lineSpacing=function(e,t){return{before:t.lengthAttr(e,"before"),after:t.lengthAttr(e,"after"),line:t.intAttr(e,"line"),lineRule:t.attr(e,"lineRule")}}(e,r),!1;case"textAlignment":return t.textAlignment=r.attr(e,"val"),!1;case"keepLines":t.keepLines=r.boolAttr(e,"val",!0);break;case"keepNext":t.keepNext=r.boolAttr(e,"val",!0);break;case"pageBreakBefore":t.pageBreakBefore=r.boolAttr(e,"val",!0);break;case"outlineLvl":t.outlineLevel=r.intAttr(e,"val");break;case"pStyle":t.styleName=r.attr(e,"val");break;case"rPr":t.runProps=F(e,r);break;default:return!1}return!0}function H(e,t){let r={id:t.attr(e,"numId"),overrides:[]};for(let a of t.elements(e))switch(a.localName){case"abstractNumId":r.abstractId=t.attr(a,"val");break;case"lvlOverride":r.overrides.push(V(a,t))}return r}function _(e,t){let r={id:t.attr(e,"abstractNumId"),levels:[]};for(let a of t.elements(e))switch(a.localName){case"name":r.name=t.attr(a,"val");break;case"multiLevelType":r.multiLevelType=t.attr(a,"val");break;case"numStyleLink":r.numberingStyleLink=t.attr(a,"val");break;case"styleLink":r.styleLink=t.attr(a,"val");break;case"lvl":r.levels.push(z(a,t))}return r}function z(e,t){let r={level:t.intAttr(e,"ilvl")};for(let a of t.elements(e))switch(a.localName){case"start":r.start=t.attr(a,"val");break;case"lvlRestart":r.restart=t.intAttr(a,"val");break;case"numFmt":r.format=t.attr(a,"val");break;case"lvlText":r.text=t.attr(a,"val");break;case"lvlJc":r.justification=t.attr(a,"val");break;case"lvlPicBulletId":r.bulletPictureId=t.attr(a,"val");break;case"pStyle":r.paragraphStyle=t.attr(a,"val");break;case"pPr":r.paragraphProps=I(a,t);break;case"rPr":r.runProps=F(a,t)}return r}function V(e,t){let r={level:t.intAttr(e,"ilvl")};for(let a of t.elements(e))switch(a.localName){case"startOverride":r.start=t.intAttr(a,"val");break;case"lvl":r.numberingLevel=z(a,t)}return r}function j(e,t){var r=t.element(e,"pict"),a=r&&t.element(r,"shape"),s=a&&t.element(a,"imagedata");return s?{id:t.attr(e,"numPicBulletId"),referenceId:t.attr(s,"id"),style:t.attr(a,"style")}:null}!function(e){e.Continuous="continuous",e.NextPage="nextPage",e.NextColumn="nextColumn",e.EvenPage="evenPage",e.OddPage="oddPage"}(E||(E={}));class W extends v{constructor(e,t,r){super(e,t),this._documentParser=r}parseXml(e){Object.assign(this,function(e,t){let r={numberings:[],abstractNumberings:[],bulletPictures:[]};for(let a of t.elements(e))switch(a.localName){case"num":r.numberings.push(H(a,t));break;case"abstractNum":r.abstractNumberings.push(_(a,t));break;case"numPicBullet":r.bulletPictures.push(j(a,t))}return r}(e,this._package.xmlParser)),this.domNumberings=this._documentParser.parseNumberingFile(e)}}class X extends v{constructor(e,t,r){super(e,t),this._documentParser=r}parseXml(e){this.styles=this._documentParser.parseStylesFile(e)}}!function(e){e.Document="document",e.Paragraph="paragraph",e.Run="run",e.Break="break",e.NoBreakHyphen="noBreakHyphen",e.Table="table",e.Row="row",e.Cell="cell",e.Hyperlink="hyperlink",e.SmartTag="smartTag",e.Drawing="drawing",e.Image="image",e.Text="text",e.Tab="tab",e.Symbol="symbol",e.BookmarkStart="bookmarkStart",e.BookmarkEnd="bookmarkEnd",e.Footer="footer",e.Header="header",e.FootnoteReference="footnoteReference",e.EndnoteReference="endnoteReference",e.Footnote="footnote",e.Endnote="endnote",e.SimpleField="simpleField",e.ComplexField="complexField",e.Instruction="instruction",e.VmlPicture="vmlPicture",e.MmlMath="mmlMath",e.MmlMathParagraph="mmlMathParagraph",e.MmlFraction="mmlFraction",e.MmlFunction="mmlFunction",e.MmlFunctionName="mmlFunctionName",e.MmlNumerator="mmlNumerator",e.MmlDenominator="mmlDenominator",e.MmlRadical="mmlRadical",e.MmlBase="mmlBase",e.MmlDegree="mmlDegree",e.MmlSuperscript="mmlSuperscript",e.MmlSubscript="mmlSubscript",e.MmlPreSubSuper="mmlPreSubSuper",e.MmlSubArgument="mmlSubArgument",e.MmlSuperArgument="mmlSuperArgument",e.MmlNary="mmlNary",e.MmlDelimiter="mmlDelimiter",e.MmlRun="mmlRun",e.MmlEquationArray="mmlEquationArray",e.MmlLimit="mmlLimit",e.MmlLimitLower="mmlLimitLower",e.MmlMatrix="mmlMatrix",e.MmlMatrixRow="mmlMatrixRow",e.MmlBox="mmlBox",e.MmlBar="mmlBar",e.MmlGroupChar="mmlGroupChar",e.VmlElement="vmlElement",e.Inserted="inserted",e.Deleted="deleted",e.DeletedText="deletedText",e.Comment="comment",e.CommentReference="commentReference",e.CommentRangeStart="commentRangeStart",e.CommentRangeEnd="commentRangeEnd",e.AltChunk="altChunk"}(T||(T={}));class G{constructor(){this.children=[],this.cssStyle={}}}class U extends G{constructor(){super(...arguments),this.type=T.Header}}class q extends G{constructor(){super(...arguments),this.type=T.Footer}}class J extends v{constructor(e,t,r){super(e,t),this._documentParser=r}parseXml(e){this.rootElement=this.createRootElement(),this.rootElement.children=this._documentParser.parseBodyElements(e)}}class Z extends J{createRootElement(){return new U}}class K extends J{createRootElement(){return new q}}function Y(e){if(void 0!==e)return parseInt(e)}class Q extends v{parseXml(e){this.props=function(e,t){const r={};for(let a of t.elements(e))switch(a.localName){case"Template":r.template=a.textContent;break;case"Pages":r.pages=Y(a.textContent);break;case"Words":r.words=Y(a.textContent);break;case"Characters":r.characters=Y(a.textContent);break;case"Application":r.application=a.textContent;break;case"Lines":r.lines=Y(a.textContent);break;case"Paragraphs":r.paragraphs=Y(a.textContent);break;case"Company":r.company=a.textContent;break;case"AppVersion":r.appVersion=a.textContent}return r}(e,this._package.xmlParser)}}class ee extends v{parseXml(e){this.props=function(e,t){const r={};for(let a of t.elements(e))switch(a.localName){case"title":r.title=a.textContent;break;case"description":r.description=a.textContent;break;case"subject":r.subject=a.textContent;break;case"creator":r.creator=a.textContent;break;case"keywords":r.keywords=a.textContent;break;case"language":r.language=a.textContent;break;case"lastModifiedBy":r.lastModifiedBy=a.textContent;break;case"revision":a.textContent&&(r.revision=parseInt(a.textContent))}return r}(e,this._package.xmlParser)}}class te{}function re(e,t){var r={name:t.attr(e,"name"),colors:{}};for(let n of t.elements(e)){var a=t.element(n,"srgbClr"),s=t.element(n,"sysClr");a?r.colors[n.localName]=t.attr(a,"val"):s&&(r.colors[n.localName]=t.attr(s,"lastClr"))}return r}function ae(e,t){var r={name:t.attr(e,"name")};for(let a of t.elements(e))switch(a.localName){case"majorFont":r.majorFont=se(a,t);break;case"minorFont":r.minorFont=se(a,t)}return r}function se(e,t){return{latinTypeface:t.elementAttr(e,"latin","typeface"),eaTypeface:t.elementAttr(e,"ea","typeface"),csTypeface:t.elementAttr(e,"cs","typeface")}}class ne extends v{constructor(e,t){super(e,t)}parseXml(e){this.theme=function(e,t){var r=new te,a=t.element(e,"themeElements");for(let e of t.elements(a))switch(e.localName){case"clrScheme":r.colorScheme=re(e,t);break;case"fontScheme":r.fontScheme=ae(e,t)}return r}(e,this._package.xmlParser)}}class le{}class oe extends le{constructor(){super(...arguments),this.type=T.Footnote}}class ie extends le{constructor(){super(...arguments),this.type=T.Endnote}}class ce extends v{constructor(e,t,r){super(e,t),this._documentParser=r}}class he extends ce{constructor(e,t,r){super(e,t,r)}parseXml(e){this.notes=this._documentParser.parseNotes(e,"footnote",oe)}}class me extends ce{constructor(e,t,r){super(e,t,r)}parseXml(e){this.notes=this._documentParser.parseNotes(e,"endnote",ie)}}function pe(e,t){var r={defaultNoteIds:[]};for(let a of t.elements(e))switch(a.localName){case"numFmt":r.nummeringFormat=t.attr(a,"val");break;case"footnote":case"endnote":r.defaultNoteIds.push(t.attr(a,"id"))}return r}class ue extends v{constructor(e,t){super(e,t)}parseXml(e){this.settings=function(e,t){var r={};for(let a of t.elements(e))switch(a.localName){case"defaultTabStop":r.defaultTabStop=t.lengthAttr(a,"val");break;case"footnotePr":r.footnoteProps=pe(a,t);break;case"endnotePr":r.endnoteProps=pe(a,t);break;case"autoHyphenation":r.autoHyphenation=t.boolAttr(a,"val")}return r}(e,this._package.xmlParser)}}class de extends v{parseXml(e){this.props=function(e,t){return t.elements(e,"property").map(e=>{const r=e.firstChild;return{formatId:t.attr(e,"fmtid"),name:t.attr(e,"name"),type:r.nodeName,value:r.textContent}})}(e,this._package.xmlParser)}}class fe extends v{constructor(e,t,r){super(e,t),this._documentParser=r}parseXml(e){this.comments=this._documentParser.parseComments(e),this.commentMap=n(this.comments,e=>e.id)}}class ge extends v{constructor(e,t){super(e,t),this.comments=[]}parseXml(e){const t=this._package.xmlParser;for(let r of t.elements(e,"commentEx"))this.comments.push({paraId:t.attr(r,"paraId"),paraIdParent:t.attr(r,"paraIdParent"),done:t.boolAttr(r,"done")});this.commentMap=n(this.comments,e=>e.paraId)}}const be=[{type:t.OfficeDocument,target:"word/document.xml"},{type:t.ExtendedProperties,target:"docProps/app.xml"},{type:t.CoreProperties,target:"docProps/core.xml"},{type:t.CustomProperties,target:"docProps/custom.xml"}];class ye{constructor(){this.parts=[],this.partsMap={}}static async load(e,t,r){var a=new ye;return a._options=r,a._parser=t,a._package=await x.load(e,r),a.rels=await a._package.loadRelationships(),await Promise.all(be.map(e=>{const t=a.rels.find(t=>t.type===e.type)??e;return a.loadRelationshipPart(t.target,t.type)})),a}save(e="blob"){return this._package.save(e)}async loadRelationshipPart(e,r){if(this.partsMap[e])return this.partsMap[e];if(!this._package.get(e))return null;let n=null;switch(r){case t.OfficeDocument:this.documentPart=n=new N(this._package,e,this._parser);break;case t.FontTable:this.fontTablePart=n=new C(this._package,e);break;case t.Numbering:this.numberingPart=n=new W(this._package,e,this._parser);break;case t.Styles:this.stylesPart=n=new X(this._package,e,this._parser);break;case t.Theme:this.themePart=n=new ne(this._package,e);break;case t.Footnotes:this.footnotesPart=n=new he(this._package,e,this._parser);break;case t.Endnotes:this.endnotesPart=n=new me(this._package,e,this._parser);break;case t.Footer:n=new K(this._package,e,this._parser);break;case t.Header:n=new Z(this._package,e,this._parser);break;case t.CoreProperties:this.corePropsPart=n=new ee(this._package,e);break;case t.ExtendedProperties:this.extendedPropsPart=n=new Q(this._package,e);break;case t.CustomProperties:n=new de(this._package,e);break;case t.Settings:this.settingsPart=n=new ue(this._package,e);break;case t.Comments:this.commentsPart=n=new fe(this._package,e,this._parser);break;case t.CommentsExtended:this.commentsExtendedPart=n=new ge(this._package,e)}if(null==n)return Promise.resolve(null);if(this.partsMap[e]=n,this.parts.push(n),await n.load(),n.rels?.length>0){const[e]=a(n.path);await Promise.all(n.rels.map(t=>this.loadRelationshipPart(s(t.target,e),t.type)))}return n}async loadDocumentImage(e,t){const r=await this.loadResource(t??this.documentPart,e,"blob");return this.blobToURL(r)}async loadNumberingImage(e){const t=await this.loadResource(this.numberingPart,e,"blob");return this.blobToURL(t)}async loadFont(e,t){const r=await this.loadResource(this.fontTablePart,e,"uint8array");return r?this.blobToURL(new Blob([ke(r,t)])):r}async loadAltChunk(e,t){return await this.loadResource(t??this.documentPart,e,"string")}blobToURL(e){return e?this._options.useBase64URL?function(e){return new Promise((t,r)=>{const a=new FileReader;a.onloadend=()=>t(a.result),a.onerror=()=>r(),a.readAsDataURL(e)})}(e):URL.createObjectURL(e):null}findPartByRelId(e,t=null){var r=(t.rels??this.rels).find(t=>t.id==e);const n=t?a(t.path)[0]:"";return r?this.partsMap[s(r.target,n)]:null}getPathById(e,t){const r=e.rels.find(e=>e.id==t),[n]=a(e.path);return r?s(r.target,n):null}loadResource(e,t,r){const a=this.getPathById(e,t);return a?this._package.load(a,r):Promise.resolve(null)}}function ke(e,t){const r=t.replace(/{|}|-/g,""),a=new Array(16);for(let e=0;e<16;e++)a[16-e-1]=parseInt(r.substring(2*e,2*e+2),16);for(let t=0;t<32;t++)e[t]=e[t]^a[t%16];return e}function ve(e,t){return{type:T.BookmarkStart,id:t.attr(e,"id"),name:t.attr(e,"name"),colFirst:t.intAttr(e,"colFirst"),colLast:t.intAttr(e,"colLast")}}function Se(e,t){return{type:T.BookmarkEnd,id:t.attr(e,"id")}}class Pe extends G{constructor(){super(...arguments),this.type=T.VmlElement,this.attrs={}}}function we(e,t){var r=new Pe;switch(e.localName){case"rect":r.tagName="rect",Object.assign(r.attrs,{width:"100%",height:"100%"});break;case"oval":r.tagName="ellipse",Object.assign(r.attrs,{cx:"50%",cy:"50%",rx:"50%",ry:"50%"});break;case"line":r.tagName="line";break;case"shape":r.tagName="g";break;case"textbox":r.tagName="foreignObject",Object.assign(r.attrs,{width:"100%",height:"100%"});break;default:return null}for(const t of k.attrs(e))switch(t.localName){case"style":r.cssStyleText=t.value;break;case"fillcolor":r.attrs.fill=t.value;break;case"from":const[e,a]=Ne(t.value);Object.assign(r.attrs,{x1:e,y1:a});break;case"to":const[s,n]=Ne(t.value);Object.assign(r.attrs,{x2:s,y2:n})}for(const a of k.elements(e))switch(a.localName){case"stroke":Object.assign(r.attrs,Ce(a));break;case"fill":Object.assign(r.attrs,xe());break;case"imagedata":r.tagName="image",Object.assign(r.attrs,{width:"100%",height:"100%"}),r.imageHref={id:k.attr(a,"id"),title:k.attr(a,"title")};break;case"txbxContent":r.children.push(...t.parseBodyElements(a));break;default:const e=we(a,t);e&&r.children.push(e)}return r}function Ce(e){return{stroke:k.attr(e,"color"),"stroke-width":k.lengthAttr(e,"weight",m)??"1px"}}function xe(e){return{}}function Ne(e){return e.split(",")}class Me extends G{constructor(){super(...arguments),this.type=T.Comment}}class Ae extends G{constructor(e){super(),this.id=e,this.type=T.CommentReference}}class Ee extends G{constructor(e){super(),this.id=e,this.type=T.CommentRangeStart}}class Te extends G{constructor(e){super(),this.id=e,this.type=T.CommentRangeEnd}}var Re="inherit",Be="black",De="black",$e="transparent";const Fe=[],Le={oMath:T.MmlMath,oMathPara:T.MmlMathParagraph,f:T.MmlFraction,func:T.MmlFunction,fName:T.MmlFunctionName,num:T.MmlNumerator,den:T.MmlDenominator,rad:T.MmlRadical,deg:T.MmlDegree,e:T.MmlBase,sSup:T.MmlSuperscript,sSub:T.MmlSubscript,sPre:T.MmlPreSubSuper,sup:T.MmlSuperArgument,sub:T.MmlSubArgument,d:T.MmlDelimiter,nary:T.MmlNary,eqArr:T.MmlEquationArray,lim:T.MmlLimit,limLow:T.MmlLimitLower,m:T.MmlMatrix,mr:T.MmlMatrixRow,box:T.MmlBox,bar:T.MmlBar,groupChr:T.MmlGroupChar};class Ie{constructor(e){this.options={ignoreWidth:!1,debug:!1,...e}}parseNotes(e,t,r){var a=[];for(let s of k.elements(e,t)){const e=new r;e.id=k.attr(s,"id"),e.noteType=k.attr(s,"type"),e.children=this.parseBodyElements(s),a.push(e)}return a}parseComments(e){var t=[];for(let r of k.elements(e,"comment")){const e=new Me;e.id=k.attr(r,"id"),e.author=k.attr(r,"author"),e.initials=k.attr(r,"initials"),e.date=k.attr(r,"date"),e.children=this.parseBodyElements(r),t.push(e)}return t}parseDocumentFile(e){var t=k.element(e,"body"),r=k.element(e,"background"),a=k.element(t,"sectPr");return{type:T.Document,children:this.parseBodyElements(t),props:a?R(a,k):{},cssStyle:r?this.parseBackground(r):{}}}parseBackground(e){var t={},r=He.colorAttr(e,"color");return r&&(t["background-color"]=r),t}parseBodyElements(e){var t=[];for(const r of k.elements(e))switch(r.localName){case"p":t.push(this.parseParagraph(r));break;case"altChunk":t.push(this.parseAltChunk(r));break;case"tbl":t.push(this.parseTable(r));break;case"sdt":t.push(...this.parseSdt(r,e=>this.parseBodyElements(e)))}return t}parseStylesFile(e){var t=[];for(const r of k.elements(e))switch(r.localName){case"style":t.push(this.parseStyle(r));break;case"docDefaults":t.push(this.parseDefaultStyles(r))}return t}parseDefaultStyles(e){var t={id:null,name:null,target:null,basedOn:null,styles:[]};for(const s of k.elements(e))switch(s.localName){case"rPrDefault":var r=k.element(s,"rPr");r&&t.styles.push({target:"span",values:this.parseDefaultProperties(r,{})});break;case"pPrDefault":var a=k.element(s,"pPr");a&&t.styles.push({target:"p",values:this.parseDefaultProperties(a,{})})}return t}parseStyle(e){var t={id:k.attr(e,"styleId"),isDefault:k.boolAttr(e,"default"),name:null,target:null,basedOn:null,styles:[],linked:null};switch(k.attr(e,"type")){case"paragraph":t.target="p";break;case"table":t.target="table";break;case"character":t.target="span"}for(const r of k.elements(e))switch(r.localName){case"basedOn":t.basedOn=k.attr(r,"val");break;case"name":t.name=k.attr(r,"val");break;case"link":t.linked=k.attr(r,"val");break;case"next":t.next=k.attr(r,"val");break;case"aliases":t.aliases=k.attr(r,"val").split(",");break;case"pPr":t.styles.push({target:"p",values:this.parseDefaultProperties(r,{})}),t.paragraphProps=I(r,k);break;case"rPr":t.styles.push({target:"span",values:this.parseDefaultProperties(r,{})}),t.runProps=F(r,k);break;case"tblPr":case"tcPr":t.styles.push({target:"td",values:this.parseDefaultProperties(r,{})});break;case"tblStylePr":for(let e of this.parseTableStyle(r))t.styles.push(e);break;case"rsid":case"qFormat":case"hidden":case"semiHidden":case"unhideWhenUsed":case"autoRedefine":case"uiPriority":break;default:this.options.debug&&console.warn(`DOCX: Unknown style element: ${r.localName}`)}return t}parseTableStyle(e){var t=[],r="",a="";switch(k.attr(e,"type")){case"firstRow":a=".first-row",r="tr.first-row td";break;case"lastRow":a=".last-row",r="tr.last-row td";break;case"firstCol":a=".first-col",r="td.first-col";break;case"lastCol":a=".last-col",r="td.last-col";break;case"band1Vert":a=":not(.no-vband)",r="td.odd-col";break;case"band2Vert":a=":not(.no-vband)",r="td.even-col";break;case"band1Horz":a=":not(.no-hband)",r="tr.odd-row";break;case"band2Horz":a=":not(.no-hband)",r="tr.even-row";break;default:return[]}for(const s of k.elements(e))switch(s.localName){case"pPr":t.push({target:`${r} p`,mod:a,values:this.parseDefaultProperties(s,{})});break;case"rPr":t.push({target:`${r} span`,mod:a,values:this.parseDefaultProperties(s,{})});break;case"tblPr":case"tcPr":t.push({target:r,mod:a,values:this.parseDefaultProperties(s,{})})}return t}parseNumberingFile(e){var t=[],r={},a=[];for(const l of k.elements(e))switch(l.localName){case"abstractNum":this.parseAbstractNumbering(l,a).forEach(e=>t.push(e));break;case"numPicBullet":a.push(this.parseNumberingPicBullet(l));break;case"num":var s=k.attr(l,"numId"),n=k.elementAttr(l,"abstractNumId","val");r[n]=s}return t.forEach(e=>e.id=r[e.id]),t}parseNumberingPicBullet(e){var t=k.element(e,"pict"),r=t&&k.element(t,"shape"),a=r&&k.element(r,"imagedata");return a?{id:k.intAttr(e,"numPicBulletId"),src:k.attr(a,"id"),style:k.attr(r,"style")}:null}parseAbstractNumbering(e,t){var r=[],a=k.attr(e,"abstractNumId");for(const s of k.elements(e))if("lvl"===s.localName)r.push(this.parseNumberingLevel(a,s,t));return r}parseNumberingLevel(e,t,r){var a={id:e,level:k.intAttr(t,"ilvl"),start:1,pStyleName:void 0,pStyle:{},rStyle:{},suff:"tab"};for(const e of k.elements(t))switch(e.localName){case"start":a.start=k.intAttr(e,"val");break;case"pPr":this.parseDefaultProperties(e,a.pStyle);break;case"rPr":this.parseDefaultProperties(e,a.rStyle);break;case"lvlPicBulletId":var s=k.intAttr(e,"val");a.bullet=r.find(e=>e?.id==s);break;case"lvlText":a.levelText=k.attr(e,"val");break;case"pStyle":a.pStyleName=k.attr(e,"val");break;case"numFmt":a.format=k.attr(e,"val");break;case"suff":a.suff=k.attr(e,"val")}return a}parseSdt(e,t){const r=k.element(e,"sdtContent");return r?t(r):[]}parseInserted(e,t){return{type:T.Inserted,children:t(e)?.children??[]}}parseDeleted(e,t){return{type:T.Deleted,children:t(e)?.children??[]}}parseAltChunk(e){return{type:T.AltChunk,children:[],id:k.attr(e,"id")}}parseParagraph(e){var t={type:T.Paragraph,children:[]};for(let r of k.elements(e))switch(r.localName){case"pPr":this.parseParagraphProperties(r,t);break;case"r":t.children.push(this.parseRun(r,t));break;case"hyperlink":t.children.push(this.parseHyperlink(r,t));break;case"smartTag":t.children.push(this.parseSmartTag(r,t));break;case"bookmarkStart":t.children.push(ve(r,k));break;case"bookmarkEnd":t.children.push(Se(r,k));break;case"commentRangeStart":t.children.push(new Ee(k.attr(r,"id")));break;case"commentRangeEnd":t.children.push(new Te(k.attr(r,"id")));break;case"oMath":case"oMathPara":t.children.push(this.parseMathElement(r));break;case"sdt":t.children.push(...this.parseSdt(r,e=>this.parseParagraph(e).children));break;case"ins":t.children.push(this.parseInserted(r,e=>this.parseParagraph(e)));break;case"del":t.children.push(this.parseDeleted(r,e=>this.parseParagraph(e)))}return t}parseParagraphProperties(e,t){this.parseDefaultProperties(e,t.cssStyle={},null,e=>{if(O(e,t,k))return!0;switch(e.localName){case"pStyle":t.styleName=k.attr(e,"val");break;case"cnfStyle":t.className=_e.classNameOfCnfStyle(e);break;case"framePr":this.parseFrame(e,t);break;case"rPr":break;default:return!1}return!0})}parseFrame(e,t){"drop"==k.attr(e,"dropCap")&&(t.cssStyle.float="left")}parseHyperlink(e,t){var r={type:T.Hyperlink,parent:t,children:[]};r.anchor=k.attr(e,"anchor"),r.id=k.attr(e,"id");for(const t of k.elements(e))if("r"===t.localName)r.children.push(this.parseRun(t,r));return r}parseSmartTag(e,t){var r={type:T.SmartTag,parent:t,children:[]},a=k.attr(e,"uri"),s=k.attr(e,"element");a&&(r.uri=a),s&&(r.element=s);for(const t of k.elements(e))if("r"===t.localName)r.children.push(this.parseRun(t,r));return r}parseRun(e,t){var a={type:T.Run,parent:t,children:[]};for(let t of k.elements(e))switch(t=this.checkAlternateContent(t),t.localName){case"t":a.children.push({type:T.Text,text:t.textContent});break;case"delText":a.children.push({type:T.DeletedText,text:t.textContent});break;case"commentReference":a.children.push(new Ae(k.attr(t,"id")));break;case"fldSimple":a.children.push({type:T.SimpleField,instruction:k.attr(t,"instr"),lock:k.boolAttr(t,"lock",!1),dirty:k.boolAttr(t,"dirty",!1)});break;case"instrText":a.fieldRun=!0,a.children.push({type:T.Instruction,text:t.textContent});break;case"fldChar":a.fieldRun=!0,a.children.push({type:T.ComplexField,charType:k.attr(t,"fldCharType"),lock:k.boolAttr(t,"lock",!1),dirty:k.boolAttr(t,"dirty",!1)});break;case"noBreakHyphen":a.children.push({type:T.NoBreakHyphen});break;case"br":a.children.push({type:T.Break,break:k.attr(t,"type")||"textWrapping"});break;case"lastRenderedPageBreak":a.children.push({type:T.Break,break:"lastRenderedPageBreak"});break;case"sym":a.children.push({type:T.Symbol,font:r(k.attr(t,"font")),char:k.attr(t,"char")});break;case"tab":a.children.push({type:T.Tab});break;case"footnoteReference":a.children.push({type:T.FootnoteReference,id:k.attr(t,"id")});break;case"endnoteReference":a.children.push({type:T.EndnoteReference,id:k.attr(t,"id")});break;case"drawing":let e=this.parseDrawing(t);e&&(a.children=[e]);break;case"pict":a.children.push(this.parseVmlPicture(t));break;case"rPr":this.parseRunProperties(t,a)}return a}parseMathElement(e){const t=`${e.localName}Pr`,r={type:Le[e.localName],children:[]};for(const s of k.elements(e)){if(Le[s.localName])r.children.push(this.parseMathElement(s));else if("r"==s.localName){var a=this.parseRun(s);a.type=T.MmlRun,r.children.push(a)}else s.localName==t&&(r.props=this.parseMathProperies(s))}return r}parseMathProperies(e){const t={};for(const r of k.elements(e))switch(r.localName){case"chr":t.char=k.attr(r,"val");break;case"vertJc":t.verticalJustification=k.attr(r,"val");break;case"pos":t.position=k.attr(r,"val");break;case"degHide":t.hideDegree=k.boolAttr(r,"val");break;case"begChr":t.beginChar=k.attr(r,"val");break;case"endChr":t.endChar=k.attr(r,"val")}return t}parseRunProperties(e,t){this.parseDefaultProperties(e,t.cssStyle={},null,e=>{switch(e.localName){case"rStyle":t.styleName=k.attr(e,"val");break;case"vertAlign":t.verticalAlign=_e.valueOfVertAlign(e,!0);break;default:return!1}return!0})}parseVmlPicture(e){const t={type:T.VmlPicture,children:[]};for(const r of k.elements(e)){const e=we(r,this);e&&t.children.push(e)}return t}checkAlternateContent(e){if("AlternateContent"!=e.localName)return e;var t=k.element(e,"Choice");if(t){var r=k.attr(t,"Requires"),a=e.lookupNamespaceURI(r);if(Fe.includes(a))return t.firstElementChild}return k.element(e,"Fallback")?.firstElementChild}parseDrawing(e){for(var t of k.elements(e))switch(t.localName){case"inline":case"anchor":return this.parseDrawingWrapper(t)}}parseDrawingWrapper(e){var t={type:T.Drawing,children:[],cssStyle:{}},r="anchor"==e.localName;let a=null,s=k.boolAttr(e,"simplePos");k.boolAttr(e,"behindDoc");let n={relative:"page",align:"left",offset:"0"},l={relative:"page",align:"top",offset:"0"};for(var o of k.elements(e))switch(o.localName){case"simplePos":s&&(n.offset=k.lengthAttr(o,"x",m),l.offset=k.lengthAttr(o,"y",m));break;case"extent":t.cssStyle.width=k.lengthAttr(o,"cx",m),t.cssStyle.height=k.lengthAttr(o,"cy",m);break;case"positionH":case"positionV":if(!s){let e="positionH"==o.localName?n:l;var i=k.element(o,"align"),c=k.element(o,"posOffset");e.relative=k.attr(o,"relativeFrom")??e.relative,i&&(e.align=i.textContent),c&&(e.offset=g(c.textContent,m))}break;case"wrapTopAndBottom":a="wrapTopAndBottom";break;case"wrapNone":a="wrapNone";break;case"graphic":var h=this.parseGraphic(o);h&&t.children.push(h)}return"wrapTopAndBottom"==a?(t.cssStyle.display="block",n.align&&(t.cssStyle["text-align"]=n.align,t.cssStyle.width="100%")):"wrapNone"==a?(t.cssStyle.display="block",t.cssStyle.position="relative",t.cssStyle.width="0px",t.cssStyle.height="0px",n.offset&&(t.cssStyle.left=n.offset),l.offset&&(t.cssStyle.top=l.offset)):!r||"left"!=n.align&&"right"!=n.align||(t.cssStyle.float=n.align),t}parseGraphic(e){var t=k.element(e,"graphicData");for(let e of k.elements(t))if("pic"===e.localName)return this.parsePicture(e);return null}parsePicture(e){var t={type:T.Image,src:"",cssStyle:{}},r=k.element(e,"blipFill"),a=k.element(r,"blip"),s=k.element(r,"srcRect");t.src=k.attr(a,"embed"),s&&(t.srcRect=[k.intAttr(s,"l",0)/1e5,k.intAttr(s,"t",0)/1e5,k.intAttr(s,"r",0)/1e5,k.intAttr(s,"b",0)/1e5]);var n=k.element(e,"spPr"),l=k.element(n,"xfrm");if(t.cssStyle.position="relative",l)for(var o of(t.rotation=k.intAttr(l,"rot",0)/6e4,k.elements(l)))switch(o.localName){case"ext":t.cssStyle.width=k.lengthAttr(o,"cx",m),t.cssStyle.height=k.lengthAttr(o,"cy",m);break;case"off":t.cssStyle.left=k.lengthAttr(o,"x",m),t.cssStyle.top=k.lengthAttr(o,"y",m)}return t}parseTable(e){var t={type:T.Table,children:[]};for(const r of k.elements(e))switch(r.localName){case"tr":t.children.push(this.parseTableRow(r));break;case"tblGrid":t.columns=this.parseTableColumns(r);break;case"tblPr":this.parseTableProperties(r,t)}return t}parseTableColumns(e){var t=[];for(const r of k.elements(e))if("gridCol"===r.localName)t.push({width:k.lengthAttr(r,"w")});return t}parseTableProperties(e,t){switch(t.cssStyle={},t.cellStyle={},this.parseDefaultProperties(e,t.cssStyle,t.cellStyle,e=>{switch(e.localName){case"tblStyle":t.styleName=k.attr(e,"val");break;case"tblLook":t.className=_e.classNameOftblLook(e);break;case"tblpPr":this.parseTablePosition(e,t);break;case"tblStyleColBandSize":t.colBandSize=k.intAttr(e,"val");break;case"tblStyleRowBandSize":t.rowBandSize=k.intAttr(e,"val");break;case"hidden":t.cssStyle.display="none";break;default:return!1}return!0}),t.cssStyle["text-align"]){case"center":delete t.cssStyle["text-align"],t.cssStyle["margin-left"]="auto",t.cssStyle["margin-right"]="auto";break;case"right":delete t.cssStyle["text-align"],t.cssStyle["margin-left"]="auto"}}parseTablePosition(e,t){var r=k.lengthAttr(e,"topFromText"),a=k.lengthAttr(e,"bottomFromText"),s=k.lengthAttr(e,"rightFromText"),n=k.lengthAttr(e,"leftFromText");t.cssStyle.float="left",t.cssStyle["margin-bottom"]=_e.addSize(t.cssStyle["margin-bottom"],a),t.cssStyle["margin-left"]=_e.addSize(t.cssStyle["margin-left"],n),t.cssStyle["margin-right"]=_e.addSize(t.cssStyle["margin-right"],s),t.cssStyle["margin-top"]=_e.addSize(t.cssStyle["margin-top"],r)}parseTableRow(e){var t={type:T.Row,children:[]};for(const r of k.elements(e))switch(r.localName){case"tc":t.children.push(this.parseTableCell(r));break;case"trPr":case"tblPrEx":this.parseTableRowProperties(r,t)}return t}parseTableRowProperties(e,t){t.cssStyle=this.parseDefaultProperties(e,{},null,e=>{switch(e.localName){case"cnfStyle":t.className=_e.classNameOfCnfStyle(e);break;case"tblHeader":t.isHeader=k.boolAttr(e,"val");break;case"gridBefore":t.gridBefore=k.intAttr(e,"val");break;case"gridAfter":t.gridAfter=k.intAttr(e,"val");break;default:return!1}return!0})}parseTableCell(e){var t={type:T.Cell,children:[]};for(const r of k.elements(e))switch(r.localName){case"tbl":t.children.push(this.parseTable(r));break;case"p":t.children.push(this.parseParagraph(r));break;case"tcPr":this.parseTableCellProperties(r,t)}return t}parseTableCellProperties(e,t){t.cssStyle=this.parseDefaultProperties(e,{},null,e=>{switch(e.localName){case"gridSpan":t.span=k.intAttr(e,"val",null);break;case"vMerge":t.verticalMerge=k.attr(e,"val")??"continue";break;case"cnfStyle":t.className=_e.classNameOfCnfStyle(e);break;default:return!1}return!0}),this.parseTableCellVerticalText(e,t)}parseTableCellVerticalText(e,t){const r={btLr:{writingMode:"vertical-rl",transform:"rotate(180deg)"},lrTb:{writingMode:"vertical-lr",transform:"none"},tbRl:{writingMode:"vertical-rl",transform:"none"}};for(const a of k.elements(e))if("textDirection"===a.localName){const e=r[k.attr(a,"val")]||{writingMode:"horizontal-tb"};t.cssStyle["writing-mode"]=e.writingMode,t.cssStyle.transform=e.transform}}parseDefaultProperties(e,t=null,r=null,a=null){t=t||{};for(const s of k.elements(e))if(!a?.(s))switch(s.localName){case"jc":t["text-align"]=_e.valueOfJc(s);break;case"textAlignment":t["vertical-align"]=_e.valueOfTextAlignment(s);break;case"color":t.color=He.colorAttr(s,"val",null,Be);break;case"sz":t["font-size"]=t["min-height"]=k.lengthAttr(s,"val",p);break;case"shd":t["background-color"]=He.colorAttr(s,"fill",null,Re);break;case"highlight":t["background-color"]=He.colorAttr(s,"val",null,$e);break;case"vertAlign":break;case"position":t.verticalAlign=k.lengthAttr(s,"val",p);break;case"tcW":if(this.options.ignoreWidth)break;case"tblW":t.width=_e.valueOfSize(s,"w");break;case"trHeight":this.parseTrHeight(s,t);break;case"strike":t["text-decoration"]=k.boolAttr(s,"val",!0)?"line-through":"none";break;case"b":t["font-weight"]=k.boolAttr(s,"val",!0)?"bold":"normal";break;case"i":t["font-style"]=k.boolAttr(s,"val",!0)?"italic":"normal";break;case"caps":t["text-transform"]=k.boolAttr(s,"val",!0)?"uppercase":"none";break;case"smallCaps":t["font-variant"]=k.boolAttr(s,"val",!0)?"small-caps":"none";break;case"u":this.parseUnderline(s,t);break;case"ind":case"tblInd":this.parseIndentation(s,t);break;case"rFonts":this.parseFont(s,t);break;case"tblBorders":this.parseBorderProperties(s,r||t);break;case"tblCellSpacing":t["border-spacing"]=_e.valueOfMargin(s),t["border-collapse"]="separate";break;case"pBdr":this.parseBorderProperties(s,t);break;case"bdr":t.border=_e.valueOfBorder(s);break;case"tcBorders":this.parseBorderProperties(s,t);break;case"vanish":k.boolAttr(s,"val",!0)&&(t.display="none");break;case"kern":case"noWrap":break;case"tblCellMar":case"tcMar":this.parseMarginProperties(s,r||t);break;case"tblLayout":t["table-layout"]=_e.valueOfTblLayout(s);break;case"vAlign":t["vertical-align"]=_e.valueOfTextAlignment(s);break;case"spacing":"pPr"==e.localName&&this.parseSpacing(s,t);break;case"wordWrap":k.boolAttr(s,"val")&&(t["overflow-wrap"]="break-word");break;case"suppressAutoHyphens":t.hyphens=k.boolAttr(s,"val",!0)?"none":"auto";break;case"lang":t.$lang=k.attr(s,"val");break;case"rtl":case"bidi":k.boolAttr(s,"val",!0)&&(t.direction="rtl");break;case"bCs":case"iCs":case"szCs":case"tabs":case"outlineLvl":case"contextualSpacing":case"tblStyleColBandSize":case"tblStyleRowBandSize":case"webHidden":case"pageBreakBefore":case"suppressLineNumbers":case"keepLines":case"keepNext":case"widowControl":case"bidi":case"rtl":case"noProof":break;default:this.options.debug&&console.warn(`DOCX: Unknown document element: ${e.localName}.${s.localName}`)}return t}parseUnderline(e,t){var r=k.attr(e,"val");if(null!=r){switch(r){case"dash":case"dashDotDotHeavy":case"dashDotHeavy":case"dashedHeavy":case"dashLong":case"dashLongHeavy":case"dotDash":case"dotDotDash":t["text-decoration"]="underline dashed";break;case"dotted":case"dottedHeavy":t["text-decoration"]="underline dotted";break;case"double":t["text-decoration"]="underline double";break;case"single":case"thick":case"words":t["text-decoration"]="underline";break;case"wave":case"wavyDouble":case"wavyHeavy":t["text-decoration"]="underline wavy";break;case"none":t["text-decoration"]="none"}var a=He.colorAttr(e,"color");a&&(t["text-decoration-color"]=a)}}parseFont(e,t){var a=[k.attr(e,"ascii"),_e.themeValue(e,"asciiTheme"),k.attr(e,"eastAsia")].filter(e=>e).map(e=>r(e));a.length>0&&(t["font-family"]=[...new Set(a)].join(", "))}parseIndentation(e,t){var r=k.lengthAttr(e,"firstLine"),a=k.lengthAttr(e,"hanging"),s=k.lengthAttr(e,"left"),n=k.lengthAttr(e,"start"),l=k.lengthAttr(e,"right"),o=k.lengthAttr(e,"end");r&&(t["text-indent"]=r),a&&(t["text-indent"]=`-${a}`),(s||n)&&(t["margin-inline-start"]=s||n),(l||o)&&(t["margin-inline-end"]=l||o)}parseSpacing(e,t){var r=k.lengthAttr(e,"before"),a=k.lengthAttr(e,"after"),s=k.intAttr(e,"line",null),n=k.attr(e,"lineRule");if(r&&(t["margin-top"]=r),a&&(t["margin-bottom"]=a),null!==s)switch(n){case"auto":t["line-height"]=`${(s/240).toFixed(2)}`;break;case"atLeast":t["line-height"]=`calc(100% + ${s/20}pt)`;break;default:t["line-height"]=t["min-height"]=s/20+"pt"}}parseMarginProperties(e,t){for(const r of k.elements(e))switch(r.localName){case"left":t["padding-left"]=_e.valueOfMargin(r);break;case"right":t["padding-right"]=_e.valueOfMargin(r);break;case"top":t["padding-top"]=_e.valueOfMargin(r);break;case"bottom":t["padding-bottom"]=_e.valueOfMargin(r)}}parseTrHeight(e,t){k.attr(e,"hRule"),t.height=k.lengthAttr(e,"val")}parseBorderProperties(e,t){for(const r of k.elements(e))switch(r.localName){case"start":case"left":t["border-left"]=_e.valueOfBorder(r);break;case"end":case"right":t["border-right"]=_e.valueOfBorder(r);break;case"top":t["border-top"]=_e.valueOfBorder(r);break;case"bottom":t["border-bottom"]=_e.valueOfBorder(r)}}}const Oe=["black","blue","cyan","darkBlue","darkCyan","darkGray","darkGreen","darkMagenta","darkRed","darkYellow","green","lightGray","magenta","none","red","white","yellow"];class He{static colorAttr(e,t,r=null,a="black"){var s=k.attr(e,t);if(s)return"auto"==s?a:Oe.includes(s)?s:`#${s}`;var n=k.attr(e,"themeColor");return n?`var(--docx-${n}-color)`:r}}class _e{static themeValue(e,t){var r=k.attr(e,t);return r?`var(--docx-${r}-font)`:null}static valueOfSize(e,t){var r=h;switch(k.attr(e,"type")){case"dxa":break;case"pct":r=f;break;case"auto":return"auto"}return k.lengthAttr(e,t,r)}static valueOfMargin(e){return k.lengthAttr(e,"w")}static valueOfBorder(e){var t=_e.parseBorderType(k.attr(e,"val"));if("none"==t)return"none";var r=He.colorAttr(e,"color");return`${k.lengthAttr(e,"sz",u)} ${t} ${"auto"==r?De:r}`}static parseBorderType(e){switch(e){case"single":case"dashDotStroked":case"thick":case"thickThinLargeGap":case"thickThinMediumGap":case"thickThinSmallGap":case"thinThickLargeGap":case"thinThickMediumGap":case"thinThickSmallGap":case"thinThickThinLargeGap":case"thinThickThinMediumGap":case"thinThickThinSmallGap":case"threeDEmboss":case"threeDEngrave":case"wave":return"solid";case"dashed":case"dashSmallGap":return"dashed";case"dotDash":case"dotDotDash":case"dotted":return"dotted";case"double":case"doubleWave":case"triple":return"double";case"inset":return"inset";case"nil":case"none":return"none";case"outset":return"outset"}return"solid"}static valueOfTblLayout(e){return"fixed"==k.attr(e,"val")?"fixed":"auto"}static classNameOfCnfStyle(e){const t=k.attr(e,"val");return["first-row","last-row","first-col","last-col","odd-col","even-col","odd-row","even-row","ne-cell","nw-cell","se-cell","sw-cell"].filter((e,r)=>"1"==t[r]).join(" ")}static valueOfJc(e){var t=k.attr(e,"val");switch(t){case"start":case"left":return"left";case"center":return"center";case"end":case"right":return"right";case"both":return"justify"}return t}static valueOfVertAlign(e,t=!1){var r=k.attr(e,"val");switch(r){case"subscript":return"sub";case"superscript":return t?"sup":"super"}return t?null:r}static valueOfTextAlignment(e){var t=k.attr(e,"val");switch(t){case"auto":case"baseline":return"baseline";case"top":return"top";case"center":return"middle";case"bottom":return"bottom"}return t}static addSize(e,t){return null==e?t:null==t?e:`calc(${e} + ${t})`}static classNameOftblLook(e){const t=k.hexAttr(e,"val",0);let r="";return(k.boolAttr(e,"firstRow")||32&t)&&(r+=" first-row"),(k.boolAttr(e,"lastRow")||64&t)&&(r+=" last-row"),(k.boolAttr(e,"firstColumn")||128&t)&&(r+=" first-col"),(k.boolAttr(e,"lastColumn")||256&t)&&(r+=" last-col"),(k.boolAttr(e,"noHBand")||512&t)&&(r+=" no-hband"),(k.boolAttr(e,"noVBand")||1024&t)&&(r+=" no-vband"),r.trim()}}const ze={pos:0,leader:"none",style:"left"};function Ve(e,t,r,a=.75){const s=e.closest("p"),n=e.getBoundingClientRect(),l=s.getBoundingClientRect(),o=getComputedStyle(s),i=t?.length>0?t.map(e=>({pos:je(e.position),leader:e.leader,style:e.style})).sort((e,t)=>e.pos-t.pos):[ze],c=i[i.length-1],h=l.width*a,m=je(r);let p=c.pos+m;if(p"clear"!=e.style&&e.pos>f);if(null==g)return;let b=1;if("right"==g.style||"center"==g.style){const t=Array.from(s.querySelectorAll(`.${e.className}`)),r=t.indexOf(e)+1,n=document.createRange();n.setStart(e,1),re.id)),e.endnotesPart&&(this.endnoteMap=n(e.endnotesPart.notes,e=>e.id)),e.settingsPart&&(this.defaultTabSize=e.settingsPart.settings?.defaultTabStop),!a.ignoreFonts&&e.fontTablePart&&this.renderFontTable(e.fontTablePart,r);var s=this.renderSections(e.documentPart.body);this.options.inWrapper?t.appendChild(this.renderWrapper(s)):qe(t,s),this.commentHighlight&&a.renderComments&&CSS.highlights.set(`${this.className}-comments`,this.commentHighlight),this.postRenderTasks.forEach(e=>e()),await Promise.allSettled(this.tasks),this.refreshTabStops()}renderTheme(e,t){const r={},a=e.theme?.fontScheme;a&&(a.majorFont&&(r["--docx-majorHAnsi-font"]=a.majorFont.latinTypeface),a.minorFont&&(r["--docx-minorHAnsi-font"]=a.minorFont.latinTypeface));const s=e.theme?.colorScheme;if(s)for(let[e,t]of Object.entries(s.colors))r[`--docx-${e}-color`]=`#${t}`;const n=this.styleToString(`.${this.className}`,r);t.appendChild(this.createStyleElement(n))}renderFontTable(e,t){for(let a of e.fonts)for(let e of a.embedFontRefs)this.tasks.push(this.document.loadFont(e.id,e.key).then(s=>{const n={"font-family":r(a.name),src:`url(${s})`};"bold"!=e.type&&"boldItalic"!=e.type||(n["font-weight"]="bold"),"italic"!=e.type&&"boldItalic"!=e.type||(n["font-style"]="italic");const l=this.styleToString("@font-face",n);t.appendChild(this.createComment(`docxjs ${a.name} font`)),t.appendChild(this.createStyleElement(l))}))}processStyleName(e){return e?`${this.className}_${function(e){return e?.replace(/[ .]+/g,"-").replace(/[&]+/g,"and").toLowerCase()}(e)}`:this.className}processStyles(e){const t=n(e.filter(e=>null!=e.id),e=>e.id);for(const a of e.filter(e=>e.basedOn)){var r=t[a.basedOn];if(r){a.paragraphProps=o(a.paragraphProps,r.paragraphProps),a.runProps=o(a.runProps,r.runProps);for(const e of r.styles){const t=a.styles.find(t=>t.target==e.target);t?this.copyStyleProperties(e.values,t.values):a.styles.push({...e,values:{...e.values}})}}else this.options.debug&&console.warn(`Can't find base style ${a.basedOn}`)}for(let t of e)t.cssName=this.processStyleName(t.id);return t}prodessNumberings(e){for(let t of e.filter(e=>e.pStyleName)){const e=this.findStyle(t.pStyleName);e?.paragraphProps?.numbering&&(e.paragraphProps.numbering.level=t.level)}}processElement(e){if(e.children)for(var t of e.children)t.parent=e,t.type==T.Table?this.processTable(t):this.processElement(t)}processTable(e){for(var t of e.children)for(var r of t.children)r.cssStyle=this.copyStyleProperties(e.cellStyle,r.cssStyle,["border-left","border-right","border-top","border-bottom","padding-left","padding-right","padding-top","padding-bottom"]),this.processElement(r)}copyStyleProperties(e,t,r=null){if(!e)return t;for(var a of(null==t&&(t={}),null==r&&(r=Object.getOwnPropertyNames(e)),r))e.hasOwnProperty(a)&&!t.hasOwnProperty(a)&&(t[a]=e[a]);return t}createPageElement(e,t){var r=this.createElement("section",{className:e});return t&&(t.pageMargins&&(r.style.paddingLeft=t.pageMargins.left,r.style.paddingRight=t.pageMargins.right,r.style.paddingTop=t.pageMargins.top,r.style.paddingBottom=t.pageMargins.bottom),t.pageSize&&(this.options.ignoreWidth||(r.style.width=t.pageSize.width),this.options.ignoreHeight||(r.style.minHeight=t.pageSize.height))),r}createSectionContent(e){var t=this.createElement("article");return e.columns&&e.columns.numberOfColumns&&(t.style.columnCount=`${e.columns.numberOfColumns}`,t.style.columnGap=e.columns.space,e.columns.separator&&(t.style.columnRule="1px solid black")),t}renderSections(e){const t=[];this.processElement(e);const r=this.splitBySection(e.children,e.props),a=this.groupByPageBreaks(r);let s=null;for(let r=0,l=a.length;r"first"==e.type):null)??(r%2==1?e.find(e=>"even"==e.type):null)??e.find(e=>"default"==e.type),l=n&&this.document.findPartByRelId(n.id,this.document.documentPart);if(l){this.currentPart=l,this.usedHederFooterParts.includes(l.path)||(this.processElement(l.rootElement),this.usedHederFooterParts.push(l.path));const[e]=this.renderElements([l.rootElement],s);t?.pageMargins&&(l.rootElement.type===T.Header?(e.style.marginTop=`calc(${t.pageMargins.header} - ${t.pageMargins.top})`,e.style.minHeight=`calc(${t.pageMargins.top} - ${t.pageMargins.header})`):l.rootElement.type===T.Footer&&(e.style.marginBottom=`calc(${t.pageMargins.footer} - ${t.pageMargins.bottom})`,e.style.minHeight=`calc(${t.pageMargins.bottom} - ${t.pageMargins.footer})`)),this.currentPart=null}}}isPageBreakElement(e){return e.type==T.Break&&("lastRenderedPageBreak"==e.break?!this.options.ignoreLastRenderedPageBreak:"page"==e.break)}isPageBreakSection(e,t){return!!e&&(!!t&&(e.pageSize?.orientation!=t.pageSize?.orientation||e.pageSize?.width!=t.pageSize?.width||e.pageSize?.height!=t.pageSize?.height))}splitBySection(e,t){var r={sectProps:null,elements:[],pageBreak:!1},a=[r];for(let t of e){if(t.type==T.Paragraph){const e=this.findStyle(t.styleName);e?.paragraphProps?.pageBreakBefore&&(r.sectProps=s,r.pageBreak=!0,r={sectProps:null,elements:[],pageBreak:!1},a.push(r))}if(r.elements.push(t),t.type==T.Paragraph){const e=t;var s=e.sectionProps,n=-1,l=-1;if(this.options.breakPages&&e.children&&(n=e.children.findIndex(e=>-1!=(l=e.children?.findIndex(this.isPageBreakElement.bind(this))??-1))),(s||-1!=n)&&(r.sectProps=s,r.pageBreak=-1!=n,r={sectProps:null,elements:[],pageBreak:!1},a.push(r)),-1!=n){let a=e.children[n],s=l=0;e--)null==a[e].sectProps?a[e].sectProps=c??t:c=a[e].sectProps;return a}groupByPageBreaks(e){let t,r=[];const a=[r];for(let s of e)r.push(s),(this.options.ignoreLastRenderedPageBreak||s.pageBreak||this.isPageBreakSection(t,s.sectProps))&&a.push(r=[]),t=s.sectProps;return a.filter(e=>e.length>0)}renderWrapper(e){return this.createElement("div",{className:`${this.className}-wrapper`},e)}renderDefaultStyle(){var e=this.className,t=`\n.${e}-wrapper { background: gray; padding: 30px; padding-bottom: 0px; display: flex; flex-flow: column; align-items: center; } \n.${e}-wrapper>section.${e} { background: white; box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); margin-bottom: 30px; }`;this.options.hideWrapperOnPrint&&(t=`@media not print { ${t} }`);var r=`${t}\n.${e} { color: black; hyphens: auto; text-underline-position: from-font; }\nsection.${e} { box-sizing: border-box; display: flex; flex-flow: column nowrap; position: relative; overflow: hidden; }\nsection.${e}>article { margin-bottom: auto; z-index: 1; }\nsection.${e}>footer { z-index: 1; }\n.${e} table { border-collapse: collapse; }\n.${e} table td, .${e} table th { vertical-align: top; }\n.${e} p { margin: 0pt; min-height: 1em; }\n.${e} span { white-space: pre-wrap; overflow-wrap: break-word; }\n.${e} a { color: inherit; text-decoration: inherit; }\n.${e} svg { fill: transparent; }\n`;return this.options.renderComments&&(r+=`\n.${e}-comment-ref { cursor: default; }\n.${e}-comment-popover { display: none; z-index: 1000; padding: 0.5rem; background: white; position: absolute; box-shadow: 0 0 0.25rem rgba(0, 0, 0, 0.25); width: 30ch; }\n.${e}-comment-ref:hover~.${e}-comment-popover { display: block; }\n.${e}-comment-author,.${e}-comment-date { font-size: 0.875rem; color: #888; }\n`),this.createStyleElement(r)}renderNumbering(e,t){var r="",a=[];for(var s of e){var n=`p.${this.numberingClass(s.id,s.level)}`,l="none";if(s.bullet){let e=`--${this.className}-${s.bullet.src}`.toLowerCase();r+=this.styleToString(`${n}:before`,{content:"' '",display:"inline-block",background:`var(${e})`},s.bullet.style),this.tasks.push(this.document.loadNumberingImage(s.bullet.src).then(r=>{var a=`${this.rootSelector} { ${e}: url(${r}) }`;t.appendChild(this.createStyleElement(a))}))}else if(s.levelText){let e=this.numberingCounter(s.id,s.level);const t=e+" "+(s.start-1);s.level>0&&(r+=this.styleToString(`p.${this.numberingClass(s.id,s.level-1)}`,{"counter-set":t})),a.push(t),r+=this.styleToString(`${n}:before`,{content:this.levelTextToContent(s.levelText,s.suff,s.id,this.numFormatToCssValue(s.format)),"counter-increment":e,...s.rStyle})}else l=this.numFormatToCssValue(s.format);r+=this.styleToString(n,{display:"list-item","list-style-position":"inside","list-style-type":l,...s.pStyle})}return a.length>0&&(r+=this.styleToString(this.rootSelector,{"counter-reset":a.join(" ")})),this.createStyleElement(r)}renderStyles(e){var t="";const r=this.styleMap,a=n(e.filter(e=>e.isDefault),e=>e.target);for(const n of e){var s=n.styles;if(n.linked){var l=n.linked&&r[n.linked];l?s=s.concat(l.styles):this.options.debug&&console.warn(`Can't find linked style ${n.linked}`)}for(const e of s){var o=`${n.target??""}.${n.cssName}`;n.target!=e.target&&(o+=` ${e.target}`),a[n.target]==n&&(o=`.${this.className} ${n.target}, `+o),t+=this.styleToString(o,e.values)}}return this.createStyleElement(t)}renderNotes(e,t,r){var a=e.map(e=>t[e]).filter(e=>e);if(a.length>0){var s=this.createElement("ol",null,this.renderElements(a));r.appendChild(s)}}renderElement(e){switch(e.type){case T.Paragraph:return this.renderParagraph(e);case T.BookmarkStart:return this.renderBookmarkStart(e);case T.BookmarkEnd:return null;case T.Run:return this.renderRun(e);case T.Table:return this.renderTable(e);case T.Row:return this.renderTableRow(e);case T.Cell:return this.renderTableCell(e);case T.Hyperlink:return this.renderHyperlink(e);case T.SmartTag:return this.renderSmartTag(e);case T.Drawing:return this.renderDrawing(e);case T.Image:return this.renderImage(e);case T.Text:case T.Text:return this.renderText(e);case T.DeletedText:return this.renderDeletedText(e);case T.Tab:return this.renderTab(e);case T.Symbol:return this.renderSymbol(e);case T.Break:return this.renderBreak(e);case T.Footer:return this.renderContainer(e,"footer");case T.Header:return this.renderContainer(e,"header");case T.Footnote:case T.Endnote:return this.renderContainer(e,"li");case T.FootnoteReference:return this.renderFootnoteReference(e);case T.EndnoteReference:return this.renderEndnoteReference(e);case T.NoBreakHyphen:return this.createElement("wbr");case T.VmlPicture:return this.renderVmlPicture(e);case T.VmlElement:return this.renderVmlElement(e);case T.MmlMath:return this.renderContainerNS(e,Xe,"math",{xmlns:Xe});case T.MmlMathParagraph:return this.renderContainer(e,"span");case T.MmlFraction:return this.renderContainerNS(e,Xe,"mfrac");case T.MmlBase:return this.renderContainerNS(e,Xe,e.parent.type==T.MmlMatrixRow?"mtd":"mrow");case T.MmlNumerator:case T.MmlDenominator:case T.MmlFunction:case T.MmlLimit:case T.MmlBox:return this.renderContainerNS(e,Xe,"mrow");case T.MmlGroupChar:return this.renderMmlGroupChar(e);case T.MmlLimitLower:return this.renderContainerNS(e,Xe,"munder");case T.MmlMatrix:return this.renderContainerNS(e,Xe,"mtable");case T.MmlMatrixRow:return this.renderContainerNS(e,Xe,"mtr");case T.MmlRadical:return this.renderMmlRadical(e);case T.MmlSuperscript:return this.renderContainerNS(e,Xe,"msup");case T.MmlSubscript:return this.renderContainerNS(e,Xe,"msub");case T.MmlDegree:case T.MmlSuperArgument:case T.MmlSubArgument:return this.renderContainerNS(e,Xe,"mn");case T.MmlFunctionName:return this.renderContainerNS(e,Xe,"ms");case T.MmlDelimiter:return this.renderMmlDelimiter(e);case T.MmlRun:return this.renderMmlRun(e);case T.MmlNary:return this.renderMmlNary(e);case T.MmlPreSubSuper:return this.renderMmlPreSubSuper(e);case T.MmlBar:return this.renderMmlBar(e);case T.MmlEquationArray:return this.renderMllList(e);case T.Inserted:return this.renderInserted(e);case T.Deleted:return this.renderDeleted(e);case T.CommentRangeStart:return this.renderCommentRangeStart(e);case T.CommentRangeEnd:return this.renderCommentRangeEnd(e);case T.CommentReference:return this.renderCommentReference(e);case T.AltChunk:return this.renderAltChunk(e)}return null}renderElements(e,t){if(null==e)return null;var r=e.flatMap(e=>this.renderElement(e)).filter(e=>null!=e);return t&&qe(t,r),r}renderContainer(e,t,r){return this.createElement(t,r,this.renderElements(e.children))}renderContainerNS(e,t,r,a){return this.createElementNS(t,r,a,this.renderElements(e.children))}renderParagraph(e){var t=this.renderContainer(e,"p");const r=this.findStyle(e.styleName);e.tabs??(e.tabs=r?.paragraphProps?.tabs),this.renderClass(e,t),this.renderStyleValues(e.cssStyle,t),this.renderCommonProperties(t.style,e);const a=e.numbering??r?.paragraphProps?.numbering;return a&&t.classList.add(this.numberingClass(a.id,a.level)),t}renderRunProperties(e,t){this.renderCommonProperties(e,t)}renderCommonProperties(e,t){null!=t&&(t.color&&(e.color=t.color),t.fontSize&&(e["font-size"]=t.fontSize))}renderHyperlink(e){var t=this.renderContainer(e,"a");this.renderStyleValues(e.cssStyle,t);let r="";if(e.id){const t=this.document.documentPart.rels.find(t=>t.id==e.id&&"External"===t.targetMode);r=t?.target??r}return e.anchor&&(r+=`#${e.anchor}`),t.href=r,t}renderSmartTag(e){return this.renderContainer(e,"span")}renderCommentRangeStart(e){if(!this.options.renderComments)return null;const t=new Range;this.commentHighlight?.add(t);const r=this.createComment(`start of comment #${e.id}`);return this.later(()=>t.setStart(r,0)),this.commentMap[e.id]=t,r}renderCommentRangeEnd(e){if(!this.options.renderComments)return null;const t=this.commentMap[e.id],r=this.createComment(`end of comment #${e.id}`);return this.later(()=>t?.setEnd(r,0)),r}renderCommentReference(e){if(!this.options.renderComments)return null;var t=this.document.commentsPart?.commentMap[e.id];if(!t)return null;const r=new DocumentFragment,a=this.createElement("span",{className:`${this.className}-comment-ref`},["💬"]),s=this.createElement("div",{className:`${this.className}-comment-popover`});return this.renderCommentContent(t,s),r.appendChild(this.createComment(`comment #${t.id} by ${t.author} on ${t.date}`)),r.appendChild(a),r.appendChild(s),r}renderAltChunk(e){if(!this.options.renderAltChunks)return null;var t=this.createElement("iframe");return this.tasks.push(this.document.loadAltChunk(e.id,this.currentPart).then(e=>{t.srcdoc=e})),t}renderCommentContent(e,t){t.appendChild(this.createElement("div",{className:`${this.className}-comment-author`},[e.author])),t.appendChild(this.createElement("div",{className:`${this.className}-comment-date`},[new Date(e.date).toLocaleString()])),this.renderElements(e.children,t)}renderDrawing(e){var t=this.renderContainer(e,"div");return t.style.display="inline-block",t.style.position="relative",t.style.textIndent="0px",this.renderStyleValues(e.cssStyle,t),t}renderImage(e){let t=this.createElement("img"),r=e.cssStyle?.transform;if(this.renderStyleValues(e.cssStyle,t),e.srcRect&&e.srcRect.some(e=>0!=e)){var[a,s,n,l]=e.srcRect;r=`scale(${1/(1-a-n)}, ${1/(1-s-l)})`,t.style["clip-path"]=`rect(${(100*s).toFixed(2)}% ${(100*(1-n)).toFixed(2)}% ${(100*(1-l)).toFixed(2)}% ${(100*a).toFixed(2)}%)`}return e.rotation&&(r=`rotate(${e.rotation}deg) ${r??""}`),t.style.transform=r?.trim(),this.document&&this.tasks.push(this.document.loadDocumentImage(e.src,this.currentPart).then(e=>{t.src=e})),t}renderText(e){return this.htmlDocument.createTextNode(e.text)}renderDeletedText(e){return this.options.renderChanges?this.renderText(e):null}renderBreak(e){return"textWrapping"==e.break?this.createElement("br"):null}renderInserted(e){return this.options.renderChanges?this.renderContainer(e,"ins"):this.renderElements(e.children)}renderDeleted(e){return this.options.renderChanges?this.renderContainer(e,"del"):null}renderSymbol(e){var t=this.createElement("span");return t.style.fontFamily=e.font,t.innerHTML=`&#x${e.char};`,t}renderFootnoteReference(e){var t=this.createElement("sup");return this.currentFootnoteIds.push(e.id),t.textContent=`${this.currentFootnoteIds.length}`,t}renderEndnoteReference(e){var t=this.createElement("sup");return this.currentEndnoteIds.push(e.id),t.textContent=`${this.currentEndnoteIds.length}`,t}renderTab(e){var t=this.createElement("span");if(t.innerHTML=" ",this.options.experimental){t.className=this.tabStopClass();var r=function(e,t){var r=e.parent;for(;null!=r&&r.type!=t;)r=r.parent;return r}(e,T.Paragraph)?.tabs;this.currentTabs.push({stops:r,span:t})}return t}renderBookmarkStart(e){return this.createElement("span",{id:e.name})}renderRun(e){if(e.fieldRun)return null;const t=this.createElement("span");if(e.id&&(t.id=e.id),this.renderClass(e,t),this.renderStyleValues(e.cssStyle,t),e.verticalAlign){const r=this.createElement(e.verticalAlign);this.renderElements(e.children,r),t.appendChild(r)}else this.renderElements(e.children,t);return t}renderTable(e){let t=this.createElement("table");return this.tableCellPositions.push(this.currentCellPosition),this.tableVerticalMerges.push(this.currentVerticalMerge),this.currentVerticalMerge={},this.currentCellPosition={col:0,row:0},e.columns&&t.appendChild(this.renderTableColumns(e.columns)),this.renderClass(e,t),this.renderElements(e.children,t),this.renderStyleValues(e.cssStyle,t),this.currentVerticalMerge=this.tableVerticalMerges.pop(),this.currentCellPosition=this.tableCellPositions.pop(),t}renderTableColumns(e){let t=this.createElement("colgroup");for(let r of e){let e=this.createElement("col");r.width&&(e.style.width=r.width),t.appendChild(e)}return t}renderTableRow(e){let t=this.createElement("tr");return this.currentCellPosition.col=0,e.gridBefore&&t.appendChild(this.renderTableCellPlaceholder(e.gridBefore)),this.renderClass(e,t),this.renderElements(e.children,t),this.renderStyleValues(e.cssStyle,t),e.gridAfter&&t.appendChild(this.renderTableCellPlaceholder(e.gridAfter)),this.currentCellPosition.row++,t}renderTableCellPlaceholder(e){const t=this.createElement("td",{colSpan:e});return t.style.border="none",t}renderTableCell(e){let t=this.renderContainer(e,"td");const r=this.currentCellPosition.col;return e.verticalMerge?"restart"==e.verticalMerge?(this.currentVerticalMerge[r]=t,t.rowSpan=1):this.currentVerticalMerge[r]&&(this.currentVerticalMerge[r].rowSpan+=1,t.style.display="none"):this.currentVerticalMerge[r]=null,this.renderClass(e,t),this.renderStyleValues(e.cssStyle,t),e.span&&(t.colSpan=e.span),this.currentCellPosition.col+=t.colSpan,t}renderVmlPicture(e){return this.renderContainer(e,"div")}renderVmlElement(e){var t=this.createSvgElement("svg");t.setAttribute("style",e.cssStyleText);const r=this.renderVmlChildElement(e);return e.imageHref?.id&&this.tasks.push(this.document?.loadDocumentImage(e.imageHref.id,this.currentPart).then(e=>r.setAttribute("href",e))),t.appendChild(r),requestAnimationFrame(()=>{const e=t.firstElementChild.getBBox();t.setAttribute("width",`${Math.ceil(e.x+e.width)}`),t.setAttribute("height",`${Math.ceil(e.y+e.height)}`)}),t}renderVmlChildElement(e){const t=this.createSvgElement(e.tagName);Object.entries(e.attrs).forEach(([e,r])=>t.setAttribute(e,r));for(let r of e.children)r.type==T.VmlElement?t.appendChild(this.renderVmlChildElement(r)):t.appendChild(...i(this.renderElement(r)));return t}renderMmlRadical(e){const t=e.children.find(e=>e.type==T.MmlBase);if(e.props?.hideDegree)return this.createElementNS(Xe,"msqrt",null,this.renderElements([t]));const r=e.children.find(e=>e.type==T.MmlDegree);return this.createElementNS(Xe,"mroot",null,this.renderElements([t,r]))}renderMmlDelimiter(e){const t=[];return t.push(this.createElementNS(Xe,"mo",null,[e.props.beginChar??"("])),t.push(...this.renderElements(e.children)),t.push(this.createElementNS(Xe,"mo",null,[e.props.endChar??")"])),this.createElementNS(Xe,"mrow",null,t)}renderMmlNary(e){const t=[],r=n(e.children,e=>e.type),a=r[T.MmlSuperArgument],s=r[T.MmlSubArgument],l=a?this.createElementNS(Xe,"mo",null,i(this.renderElement(a))):null,o=s?this.createElementNS(Xe,"mo",null,i(this.renderElement(s))):null,c=this.createElementNS(Xe,"mo",null,[e.props?.char??"∫"]);return l||o?t.push(this.createElementNS(Xe,"munderover",null,[c,o,l])):l?t.push(this.createElementNS(Xe,"mover",null,[c,l])):o?t.push(this.createElementNS(Xe,"munder",null,[c,o])):t.push(c),t.push(...this.renderElements(r[T.MmlBase].children)),this.createElementNS(Xe,"mrow",null,t)}renderMmlPreSubSuper(e){const t=[],r=n(e.children,e=>e.type),a=r[T.MmlSuperArgument],s=r[T.MmlSubArgument],l=a?this.createElementNS(Xe,"mo",null,i(this.renderElement(a))):null,o=s?this.createElementNS(Xe,"mo",null,i(this.renderElement(s))):null,c=this.createElementNS(Xe,"mo",null);return t.push(this.createElementNS(Xe,"msubsup",null,[c,o,l])),t.push(...this.renderElements(r[T.MmlBase].children)),this.createElementNS(Xe,"mrow",null,t)}renderMmlGroupChar(e){const t="bot"===e.props.verticalJustification?"mover":"munder",r=this.renderContainerNS(e,Xe,t);return e.props.char&&r.appendChild(this.createElementNS(Xe,"mo",null,[e.props.char])),r}renderMmlBar(e){const t=this.renderContainerNS(e,Xe,"mrow");switch(e.props.position){case"top":t.style.textDecoration="overline";break;case"bottom":t.style.textDecoration="underline"}return t}renderMmlRun(e){const t=this.createElementNS(Xe,"ms",null,this.renderElements(e.children));return this.renderClass(e,t),this.renderStyleValues(e.cssStyle,t),t}renderMllList(e){const t=this.createElementNS(Xe,"mtable");this.renderClass(e,t),this.renderStyleValues(e.cssStyle,t);for(let r of this.renderElements(e.children))t.appendChild(this.createElementNS(Xe,"mtr",null,[this.createElementNS(Xe,"mtd",null,[r])]));return t}renderStyleValues(e,t){for(let r in e)r.startsWith("$")?t.setAttribute(r.slice(1),e[r]):t.style[r]=e[r]}renderClass(e,t){e.className&&(t.className=e.className),e.styleName&&t.classList.add(this.processStyleName(e.styleName))}findStyle(e){return e&&this.styleMap?.[e]}numberingClass(e,t){return`${this.className}-num-${e}-${t}`}tabStopClass(){return`${this.className}-tab-stop`}styleToString(e,t,r=null){let a=`${e} {\r\n`;for(const e in t)e.startsWith("$")||(a+=` ${e}: ${t[e]};\r\n`);return r&&(a+=r),a+"}\r\n"}numberingCounter(e,t){return`${this.className}-num-${e}-${t}`}levelTextToContent(e,t,r,a){return`"${e.replace(/%\d*/g,e=>{let t=parseInt(e.substring(1),10)-1;return`"counter(${this.numberingCounter(r,t)}, ${a})"`})}${{tab:"\\9",space:"\\a0"}[t]??""}"`}numFormatToCssValue(e){return{none:"none",bullet:"disc",decimal:"decimal",lowerLetter:"lower-alpha",upperLetter:"upper-alpha",lowerRoman:"lower-roman",upperRoman:"upper-roman",decimalZero:"decimal-leading-zero",aiueo:"katakana",aiueoFullWidth:"katakana",chineseCounting:"simp-chinese-informal",chineseCountingThousand:"simp-chinese-informal",chineseLegalSimplified:"simp-chinese-formal",chosung:"hangul-consonant",ideographDigital:"cjk-ideographic",ideographTraditional:"cjk-heavenly-stem",ideographLegalTraditional:"trad-chinese-formal",ideographZodiac:"cjk-earthly-branch",iroha:"katakana-iroha",irohaFullWidth:"katakana-iroha",japaneseCounting:"japanese-informal",japaneseDigitalTenThousand:"cjk-decimal",japaneseLegal:"japanese-formal",thaiNumbers:"thai",koreanCounting:"korean-hangul-formal",koreanDigital:"korean-hangul-formal",koreanDigital2:"korean-hanja-informal",hebrew1:"hebrew",hebrew2:"hebrew",hindiNumbers:"devanagari",ganada:"hangul",taiwaneseCounting:"cjk-ideographic",taiwaneseCountingThousand:"cjk-ideographic",taiwaneseDigital:"cjk-decimal"}[e]??e}refreshTabStops(){this.options.experimental&&setTimeout(()=>{const e=function(e=document.body){const t=document.createElement("div");t.style.width="100pt",e.appendChild(t);const r=100/t.offsetWidth;return e.removeChild(t),r}();for(let t of this.currentTabs)Ve(t.span,t.stops,this.defaultTabSize,e)},500)}createElementNS(e,t,r,a){var s=e?this.htmlDocument.createElementNS(e,t):this.htmlDocument.createElement(t);return Object.assign(s,r),a&&qe(s,a),s}createElement(e,t,r){return this.createElementNS(void 0,e,t,r)}createSvgElement(e,t,r){return this.createElementNS(We,e,t,r)}createStyleElement(e){return this.createElement("style",{innerHTML:e})}createComment(e){return this.htmlDocument.createComment(e)}later(e){this.postRenderTasks.push(e)}}function Ue(e){e.innerHTML=""}function qe(e,t){t.forEach(t=>{return e.appendChild("string"==typeof(r=t)||r instanceof String?document.createTextNode(t):t);var r})}const Je={ignoreHeight:!1,ignoreWidth:!1,ignoreFonts:!1,breakPages:!0,debug:!1,experimental:!1,className:"docx",inWrapper:!0,hideWrapperOnPrint:!1,trimXmlDeclaration:!0,ignoreLastRenderedPageBreak:!0,renderHeaders:!0,renderFooters:!0,renderFootnotes:!0,renderEndnotes:!0,useBase64URL:!1,renderChanges:!1,renderComments:!1,renderAltChunks:!0};function Ze(e,t){const r={...Je,...t};return ye.load(e,new Ie(r),r)}async function Ke(e,t,r,a){const s={...Je,...a},n=new Ge(window.document);return await n.render(e,t,r,s)}async function Ye(e,t,r,a){const s=await Ze(e,a);return await Ke(s,t,r,a),s}export{Je as defaultOptions,Ze as parseAsync,Ye as renderAsync,Ke as renderDocument}; -//# sourceMappingURL=docx-preview.min.mjs.map diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.min.mjs.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.min.mjs.map deleted file mode 100644 index d7f9490f7..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.min.mjs.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"docx-preview.min.mjs","sources":["../src/common/relationship.ts","../src/utils.ts","../src/document/common.ts","../src/parser/xml-parser.ts","../src/common/part.ts","../src/font-table/fonts.ts","../src/font-table/font-table.ts","../src/common/open-xml-package.ts","../src/document/document-part.ts","../src/document/border.ts","../src/document/section.ts","../src/document/dom.ts","../src/document/run.ts","../src/document/paragraph.ts","../src/document/line-spacing.ts","../src/numbering/numbering.ts","../src/numbering/numbering-part.ts","../src/styles/styles-part.ts","../src/header-footer/elements.ts","../src/header-footer/parts.ts","../src/document-props/extended-props.ts","../src/document-props/extended-props-part.ts","../src/document-props/core-props-part.ts","../src/document-props/core-props.ts","../src/theme/theme.ts","../src/theme/theme-part.ts","../src/notes/elements.ts","../src/notes/parts.ts","../src/settings/settings.ts","../src/settings/settings-part.ts","../src/document-props/custom-props-part.ts","../src/document-props/custom-props.ts","../src/comments/comments-part.ts","../src/comments/comments-extended-part.ts","../src/word-document.ts","../src/document/bookmarks.ts","../src/vml/vml.ts","../src/comments/elements.ts","../src/document-parser.ts","../src/javascript.ts","../src/html-renderer.ts","../src/docx-preview.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["RelationshipTypes","encloseFontFamily","fontFamily","test","splitPath","path","si","lastIndexOf","substring","resolvePath","base","prefix","URL","toString","length","keyBy","array","by","reduce","a","x","isObject","item","Array","isArray","mergeDeep","target","sources","source","shift","key","asArray","val","ns","LengthUsage","mul","unit","min","max","convertLength","usage","num","parseInt","clamp","toFixed","parseCommonProperty","elem","props","xml","namespaceURI","localName","color","attr","fontSize","lengthAttr","XmlParser","elements","result","i","l","childNodes","c","nodeType","Node","ELEMENT_NODE","push","element","elementAttr","attrLocalName","el","this","undefined","attrs","from","attributes","value","intAttr","node","attrName","defaultValue","hexAttr","floatAttr","parseFloat","boolAttr","v","convertBoolean","globalXmlParser","Part","constructor","_package","load","rels","loadRelationships","xmlText","xmlDoc","parseXmlDocument","options","keepOrigin","_xmlDocument","parseXml","firstElementChild","save","update","XMLSerializer","serializeToString","root","embedFontTypeMap","embedRegular","embedBold","embedItalic","embedBoldItalic","parseFonts","map","name","embedFontRefs","family","altName","parseEmbedFontRef","parseFont","id","type","FontTablePart","fonts","xmlParser","OpenXmlPackage","_zip","get","p","startsWith","substr","normalizePath","files","replace","content","file","input","zip","JSZip","loadAsync","generateAsync","async","Promise","resolve","relsPath","f","fn","txt","e","targetMode","xmlString","trimXmlDeclaration","data","charCodeAt","DOMParser","parseFromString","errorText","doc","getElementsByTagName","textContent","Error","parseXmlString","DocumentPart","pkg","parser","super","_documentParser","body","parseDocumentFile","parseBorder","size","offset","frame","shadow","parseBorders","left","top","right","bottom","SectionType","DomType","parseSectionProperties","section","pageSize","width","height","orientation","pageMargins","header","footer","gutter","columns","parseColumns","headerRefs","parseFooterHeaderReference","footerRefs","titlePage","pageBorders","pageNumber","parsePageNumber","numberOfColumns","space","separator","equalWidth","chapSep","chapStyle","format","start","parseRunProperties","parseRunProperty","parseParagraphProperties","parseParagraphProperty","tabs","position","leader","style","parseTabs","sectionProps","numbering","level","parseNumbering","lineSpacing","before","after","line","lineRule","parseLineSpacing","textAlignment","keepLines","keepNext","pageBreakBefore","outlineLevel","styleName","runProps","overrides","abstractId","parseNumberingLevelOverrride","parseAbstractNumbering","levels","multiLevelType","numberingStyleLink","styleLink","parseNumberingLevel","restart","text","justification","bulletPictureId","paragraphStyle","paragraphProps","numberingLevel","parseNumberingBulletPicture","pict","shape","imagedata","referenceId","NumberingPart","Object","assign","numberings","abstractNumberings","bulletPictures","parseNumberingPart","domNumberings","parseNumberingFile","StylesPart","styles","parseStylesFile","OpenXmlElementBase","children","cssStyle","WmlHeader","Header","WmlFooter","Footer","BaseHeaderFooterPart","rootElement","createRootElement","parseBodyElements","HeaderPart","FooterPart","safeParseToInt","ExtendedPropsPart","template","pages","words","characters","application","lines","paragraphs","company","appVersion","parseExtendedProps","CorePropsPart","title","description","subject","creator","keywords","language","lastModifiedBy","revision","parseCoreProps","DmlTheme","parseColorScheme","colors","srgbClr","sysClr","parseFontScheme","majorFont","parseFontInfo","minorFont","latinTypeface","eaTypeface","csTypeface","ThemePart","theme","themeElements","colorScheme","fontScheme","parseTheme","WmlBaseNote","WmlFootnote","Footnote","WmlEndnote","Endnote","BaseNotePart","FootnotesPart","notes","parseNotes","EndnotesPart","parseNoteProperties","defaultNoteIds","nummeringFormat","SettingsPart","settings","defaultTabStop","footnoteProps","endnoteProps","autoHyphenation","parseSettings","CustomPropsPart","firstChild","formatId","nodeName","parseCustomProps","CommentsPart","comments","parseComments","commentMap","CommentsExtendedPart","paraId","paraIdParent","done","topLevelRels","OfficeDocument","ExtendedProperties","CoreProperties","CustomProperties","WordDocument","parts","partsMap","blob","d","_options","_parser","all","rel","r","find","loadRelationshipPart","part","documentPart","FontTable","fontTablePart","Numbering","numberingPart","Styles","stylesPart","Theme","themePart","Footnotes","footnotesPart","Endnotes","endnotesPart","corePropsPart","extendedPropsPart","Settings","settingsPart","Comments","commentsPart","CommentsExtended","commentsExtendedPart","folder","loadDocumentImage","loadResource","blobToURL","loadNumberingImage","loadFont","Blob","deobfuscate","loadAltChunk","useBase64URL","reject","reader","FileReader","onloadend","onerror","readAsDataURL","blobToBase64","createObjectURL","findPartByRelId","basePart","getPathById","outputType","guidKey","trimmed","numbers","parseBookmarkStart","BookmarkStart","colFirst","colLast","parseBookmarkEnd","BookmarkEnd","VmlElement","parseVmlElement","tagName","cx","cy","rx","ry","at","cssStyleText","fill","x1","y1","parsePoint","x2","y2","parseStroke","parseFill","imageHref","child","stroke","split","WmlComment","Comment","WmlCommentReference","CommentReference","WmlCommentRangeStart","CommentRangeStart","WmlCommentRangeEnd","CommentRangeEnd","autos","supportedNamespaceURIs","mmlTagMap","oMath","MmlMath","oMathPara","MmlMathParagraph","MmlFraction","func","MmlFunction","fName","MmlFunctionName","MmlNumerator","den","MmlDenominator","rad","MmlRadical","deg","MmlDegree","MmlBase","sSup","MmlSuperscript","sSub","MmlSubscript","sPre","MmlPreSubSuper","sup","MmlSuperArgument","sub","MmlSubArgument","MmlDelimiter","nary","MmlNary","eqArr","MmlEquationArray","lim","MmlLimit","limLow","MmlLimitLower","m","MmlMatrix","mr","MmlMatrixRow","box","MmlBox","bar","MmlBar","groupChr","MmlGroupChar","DocumentParser","ignoreWidth","debug","elemName","elemClass","noteType","author","initials","date","xbody","background","sectPr","Document","parseBackground","xmlUtil","colorAttr","parseParagraph","parseAltChunk","parseTable","parseSdt","xstyles","n","parseStyle","parseDefaultStyles","basedOn","rPr","values","parseDefaultProperties","pPr","isDefault","linked","next","aliases","s","parseTableStyle","console","warn","selector","modificator","mod","mapping","bullets","forEach","parseNumberingPicBullet","numId","abstractNumId","src","pStyleName","pStyle","rStyle","suff","bulletId","bullet","levelText","sdtContent","parseInserted","parentParser","Inserted","parseDeleted","Deleted","AltChunk","Paragraph","parseRun","parseHyperlink","parseSmartTag","parseMathElement","paragraph","className","classNameOfCnfStyle","parseFrame","parent","Hyperlink","anchor","SmartTag","uri","Run","checkAlternateContent","Text","DeletedText","SimpleField","instruction","lock","dirty","fieldRun","Instruction","ComplexField","charType","NoBreakHyphen","Break","break","Symbol","font","char","Tab","FootnoteReference","EndnoteReference","parseDrawing","parseVmlPicture","propsTag","run","MmlRun","parseMathProperies","verticalJustification","hideDegree","beginChar","endChar","verticalAlign","valueOfVertAlign","VmlPicture","choice","requires","lookupNamespaceURI","includes","parseDrawingWrapper","Drawing","isAnchor","wrapType","simplePos","posX","relative","align","posY","pos","alignNode","offsetNode","g","parseGraphic","graphicData","parsePicture","Image","blipFill","blip","srcRect","spPr","xfrm","rotation","Table","parseTableRow","parseTableColumns","parseTableProperties","table","cellStyle","classNameOftblLook","parseTablePosition","colBandSize","rowBandSize","topFromText","bottomFromText","rightFromText","leftFromText","addSize","Row","parseTableCell","parseTableRowProperties","row","isHeader","gridBefore","gridAfter","Cell","parseTableCellProperties","cell","span","verticalMerge","parseTableCellVerticalText","directionMap","btLr","writingMode","transform","lrTb","tbRl","childStyle","handler","valueOfJc","valueOfTextAlignment","valueOfSize","parseTrHeight","parseUnderline","parseIndentation","parseBorderProperties","valueOfMargin","valueOfBorder","parseMarginProperties","valueOfTblLayout","parseSpacing","col","themeValue","filter","Set","join","firstLine","hanging","end","output","knownColors","defValue","autoColor","themeColor","parseBorderType","_","asTagName","b","trim","defaultTab","updateTabStop","defaultTabSize","pixelToPoint","closest","ebb","getBoundingClientRect","pbb","pcs","getComputedStyle","tabStops","t","lengthToPoint","sort","lastTab","pWidthPt","marginLeft","pOffset","tab","querySelectorAll","nextIdx","indexOf","range","document","createRange","setStart","setEndBefore","setEndAfter","nextBB","innerHTML","textDecoration","wordSpacing","textDecorationStyle","HtmlRenderer","htmlDocument","styleMap","currentPart","tableVerticalMerges","currentVerticalMerge","tableCellPositions","currentCellPosition","footnoteMap","endnoteMap","currentEndnoteIds","usedHederFooterParts","currentTabs","tasks","postRenderTasks","render","bodyContainer","styleContainer","rootSelector","inWrapper","renderComments","globalThis","Highlight","commentHighlight","removeAllElements","appendChild","createComment","renderDefaultStyle","renderTheme","processStyles","renderStyles","prodessNumberings","renderNumbering","ignoreFonts","renderFontTable","sectionElements","renderSections","renderWrapper","appendChildren","CSS","highlights","set","allSettled","refreshTabStops","variables","k","entries","cssText","styleToString","createStyleElement","fontsPart","ref","then","fontData","cssValues","processStyleName","toLowerCase","escapeClassName","stylesMap","baseStyle","baseValues","styleValues","copyStyleProperties","cssName","findStyle","processElement","processTable","getOwnPropertyNames","hasOwnProperty","createPageElement","createElement","paddingLeft","paddingRight","paddingTop","paddingBottom","ignoreHeight","minHeight","createSectionContent","columnCount","columnGap","columnRule","sections","splitBySection","groupByPageBreaks","prevProps","currentFootnoteIds","sectProps","pageElement","renderStyleValues","renderHeaders","renderHeaderFooter","sect","contentElement","renderElements","renderFootnotes","renderNotes","renderEndnotes","renderFooters","refs","page","firstOfSection","into","marginTop","marginBottom","isPageBreakElement","ignoreLastRenderedPageBreak","isPageBreakSection","prev","defaultProps","current","pageBreak","pBreakIndex","rBreakIndex","breakPages","findIndex","bind","breakRun","splitRun","newParagraph","slice","runChildren","newRun","currentSectProps","wrapperStyle","hideWrapperOnPrint","styleText","resetCounters","numberingClass","listStyleType","valiable","display","counter","numberingCounter","counterReset","levelTextToContent","numFormatToCssValue","defautStyles","subStyles","linkedStyle","concat","subStyle","noteIds","notesMap","renderElement","renderParagraph","renderBookmarkStart","renderRun","renderTable","renderTableRow","renderTableCell","renderHyperlink","renderSmartTag","renderDrawing","renderImage","renderText","renderDeletedText","renderTab","renderSymbol","renderBreak","renderContainer","renderFootnoteReference","renderEndnoteReference","renderVmlPicture","renderVmlElement","renderContainerNS","xmlns","renderMmlGroupChar","renderMmlRadical","renderMmlDelimiter","renderMmlRun","renderMmlNary","renderMmlPreSubSuper","renderMmlBar","renderMllList","renderInserted","renderDeleted","renderCommentRangeStart","renderCommentRangeEnd","renderCommentReference","renderAltChunk","elems","flatMap","createElementNS","renderClass","renderCommonProperties","classList","add","renderRunProperties","href","it","commentStart","rng","Range","later","commentEnd","setEnd","commentRef","comment","frg","DocumentFragment","commentRefEl","commentsContainerEl","renderCommentContent","renderAltChunks","srcdoc","container","Date","toLocaleString","textIndent","some","createTextNode","renderChanges","tabSpan","experimental","tabStopClass","stops","findParent","wrapper","renderTableColumns","pop","colElem","renderTableCellPlaceholder","colSpan","rowSpan","createSvgElement","setAttribute","renderVmlChildElement","requestAnimationFrame","bb","getBBox","Math","ceil","y","degree","grouped","supElem","subElem","charElem","stubElem","ouput","lvl","selectors","numformat","none","decimal","lowerLetter","upperLetter","lowerRoman","upperRoman","decimalZero","aiueo","aiueoFullWidth","chineseCounting","chineseCountingThousand","chineseLegalSimplified","chosung","ideographDigital","ideographTraditional","ideographLegalTraditional","ideographZodiac","iroha","irohaFullWidth","japaneseCounting","japaneseDigitalTenThousand","japaneseLegal","thaiNumbers","koreanCounting","koreanDigital","koreanDigital2","hebrew1","hebrew2","hindiNumbers","ganada","taiwaneseCounting","taiwaneseCountingThousand","taiwaneseDigital","setTimeout","temp","offsetWidth","removeChild","computePixelToPoint","String","defaultOptions","parseAsync","userOptions","ops","renderDocument","renderer","window","renderAsync"],"mappings":";;;;;;qBASA,IAAYA,ECLN,SAAUC,EAAkBC,GAC9B,MAAO,qBAAqBC,KAAKD,GAAc,IAAIA,KAAgBA,CACvE,CAEM,SAAUE,EAAUC,GACtB,IAAIC,EAAKD,EAAKE,YAAY,KAAO,EAIjC,MAAO,CAHY,GAAND,EAAU,GAAKD,EAAKG,UAAU,EAAGF,GACzB,GAANA,EAAUD,EAAOA,EAAKG,UAAUF,GAGnD,CAEM,SAAUG,EAAYJ,EAAcK,GACtC,IACI,MAAMC,EAAS,eAEf,OADY,IAAIC,IAAIP,EAAMM,EAASD,GAAMG,WAC9BL,UAAUG,EAAOG,OAChC,CAAE,MACE,MAAO,GAAGJ,IAAOL,GACrB,CACJ,CAEM,SAAUU,EAAeC,EAAYC,GACvC,OAAOD,EAAME,OAAO,CAACC,EAAGC,KACpBD,EAAEF,EAAGG,IAAMA,EACJD,GACR,CAAA,EACP,CAWM,SAAUE,EAASC,GACrB,OAAOA,GAAwB,iBAATA,IAAsBC,MAAMC,QAAQF,EAC9D,UAMgBG,EAAUC,KAAWC,GACjC,IAAKA,EAAQb,OACT,OAAOY,EAEX,MAAME,EAASD,EAAQE,QAEvB,GAAIR,EAASK,IAAWL,EAASO,GAC7B,IAAK,MAAME,KAAOF,EACd,GAAIP,EAASO,EAAOE,IAAO,CAEvB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,cAAc,EACd7X,UAAW,OACX2L,WAAW,EACXyG,oBAAoB,EACpBrsB,oBAAoB,EACpBkrB,6BAA6B,EAC7BhB,eAAe,EACfQ,eAAe,EACfH,iBAAiB,EACpBE,gBAAgB,EAChB/a,cAAc,EACdkiB,eAAe,EACZ/L,gBAAgB,EAChBuL,iBAAiB,GAGf,SAAUgF,GAAWn2B,EAAkBo2B,GACzC,MAAMC,EAAM,IAAKH,MAAmBE,GACpC,OAAOtpB,GAAa3Q,KAAK6D,EAAM,IAAI6V,GAAewgB,GAAMA,EAC5D,CAEOh3B,eAAei3B,GAAexS,EAAe0B,EAA4BC,EAA8B2Q,GAC1G,MAAMC,EAAM,IAAKH,MAAmBE,GAC9BG,EAAW,IAAI/R,GAAagS,OAAO1S,UAC5C,aAAayS,EAAShR,OAAOzB,EAAU0B,EAAeC,EAAgB4Q,EACvE,CAEOh3B,eAAeo3B,GAAYz2B,EAAkBwlB,EAA4BC,EAA8B2Q,GAC7G,MAAM/1B,QAAY81B,GAAWn2B,EAAMo2B,GAEhC,aADGE,GAAej2B,EAAKmlB,EAAeC,EAAgB2Q,GAC/C/1B,CACX"} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.mjs b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.mjs deleted file mode 100644 index 0ab9123ae..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.mjs +++ /dev/null @@ -1,3991 +0,0 @@ -/* - * @license - * docx-preview - * Released under Apache License 2.0 - * Copyright Volodymyr Baydalka - */ -import JSZip from 'jszip'; - -var RelationshipTypes; -(function (RelationshipTypes) { - RelationshipTypes["OfficeDocument"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"; - RelationshipTypes["FontTable"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable"; - RelationshipTypes["Image"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"; - RelationshipTypes["Numbering"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering"; - RelationshipTypes["Styles"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"; - RelationshipTypes["StylesWithEffects"] = "http://schemas.microsoft.com/office/2007/relationships/stylesWithEffects"; - RelationshipTypes["Theme"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme"; - RelationshipTypes["Settings"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings"; - RelationshipTypes["WebSettings"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings"; - RelationshipTypes["Hyperlink"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"; - RelationshipTypes["Footnotes"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes"; - RelationshipTypes["Endnotes"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes"; - RelationshipTypes["Footer"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer"; - RelationshipTypes["Header"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header"; - RelationshipTypes["ExtendedProperties"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"; - RelationshipTypes["CoreProperties"] = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"; - RelationshipTypes["CustomProperties"] = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/custom-properties"; - RelationshipTypes["Comments"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"; - RelationshipTypes["CommentsExtended"] = "http://schemas.microsoft.com/office/2011/relationships/commentsExtended"; - RelationshipTypes["AltChunk"] = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk"; -})(RelationshipTypes || (RelationshipTypes = {})); -function parseRelationships(root, xml) { - return xml.elements(root).map(e => ({ - id: xml.attr(e, "Id"), - type: xml.attr(e, "Type"), - target: xml.attr(e, "Target"), - targetMode: xml.attr(e, "TargetMode") - })); -} - -function escapeClassName(className) { - return className?.replace(/[ .]+/g, '-').replace(/[&]+/g, 'and').toLowerCase(); -} -function encloseFontFamily(fontFamily) { - return /^[^"'].*\s.*[^"']$/.test(fontFamily) ? `'${fontFamily}'` : fontFamily; -} -function splitPath(path) { - let si = path.lastIndexOf('/') + 1; - let folder = si == 0 ? "" : path.substring(0, si); - let fileName = si == 0 ? path : path.substring(si); - return [folder, fileName]; -} -function resolvePath(path, base) { - try { - const prefix = "http://docx/"; - const url = new URL(path, prefix + base).toString(); - return url.substring(prefix.length); - } - catch { - return `${base}${path}`; - } -} -function keyBy(array, by) { - return array.reduce((a, x) => { - a[by(x)] = x; - return a; - }, {}); -} -function blobToBase64(blob) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onloadend = () => resolve(reader.result); - reader.onerror = () => reject(); - reader.readAsDataURL(blob); - }); -} -function isObject(item) { - return item && typeof item === 'object' && !Array.isArray(item); -} -function isString(item) { - return typeof item === 'string' || item instanceof String; -} -function mergeDeep(target, ...sources) { - if (!sources.length) - return target; - const source = sources.shift(); - if (isObject(target) && isObject(source)) { - for (const key in source) { - if (isObject(source[key])) { - const val = target[key] ?? (target[key] = {}); - mergeDeep(val, source[key]); - } - else { - target[key] = source[key]; - } - } - } - return mergeDeep(target, ...sources); -} -function asArray(val) { - return Array.isArray(val) ? val : [val]; -} -function clamp(val, min, max) { - return min > val ? min : (max < val ? max : val); -} - -const ns$1 = { - wordml: "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}; -const LengthUsage = { - Dxa: { mul: 0.05, unit: "pt" }, - Emu: { mul: 1 / 12700, unit: "pt" }, - FontSize: { mul: 0.5, unit: "pt" }, - Border: { mul: 0.125, unit: "pt", min: 0.25, max: 12 }, - Point: { mul: 1, unit: "pt" }, - Percent: { mul: 0.02, unit: "%" }}; -function convertLength(val, usage = LengthUsage.Dxa) { - if (val == null || /.+(p[xt]|[%])$/.test(val)) { - return val; - } - var num = parseInt(val) * usage.mul; - if (usage.min && usage.max) - num = clamp(num, usage.min, usage.max); - return `${num.toFixed(2)}${usage.unit}`; -} -function convertBoolean(v, defaultValue = false) { - switch (v) { - case "1": return true; - case "0": return false; - case "on": return true; - case "off": return false; - case "true": return true; - case "false": return false; - default: return defaultValue; - } -} -function parseCommonProperty(elem, props, xml) { - if (elem.namespaceURI != ns$1.wordml) - return false; - switch (elem.localName) { - case "color": - props.color = xml.attr(elem, "val"); - break; - case "sz": - props.fontSize = xml.lengthAttr(elem, "val", LengthUsage.FontSize); - break; - default: - return false; - } - return true; -} - -function parseXmlString(xmlString, trimXmlDeclaration = false) { - if (trimXmlDeclaration) - xmlString = xmlString.replace(/<[?].*[?]>/, ""); - xmlString = removeUTF8BOM(xmlString); - const result = new DOMParser().parseFromString(xmlString, "application/xml"); - const errorText = hasXmlParserError(result); - if (errorText) - throw new Error(errorText); - return result; -} -function hasXmlParserError(doc) { - return doc.getElementsByTagName("parsererror")[0]?.textContent; -} -function removeUTF8BOM(data) { - return data.charCodeAt(0) === 0xFEFF ? data.substring(1) : data; -} -function serializeXmlString(elem) { - return new XMLSerializer().serializeToString(elem); -} -class XmlParser { - elements(elem, localName = null) { - const result = []; - for (let i = 0, l = elem.childNodes.length; i < l; i++) { - let c = elem.childNodes.item(i); - if (c.nodeType == Node.ELEMENT_NODE && (localName == null || c.localName == localName)) - result.push(c); - } - return result; - } - element(elem, localName) { - for (let i = 0, l = elem.childNodes.length; i < l; i++) { - let c = elem.childNodes.item(i); - if (c.nodeType == 1 && c.localName == localName) - return c; - } - return null; - } - elementAttr(elem, localName, attrLocalName) { - var el = this.element(elem, localName); - return el ? this.attr(el, attrLocalName) : undefined; - } - attrs(elem) { - return Array.from(elem.attributes); - } - attr(elem, localName) { - for (let i = 0, l = elem.attributes.length; i < l; i++) { - let a = elem.attributes.item(i); - if (a.localName == localName) - return a.value; - } - return null; - } - intAttr(node, attrName, defaultValue = null) { - var val = this.attr(node, attrName); - return val ? parseInt(val) : defaultValue; - } - hexAttr(node, attrName, defaultValue = null) { - var val = this.attr(node, attrName); - return val ? parseInt(val, 16) : defaultValue; - } - floatAttr(node, attrName, defaultValue = null) { - var val = this.attr(node, attrName); - return val ? parseFloat(val) : defaultValue; - } - boolAttr(node, attrName, defaultValue = null) { - return convertBoolean(this.attr(node, attrName), defaultValue); - } - lengthAttr(node, attrName, usage = LengthUsage.Dxa) { - return convertLength(this.attr(node, attrName), usage); - } -} -const globalXmlParser = new XmlParser(); - -class Part { - constructor(_package, path) { - this._package = _package; - this.path = path; - } - async load() { - this.rels = await this._package.loadRelationships(this.path); - const xmlText = await this._package.load(this.path); - const xmlDoc = this._package.parseXmlDocument(xmlText); - if (this._package.options.keepOrigin) { - this._xmlDocument = xmlDoc; - } - this.parseXml(xmlDoc.firstElementChild); - } - save() { - this._package.update(this.path, serializeXmlString(this._xmlDocument)); - } - parseXml(root) { - } -} - -const embedFontTypeMap = { - embedRegular: 'regular', - embedBold: 'bold', - embedItalic: 'italic', - embedBoldItalic: 'boldItalic', -}; -function parseFonts(root, xml) { - return xml.elements(root).map(el => parseFont(el, xml)); -} -function parseFont(elem, xml) { - let result = { - name: xml.attr(elem, "name"), - embedFontRefs: [] - }; - for (let el of xml.elements(elem)) { - switch (el.localName) { - case "family": - result.family = xml.attr(el, "val"); - break; - case "altName": - result.altName = xml.attr(el, "val"); - break; - case "embedRegular": - case "embedBold": - case "embedItalic": - case "embedBoldItalic": - result.embedFontRefs.push(parseEmbedFontRef(el, xml)); - break; - } - } - return result; -} -function parseEmbedFontRef(elem, xml) { - return { - id: xml.attr(elem, "id"), - key: xml.attr(elem, "fontKey"), - type: embedFontTypeMap[elem.localName] - }; -} - -class FontTablePart extends Part { - parseXml(root) { - this.fonts = parseFonts(root, this._package.xmlParser); - } -} - -class OpenXmlPackage { - constructor(_zip, options) { - this._zip = _zip; - this.options = options; - this.xmlParser = new XmlParser(); - } - get(path) { - const p = normalizePath(path); - return this._zip.files[p] ?? this._zip.files[p.replace(/\//g, '\\')]; - } - update(path, content) { - this._zip.file(path, content); - } - static async load(input, options) { - const zip = await JSZip.loadAsync(input); - return new OpenXmlPackage(zip, options); - } - save(type = "blob") { - return this._zip.generateAsync({ type }); - } - load(path, type = "string") { - return this.get(path)?.async(type) ?? Promise.resolve(null); - } - async loadRelationships(path = null) { - let relsPath = `_rels/.rels`; - if (path != null) { - const [f, fn] = splitPath(path); - relsPath = `${f}_rels/${fn}.rels`; - } - const txt = await this.load(relsPath); - return txt ? parseRelationships(this.parseXmlDocument(txt).firstElementChild, this.xmlParser) : null; - } - parseXmlDocument(txt) { - return parseXmlString(txt, this.options.trimXmlDeclaration); - } -} -function normalizePath(path) { - return path.startsWith('/') ? path.substr(1) : path; -} - -class DocumentPart extends Part { - constructor(pkg, path, parser) { - super(pkg, path); - this._documentParser = parser; - } - parseXml(root) { - this.body = this._documentParser.parseDocumentFile(root); - } -} - -function parseBorder(elem, xml) { - return { - type: xml.attr(elem, "val"), - color: xml.attr(elem, "color"), - size: xml.lengthAttr(elem, "sz", LengthUsage.Border), - offset: xml.lengthAttr(elem, "space", LengthUsage.Point), - frame: xml.boolAttr(elem, 'frame'), - shadow: xml.boolAttr(elem, 'shadow') - }; -} -function parseBorders(elem, xml) { - var result = {}; - for (let e of xml.elements(elem)) { - switch (e.localName) { - case "left": - result.left = parseBorder(e, xml); - break; - case "top": - result.top = parseBorder(e, xml); - break; - case "right": - result.right = parseBorder(e, xml); - break; - case "bottom": - result.bottom = parseBorder(e, xml); - break; - } - } - return result; -} - -var SectionType; -(function (SectionType) { - SectionType["Continuous"] = "continuous"; - SectionType["NextPage"] = "nextPage"; - SectionType["NextColumn"] = "nextColumn"; - SectionType["EvenPage"] = "evenPage"; - SectionType["OddPage"] = "oddPage"; -})(SectionType || (SectionType = {})); -function parseSectionProperties(elem, xml = globalXmlParser) { - var section = {}; - for (let e of xml.elements(elem)) { - switch (e.localName) { - case "pgSz": - section.pageSize = { - width: xml.lengthAttr(e, "w"), - height: xml.lengthAttr(e, "h"), - orientation: xml.attr(e, "orient") - }; - break; - case "type": - section.type = xml.attr(e, "val"); - break; - case "pgMar": - section.pageMargins = { - left: xml.lengthAttr(e, "left"), - right: xml.lengthAttr(e, "right"), - top: xml.lengthAttr(e, "top"), - bottom: xml.lengthAttr(e, "bottom"), - header: xml.lengthAttr(e, "header"), - footer: xml.lengthAttr(e, "footer"), - gutter: xml.lengthAttr(e, "gutter"), - }; - break; - case "cols": - section.columns = parseColumns(e, xml); - break; - case "headerReference": - (section.headerRefs ?? (section.headerRefs = [])).push(parseFooterHeaderReference(e, xml)); - break; - case "footerReference": - (section.footerRefs ?? (section.footerRefs = [])).push(parseFooterHeaderReference(e, xml)); - break; - case "titlePg": - section.titlePage = xml.boolAttr(e, "val", true); - break; - case "pgBorders": - section.pageBorders = parseBorders(e, xml); - break; - case "pgNumType": - section.pageNumber = parsePageNumber(e, xml); - break; - } - } - return section; -} -function parseColumns(elem, xml) { - return { - numberOfColumns: xml.intAttr(elem, "num"), - space: xml.lengthAttr(elem, "space"), - separator: xml.boolAttr(elem, "sep"), - equalWidth: xml.boolAttr(elem, "equalWidth", true), - columns: xml.elements(elem, "col") - .map(e => ({ - width: xml.lengthAttr(e, "w"), - space: xml.lengthAttr(e, "space") - })) - }; -} -function parsePageNumber(elem, xml) { - return { - chapSep: xml.attr(elem, "chapSep"), - chapStyle: xml.attr(elem, "chapStyle"), - format: xml.attr(elem, "fmt"), - start: xml.intAttr(elem, "start") - }; -} -function parseFooterHeaderReference(elem, xml) { - return { - id: xml.attr(elem, "id"), - type: xml.attr(elem, "type"), - }; -} - -function parseLineSpacing(elem, xml) { - return { - before: xml.lengthAttr(elem, "before"), - after: xml.lengthAttr(elem, "after"), - line: xml.intAttr(elem, "line"), - lineRule: xml.attr(elem, "lineRule") - }; -} - -function parseRunProperties(elem, xml) { - let result = {}; - for (let el of xml.elements(elem)) { - parseRunProperty(el, result, xml); - } - return result; -} -function parseRunProperty(elem, props, xml) { - if (parseCommonProperty(elem, props, xml)) - return true; - return false; -} - -function parseParagraphProperties(elem, xml) { - let result = {}; - for (let el of xml.elements(elem)) { - parseParagraphProperty(el, result, xml); - } - return result; -} -function parseParagraphProperty(elem, props, xml) { - if (elem.namespaceURI != ns$1.wordml) - return false; - if (parseCommonProperty(elem, props, xml)) - return true; - switch (elem.localName) { - case "tabs": - props.tabs = parseTabs(elem, xml); - break; - case "sectPr": - props.sectionProps = parseSectionProperties(elem, xml); - break; - case "numPr": - props.numbering = parseNumbering$1(elem, xml); - break; - case "spacing": - props.lineSpacing = parseLineSpacing(elem, xml); - return false; - case "textAlignment": - props.textAlignment = xml.attr(elem, "val"); - return false; - case "keepLines": - props.keepLines = xml.boolAttr(elem, "val", true); - break; - case "keepNext": - props.keepNext = xml.boolAttr(elem, "val", true); - break; - case "pageBreakBefore": - props.pageBreakBefore = xml.boolAttr(elem, "val", true); - break; - case "outlineLvl": - props.outlineLevel = xml.intAttr(elem, "val"); - break; - case "pStyle": - props.styleName = xml.attr(elem, "val"); - break; - case "rPr": - props.runProps = parseRunProperties(elem, xml); - break; - default: - return false; - } - return true; -} -function parseTabs(elem, xml) { - return xml.elements(elem, "tab") - .map(e => ({ - position: xml.lengthAttr(e, "pos"), - leader: xml.attr(e, "leader"), - style: xml.attr(e, "val") - })); -} -function parseNumbering$1(elem, xml) { - var result = {}; - for (let e of xml.elements(elem)) { - switch (e.localName) { - case "numId": - result.id = xml.attr(e, "val"); - break; - case "ilvl": - result.level = xml.intAttr(e, "val"); - break; - } - } - return result; -} - -function parseNumberingPart(elem, xml) { - let result = { - numberings: [], - abstractNumberings: [], - bulletPictures: [] - }; - for (let e of xml.elements(elem)) { - switch (e.localName) { - case "num": - result.numberings.push(parseNumbering(e, xml)); - break; - case "abstractNum": - result.abstractNumberings.push(parseAbstractNumbering(e, xml)); - break; - case "numPicBullet": - result.bulletPictures.push(parseNumberingBulletPicture(e, xml)); - break; - } - } - return result; -} -function parseNumbering(elem, xml) { - let result = { - id: xml.attr(elem, 'numId'), - overrides: [] - }; - for (let e of xml.elements(elem)) { - switch (e.localName) { - case "abstractNumId": - result.abstractId = xml.attr(e, "val"); - break; - case "lvlOverride": - result.overrides.push(parseNumberingLevelOverrride(e, xml)); - break; - } - } - return result; -} -function parseAbstractNumbering(elem, xml) { - let result = { - id: xml.attr(elem, 'abstractNumId'), - levels: [] - }; - for (let e of xml.elements(elem)) { - switch (e.localName) { - case "name": - result.name = xml.attr(e, "val"); - break; - case "multiLevelType": - result.multiLevelType = xml.attr(e, "val"); - break; - case "numStyleLink": - result.numberingStyleLink = xml.attr(e, "val"); - break; - case "styleLink": - result.styleLink = xml.attr(e, "val"); - break; - case "lvl": - result.levels.push(parseNumberingLevel(e, xml)); - break; - } - } - return result; -} -function parseNumberingLevel(elem, xml) { - let result = { - level: xml.intAttr(elem, 'ilvl') - }; - for (let e of xml.elements(elem)) { - switch (e.localName) { - case "start": - result.start = xml.attr(e, "val"); - break; - case "lvlRestart": - result.restart = xml.intAttr(e, "val"); - break; - case "numFmt": - result.format = xml.attr(e, "val"); - break; - case "lvlText": - result.text = xml.attr(e, "val"); - break; - case "lvlJc": - result.justification = xml.attr(e, "val"); - break; - case "lvlPicBulletId": - result.bulletPictureId = xml.attr(e, "val"); - break; - case "pStyle": - result.paragraphStyle = xml.attr(e, "val"); - break; - case "pPr": - result.paragraphProps = parseParagraphProperties(e, xml); - break; - case "rPr": - result.runProps = parseRunProperties(e, xml); - break; - } - } - return result; -} -function parseNumberingLevelOverrride(elem, xml) { - let result = { - level: xml.intAttr(elem, 'ilvl') - }; - for (let e of xml.elements(elem)) { - switch (e.localName) { - case "startOverride": - result.start = xml.intAttr(e, "val"); - break; - case "lvl": - result.numberingLevel = parseNumberingLevel(e, xml); - break; - } - } - return result; -} -function parseNumberingBulletPicture(elem, xml) { - var pict = xml.element(elem, "pict"); - var shape = pict && xml.element(pict, "shape"); - var imagedata = shape && xml.element(shape, "imagedata"); - return imagedata ? { - id: xml.attr(elem, "numPicBulletId"), - referenceId: xml.attr(imagedata, "id"), - style: xml.attr(shape, "style") - } : null; -} - -class NumberingPart extends Part { - constructor(pkg, path, parser) { - super(pkg, path); - this._documentParser = parser; - } - parseXml(root) { - Object.assign(this, parseNumberingPart(root, this._package.xmlParser)); - this.domNumberings = this._documentParser.parseNumberingFile(root); - } -} - -class StylesPart extends Part { - constructor(pkg, path, parser) { - super(pkg, path); - this._documentParser = parser; - } - parseXml(root) { - this.styles = this._documentParser.parseStylesFile(root); - } -} - -var DomType; -(function (DomType) { - DomType["Document"] = "document"; - DomType["Paragraph"] = "paragraph"; - DomType["Run"] = "run"; - DomType["Break"] = "break"; - DomType["NoBreakHyphen"] = "noBreakHyphen"; - DomType["Table"] = "table"; - DomType["Row"] = "row"; - DomType["Cell"] = "cell"; - DomType["Hyperlink"] = "hyperlink"; - DomType["SmartTag"] = "smartTag"; - DomType["Drawing"] = "drawing"; - DomType["Image"] = "image"; - DomType["Text"] = "text"; - DomType["Tab"] = "tab"; - DomType["Symbol"] = "symbol"; - DomType["BookmarkStart"] = "bookmarkStart"; - DomType["BookmarkEnd"] = "bookmarkEnd"; - DomType["Footer"] = "footer"; - DomType["Header"] = "header"; - DomType["FootnoteReference"] = "footnoteReference"; - DomType["EndnoteReference"] = "endnoteReference"; - DomType["Footnote"] = "footnote"; - DomType["Endnote"] = "endnote"; - DomType["SimpleField"] = "simpleField"; - DomType["ComplexField"] = "complexField"; - DomType["Instruction"] = "instruction"; - DomType["VmlPicture"] = "vmlPicture"; - DomType["MmlMath"] = "mmlMath"; - DomType["MmlMathParagraph"] = "mmlMathParagraph"; - DomType["MmlFraction"] = "mmlFraction"; - DomType["MmlFunction"] = "mmlFunction"; - DomType["MmlFunctionName"] = "mmlFunctionName"; - DomType["MmlNumerator"] = "mmlNumerator"; - DomType["MmlDenominator"] = "mmlDenominator"; - DomType["MmlRadical"] = "mmlRadical"; - DomType["MmlBase"] = "mmlBase"; - DomType["MmlDegree"] = "mmlDegree"; - DomType["MmlSuperscript"] = "mmlSuperscript"; - DomType["MmlSubscript"] = "mmlSubscript"; - DomType["MmlPreSubSuper"] = "mmlPreSubSuper"; - DomType["MmlSubArgument"] = "mmlSubArgument"; - DomType["MmlSuperArgument"] = "mmlSuperArgument"; - DomType["MmlNary"] = "mmlNary"; - DomType["MmlDelimiter"] = "mmlDelimiter"; - DomType["MmlRun"] = "mmlRun"; - DomType["MmlEquationArray"] = "mmlEquationArray"; - DomType["MmlLimit"] = "mmlLimit"; - DomType["MmlLimitLower"] = "mmlLimitLower"; - DomType["MmlMatrix"] = "mmlMatrix"; - DomType["MmlMatrixRow"] = "mmlMatrixRow"; - DomType["MmlBox"] = "mmlBox"; - DomType["MmlBar"] = "mmlBar"; - DomType["MmlGroupChar"] = "mmlGroupChar"; - DomType["VmlElement"] = "vmlElement"; - DomType["Inserted"] = "inserted"; - DomType["Deleted"] = "deleted"; - DomType["DeletedText"] = "deletedText"; - DomType["Comment"] = "comment"; - DomType["CommentReference"] = "commentReference"; - DomType["CommentRangeStart"] = "commentRangeStart"; - DomType["CommentRangeEnd"] = "commentRangeEnd"; - DomType["AltChunk"] = "altChunk"; -})(DomType || (DomType = {})); -class OpenXmlElementBase { - constructor() { - this.children = []; - this.cssStyle = {}; - } -} - -class WmlHeader extends OpenXmlElementBase { - constructor() { - super(...arguments); - this.type = DomType.Header; - } -} -class WmlFooter extends OpenXmlElementBase { - constructor() { - super(...arguments); - this.type = DomType.Footer; - } -} - -class BaseHeaderFooterPart extends Part { - constructor(pkg, path, parser) { - super(pkg, path); - this._documentParser = parser; - } - parseXml(root) { - this.rootElement = this.createRootElement(); - this.rootElement.children = this._documentParser.parseBodyElements(root); - } -} -class HeaderPart extends BaseHeaderFooterPart { - createRootElement() { - return new WmlHeader(); - } -} -class FooterPart extends BaseHeaderFooterPart { - createRootElement() { - return new WmlFooter(); - } -} - -function parseExtendedProps(root, xmlParser) { - const result = {}; - for (let el of xmlParser.elements(root)) { - switch (el.localName) { - case "Template": - result.template = el.textContent; - break; - case "Pages": - result.pages = safeParseToInt(el.textContent); - break; - case "Words": - result.words = safeParseToInt(el.textContent); - break; - case "Characters": - result.characters = safeParseToInt(el.textContent); - break; - case "Application": - result.application = el.textContent; - break; - case "Lines": - result.lines = safeParseToInt(el.textContent); - break; - case "Paragraphs": - result.paragraphs = safeParseToInt(el.textContent); - break; - case "Company": - result.company = el.textContent; - break; - case "AppVersion": - result.appVersion = el.textContent; - break; - } - } - return result; -} -function safeParseToInt(value) { - if (typeof value === 'undefined') - return; - return parseInt(value); -} - -class ExtendedPropsPart extends Part { - parseXml(root) { - this.props = parseExtendedProps(root, this._package.xmlParser); - } -} - -function parseCoreProps(root, xmlParser) { - const result = {}; - for (let el of xmlParser.elements(root)) { - switch (el.localName) { - case "title": - result.title = el.textContent; - break; - case "description": - result.description = el.textContent; - break; - case "subject": - result.subject = el.textContent; - break; - case "creator": - result.creator = el.textContent; - break; - case "keywords": - result.keywords = el.textContent; - break; - case "language": - result.language = el.textContent; - break; - case "lastModifiedBy": - result.lastModifiedBy = el.textContent; - break; - case "revision": - el.textContent && (result.revision = parseInt(el.textContent)); - break; - } - } - return result; -} - -class CorePropsPart extends Part { - parseXml(root) { - this.props = parseCoreProps(root, this._package.xmlParser); - } -} - -class DmlTheme { -} -function parseTheme(elem, xml) { - var result = new DmlTheme(); - var themeElements = xml.element(elem, "themeElements"); - for (let el of xml.elements(themeElements)) { - switch (el.localName) { - case "clrScheme": - result.colorScheme = parseColorScheme(el, xml); - break; - case "fontScheme": - result.fontScheme = parseFontScheme(el, xml); - break; - } - } - return result; -} -function parseColorScheme(elem, xml) { - var result = { - name: xml.attr(elem, "name"), - colors: {} - }; - for (let el of xml.elements(elem)) { - var srgbClr = xml.element(el, "srgbClr"); - var sysClr = xml.element(el, "sysClr"); - if (srgbClr) { - result.colors[el.localName] = xml.attr(srgbClr, "val"); - } - else if (sysClr) { - result.colors[el.localName] = xml.attr(sysClr, "lastClr"); - } - } - return result; -} -function parseFontScheme(elem, xml) { - var result = { - name: xml.attr(elem, "name"), - }; - for (let el of xml.elements(elem)) { - switch (el.localName) { - case "majorFont": - result.majorFont = parseFontInfo(el, xml); - break; - case "minorFont": - result.minorFont = parseFontInfo(el, xml); - break; - } - } - return result; -} -function parseFontInfo(elem, xml) { - return { - latinTypeface: xml.elementAttr(elem, "latin", "typeface"), - eaTypeface: xml.elementAttr(elem, "ea", "typeface"), - csTypeface: xml.elementAttr(elem, "cs", "typeface"), - }; -} - -class ThemePart extends Part { - constructor(pkg, path) { - super(pkg, path); - } - parseXml(root) { - this.theme = parseTheme(root, this._package.xmlParser); - } -} - -class WmlBaseNote { -} -class WmlFootnote extends WmlBaseNote { - constructor() { - super(...arguments); - this.type = DomType.Footnote; - } -} -class WmlEndnote extends WmlBaseNote { - constructor() { - super(...arguments); - this.type = DomType.Endnote; - } -} - -class BaseNotePart extends Part { - constructor(pkg, path, parser) { - super(pkg, path); - this._documentParser = parser; - } -} -class FootnotesPart extends BaseNotePart { - constructor(pkg, path, parser) { - super(pkg, path, parser); - } - parseXml(root) { - this.notes = this._documentParser.parseNotes(root, "footnote", WmlFootnote); - } -} -class EndnotesPart extends BaseNotePart { - constructor(pkg, path, parser) { - super(pkg, path, parser); - } - parseXml(root) { - this.notes = this._documentParser.parseNotes(root, "endnote", WmlEndnote); - } -} - -function parseSettings(elem, xml) { - var result = {}; - for (let el of xml.elements(elem)) { - switch (el.localName) { - case "defaultTabStop": - result.defaultTabStop = xml.lengthAttr(el, "val"); - break; - case "footnotePr": - result.footnoteProps = parseNoteProperties(el, xml); - break; - case "endnotePr": - result.endnoteProps = parseNoteProperties(el, xml); - break; - case "autoHyphenation": - result.autoHyphenation = xml.boolAttr(el, "val"); - break; - } - } - return result; -} -function parseNoteProperties(elem, xml) { - var result = { - defaultNoteIds: [] - }; - for (let el of xml.elements(elem)) { - switch (el.localName) { - case "numFmt": - result.nummeringFormat = xml.attr(el, "val"); - break; - case "footnote": - case "endnote": - result.defaultNoteIds.push(xml.attr(el, "id")); - break; - } - } - return result; -} - -class SettingsPart extends Part { - constructor(pkg, path) { - super(pkg, path); - } - parseXml(root) { - this.settings = parseSettings(root, this._package.xmlParser); - } -} - -function parseCustomProps(root, xml) { - return xml.elements(root, "property").map(e => { - const firstChild = e.firstChild; - return { - formatId: xml.attr(e, "fmtid"), - name: xml.attr(e, "name"), - type: firstChild.nodeName, - value: firstChild.textContent - }; - }); -} - -class CustomPropsPart extends Part { - parseXml(root) { - this.props = parseCustomProps(root, this._package.xmlParser); - } -} - -class CommentsPart extends Part { - constructor(pkg, path, parser) { - super(pkg, path); - this._documentParser = parser; - } - parseXml(root) { - this.comments = this._documentParser.parseComments(root); - this.commentMap = keyBy(this.comments, x => x.id); - } -} - -class CommentsExtendedPart extends Part { - constructor(pkg, path) { - super(pkg, path); - this.comments = []; - } - parseXml(root) { - const xml = this._package.xmlParser; - for (let el of xml.elements(root, "commentEx")) { - this.comments.push({ - paraId: xml.attr(el, 'paraId'), - paraIdParent: xml.attr(el, 'paraIdParent'), - done: xml.boolAttr(el, 'done') - }); - } - this.commentMap = keyBy(this.comments, x => x.paraId); - } -} - -const topLevelRels = [ - { type: RelationshipTypes.OfficeDocument, target: "word/document.xml" }, - { type: RelationshipTypes.ExtendedProperties, target: "docProps/app.xml" }, - { type: RelationshipTypes.CoreProperties, target: "docProps/core.xml" }, - { type: RelationshipTypes.CustomProperties, target: "docProps/custom.xml" }, -]; -class WordDocument { - constructor() { - this.parts = []; - this.partsMap = {}; - } - static async load(blob, parser, options) { - var d = new WordDocument(); - d._options = options; - d._parser = parser; - d._package = await OpenXmlPackage.load(blob, options); - d.rels = await d._package.loadRelationships(); - await Promise.all(topLevelRels.map(rel => { - const r = d.rels.find(x => x.type === rel.type) ?? rel; - return d.loadRelationshipPart(r.target, r.type); - })); - return d; - } - save(type = "blob") { - return this._package.save(type); - } - async loadRelationshipPart(path, type) { - if (this.partsMap[path]) - return this.partsMap[path]; - if (!this._package.get(path)) - return null; - let part = null; - switch (type) { - case RelationshipTypes.OfficeDocument: - this.documentPart = part = new DocumentPart(this._package, path, this._parser); - break; - case RelationshipTypes.FontTable: - this.fontTablePart = part = new FontTablePart(this._package, path); - break; - case RelationshipTypes.Numbering: - this.numberingPart = part = new NumberingPart(this._package, path, this._parser); - break; - case RelationshipTypes.Styles: - this.stylesPart = part = new StylesPart(this._package, path, this._parser); - break; - case RelationshipTypes.Theme: - this.themePart = part = new ThemePart(this._package, path); - break; - case RelationshipTypes.Footnotes: - this.footnotesPart = part = new FootnotesPart(this._package, path, this._parser); - break; - case RelationshipTypes.Endnotes: - this.endnotesPart = part = new EndnotesPart(this._package, path, this._parser); - break; - case RelationshipTypes.Footer: - part = new FooterPart(this._package, path, this._parser); - break; - case RelationshipTypes.Header: - part = new HeaderPart(this._package, path, this._parser); - break; - case RelationshipTypes.CoreProperties: - this.corePropsPart = part = new CorePropsPart(this._package, path); - break; - case RelationshipTypes.ExtendedProperties: - this.extendedPropsPart = part = new ExtendedPropsPart(this._package, path); - break; - case RelationshipTypes.CustomProperties: - part = new CustomPropsPart(this._package, path); - break; - case RelationshipTypes.Settings: - this.settingsPart = part = new SettingsPart(this._package, path); - break; - case RelationshipTypes.Comments: - this.commentsPart = part = new CommentsPart(this._package, path, this._parser); - break; - case RelationshipTypes.CommentsExtended: - this.commentsExtendedPart = part = new CommentsExtendedPart(this._package, path); - break; - } - if (part == null) - return Promise.resolve(null); - this.partsMap[path] = part; - this.parts.push(part); - await part.load(); - if (part.rels?.length > 0) { - const [folder] = splitPath(part.path); - await Promise.all(part.rels.map(rel => this.loadRelationshipPart(resolvePath(rel.target, folder), rel.type))); - } - return part; - } - async loadDocumentImage(id, part) { - const x = await this.loadResource(part ?? this.documentPart, id, "blob"); - return this.blobToURL(x); - } - async loadNumberingImage(id) { - const x = await this.loadResource(this.numberingPart, id, "blob"); - return this.blobToURL(x); - } - async loadFont(id, key) { - const x = await this.loadResource(this.fontTablePart, id, "uint8array"); - return x ? this.blobToURL(new Blob([deobfuscate(x, key)])) : x; - } - async loadAltChunk(id, part) { - return await this.loadResource(part ?? this.documentPart, id, "string"); - } - blobToURL(blob) { - if (!blob) - return null; - if (this._options.useBase64URL) { - return blobToBase64(blob); - } - return URL.createObjectURL(blob); - } - findPartByRelId(id, basePart = null) { - var rel = (basePart.rels ?? this.rels).find(r => r.id == id); - const folder = basePart ? splitPath(basePart.path)[0] : ''; - return rel ? this.partsMap[resolvePath(rel.target, folder)] : null; - } - getPathById(part, id) { - const rel = part.rels.find(x => x.id == id); - const [folder] = splitPath(part.path); - return rel ? resolvePath(rel.target, folder) : null; - } - loadResource(part, id, outputType) { - const path = this.getPathById(part, id); - return path ? this._package.load(path, outputType) : Promise.resolve(null); - } -} -function deobfuscate(data, guidKey) { - const len = 16; - const trimmed = guidKey.replace(/{|}|-/g, ""); - const numbers = new Array(len); - for (let i = 0; i < len; i++) - numbers[len - i - 1] = parseInt(trimmed.substring(i * 2, i * 2 + 2), 16); - for (let i = 0; i < 32; i++) - data[i] = data[i] ^ numbers[i % len]; - return data; -} - -function parseBookmarkStart(elem, xml) { - return { - type: DomType.BookmarkStart, - id: xml.attr(elem, "id"), - name: xml.attr(elem, "name"), - colFirst: xml.intAttr(elem, "colFirst"), - colLast: xml.intAttr(elem, "colLast") - }; -} -function parseBookmarkEnd(elem, xml) { - return { - type: DomType.BookmarkEnd, - id: xml.attr(elem, "id") - }; -} - -class VmlElement extends OpenXmlElementBase { - constructor() { - super(...arguments); - this.type = DomType.VmlElement; - this.attrs = {}; - } -} -function parseVmlElement(elem, parser) { - var result = new VmlElement(); - switch (elem.localName) { - case "rect": - result.tagName = "rect"; - Object.assign(result.attrs, { width: '100%', height: '100%' }); - break; - case "oval": - result.tagName = "ellipse"; - Object.assign(result.attrs, { cx: "50%", cy: "50%", rx: "50%", ry: "50%" }); - break; - case "line": - result.tagName = "line"; - break; - case "shape": - result.tagName = "g"; - break; - case "textbox": - result.tagName = "foreignObject"; - Object.assign(result.attrs, { width: '100%', height: '100%' }); - break; - default: - return null; - } - for (const at of globalXmlParser.attrs(elem)) { - switch (at.localName) { - case "style": - result.cssStyleText = at.value; - break; - case "fillcolor": - result.attrs.fill = at.value; - break; - case "from": - const [x1, y1] = parsePoint(at.value); - Object.assign(result.attrs, { x1, y1 }); - break; - case "to": - const [x2, y2] = parsePoint(at.value); - Object.assign(result.attrs, { x2, y2 }); - break; - } - } - for (const el of globalXmlParser.elements(elem)) { - switch (el.localName) { - case "stroke": - Object.assign(result.attrs, parseStroke(el)); - break; - case "fill": - Object.assign(result.attrs, parseFill()); - break; - case "imagedata": - result.tagName = "image"; - Object.assign(result.attrs, { width: '100%', height: '100%' }); - result.imageHref = { - id: globalXmlParser.attr(el, "id"), - title: globalXmlParser.attr(el, "title"), - }; - break; - case "txbxContent": - result.children.push(...parser.parseBodyElements(el)); - break; - default: - const child = parseVmlElement(el, parser); - child && result.children.push(child); - break; - } - } - return result; -} -function parseStroke(el) { - return { - 'stroke': globalXmlParser.attr(el, "color"), - 'stroke-width': globalXmlParser.lengthAttr(el, "weight", LengthUsage.Emu) ?? '1px' - }; -} -function parseFill(el) { - return {}; -} -function parsePoint(val) { - return val.split(","); -} - -class WmlComment extends OpenXmlElementBase { - constructor() { - super(...arguments); - this.type = DomType.Comment; - } -} -class WmlCommentReference extends OpenXmlElementBase { - constructor(id) { - super(); - this.id = id; - this.type = DomType.CommentReference; - } -} -class WmlCommentRangeStart extends OpenXmlElementBase { - constructor(id) { - super(); - this.id = id; - this.type = DomType.CommentRangeStart; - } -} -class WmlCommentRangeEnd extends OpenXmlElementBase { - constructor(id) { - super(); - this.id = id; - this.type = DomType.CommentRangeEnd; - } -} - -var autos = { - shd: "inherit", - color: "black", - borderColor: "black", - highlight: "transparent" -}; -const supportedNamespaceURIs = []; -const mmlTagMap = { - "oMath": DomType.MmlMath, - "oMathPara": DomType.MmlMathParagraph, - "f": DomType.MmlFraction, - "func": DomType.MmlFunction, - "fName": DomType.MmlFunctionName, - "num": DomType.MmlNumerator, - "den": DomType.MmlDenominator, - "rad": DomType.MmlRadical, - "deg": DomType.MmlDegree, - "e": DomType.MmlBase, - "sSup": DomType.MmlSuperscript, - "sSub": DomType.MmlSubscript, - "sPre": DomType.MmlPreSubSuper, - "sup": DomType.MmlSuperArgument, - "sub": DomType.MmlSubArgument, - "d": DomType.MmlDelimiter, - "nary": DomType.MmlNary, - "eqArr": DomType.MmlEquationArray, - "lim": DomType.MmlLimit, - "limLow": DomType.MmlLimitLower, - "m": DomType.MmlMatrix, - "mr": DomType.MmlMatrixRow, - "box": DomType.MmlBox, - "bar": DomType.MmlBar, - "groupChr": DomType.MmlGroupChar -}; -class DocumentParser { - constructor(options) { - this.options = { - ignoreWidth: false, - debug: false, - ...options - }; - } - parseNotes(xmlDoc, elemName, elemClass) { - var result = []; - for (let el of globalXmlParser.elements(xmlDoc, elemName)) { - const node = new elemClass(); - node.id = globalXmlParser.attr(el, "id"); - node.noteType = globalXmlParser.attr(el, "type"); - node.children = this.parseBodyElements(el); - result.push(node); - } - return result; - } - parseComments(xmlDoc) { - var result = []; - for (let el of globalXmlParser.elements(xmlDoc, "comment")) { - const item = new WmlComment(); - item.id = globalXmlParser.attr(el, "id"); - item.author = globalXmlParser.attr(el, "author"); - item.initials = globalXmlParser.attr(el, "initials"); - item.date = globalXmlParser.attr(el, "date"); - item.children = this.parseBodyElements(el); - result.push(item); - } - return result; - } - parseDocumentFile(xmlDoc) { - var xbody = globalXmlParser.element(xmlDoc, "body"); - var background = globalXmlParser.element(xmlDoc, "background"); - var sectPr = globalXmlParser.element(xbody, "sectPr"); - return { - type: DomType.Document, - children: this.parseBodyElements(xbody), - props: sectPr ? parseSectionProperties(sectPr, globalXmlParser) : {}, - cssStyle: background ? this.parseBackground(background) : {}, - }; - } - parseBackground(elem) { - var result = {}; - var color = xmlUtil.colorAttr(elem, "color"); - if (color) { - result["background-color"] = color; - } - return result; - } - parseBodyElements(element) { - var children = []; - for (const elem of globalXmlParser.elements(element)) { - switch (elem.localName) { - case "p": - children.push(this.parseParagraph(elem)); - break; - case "altChunk": - children.push(this.parseAltChunk(elem)); - break; - case "tbl": - children.push(this.parseTable(elem)); - break; - case "sdt": - children.push(...this.parseSdt(elem, e => this.parseBodyElements(e))); - break; - } - } - return children; - } - parseStylesFile(xstyles) { - var result = []; - for (const n of globalXmlParser.elements(xstyles)) { - switch (n.localName) { - case "style": - result.push(this.parseStyle(n)); - break; - case "docDefaults": - result.push(this.parseDefaultStyles(n)); - break; - } - } - return result; - } - parseDefaultStyles(node) { - var result = { - id: null, - name: null, - target: null, - basedOn: null, - styles: [] - }; - for (const c of globalXmlParser.elements(node)) { - switch (c.localName) { - case "rPrDefault": - var rPr = globalXmlParser.element(c, "rPr"); - if (rPr) - result.styles.push({ - target: "span", - values: this.parseDefaultProperties(rPr, {}) - }); - break; - case "pPrDefault": - var pPr = globalXmlParser.element(c, "pPr"); - if (pPr) - result.styles.push({ - target: "p", - values: this.parseDefaultProperties(pPr, {}) - }); - break; - } - } - return result; - } - parseStyle(node) { - var result = { - id: globalXmlParser.attr(node, "styleId"), - isDefault: globalXmlParser.boolAttr(node, "default"), - name: null, - target: null, - basedOn: null, - styles: [], - linked: null - }; - switch (globalXmlParser.attr(node, "type")) { - case "paragraph": - result.target = "p"; - break; - case "table": - result.target = "table"; - break; - case "character": - result.target = "span"; - break; - } - for (const n of globalXmlParser.elements(node)) { - switch (n.localName) { - case "basedOn": - result.basedOn = globalXmlParser.attr(n, "val"); - break; - case "name": - result.name = globalXmlParser.attr(n, "val"); - break; - case "link": - result.linked = globalXmlParser.attr(n, "val"); - break; - case "next": - result.next = globalXmlParser.attr(n, "val"); - break; - case "aliases": - result.aliases = globalXmlParser.attr(n, "val").split(","); - break; - case "pPr": - result.styles.push({ - target: "p", - values: this.parseDefaultProperties(n, {}) - }); - result.paragraphProps = parseParagraphProperties(n, globalXmlParser); - break; - case "rPr": - result.styles.push({ - target: "span", - values: this.parseDefaultProperties(n, {}) - }); - result.runProps = parseRunProperties(n, globalXmlParser); - break; - case "tblPr": - case "tcPr": - result.styles.push({ - target: "td", - values: this.parseDefaultProperties(n, {}) - }); - break; - case "tblStylePr": - for (let s of this.parseTableStyle(n)) - result.styles.push(s); - break; - case "rsid": - case "qFormat": - case "hidden": - case "semiHidden": - case "unhideWhenUsed": - case "autoRedefine": - case "uiPriority": - break; - default: - this.options.debug && console.warn(`DOCX: Unknown style element: ${n.localName}`); - } - } - return result; - } - parseTableStyle(node) { - var result = []; - var type = globalXmlParser.attr(node, "type"); - var selector = ""; - var modificator = ""; - switch (type) { - case "firstRow": - modificator = ".first-row"; - selector = "tr.first-row td"; - break; - case "lastRow": - modificator = ".last-row"; - selector = "tr.last-row td"; - break; - case "firstCol": - modificator = ".first-col"; - selector = "td.first-col"; - break; - case "lastCol": - modificator = ".last-col"; - selector = "td.last-col"; - break; - case "band1Vert": - modificator = ":not(.no-vband)"; - selector = "td.odd-col"; - break; - case "band2Vert": - modificator = ":not(.no-vband)"; - selector = "td.even-col"; - break; - case "band1Horz": - modificator = ":not(.no-hband)"; - selector = "tr.odd-row"; - break; - case "band2Horz": - modificator = ":not(.no-hband)"; - selector = "tr.even-row"; - break; - default: return []; - } - for (const n of globalXmlParser.elements(node)) { - switch (n.localName) { - case "pPr": - result.push({ - target: `${selector} p`, - mod: modificator, - values: this.parseDefaultProperties(n, {}) - }); - break; - case "rPr": - result.push({ - target: `${selector} span`, - mod: modificator, - values: this.parseDefaultProperties(n, {}) - }); - break; - case "tblPr": - case "tcPr": - result.push({ - target: selector, - mod: modificator, - values: this.parseDefaultProperties(n, {}) - }); - break; - } - } - return result; - } - parseNumberingFile(node) { - var result = []; - var mapping = {}; - var bullets = []; - for (const n of globalXmlParser.elements(node)) { - switch (n.localName) { - case "abstractNum": - this.parseAbstractNumbering(n, bullets) - .forEach(x => result.push(x)); - break; - case "numPicBullet": - bullets.push(this.parseNumberingPicBullet(n)); - break; - case "num": - var numId = globalXmlParser.attr(n, "numId"); - var abstractNumId = globalXmlParser.elementAttr(n, "abstractNumId", "val"); - mapping[abstractNumId] = numId; - break; - } - } - result.forEach(x => x.id = mapping[x.id]); - return result; - } - parseNumberingPicBullet(elem) { - var pict = globalXmlParser.element(elem, "pict"); - var shape = pict && globalXmlParser.element(pict, "shape"); - var imagedata = shape && globalXmlParser.element(shape, "imagedata"); - return imagedata ? { - id: globalXmlParser.intAttr(elem, "numPicBulletId"), - src: globalXmlParser.attr(imagedata, "id"), - style: globalXmlParser.attr(shape, "style") - } : null; - } - parseAbstractNumbering(node, bullets) { - var result = []; - var id = globalXmlParser.attr(node, "abstractNumId"); - for (const n of globalXmlParser.elements(node)) { - switch (n.localName) { - case "lvl": - result.push(this.parseNumberingLevel(id, n, bullets)); - break; - } - } - return result; - } - parseNumberingLevel(id, node, bullets) { - var result = { - id: id, - level: globalXmlParser.intAttr(node, "ilvl"), - start: 1, - pStyleName: undefined, - pStyle: {}, - rStyle: {}, - suff: "tab" - }; - for (const n of globalXmlParser.elements(node)) { - switch (n.localName) { - case "start": - result.start = globalXmlParser.intAttr(n, "val"); - break; - case "pPr": - this.parseDefaultProperties(n, result.pStyle); - break; - case "rPr": - this.parseDefaultProperties(n, result.rStyle); - break; - case "lvlPicBulletId": - var bulletId = globalXmlParser.intAttr(n, "val"); - result.bullet = bullets.find(x => x?.id == bulletId); - break; - case "lvlText": - result.levelText = globalXmlParser.attr(n, "val"); - break; - case "pStyle": - result.pStyleName = globalXmlParser.attr(n, "val"); - break; - case "numFmt": - result.format = globalXmlParser.attr(n, "val"); - break; - case "suff": - result.suff = globalXmlParser.attr(n, "val"); - break; - } - } - return result; - } - parseSdt(node, parser) { - const sdtContent = globalXmlParser.element(node, "sdtContent"); - return sdtContent ? parser(sdtContent) : []; - } - parseInserted(node, parentParser) { - return { - type: DomType.Inserted, - children: parentParser(node)?.children ?? [] - }; - } - parseDeleted(node, parentParser) { - return { - type: DomType.Deleted, - children: parentParser(node)?.children ?? [] - }; - } - parseAltChunk(node) { - return { type: DomType.AltChunk, children: [], id: globalXmlParser.attr(node, "id") }; - } - parseParagraph(node) { - var result = { type: DomType.Paragraph, children: [] }; - for (let el of globalXmlParser.elements(node)) { - switch (el.localName) { - case "pPr": - this.parseParagraphProperties(el, result); - break; - case "r": - result.children.push(this.parseRun(el, result)); - break; - case "hyperlink": - result.children.push(this.parseHyperlink(el, result)); - break; - case "smartTag": - result.children.push(this.parseSmartTag(el, result)); - break; - case "bookmarkStart": - result.children.push(parseBookmarkStart(el, globalXmlParser)); - break; - case "bookmarkEnd": - result.children.push(parseBookmarkEnd(el, globalXmlParser)); - break; - case "commentRangeStart": - result.children.push(new WmlCommentRangeStart(globalXmlParser.attr(el, "id"))); - break; - case "commentRangeEnd": - result.children.push(new WmlCommentRangeEnd(globalXmlParser.attr(el, "id"))); - break; - case "oMath": - case "oMathPara": - result.children.push(this.parseMathElement(el)); - break; - case "sdt": - result.children.push(...this.parseSdt(el, e => this.parseParagraph(e).children)); - break; - case "ins": - result.children.push(this.parseInserted(el, e => this.parseParagraph(e))); - break; - case "del": - result.children.push(this.parseDeleted(el, e => this.parseParagraph(e))); - break; - } - } - return result; - } - parseParagraphProperties(elem, paragraph) { - this.parseDefaultProperties(elem, paragraph.cssStyle = {}, null, c => { - if (parseParagraphProperty(c, paragraph, globalXmlParser)) - return true; - switch (c.localName) { - case "pStyle": - paragraph.styleName = globalXmlParser.attr(c, "val"); - break; - case "cnfStyle": - paragraph.className = values.classNameOfCnfStyle(c); - break; - case "framePr": - this.parseFrame(c, paragraph); - break; - case "rPr": - break; - default: - return false; - } - return true; - }); - } - parseFrame(node, paragraph) { - var dropCap = globalXmlParser.attr(node, "dropCap"); - if (dropCap == "drop") - paragraph.cssStyle["float"] = "left"; - } - parseHyperlink(node, parent) { - var result = { type: DomType.Hyperlink, parent: parent, children: [] }; - result.anchor = globalXmlParser.attr(node, "anchor"); - result.id = globalXmlParser.attr(node, "id"); - for (const c of globalXmlParser.elements(node)) { - switch (c.localName) { - case "r": - result.children.push(this.parseRun(c, result)); - break; - } - } - return result; - } - parseSmartTag(node, parent) { - var result = { type: DomType.SmartTag, parent, children: [] }; - var uri = globalXmlParser.attr(node, "uri"); - var element = globalXmlParser.attr(node, "element"); - if (uri) - result.uri = uri; - if (element) - result.element = element; - for (const c of globalXmlParser.elements(node)) { - switch (c.localName) { - case "r": - result.children.push(this.parseRun(c, result)); - break; - } - } - return result; - } - parseRun(node, parent) { - var result = { type: DomType.Run, parent: parent, children: [] }; - for (let c of globalXmlParser.elements(node)) { - c = this.checkAlternateContent(c); - switch (c.localName) { - case "t": - result.children.push({ - type: DomType.Text, - text: c.textContent - }); - break; - case "delText": - result.children.push({ - type: DomType.DeletedText, - text: c.textContent - }); - break; - case "commentReference": - result.children.push(new WmlCommentReference(globalXmlParser.attr(c, "id"))); - break; - case "fldSimple": - result.children.push({ - type: DomType.SimpleField, - instruction: globalXmlParser.attr(c, "instr"), - lock: globalXmlParser.boolAttr(c, "lock", false), - dirty: globalXmlParser.boolAttr(c, "dirty", false) - }); - break; - case "instrText": - result.fieldRun = true; - result.children.push({ - type: DomType.Instruction, - text: c.textContent - }); - break; - case "fldChar": - result.fieldRun = true; - result.children.push({ - type: DomType.ComplexField, - charType: globalXmlParser.attr(c, "fldCharType"), - lock: globalXmlParser.boolAttr(c, "lock", false), - dirty: globalXmlParser.boolAttr(c, "dirty", false) - }); - break; - case "noBreakHyphen": - result.children.push({ type: DomType.NoBreakHyphen }); - break; - case "br": - result.children.push({ - type: DomType.Break, - break: globalXmlParser.attr(c, "type") || "textWrapping" - }); - break; - case "lastRenderedPageBreak": - result.children.push({ - type: DomType.Break, - break: "lastRenderedPageBreak" - }); - break; - case "sym": - result.children.push({ - type: DomType.Symbol, - font: encloseFontFamily(globalXmlParser.attr(c, "font")), - char: globalXmlParser.attr(c, "char") - }); - break; - case "tab": - result.children.push({ type: DomType.Tab }); - break; - case "footnoteReference": - result.children.push({ - type: DomType.FootnoteReference, - id: globalXmlParser.attr(c, "id") - }); - break; - case "endnoteReference": - result.children.push({ - type: DomType.EndnoteReference, - id: globalXmlParser.attr(c, "id") - }); - break; - case "drawing": - let d = this.parseDrawing(c); - if (d) - result.children = [d]; - break; - case "pict": - result.children.push(this.parseVmlPicture(c)); - break; - case "rPr": - this.parseRunProperties(c, result); - break; - } - } - return result; - } - parseMathElement(elem) { - const propsTag = `${elem.localName}Pr`; - const result = { type: mmlTagMap[elem.localName], children: [] }; - for (const el of globalXmlParser.elements(elem)) { - const childType = mmlTagMap[el.localName]; - if (childType) { - result.children.push(this.parseMathElement(el)); - } - else if (el.localName == "r") { - var run = this.parseRun(el); - run.type = DomType.MmlRun; - result.children.push(run); - } - else if (el.localName == propsTag) { - result.props = this.parseMathProperies(el); - } - } - return result; - } - parseMathProperies(elem) { - const result = {}; - for (const el of globalXmlParser.elements(elem)) { - switch (el.localName) { - case "chr": - result.char = globalXmlParser.attr(el, "val"); - break; - case "vertJc": - result.verticalJustification = globalXmlParser.attr(el, "val"); - break; - case "pos": - result.position = globalXmlParser.attr(el, "val"); - break; - case "degHide": - result.hideDegree = globalXmlParser.boolAttr(el, "val"); - break; - case "begChr": - result.beginChar = globalXmlParser.attr(el, "val"); - break; - case "endChr": - result.endChar = globalXmlParser.attr(el, "val"); - break; - } - } - return result; - } - parseRunProperties(elem, run) { - this.parseDefaultProperties(elem, run.cssStyle = {}, null, c => { - switch (c.localName) { - case "rStyle": - run.styleName = globalXmlParser.attr(c, "val"); - break; - case "vertAlign": - run.verticalAlign = values.valueOfVertAlign(c, true); - break; - default: - return false; - } - return true; - }); - } - parseVmlPicture(elem) { - const result = { type: DomType.VmlPicture, children: [] }; - for (const el of globalXmlParser.elements(elem)) { - const child = parseVmlElement(el, this); - child && result.children.push(child); - } - return result; - } - checkAlternateContent(elem) { - if (elem.localName != 'AlternateContent') - return elem; - var choice = globalXmlParser.element(elem, "Choice"); - if (choice) { - var requires = globalXmlParser.attr(choice, "Requires"); - var namespaceURI = elem.lookupNamespaceURI(requires); - if (supportedNamespaceURIs.includes(namespaceURI)) - return choice.firstElementChild; - } - return globalXmlParser.element(elem, "Fallback")?.firstElementChild; - } - parseDrawing(node) { - for (var n of globalXmlParser.elements(node)) { - switch (n.localName) { - case "inline": - case "anchor": - return this.parseDrawingWrapper(n); - } - } - } - parseDrawingWrapper(node) { - var result = { type: DomType.Drawing, children: [], cssStyle: {} }; - var isAnchor = node.localName == "anchor"; - let wrapType = null; - let simplePos = globalXmlParser.boolAttr(node, "simplePos"); - globalXmlParser.boolAttr(node, "behindDoc"); - let posX = { relative: "page", align: "left", offset: "0" }; - let posY = { relative: "page", align: "top", offset: "0" }; - for (var n of globalXmlParser.elements(node)) { - switch (n.localName) { - case "simplePos": - if (simplePos) { - posX.offset = globalXmlParser.lengthAttr(n, "x", LengthUsage.Emu); - posY.offset = globalXmlParser.lengthAttr(n, "y", LengthUsage.Emu); - } - break; - case "extent": - result.cssStyle["width"] = globalXmlParser.lengthAttr(n, "cx", LengthUsage.Emu); - result.cssStyle["height"] = globalXmlParser.lengthAttr(n, "cy", LengthUsage.Emu); - break; - case "positionH": - case "positionV": - if (!simplePos) { - let pos = n.localName == "positionH" ? posX : posY; - var alignNode = globalXmlParser.element(n, "align"); - var offsetNode = globalXmlParser.element(n, "posOffset"); - pos.relative = globalXmlParser.attr(n, "relativeFrom") ?? pos.relative; - if (alignNode) - pos.align = alignNode.textContent; - if (offsetNode) - pos.offset = convertLength(offsetNode.textContent, LengthUsage.Emu); - } - break; - case "wrapTopAndBottom": - wrapType = "wrapTopAndBottom"; - break; - case "wrapNone": - wrapType = "wrapNone"; - break; - case "graphic": - var g = this.parseGraphic(n); - if (g) - result.children.push(g); - break; - } - } - if (wrapType == "wrapTopAndBottom") { - result.cssStyle['display'] = 'block'; - if (posX.align) { - result.cssStyle['text-align'] = posX.align; - result.cssStyle['width'] = "100%"; - } - } - else if (wrapType == "wrapNone") { - result.cssStyle['display'] = 'block'; - result.cssStyle['position'] = 'relative'; - result.cssStyle["width"] = "0px"; - result.cssStyle["height"] = "0px"; - if (posX.offset) - result.cssStyle["left"] = posX.offset; - if (posY.offset) - result.cssStyle["top"] = posY.offset; - } - else if (isAnchor && (posX.align == 'left' || posX.align == 'right')) { - result.cssStyle["float"] = posX.align; - } - return result; - } - parseGraphic(elem) { - var graphicData = globalXmlParser.element(elem, "graphicData"); - for (let n of globalXmlParser.elements(graphicData)) { - switch (n.localName) { - case "pic": - return this.parsePicture(n); - } - } - return null; - } - parsePicture(elem) { - var result = { type: DomType.Image, src: "", cssStyle: {} }; - var blipFill = globalXmlParser.element(elem, "blipFill"); - var blip = globalXmlParser.element(blipFill, "blip"); - var srcRect = globalXmlParser.element(blipFill, "srcRect"); - result.src = globalXmlParser.attr(blip, "embed"); - if (srcRect) { - result.srcRect = [ - globalXmlParser.intAttr(srcRect, "l", 0) / 100000, - globalXmlParser.intAttr(srcRect, "t", 0) / 100000, - globalXmlParser.intAttr(srcRect, "r", 0) / 100000, - globalXmlParser.intAttr(srcRect, "b", 0) / 100000, - ]; - } - var spPr = globalXmlParser.element(elem, "spPr"); - var xfrm = globalXmlParser.element(spPr, "xfrm"); - result.cssStyle["position"] = "relative"; - if (xfrm) { - result.rotation = globalXmlParser.intAttr(xfrm, "rot", 0) / 60000; - for (var n of globalXmlParser.elements(xfrm)) { - switch (n.localName) { - case "ext": - result.cssStyle["width"] = globalXmlParser.lengthAttr(n, "cx", LengthUsage.Emu); - result.cssStyle["height"] = globalXmlParser.lengthAttr(n, "cy", LengthUsage.Emu); - break; - case "off": - result.cssStyle["left"] = globalXmlParser.lengthAttr(n, "x", LengthUsage.Emu); - result.cssStyle["top"] = globalXmlParser.lengthAttr(n, "y", LengthUsage.Emu); - break; - } - } - } - return result; - } - parseTable(node) { - var result = { type: DomType.Table, children: [] }; - for (const c of globalXmlParser.elements(node)) { - switch (c.localName) { - case "tr": - result.children.push(this.parseTableRow(c)); - break; - case "tblGrid": - result.columns = this.parseTableColumns(c); - break; - case "tblPr": - this.parseTableProperties(c, result); - break; - } - } - return result; - } - parseTableColumns(node) { - var result = []; - for (const n of globalXmlParser.elements(node)) { - switch (n.localName) { - case "gridCol": - result.push({ width: globalXmlParser.lengthAttr(n, "w") }); - break; - } - } - return result; - } - parseTableProperties(elem, table) { - table.cssStyle = {}; - table.cellStyle = {}; - this.parseDefaultProperties(elem, table.cssStyle, table.cellStyle, c => { - switch (c.localName) { - case "tblStyle": - table.styleName = globalXmlParser.attr(c, "val"); - break; - case "tblLook": - table.className = values.classNameOftblLook(c); - break; - case "tblpPr": - this.parseTablePosition(c, table); - break; - case "tblStyleColBandSize": - table.colBandSize = globalXmlParser.intAttr(c, "val"); - break; - case "tblStyleRowBandSize": - table.rowBandSize = globalXmlParser.intAttr(c, "val"); - break; - case "hidden": - table.cssStyle["display"] = "none"; - break; - default: - return false; - } - return true; - }); - switch (table.cssStyle["text-align"]) { - case "center": - delete table.cssStyle["text-align"]; - table.cssStyle["margin-left"] = "auto"; - table.cssStyle["margin-right"] = "auto"; - break; - case "right": - delete table.cssStyle["text-align"]; - table.cssStyle["margin-left"] = "auto"; - break; - } - } - parseTablePosition(node, table) { - var topFromText = globalXmlParser.lengthAttr(node, "topFromText"); - var bottomFromText = globalXmlParser.lengthAttr(node, "bottomFromText"); - var rightFromText = globalXmlParser.lengthAttr(node, "rightFromText"); - var leftFromText = globalXmlParser.lengthAttr(node, "leftFromText"); - table.cssStyle["float"] = 'left'; - table.cssStyle["margin-bottom"] = values.addSize(table.cssStyle["margin-bottom"], bottomFromText); - table.cssStyle["margin-left"] = values.addSize(table.cssStyle["margin-left"], leftFromText); - table.cssStyle["margin-right"] = values.addSize(table.cssStyle["margin-right"], rightFromText); - table.cssStyle["margin-top"] = values.addSize(table.cssStyle["margin-top"], topFromText); - } - parseTableRow(node) { - var result = { type: DomType.Row, children: [] }; - for (const c of globalXmlParser.elements(node)) { - switch (c.localName) { - case "tc": - result.children.push(this.parseTableCell(c)); - break; - case "trPr": - case "tblPrEx": - this.parseTableRowProperties(c, result); - break; - } - } - return result; - } - parseTableRowProperties(elem, row) { - row.cssStyle = this.parseDefaultProperties(elem, {}, null, c => { - switch (c.localName) { - case "cnfStyle": - row.className = values.classNameOfCnfStyle(c); - break; - case "tblHeader": - row.isHeader = globalXmlParser.boolAttr(c, "val"); - break; - case "gridBefore": - row.gridBefore = globalXmlParser.intAttr(c, "val"); - break; - case "gridAfter": - row.gridAfter = globalXmlParser.intAttr(c, "val"); - break; - default: - return false; - } - return true; - }); - } - parseTableCell(node) { - var result = { type: DomType.Cell, children: [] }; - for (const c of globalXmlParser.elements(node)) { - switch (c.localName) { - case "tbl": - result.children.push(this.parseTable(c)); - break; - case "p": - result.children.push(this.parseParagraph(c)); - break; - case "tcPr": - this.parseTableCellProperties(c, result); - break; - } - } - return result; - } - parseTableCellProperties(elem, cell) { - cell.cssStyle = this.parseDefaultProperties(elem, {}, null, c => { - switch (c.localName) { - case "gridSpan": - cell.span = globalXmlParser.intAttr(c, "val", null); - break; - case "vMerge": - cell.verticalMerge = globalXmlParser.attr(c, "val") ?? "continue"; - break; - case "cnfStyle": - cell.className = values.classNameOfCnfStyle(c); - break; - default: - return false; - } - return true; - }); - this.parseTableCellVerticalText(elem, cell); - } - parseTableCellVerticalText(elem, cell) { - const directionMap = { - "btLr": { - writingMode: "vertical-rl", - transform: "rotate(180deg)" - }, - "lrTb": { - writingMode: "vertical-lr", - transform: "none" - }, - "tbRl": { - writingMode: "vertical-rl", - transform: "none" - } - }; - for (const c of globalXmlParser.elements(elem)) { - if (c.localName === "textDirection") { - const direction = globalXmlParser.attr(c, "val"); - const style = directionMap[direction] || { writingMode: "horizontal-tb" }; - cell.cssStyle["writing-mode"] = style.writingMode; - cell.cssStyle["transform"] = style.transform; - } - } - } - parseDefaultProperties(elem, style = null, childStyle = null, handler = null) { - style = style || {}; - for (const c of globalXmlParser.elements(elem)) { - if (handler?.(c)) - continue; - switch (c.localName) { - case "jc": - style["text-align"] = values.valueOfJc(c); - break; - case "textAlignment": - style["vertical-align"] = values.valueOfTextAlignment(c); - break; - case "color": - style["color"] = xmlUtil.colorAttr(c, "val", null, autos.color); - break; - case "sz": - style["font-size"] = style["min-height"] = globalXmlParser.lengthAttr(c, "val", LengthUsage.FontSize); - break; - case "shd": - style["background-color"] = xmlUtil.colorAttr(c, "fill", null, autos.shd); - break; - case "highlight": - style["background-color"] = xmlUtil.colorAttr(c, "val", null, autos.highlight); - break; - case "vertAlign": - break; - case "position": - style.verticalAlign = globalXmlParser.lengthAttr(c, "val", LengthUsage.FontSize); - break; - case "tcW": - if (this.options.ignoreWidth) - break; - case "tblW": - style["width"] = values.valueOfSize(c, "w"); - break; - case "trHeight": - this.parseTrHeight(c, style); - break; - case "strike": - style["text-decoration"] = globalXmlParser.boolAttr(c, "val", true) ? "line-through" : "none"; - break; - case "b": - style["font-weight"] = globalXmlParser.boolAttr(c, "val", true) ? "bold" : "normal"; - break; - case "i": - style["font-style"] = globalXmlParser.boolAttr(c, "val", true) ? "italic" : "normal"; - break; - case "caps": - style["text-transform"] = globalXmlParser.boolAttr(c, "val", true) ? "uppercase" : "none"; - break; - case "smallCaps": - style["font-variant"] = globalXmlParser.boolAttr(c, "val", true) ? "small-caps" : "none"; - break; - case "u": - this.parseUnderline(c, style); - break; - case "ind": - case "tblInd": - this.parseIndentation(c, style); - break; - case "rFonts": - this.parseFont(c, style); - break; - case "tblBorders": - this.parseBorderProperties(c, childStyle || style); - break; - case "tblCellSpacing": - style["border-spacing"] = values.valueOfMargin(c); - style["border-collapse"] = "separate"; - break; - case "pBdr": - this.parseBorderProperties(c, style); - break; - case "bdr": - style["border"] = values.valueOfBorder(c); - break; - case "tcBorders": - this.parseBorderProperties(c, style); - break; - case "vanish": - if (globalXmlParser.boolAttr(c, "val", true)) - style["display"] = "none"; - break; - case "kern": - break; - case "noWrap": - break; - case "tblCellMar": - case "tcMar": - this.parseMarginProperties(c, childStyle || style); - break; - case "tblLayout": - style["table-layout"] = values.valueOfTblLayout(c); - break; - case "vAlign": - style["vertical-align"] = values.valueOfTextAlignment(c); - break; - case "spacing": - if (elem.localName == "pPr") - this.parseSpacing(c, style); - break; - case "wordWrap": - if (globalXmlParser.boolAttr(c, "val")) - style["overflow-wrap"] = "break-word"; - break; - case "suppressAutoHyphens": - style["hyphens"] = globalXmlParser.boolAttr(c, "val", true) ? "none" : "auto"; - break; - case "lang": - style["$lang"] = globalXmlParser.attr(c, "val"); - break; - case "rtl": - case "bidi": - if (globalXmlParser.boolAttr(c, "val", true)) - style["direction"] = "rtl"; - break; - case "bCs": - case "iCs": - case "szCs": - case "tabs": - case "outlineLvl": - case "contextualSpacing": - case "tblStyleColBandSize": - case "tblStyleRowBandSize": - case "webHidden": - case "pageBreakBefore": - case "suppressLineNumbers": - case "keepLines": - case "keepNext": - case "widowControl": - case "bidi": - case "rtl": - case "noProof": - break; - default: - if (this.options.debug) - console.warn(`DOCX: Unknown document element: ${elem.localName}.${c.localName}`); - break; - } - } - return style; - } - parseUnderline(node, style) { - var val = globalXmlParser.attr(node, "val"); - if (val == null) - return; - switch (val) { - case "dash": - case "dashDotDotHeavy": - case "dashDotHeavy": - case "dashedHeavy": - case "dashLong": - case "dashLongHeavy": - case "dotDash": - case "dotDotDash": - style["text-decoration"] = "underline dashed"; - break; - case "dotted": - case "dottedHeavy": - style["text-decoration"] = "underline dotted"; - break; - case "double": - style["text-decoration"] = "underline double"; - break; - case "single": - case "thick": - style["text-decoration"] = "underline"; - break; - case "wave": - case "wavyDouble": - case "wavyHeavy": - style["text-decoration"] = "underline wavy"; - break; - case "words": - style["text-decoration"] = "underline"; - break; - case "none": - style["text-decoration"] = "none"; - break; - } - var col = xmlUtil.colorAttr(node, "color"); - if (col) - style["text-decoration-color"] = col; - } - parseFont(node, style) { - var ascii = globalXmlParser.attr(node, "ascii"); - var asciiTheme = values.themeValue(node, "asciiTheme"); - var eastAsia = globalXmlParser.attr(node, "eastAsia"); - var fonts = [ascii, asciiTheme, eastAsia].filter(x => x).map(x => encloseFontFamily(x)); - if (fonts.length > 0) - style["font-family"] = [...new Set(fonts)].join(', '); - } - parseIndentation(node, style) { - var firstLine = globalXmlParser.lengthAttr(node, "firstLine"); - var hanging = globalXmlParser.lengthAttr(node, "hanging"); - var left = globalXmlParser.lengthAttr(node, "left"); - var start = globalXmlParser.lengthAttr(node, "start"); - var right = globalXmlParser.lengthAttr(node, "right"); - var end = globalXmlParser.lengthAttr(node, "end"); - if (firstLine) - style["text-indent"] = firstLine; - if (hanging) - style["text-indent"] = `-${hanging}`; - if (left || start) - style["margin-inline-start"] = left || start; - if (right || end) - style["margin-inline-end"] = right || end; - } - parseSpacing(node, style) { - var before = globalXmlParser.lengthAttr(node, "before"); - var after = globalXmlParser.lengthAttr(node, "after"); - var line = globalXmlParser.intAttr(node, "line", null); - var lineRule = globalXmlParser.attr(node, "lineRule"); - if (before) - style["margin-top"] = before; - if (after) - style["margin-bottom"] = after; - if (line !== null) { - switch (lineRule) { - case "auto": - style["line-height"] = `${(line / 240).toFixed(2)}`; - break; - case "atLeast": - style["line-height"] = `calc(100% + ${line / 20}pt)`; - break; - default: - style["line-height"] = style["min-height"] = `${line / 20}pt`; - break; - } - } - } - parseMarginProperties(node, output) { - for (const c of globalXmlParser.elements(node)) { - switch (c.localName) { - case "left": - output["padding-left"] = values.valueOfMargin(c); - break; - case "right": - output["padding-right"] = values.valueOfMargin(c); - break; - case "top": - output["padding-top"] = values.valueOfMargin(c); - break; - case "bottom": - output["padding-bottom"] = values.valueOfMargin(c); - break; - } - } - } - parseTrHeight(node, output) { - switch (globalXmlParser.attr(node, "hRule")) { - case "exact": - output["height"] = globalXmlParser.lengthAttr(node, "val"); - break; - case "atLeast": - default: - output["height"] = globalXmlParser.lengthAttr(node, "val"); - break; - } - } - parseBorderProperties(node, output) { - for (const c of globalXmlParser.elements(node)) { - switch (c.localName) { - case "start": - case "left": - output["border-left"] = values.valueOfBorder(c); - break; - case "end": - case "right": - output["border-right"] = values.valueOfBorder(c); - break; - case "top": - output["border-top"] = values.valueOfBorder(c); - break; - case "bottom": - output["border-bottom"] = values.valueOfBorder(c); - break; - } - } - } -} -const knownColors = ['black', 'blue', 'cyan', 'darkBlue', 'darkCyan', 'darkGray', 'darkGreen', 'darkMagenta', 'darkRed', 'darkYellow', 'green', 'lightGray', 'magenta', 'none', 'red', 'white', 'yellow']; -class xmlUtil { - static colorAttr(node, attrName, defValue = null, autoColor = 'black') { - var v = globalXmlParser.attr(node, attrName); - if (v) { - if (v == "auto") { - return autoColor; - } - else if (knownColors.includes(v)) { - return v; - } - return `#${v}`; - } - var themeColor = globalXmlParser.attr(node, "themeColor"); - return themeColor ? `var(--docx-${themeColor}-color)` : defValue; - } -} -class values { - static themeValue(c, attr) { - var val = globalXmlParser.attr(c, attr); - return val ? `var(--docx-${val}-font)` : null; - } - static valueOfSize(c, attr) { - var type = LengthUsage.Dxa; - switch (globalXmlParser.attr(c, "type")) { - case "dxa": break; - case "pct": - type = LengthUsage.Percent; - break; - case "auto": return "auto"; - } - return globalXmlParser.lengthAttr(c, attr, type); - } - static valueOfMargin(c) { - return globalXmlParser.lengthAttr(c, "w"); - } - static valueOfBorder(c) { - var type = values.parseBorderType(globalXmlParser.attr(c, "val")); - if (type == "none") - return "none"; - var color = xmlUtil.colorAttr(c, "color"); - var size = globalXmlParser.lengthAttr(c, "sz", LengthUsage.Border); - return `${size} ${type} ${color == "auto" ? autos.borderColor : color}`; - } - static parseBorderType(type) { - switch (type) { - case "single": return "solid"; - case "dashDotStroked": return "solid"; - case "dashed": return "dashed"; - case "dashSmallGap": return "dashed"; - case "dotDash": return "dotted"; - case "dotDotDash": return "dotted"; - case "dotted": return "dotted"; - case "double": return "double"; - case "doubleWave": return "double"; - case "inset": return "inset"; - case "nil": return "none"; - case "none": return "none"; - case "outset": return "outset"; - case "thick": return "solid"; - case "thickThinLargeGap": return "solid"; - case "thickThinMediumGap": return "solid"; - case "thickThinSmallGap": return "solid"; - case "thinThickLargeGap": return "solid"; - case "thinThickMediumGap": return "solid"; - case "thinThickSmallGap": return "solid"; - case "thinThickThinLargeGap": return "solid"; - case "thinThickThinMediumGap": return "solid"; - case "thinThickThinSmallGap": return "solid"; - case "threeDEmboss": return "solid"; - case "threeDEngrave": return "solid"; - case "triple": return "double"; - case "wave": return "solid"; - } - return 'solid'; - } - static valueOfTblLayout(c) { - var type = globalXmlParser.attr(c, "val"); - return type == "fixed" ? "fixed" : "auto"; - } - static classNameOfCnfStyle(c) { - const val = globalXmlParser.attr(c, "val"); - const classes = [ - 'first-row', 'last-row', 'first-col', 'last-col', - 'odd-col', 'even-col', 'odd-row', 'even-row', - 'ne-cell', 'nw-cell', 'se-cell', 'sw-cell' - ]; - return classes.filter((_, i) => val[i] == '1').join(' '); - } - static valueOfJc(c) { - var type = globalXmlParser.attr(c, "val"); - switch (type) { - case "start": - case "left": return "left"; - case "center": return "center"; - case "end": - case "right": return "right"; - case "both": return "justify"; - } - return type; - } - static valueOfVertAlign(c, asTagName = false) { - var type = globalXmlParser.attr(c, "val"); - switch (type) { - case "subscript": return "sub"; - case "superscript": return asTagName ? "sup" : "super"; - } - return asTagName ? null : type; - } - static valueOfTextAlignment(c) { - var type = globalXmlParser.attr(c, "val"); - switch (type) { - case "auto": - case "baseline": return "baseline"; - case "top": return "top"; - case "center": return "middle"; - case "bottom": return "bottom"; - } - return type; - } - static addSize(a, b) { - if (a == null) - return b; - if (b == null) - return a; - return `calc(${a} + ${b})`; - } - static classNameOftblLook(c) { - const val = globalXmlParser.hexAttr(c, "val", 0); - let className = ""; - if (globalXmlParser.boolAttr(c, "firstRow") || (val & 0x0020)) - className += " first-row"; - if (globalXmlParser.boolAttr(c, "lastRow") || (val & 0x0040)) - className += " last-row"; - if (globalXmlParser.boolAttr(c, "firstColumn") || (val & 0x0080)) - className += " first-col"; - if (globalXmlParser.boolAttr(c, "lastColumn") || (val & 0x0100)) - className += " last-col"; - if (globalXmlParser.boolAttr(c, "noHBand") || (val & 0x0200)) - className += " no-hband"; - if (globalXmlParser.boolAttr(c, "noVBand") || (val & 0x0400)) - className += " no-vband"; - return className.trim(); - } -} - -const defaultTab = { pos: 0, leader: "none", style: "left" }; -const maxTabs = 50; -function computePixelToPoint(container = document.body) { - const temp = document.createElement("div"); - temp.style.width = '100pt'; - container.appendChild(temp); - const result = 100 / temp.offsetWidth; - container.removeChild(temp); - return result; -} -function updateTabStop(elem, tabs, defaultTabSize, pixelToPoint = 72 / 96) { - const p = elem.closest("p"); - const ebb = elem.getBoundingClientRect(); - const pbb = p.getBoundingClientRect(); - const pcs = getComputedStyle(p); - const tabStops = tabs?.length > 0 ? tabs.map(t => ({ - pos: lengthToPoint(t.position), - leader: t.leader, - style: t.style - })).sort((a, b) => a.pos - b.pos) : [defaultTab]; - const lastTab = tabStops[tabStops.length - 1]; - const pWidthPt = pbb.width * pixelToPoint; - const size = lengthToPoint(defaultTabSize); - let pos = lastTab.pos + size; - if (pos < pWidthPt) { - for (; pos < pWidthPt && tabStops.length < maxTabs; pos += size) { - tabStops.push({ ...defaultTab, pos: pos }); - } - } - const marginLeft = parseFloat(pcs.marginLeft); - const pOffset = pbb.left + marginLeft; - const left = (ebb.left - pOffset) * pixelToPoint; - const tab = tabStops.find(t => t.style != "clear" && t.pos > left); - if (tab == null) - return; - let width = 1; - if (tab.style == "right" || tab.style == "center") { - const tabStops = Array.from(p.querySelectorAll(`.${elem.className}`)); - const nextIdx = tabStops.indexOf(elem) + 1; - const range = document.createRange(); - range.setStart(elem, 1); - if (nextIdx < tabStops.length) { - range.setEndBefore(tabStops[nextIdx]); - } - else { - range.setEndAfter(p); - } - const mul = tab.style == "center" ? 0.5 : 1; - const nextBB = range.getBoundingClientRect(); - const offset = nextBB.left + mul * nextBB.width - (pbb.left - marginLeft); - width = tab.pos - offset * pixelToPoint; - } - else { - width = tab.pos - left; - } - elem.innerHTML = " "; - elem.style.textDecoration = "inherit"; - elem.style.wordSpacing = `${width.toFixed(0)}pt`; - switch (tab.leader) { - case "dot": - case "middleDot": - elem.style.textDecoration = "underline"; - elem.style.textDecorationStyle = "dotted"; - break; - case "hyphen": - case "heavy": - case "underscore": - elem.style.textDecoration = "underline"; - break; - } -} -function lengthToPoint(length) { - return parseFloat(length); -} - -const ns = { - svg: "http://www.w3.org/2000/svg", - mathML: "http://www.w3.org/1998/Math/MathML" -}; -class HtmlRenderer { - constructor(htmlDocument) { - this.htmlDocument = htmlDocument; - this.className = "docx"; - this.styleMap = {}; - this.currentPart = null; - this.tableVerticalMerges = []; - this.currentVerticalMerge = null; - this.tableCellPositions = []; - this.currentCellPosition = null; - this.footnoteMap = {}; - this.endnoteMap = {}; - this.currentEndnoteIds = []; - this.usedHederFooterParts = []; - this.currentTabs = []; - this.commentMap = {}; - this.tasks = []; - this.postRenderTasks = []; - } - async render(document, bodyContainer, styleContainer = null, options) { - this.document = document; - this.options = options; - this.className = options.className; - this.rootSelector = options.inWrapper ? `.${this.className}-wrapper` : ':root'; - this.styleMap = null; - this.tasks = []; - if (this.options.renderComments && globalThis.Highlight) { - this.commentHighlight = new Highlight(); - } - styleContainer = styleContainer || bodyContainer; - removeAllElements(styleContainer); - removeAllElements(bodyContainer); - styleContainer.appendChild(this.createComment("docxjs library predefined styles")); - styleContainer.appendChild(this.renderDefaultStyle()); - if (document.themePart) { - styleContainer.appendChild(this.createComment("docxjs document theme values")); - this.renderTheme(document.themePart, styleContainer); - } - if (document.stylesPart != null) { - this.styleMap = this.processStyles(document.stylesPart.styles); - styleContainer.appendChild(this.createComment("docxjs document styles")); - styleContainer.appendChild(this.renderStyles(document.stylesPart.styles)); - } - if (document.numberingPart) { - this.prodessNumberings(document.numberingPart.domNumberings); - styleContainer.appendChild(this.createComment("docxjs document numbering styles")); - styleContainer.appendChild(this.renderNumbering(document.numberingPart.domNumberings, styleContainer)); - } - if (document.footnotesPart) { - this.footnoteMap = keyBy(document.footnotesPart.notes, x => x.id); - } - if (document.endnotesPart) { - this.endnoteMap = keyBy(document.endnotesPart.notes, x => x.id); - } - if (document.settingsPart) { - this.defaultTabSize = document.settingsPart.settings?.defaultTabStop; - } - if (!options.ignoreFonts && document.fontTablePart) - this.renderFontTable(document.fontTablePart, styleContainer); - var sectionElements = this.renderSections(document.documentPart.body); - if (this.options.inWrapper) { - bodyContainer.appendChild(this.renderWrapper(sectionElements)); - } - else { - appendChildren(bodyContainer, sectionElements); - } - if (this.commentHighlight && options.renderComments) { - CSS.highlights.set(`${this.className}-comments`, this.commentHighlight); - } - this.postRenderTasks.forEach(t => t()); - await Promise.allSettled(this.tasks); - this.refreshTabStops(); - } - renderTheme(themePart, styleContainer) { - const variables = {}; - const fontScheme = themePart.theme?.fontScheme; - if (fontScheme) { - if (fontScheme.majorFont) { - variables['--docx-majorHAnsi-font'] = fontScheme.majorFont.latinTypeface; - } - if (fontScheme.minorFont) { - variables['--docx-minorHAnsi-font'] = fontScheme.minorFont.latinTypeface; - } - } - const colorScheme = themePart.theme?.colorScheme; - if (colorScheme) { - for (let [k, v] of Object.entries(colorScheme.colors)) { - variables[`--docx-${k}-color`] = `#${v}`; - } - } - const cssText = this.styleToString(`.${this.className}`, variables); - styleContainer.appendChild(this.createStyleElement(cssText)); - } - renderFontTable(fontsPart, styleContainer) { - for (let f of fontsPart.fonts) { - for (let ref of f.embedFontRefs) { - this.tasks.push(this.document.loadFont(ref.id, ref.key).then(fontData => { - const cssValues = { - 'font-family': encloseFontFamily(f.name), - 'src': `url(${fontData})` - }; - if (ref.type == "bold" || ref.type == "boldItalic") { - cssValues['font-weight'] = 'bold'; - } - if (ref.type == "italic" || ref.type == "boldItalic") { - cssValues['font-style'] = 'italic'; - } - const cssText = this.styleToString("@font-face", cssValues); - styleContainer.appendChild(this.createComment(`docxjs ${f.name} font`)); - styleContainer.appendChild(this.createStyleElement(cssText)); - })); - } - } - } - processStyleName(className) { - return className ? `${this.className}_${escapeClassName(className)}` : this.className; - } - processStyles(styles) { - const stylesMap = keyBy(styles.filter(x => x.id != null), x => x.id); - for (const style of styles.filter(x => x.basedOn)) { - var baseStyle = stylesMap[style.basedOn]; - if (baseStyle) { - style.paragraphProps = mergeDeep(style.paragraphProps, baseStyle.paragraphProps); - style.runProps = mergeDeep(style.runProps, baseStyle.runProps); - for (const baseValues of baseStyle.styles) { - const styleValues = style.styles.find(x => x.target == baseValues.target); - if (styleValues) { - this.copyStyleProperties(baseValues.values, styleValues.values); - } - else { - style.styles.push({ ...baseValues, values: { ...baseValues.values } }); - } - } - } - else if (this.options.debug) - console.warn(`Can't find base style ${style.basedOn}`); - } - for (let style of styles) { - style.cssName = this.processStyleName(style.id); - } - return stylesMap; - } - prodessNumberings(numberings) { - for (let num of numberings.filter(n => n.pStyleName)) { - const style = this.findStyle(num.pStyleName); - if (style?.paragraphProps?.numbering) { - style.paragraphProps.numbering.level = num.level; - } - } - } - processElement(element) { - if (element.children) { - for (var e of element.children) { - e.parent = element; - if (e.type == DomType.Table) { - this.processTable(e); - } - else { - this.processElement(e); - } - } - } - } - processTable(table) { - for (var r of table.children) { - for (var c of r.children) { - c.cssStyle = this.copyStyleProperties(table.cellStyle, c.cssStyle, [ - "border-left", "border-right", "border-top", "border-bottom", - "padding-left", "padding-right", "padding-top", "padding-bottom" - ]); - this.processElement(c); - } - } - } - copyStyleProperties(input, output, attrs = null) { - if (!input) - return output; - if (output == null) - output = {}; - if (attrs == null) - attrs = Object.getOwnPropertyNames(input); - for (var key of attrs) { - if (input.hasOwnProperty(key) && !output.hasOwnProperty(key)) - output[key] = input[key]; - } - return output; - } - createPageElement(className, props) { - var elem = this.createElement("section", { className }); - if (props) { - if (props.pageMargins) { - elem.style.paddingLeft = props.pageMargins.left; - elem.style.paddingRight = props.pageMargins.right; - elem.style.paddingTop = props.pageMargins.top; - elem.style.paddingBottom = props.pageMargins.bottom; - } - if (props.pageSize) { - if (!this.options.ignoreWidth) - elem.style.width = props.pageSize.width; - if (!this.options.ignoreHeight) - elem.style.minHeight = props.pageSize.height; - } - } - return elem; - } - createSectionContent(props) { - var elem = this.createElement("article"); - if (props.columns && props.columns.numberOfColumns) { - elem.style.columnCount = `${props.columns.numberOfColumns}`; - elem.style.columnGap = props.columns.space; - if (props.columns.separator) { - elem.style.columnRule = "1px solid black"; - } - } - return elem; - } - renderSections(document) { - const result = []; - this.processElement(document); - const sections = this.splitBySection(document.children, document.props); - const pages = this.groupByPageBreaks(sections); - let prevProps = null; - for (let i = 0, l = pages.length; i < l; i++) { - this.currentFootnoteIds = []; - const section = pages[i][0]; - let props = section.sectProps; - const pageElement = this.createPageElement(this.className, props); - this.renderStyleValues(document.cssStyle, pageElement); - this.options.renderHeaders && this.renderHeaderFooter(props.headerRefs, props, result.length, prevProps != props, pageElement); - for (const sect of pages[i]) { - var contentElement = this.createSectionContent(sect.sectProps); - this.renderElements(sect.elements, contentElement); - pageElement.appendChild(contentElement); - props = sect.sectProps; - } - if (this.options.renderFootnotes) { - this.renderNotes(this.currentFootnoteIds, this.footnoteMap, pageElement); - } - if (this.options.renderEndnotes && i == l - 1) { - this.renderNotes(this.currentEndnoteIds, this.endnoteMap, pageElement); - } - this.options.renderFooters && this.renderHeaderFooter(props.footerRefs, props, result.length, prevProps != props, pageElement); - result.push(pageElement); - prevProps = props; - } - return result; - } - renderHeaderFooter(refs, props, page, firstOfSection, into) { - if (!refs) - return; - var ref = (props.titlePage && firstOfSection ? refs.find(x => x.type == "first") : null) - ?? (page % 2 == 1 ? refs.find(x => x.type == "even") : null) - ?? refs.find(x => x.type == "default"); - var part = ref && this.document.findPartByRelId(ref.id, this.document.documentPart); - if (part) { - this.currentPart = part; - if (!this.usedHederFooterParts.includes(part.path)) { - this.processElement(part.rootElement); - this.usedHederFooterParts.push(part.path); - } - const [el] = this.renderElements([part.rootElement], into); - if (props?.pageMargins) { - if (part.rootElement.type === DomType.Header) { - el.style.marginTop = `calc(${props.pageMargins.header} - ${props.pageMargins.top})`; - el.style.minHeight = `calc(${props.pageMargins.top} - ${props.pageMargins.header})`; - } - else if (part.rootElement.type === DomType.Footer) { - el.style.marginBottom = `calc(${props.pageMargins.footer} - ${props.pageMargins.bottom})`; - el.style.minHeight = `calc(${props.pageMargins.bottom} - ${props.pageMargins.footer})`; - } - } - this.currentPart = null; - } - } - isPageBreakElement(elem) { - if (elem.type != DomType.Break) - return false; - if (elem.break == "lastRenderedPageBreak") - return !this.options.ignoreLastRenderedPageBreak; - return elem.break == "page"; - } - isPageBreakSection(prev, next) { - if (!prev) - return false; - if (!next) - return false; - return prev.pageSize?.orientation != next.pageSize?.orientation - || prev.pageSize?.width != next.pageSize?.width - || prev.pageSize?.height != next.pageSize?.height; - } - splitBySection(elements, defaultProps) { - var current = { sectProps: null, elements: [], pageBreak: false }; - var result = [current]; - for (let elem of elements) { - if (elem.type == DomType.Paragraph) { - const s = this.findStyle(elem.styleName); - if (s?.paragraphProps?.pageBreakBefore) { - current.sectProps = sectProps; - current.pageBreak = true; - current = { sectProps: null, elements: [], pageBreak: false }; - result.push(current); - } - } - current.elements.push(elem); - if (elem.type == DomType.Paragraph) { - const p = elem; - var sectProps = p.sectionProps; - var pBreakIndex = -1; - var rBreakIndex = -1; - if (this.options.breakPages && p.children) { - pBreakIndex = p.children.findIndex(r => { - rBreakIndex = r.children?.findIndex(this.isPageBreakElement.bind(this)) ?? -1; - return rBreakIndex != -1; - }); - } - if (sectProps || pBreakIndex != -1) { - current.sectProps = sectProps; - current.pageBreak = pBreakIndex != -1; - current = { sectProps: null, elements: [], pageBreak: false }; - result.push(current); - } - if (pBreakIndex != -1) { - let breakRun = p.children[pBreakIndex]; - let splitRun = rBreakIndex < breakRun.children.length - 1; - if (pBreakIndex < p.children.length - 1 || splitRun) { - var children = elem.children; - var newParagraph = { ...elem, children: children.slice(pBreakIndex) }; - elem.children = children.slice(0, pBreakIndex); - current.elements.push(newParagraph); - if (splitRun) { - let runChildren = breakRun.children; - let newRun = { ...breakRun, children: runChildren.slice(0, rBreakIndex) }; - elem.children.push(newRun); - breakRun.children = runChildren.slice(rBreakIndex); - } - } - } - } - } - let currentSectProps = null; - for (let i = result.length - 1; i >= 0; i--) { - if (result[i].sectProps == null) { - result[i].sectProps = currentSectProps ?? defaultProps; - } - else { - currentSectProps = result[i].sectProps; - } - } - return result; - } - groupByPageBreaks(sections) { - let current = []; - let prev; - const result = [current]; - for (let s of sections) { - current.push(s); - if (this.options.ignoreLastRenderedPageBreak || s.pageBreak || this.isPageBreakSection(prev, s.sectProps)) - result.push(current = []); - prev = s.sectProps; - } - return result.filter(x => x.length > 0); - } - renderWrapper(children) { - return this.createElement("div", { className: `${this.className}-wrapper` }, children); - } - renderDefaultStyle() { - var c = this.className; - var wrapperStyle = ` -.${c}-wrapper { background: gray; padding: 30px; padding-bottom: 0px; display: flex; flex-flow: column; align-items: center; } -.${c}-wrapper>section.${c} { background: white; box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); margin-bottom: 30px; }`; - if (this.options.hideWrapperOnPrint) { - wrapperStyle = `@media not print { ${wrapperStyle} }`; - } - var styleText = `${wrapperStyle} -.${c} { color: black; hyphens: auto; text-underline-position: from-font; } -section.${c} { box-sizing: border-box; display: flex; flex-flow: column nowrap; position: relative; overflow: hidden; } -section.${c}>article { margin-bottom: auto; z-index: 1; } -section.${c}>footer { z-index: 1; } -.${c} table { border-collapse: collapse; } -.${c} table td, .${c} table th { vertical-align: top; } -.${c} p { margin: 0pt; min-height: 1em; } -.${c} span { white-space: pre-wrap; overflow-wrap: break-word; } -.${c} a { color: inherit; text-decoration: inherit; } -.${c} svg { fill: transparent; } -`; - if (this.options.renderComments) { - styleText += ` -.${c}-comment-ref { cursor: default; } -.${c}-comment-popover { display: none; z-index: 1000; padding: 0.5rem; background: white; position: absolute; box-shadow: 0 0 0.25rem rgba(0, 0, 0, 0.25); width: 30ch; } -.${c}-comment-ref:hover~.${c}-comment-popover { display: block; } -.${c}-comment-author,.${c}-comment-date { font-size: 0.875rem; color: #888; } -`; - } - return this.createStyleElement(styleText); - } - renderNumbering(numberings, styleContainer) { - var styleText = ""; - var resetCounters = []; - for (var num of numberings) { - var selector = `p.${this.numberingClass(num.id, num.level)}`; - var listStyleType = "none"; - if (num.bullet) { - let valiable = `--${this.className}-${num.bullet.src}`.toLowerCase(); - styleText += this.styleToString(`${selector}:before`, { - "content": "' '", - "display": "inline-block", - "background": `var(${valiable})` - }, num.bullet.style); - this.tasks.push(this.document.loadNumberingImage(num.bullet.src).then(data => { - var text = `${this.rootSelector} { ${valiable}: url(${data}) }`; - styleContainer.appendChild(this.createStyleElement(text)); - })); - } - else if (num.levelText) { - let counter = this.numberingCounter(num.id, num.level); - const counterReset = counter + " " + (num.start - 1); - if (num.level > 0) { - styleText += this.styleToString(`p.${this.numberingClass(num.id, num.level - 1)}`, { - "counter-set": counterReset - }); - } - resetCounters.push(counterReset); - styleText += this.styleToString(`${selector}:before`, { - "content": this.levelTextToContent(num.levelText, num.suff, num.id, this.numFormatToCssValue(num.format)), - "counter-increment": counter, - ...num.rStyle, - }); - } - else { - listStyleType = this.numFormatToCssValue(num.format); - } - styleText += this.styleToString(selector, { - "display": "list-item", - "list-style-position": "inside", - "list-style-type": listStyleType, - ...num.pStyle - }); - } - if (resetCounters.length > 0) { - styleText += this.styleToString(this.rootSelector, { - "counter-reset": resetCounters.join(" ") - }); - } - return this.createStyleElement(styleText); - } - renderStyles(styles) { - var styleText = ""; - const stylesMap = this.styleMap; - const defautStyles = keyBy(styles.filter(s => s.isDefault), s => s.target); - for (const style of styles) { - var subStyles = style.styles; - if (style.linked) { - var linkedStyle = style.linked && stylesMap[style.linked]; - if (linkedStyle) - subStyles = subStyles.concat(linkedStyle.styles); - else if (this.options.debug) - console.warn(`Can't find linked style ${style.linked}`); - } - for (const subStyle of subStyles) { - var selector = `${style.target ?? ''}.${style.cssName}`; - if (style.target != subStyle.target) - selector += ` ${subStyle.target}`; - if (defautStyles[style.target] == style) - selector = `.${this.className} ${style.target}, ` + selector; - styleText += this.styleToString(selector, subStyle.values); - } - } - return this.createStyleElement(styleText); - } - renderNotes(noteIds, notesMap, into) { - var notes = noteIds.map(id => notesMap[id]).filter(x => x); - if (notes.length > 0) { - var result = this.createElement("ol", null, this.renderElements(notes)); - into.appendChild(result); - } - } - renderElement(elem) { - switch (elem.type) { - case DomType.Paragraph: - return this.renderParagraph(elem); - case DomType.BookmarkStart: - return this.renderBookmarkStart(elem); - case DomType.BookmarkEnd: - return null; - case DomType.Run: - return this.renderRun(elem); - case DomType.Table: - return this.renderTable(elem); - case DomType.Row: - return this.renderTableRow(elem); - case DomType.Cell: - return this.renderTableCell(elem); - case DomType.Hyperlink: - return this.renderHyperlink(elem); - case DomType.SmartTag: - return this.renderSmartTag(elem); - case DomType.Drawing: - return this.renderDrawing(elem); - case DomType.Image: - return this.renderImage(elem); - case DomType.Text: - return this.renderText(elem); - case DomType.Text: - return this.renderText(elem); - case DomType.DeletedText: - return this.renderDeletedText(elem); - case DomType.Tab: - return this.renderTab(elem); - case DomType.Symbol: - return this.renderSymbol(elem); - case DomType.Break: - return this.renderBreak(elem); - case DomType.Footer: - return this.renderContainer(elem, "footer"); - case DomType.Header: - return this.renderContainer(elem, "header"); - case DomType.Footnote: - case DomType.Endnote: - return this.renderContainer(elem, "li"); - case DomType.FootnoteReference: - return this.renderFootnoteReference(elem); - case DomType.EndnoteReference: - return this.renderEndnoteReference(elem); - case DomType.NoBreakHyphen: - return this.createElement("wbr"); - case DomType.VmlPicture: - return this.renderVmlPicture(elem); - case DomType.VmlElement: - return this.renderVmlElement(elem); - case DomType.MmlMath: - return this.renderContainerNS(elem, ns.mathML, "math", { xmlns: ns.mathML }); - case DomType.MmlMathParagraph: - return this.renderContainer(elem, "span"); - case DomType.MmlFraction: - return this.renderContainerNS(elem, ns.mathML, "mfrac"); - case DomType.MmlBase: - return this.renderContainerNS(elem, ns.mathML, elem.parent.type == DomType.MmlMatrixRow ? "mtd" : "mrow"); - case DomType.MmlNumerator: - case DomType.MmlDenominator: - case DomType.MmlFunction: - case DomType.MmlLimit: - case DomType.MmlBox: - return this.renderContainerNS(elem, ns.mathML, "mrow"); - case DomType.MmlGroupChar: - return this.renderMmlGroupChar(elem); - case DomType.MmlLimitLower: - return this.renderContainerNS(elem, ns.mathML, "munder"); - case DomType.MmlMatrix: - return this.renderContainerNS(elem, ns.mathML, "mtable"); - case DomType.MmlMatrixRow: - return this.renderContainerNS(elem, ns.mathML, "mtr"); - case DomType.MmlRadical: - return this.renderMmlRadical(elem); - case DomType.MmlSuperscript: - return this.renderContainerNS(elem, ns.mathML, "msup"); - case DomType.MmlSubscript: - return this.renderContainerNS(elem, ns.mathML, "msub"); - case DomType.MmlDegree: - case DomType.MmlSuperArgument: - case DomType.MmlSubArgument: - return this.renderContainerNS(elem, ns.mathML, "mn"); - case DomType.MmlFunctionName: - return this.renderContainerNS(elem, ns.mathML, "ms"); - case DomType.MmlDelimiter: - return this.renderMmlDelimiter(elem); - case DomType.MmlRun: - return this.renderMmlRun(elem); - case DomType.MmlNary: - return this.renderMmlNary(elem); - case DomType.MmlPreSubSuper: - return this.renderMmlPreSubSuper(elem); - case DomType.MmlBar: - return this.renderMmlBar(elem); - case DomType.MmlEquationArray: - return this.renderMllList(elem); - case DomType.Inserted: - return this.renderInserted(elem); - case DomType.Deleted: - return this.renderDeleted(elem); - case DomType.CommentRangeStart: - return this.renderCommentRangeStart(elem); - case DomType.CommentRangeEnd: - return this.renderCommentRangeEnd(elem); - case DomType.CommentReference: - return this.renderCommentReference(elem); - case DomType.AltChunk: - return this.renderAltChunk(elem); - } - return null; - } - renderElements(elems, into) { - if (elems == null) - return null; - var result = elems.flatMap(e => this.renderElement(e)).filter(e => e != null); - if (into) - appendChildren(into, result); - return result; - } - renderContainer(elem, tagName, props) { - return this.createElement(tagName, props, this.renderElements(elem.children)); - } - renderContainerNS(elem, ns, tagName, props) { - return this.createElementNS(ns, tagName, props, this.renderElements(elem.children)); - } - renderParagraph(elem) { - var result = this.renderContainer(elem, "p"); - const style = this.findStyle(elem.styleName); - elem.tabs ?? (elem.tabs = style?.paragraphProps?.tabs); - this.renderClass(elem, result); - this.renderStyleValues(elem.cssStyle, result); - this.renderCommonProperties(result.style, elem); - const numbering = elem.numbering ?? style?.paragraphProps?.numbering; - if (numbering) { - result.classList.add(this.numberingClass(numbering.id, numbering.level)); - } - return result; - } - renderRunProperties(style, props) { - this.renderCommonProperties(style, props); - } - renderCommonProperties(style, props) { - if (props == null) - return; - if (props.color) { - style["color"] = props.color; - } - if (props.fontSize) { - style["font-size"] = props.fontSize; - } - } - renderHyperlink(elem) { - var result = this.renderContainer(elem, "a"); - this.renderStyleValues(elem.cssStyle, result); - let href = ''; - if (elem.id) { - const rel = this.document.documentPart.rels.find(it => it.id == elem.id && it.targetMode === "External"); - href = rel?.target ?? href; - } - if (elem.anchor) { - href += `#${elem.anchor}`; - } - result.href = href; - return result; - } - renderSmartTag(elem) { - return this.renderContainer(elem, "span"); - } - renderCommentRangeStart(commentStart) { - if (!this.options.renderComments) - return null; - const rng = new Range(); - this.commentHighlight?.add(rng); - const result = this.createComment(`start of comment #${commentStart.id}`); - this.later(() => rng.setStart(result, 0)); - this.commentMap[commentStart.id] = rng; - return result; - } - renderCommentRangeEnd(commentEnd) { - if (!this.options.renderComments) - return null; - const rng = this.commentMap[commentEnd.id]; - const result = this.createComment(`end of comment #${commentEnd.id}`); - this.later(() => rng?.setEnd(result, 0)); - return result; - } - renderCommentReference(commentRef) { - if (!this.options.renderComments) - return null; - var comment = this.document.commentsPart?.commentMap[commentRef.id]; - if (!comment) - return null; - const frg = new DocumentFragment(); - const commentRefEl = this.createElement("span", { className: `${this.className}-comment-ref` }, ['💬']); - const commentsContainerEl = this.createElement("div", { className: `${this.className}-comment-popover` }); - this.renderCommentContent(comment, commentsContainerEl); - frg.appendChild(this.createComment(`comment #${comment.id} by ${comment.author} on ${comment.date}`)); - frg.appendChild(commentRefEl); - frg.appendChild(commentsContainerEl); - return frg; - } - renderAltChunk(elem) { - if (!this.options.renderAltChunks) - return null; - var result = this.createElement("iframe"); - this.tasks.push(this.document.loadAltChunk(elem.id, this.currentPart).then(x => { - result.srcdoc = x; - })); - return result; - } - renderCommentContent(comment, container) { - container.appendChild(this.createElement('div', { className: `${this.className}-comment-author` }, [comment.author])); - container.appendChild(this.createElement('div', { className: `${this.className}-comment-date` }, [new Date(comment.date).toLocaleString()])); - this.renderElements(comment.children, container); - } - renderDrawing(elem) { - var result = this.renderContainer(elem, "div"); - result.style.display = "inline-block"; - result.style.position = "relative"; - result.style.textIndent = "0px"; - this.renderStyleValues(elem.cssStyle, result); - return result; - } - renderImage(elem) { - let result = this.createElement("img"); - let transform = elem.cssStyle?.transform; - this.renderStyleValues(elem.cssStyle, result); - if (elem.srcRect && elem.srcRect.some(x => x != 0)) { - var [left, top, right, bottom] = elem.srcRect; - transform = `scale(${1 / (1 - left - right)}, ${1 / (1 - top - bottom)})`; - result.style['clip-path'] = `rect(${(100 * top).toFixed(2)}% ${(100 * (1 - right)).toFixed(2)}% ${(100 * (1 - bottom)).toFixed(2)}% ${(100 * left).toFixed(2)}%)`; - } - if (elem.rotation) - transform = `rotate(${elem.rotation}deg) ${transform ?? ''}`; - result.style.transform = transform?.trim(); - if (this.document) { - this.tasks.push(this.document.loadDocumentImage(elem.src, this.currentPart).then(x => { - result.src = x; - })); - } - return result; - } - renderText(elem) { - return this.htmlDocument.createTextNode(elem.text); - } - renderDeletedText(elem) { - return this.options.renderChanges ? this.renderText(elem) : null; - } - renderBreak(elem) { - if (elem.break == "textWrapping") { - return this.createElement("br"); - } - return null; - } - renderInserted(elem) { - if (this.options.renderChanges) - return this.renderContainer(elem, "ins"); - return this.renderElements(elem.children); - } - renderDeleted(elem) { - if (this.options.renderChanges) - return this.renderContainer(elem, "del"); - return null; - } - renderSymbol(elem) { - var span = this.createElement("span"); - span.style.fontFamily = elem.font; - span.innerHTML = `&#x${elem.char};`; - return span; - } - renderFootnoteReference(elem) { - var result = this.createElement("sup"); - this.currentFootnoteIds.push(elem.id); - result.textContent = `${this.currentFootnoteIds.length}`; - return result; - } - renderEndnoteReference(elem) { - var result = this.createElement("sup"); - this.currentEndnoteIds.push(elem.id); - result.textContent = `${this.currentEndnoteIds.length}`; - return result; - } - renderTab(elem) { - var tabSpan = this.createElement("span"); - tabSpan.innerHTML = " "; - if (this.options.experimental) { - tabSpan.className = this.tabStopClass(); - var stops = findParent(elem, DomType.Paragraph)?.tabs; - this.currentTabs.push({ stops, span: tabSpan }); - } - return tabSpan; - } - renderBookmarkStart(elem) { - return this.createElement("span", { id: elem.name }); - } - renderRun(elem) { - if (elem.fieldRun) - return null; - const result = this.createElement("span"); - if (elem.id) - result.id = elem.id; - this.renderClass(elem, result); - this.renderStyleValues(elem.cssStyle, result); - if (elem.verticalAlign) { - const wrapper = this.createElement(elem.verticalAlign); - this.renderElements(elem.children, wrapper); - result.appendChild(wrapper); - } - else { - this.renderElements(elem.children, result); - } - return result; - } - renderTable(elem) { - let result = this.createElement("table"); - this.tableCellPositions.push(this.currentCellPosition); - this.tableVerticalMerges.push(this.currentVerticalMerge); - this.currentVerticalMerge = {}; - this.currentCellPosition = { col: 0, row: 0 }; - if (elem.columns) - result.appendChild(this.renderTableColumns(elem.columns)); - this.renderClass(elem, result); - this.renderElements(elem.children, result); - this.renderStyleValues(elem.cssStyle, result); - this.currentVerticalMerge = this.tableVerticalMerges.pop(); - this.currentCellPosition = this.tableCellPositions.pop(); - return result; - } - renderTableColumns(columns) { - let result = this.createElement("colgroup"); - for (let col of columns) { - let colElem = this.createElement("col"); - if (col.width) - colElem.style.width = col.width; - result.appendChild(colElem); - } - return result; - } - renderTableRow(elem) { - let result = this.createElement("tr"); - this.currentCellPosition.col = 0; - if (elem.gridBefore) - result.appendChild(this.renderTableCellPlaceholder(elem.gridBefore)); - this.renderClass(elem, result); - this.renderElements(elem.children, result); - this.renderStyleValues(elem.cssStyle, result); - if (elem.gridAfter) - result.appendChild(this.renderTableCellPlaceholder(elem.gridAfter)); - this.currentCellPosition.row++; - return result; - } - renderTableCellPlaceholder(colSpan) { - const result = this.createElement("td", { colSpan }); - result.style['border'] = 'none'; - return result; - } - renderTableCell(elem) { - let result = this.renderContainer(elem, "td"); - const key = this.currentCellPosition.col; - if (elem.verticalMerge) { - if (elem.verticalMerge == "restart") { - this.currentVerticalMerge[key] = result; - result.rowSpan = 1; - } - else if (this.currentVerticalMerge[key]) { - this.currentVerticalMerge[key].rowSpan += 1; - result.style.display = "none"; - } - } - else { - this.currentVerticalMerge[key] = null; - } - this.renderClass(elem, result); - this.renderStyleValues(elem.cssStyle, result); - if (elem.span) - result.colSpan = elem.span; - this.currentCellPosition.col += result.colSpan; - return result; - } - renderVmlPicture(elem) { - return this.renderContainer(elem, "div"); - } - renderVmlElement(elem) { - var container = this.createSvgElement("svg"); - container.setAttribute("style", elem.cssStyleText); - const result = this.renderVmlChildElement(elem); - if (elem.imageHref?.id) { - this.tasks.push(this.document?.loadDocumentImage(elem.imageHref.id, this.currentPart) - .then(x => result.setAttribute("href", x))); - } - container.appendChild(result); - requestAnimationFrame(() => { - const bb = container.firstElementChild.getBBox(); - container.setAttribute("width", `${Math.ceil(bb.x + bb.width)}`); - container.setAttribute("height", `${Math.ceil(bb.y + bb.height)}`); - }); - return container; - } - renderVmlChildElement(elem) { - const result = this.createSvgElement(elem.tagName); - Object.entries(elem.attrs).forEach(([k, v]) => result.setAttribute(k, v)); - for (let child of elem.children) { - if (child.type == DomType.VmlElement) { - result.appendChild(this.renderVmlChildElement(child)); - } - else { - result.appendChild(...asArray(this.renderElement(child))); - } - } - return result; - } - renderMmlRadical(elem) { - const base = elem.children.find(el => el.type == DomType.MmlBase); - if (elem.props?.hideDegree) { - return this.createElementNS(ns.mathML, "msqrt", null, this.renderElements([base])); - } - const degree = elem.children.find(el => el.type == DomType.MmlDegree); - return this.createElementNS(ns.mathML, "mroot", null, this.renderElements([base, degree])); - } - renderMmlDelimiter(elem) { - const children = []; - children.push(this.createElementNS(ns.mathML, "mo", null, [elem.props.beginChar ?? '('])); - children.push(...this.renderElements(elem.children)); - children.push(this.createElementNS(ns.mathML, "mo", null, [elem.props.endChar ?? ')'])); - return this.createElementNS(ns.mathML, "mrow", null, children); - } - renderMmlNary(elem) { - const children = []; - const grouped = keyBy(elem.children, x => x.type); - const sup = grouped[DomType.MmlSuperArgument]; - const sub = grouped[DomType.MmlSubArgument]; - const supElem = sup ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sup))) : null; - const subElem = sub ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sub))) : null; - const charElem = this.createElementNS(ns.mathML, "mo", null, [elem.props?.char ?? '\u222B']); - if (supElem || subElem) { - children.push(this.createElementNS(ns.mathML, "munderover", null, [charElem, subElem, supElem])); - } - else if (supElem) { - children.push(this.createElementNS(ns.mathML, "mover", null, [charElem, supElem])); - } - else if (subElem) { - children.push(this.createElementNS(ns.mathML, "munder", null, [charElem, subElem])); - } - else { - children.push(charElem); - } - children.push(...this.renderElements(grouped[DomType.MmlBase].children)); - return this.createElementNS(ns.mathML, "mrow", null, children); - } - renderMmlPreSubSuper(elem) { - const children = []; - const grouped = keyBy(elem.children, x => x.type); - const sup = grouped[DomType.MmlSuperArgument]; - const sub = grouped[DomType.MmlSubArgument]; - const supElem = sup ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sup))) : null; - const subElem = sub ? this.createElementNS(ns.mathML, "mo", null, asArray(this.renderElement(sub))) : null; - const stubElem = this.createElementNS(ns.mathML, "mo", null); - children.push(this.createElementNS(ns.mathML, "msubsup", null, [stubElem, subElem, supElem])); - children.push(...this.renderElements(grouped[DomType.MmlBase].children)); - return this.createElementNS(ns.mathML, "mrow", null, children); - } - renderMmlGroupChar(elem) { - const tagName = elem.props.verticalJustification === "bot" ? "mover" : "munder"; - const result = this.renderContainerNS(elem, ns.mathML, tagName); - if (elem.props.char) { - result.appendChild(this.createElementNS(ns.mathML, "mo", null, [elem.props.char])); - } - return result; - } - renderMmlBar(elem) { - const result = this.renderContainerNS(elem, ns.mathML, "mrow"); - switch (elem.props.position) { - case "top": - result.style.textDecoration = "overline"; - break; - case "bottom": - result.style.textDecoration = "underline"; - break; - } - return result; - } - renderMmlRun(elem) { - const result = this.createElementNS(ns.mathML, "ms", null, this.renderElements(elem.children)); - this.renderClass(elem, result); - this.renderStyleValues(elem.cssStyle, result); - return result; - } - renderMllList(elem) { - const result = this.createElementNS(ns.mathML, "mtable"); - this.renderClass(elem, result); - this.renderStyleValues(elem.cssStyle, result); - for (let child of this.renderElements(elem.children)) { - result.appendChild(this.createElementNS(ns.mathML, "mtr", null, [ - this.createElementNS(ns.mathML, "mtd", null, [child]) - ])); - } - return result; - } - renderStyleValues(style, ouput) { - for (let k in style) { - if (k.startsWith("$")) { - ouput.setAttribute(k.slice(1), style[k]); - } - else { - ouput.style[k] = style[k]; - } - } - } - renderClass(input, ouput) { - if (input.className) - ouput.className = input.className; - if (input.styleName) - ouput.classList.add(this.processStyleName(input.styleName)); - } - findStyle(styleName) { - return styleName && this.styleMap?.[styleName]; - } - numberingClass(id, lvl) { - return `${this.className}-num-${id}-${lvl}`; - } - tabStopClass() { - return `${this.className}-tab-stop`; - } - styleToString(selectors, values, cssText = null) { - let result = `${selectors} {\r\n`; - for (const key in values) { - if (key.startsWith('$')) - continue; - result += ` ${key}: ${values[key]};\r\n`; - } - if (cssText) - result += cssText; - return result + "}\r\n"; - } - numberingCounter(id, lvl) { - return `${this.className}-num-${id}-${lvl}`; - } - levelTextToContent(text, suff, id, numformat) { - const suffMap = { - "tab": "\\9", - "space": "\\a0", - }; - var result = text.replace(/%\d*/g, s => { - let lvl = parseInt(s.substring(1), 10) - 1; - return `"counter(${this.numberingCounter(id, lvl)}, ${numformat})"`; - }); - return `"${result}${suffMap[suff] ?? ""}"`; - } - numFormatToCssValue(format) { - var mapping = { - none: "none", - bullet: "disc", - decimal: "decimal", - lowerLetter: "lower-alpha", - upperLetter: "upper-alpha", - lowerRoman: "lower-roman", - upperRoman: "upper-roman", - decimalZero: "decimal-leading-zero", - aiueo: "katakana", - aiueoFullWidth: "katakana", - chineseCounting: "simp-chinese-informal", - chineseCountingThousand: "simp-chinese-informal", - chineseLegalSimplified: "simp-chinese-formal", - chosung: "hangul-consonant", - ideographDigital: "cjk-ideographic", - ideographTraditional: "cjk-heavenly-stem", - ideographLegalTraditional: "trad-chinese-formal", - ideographZodiac: "cjk-earthly-branch", - iroha: "katakana-iroha", - irohaFullWidth: "katakana-iroha", - japaneseCounting: "japanese-informal", - japaneseDigitalTenThousand: "cjk-decimal", - japaneseLegal: "japanese-formal", - thaiNumbers: "thai", - koreanCounting: "korean-hangul-formal", - koreanDigital: "korean-hangul-formal", - koreanDigital2: "korean-hanja-informal", - hebrew1: "hebrew", - hebrew2: "hebrew", - hindiNumbers: "devanagari", - ganada: "hangul", - taiwaneseCounting: "cjk-ideographic", - taiwaneseCountingThousand: "cjk-ideographic", - taiwaneseDigital: "cjk-decimal", - }; - return mapping[format] ?? format; - } - refreshTabStops() { - if (!this.options.experimental) - return; - setTimeout(() => { - const pixelToPoint = computePixelToPoint(); - for (let tab of this.currentTabs) { - updateTabStop(tab.span, tab.stops, this.defaultTabSize, pixelToPoint); - } - }, 500); - } - createElementNS(ns, tagName, props, children) { - var result = ns ? this.htmlDocument.createElementNS(ns, tagName) : this.htmlDocument.createElement(tagName); - Object.assign(result, props); - children && appendChildren(result, children); - return result; - } - createElement(tagName, props, children) { - return this.createElementNS(undefined, tagName, props, children); - } - createSvgElement(tagName, props, children) { - return this.createElementNS(ns.svg, tagName, props, children); - } - createStyleElement(cssText) { - return this.createElement("style", { innerHTML: cssText }); - } - createComment(text) { - return this.htmlDocument.createComment(text); - } - later(func) { - this.postRenderTasks.push(func); - } -} -function removeAllElements(elem) { - elem.innerHTML = ''; -} -function appendChildren(elem, children) { - children.forEach(c => elem.appendChild(isString(c) ? document.createTextNode(c) : c)); -} -function findParent(elem, type) { - var parent = elem.parent; - while (parent != null && parent.type != type) - parent = parent.parent; - return parent; -} - -const defaultOptions = { - ignoreHeight: false, - ignoreWidth: false, - ignoreFonts: false, - breakPages: true, - debug: false, - experimental: false, - className: "docx", - inWrapper: true, - hideWrapperOnPrint: false, - trimXmlDeclaration: true, - ignoreLastRenderedPageBreak: true, - renderHeaders: true, - renderFooters: true, - renderFootnotes: true, - renderEndnotes: true, - useBase64URL: false, - renderChanges: false, - renderComments: false, - renderAltChunks: true -}; -function parseAsync(data, userOptions) { - const ops = { ...defaultOptions, ...userOptions }; - return WordDocument.load(data, new DocumentParser(ops), ops); -} -async function renderDocument(document, bodyContainer, styleContainer, userOptions) { - const ops = { ...defaultOptions, ...userOptions }; - const renderer = new HtmlRenderer(window.document); - return await renderer.render(document, bodyContainer, styleContainer, ops); -} -async function renderAsync(data, bodyContainer, styleContainer, userOptions) { - const doc = await parseAsync(data, userOptions); - await renderDocument(doc, bodyContainer, styleContainer, userOptions); - return doc; -} - -export { defaultOptions, parseAsync, renderAsync, renderDocument }; -//# sourceMappingURL=docx-preview.mjs.map diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.mjs.map b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.mjs.map deleted file mode 100644 index dc2da7b05..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/docx-preview/dist/docx-preview.mjs.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"docx-preview.mjs","sources":["../src/common/relationship.ts","../src/utils.ts","../src/document/common.ts","../src/parser/xml-parser.ts","../src/common/part.ts","../src/font-table/fonts.ts","../src/font-table/font-table.ts","../src/common/open-xml-package.ts","../src/document/document-part.ts","../src/document/border.ts","../src/document/section.ts","../src/document/line-spacing.ts","../src/document/run.ts","../src/document/paragraph.ts","../src/numbering/numbering.ts","../src/numbering/numbering-part.ts","../src/styles/styles-part.ts","../src/document/dom.ts","../src/header-footer/elements.ts","../src/header-footer/parts.ts","../src/document-props/extended-props.ts","../src/document-props/extended-props-part.ts","../src/document-props/core-props.ts","../src/document-props/core-props-part.ts","../src/theme/theme.ts","../src/theme/theme-part.ts","../src/notes/elements.ts","../src/notes/parts.ts","../src/settings/settings.ts","../src/settings/settings-part.ts","../src/document-props/custom-props.ts","../src/document-props/custom-props-part.ts","../src/comments/comments-part.ts","../src/comments/comments-extended-part.ts","../src/word-document.ts","../src/document/bookmarks.ts","../src/vml/vml.ts","../src/comments/elements.ts","../src/document-parser.ts","../src/javascript.ts","../src/html-renderer.ts","../src/docx-preview.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["ns","parseNumbering","xml"],"mappings":";;;;;;;;AASA,IAAY,iBAqBX;AArBD,CAAA,UAAY,iBAAiB,EAAA;AACzB,IAAA,iBAAA,CAAA,gBAAA,CAAA,GAAA,oFAAqG;AACrG,IAAA,iBAAA,CAAA,WAAA,CAAA,GAAA,+EAA2F;AAC3F,IAAA,iBAAA,CAAA,OAAA,CAAA,GAAA,2EAAmF;AACnF,IAAA,iBAAA,CAAA,WAAA,CAAA,GAAA,+EAA2F;AAC3F,IAAA,iBAAA,CAAA,QAAA,CAAA,GAAA,4EAAqF;AACrF,IAAA,iBAAA,CAAA,mBAAA,CAAA,GAAA,0EAA8F;AAC9F,IAAA,iBAAA,CAAA,OAAA,CAAA,GAAA,2EAAmF;AACnF,IAAA,iBAAA,CAAA,UAAA,CAAA,GAAA,8EAAyF;AACzF,IAAA,iBAAA,CAAA,aAAA,CAAA,GAAA,iFAA+F;AAC/F,IAAA,iBAAA,CAAA,WAAA,CAAA,GAAA,+EAA2F;AAC3F,IAAA,iBAAA,CAAA,WAAA,CAAA,GAAA,+EAA2F;AAC9F,IAAA,iBAAA,CAAA,UAAA,CAAA,GAAA,8EAAyF;AACtF,IAAA,iBAAA,CAAA,QAAA,CAAA,GAAA,4EAAqF;AACrF,IAAA,iBAAA,CAAA,QAAA,CAAA,GAAA,4EAAqF;AACrF,IAAA,iBAAA,CAAA,oBAAA,CAAA,GAAA,yFAA8G;AAC9G,IAAA,iBAAA,CAAA,gBAAA,CAAA,GAAA,uFAAwG;AAC3G,IAAA,iBAAA,CAAA,kBAAA,CAAA,GAAA,yFAA4G;AAC5G,IAAA,iBAAA,CAAA,UAAA,CAAA,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3E;AAEO,eAAe,WAAW,CAAC,IAAgB,EAAE,aAA0B,EAAE,cAA4B,EAAE,WAA8B,EAAA;IAC3I,MAAM,GAAG,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,WAAW,CAAC;IAC/C,MAAM,cAAc,CAAC,GAAG,EAAE,aAAa,EAAE,cAAc,EAAE,WAAW,CAAC;AAClE,IAAA,OAAO,GAAG;AACd;;;;"} \ No newline at end of file diff --git a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/jszip/dist/jszip.js b/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/jszip/dist/jszip.js deleted file mode 100644 index 60fbb41a6..000000000 --- a/apps/macos/Sources/Clawdis/Resources/WebChat/vendor/jszip/dist/jszip.js +++ /dev/null @@ -1,11577 +0,0 @@ -/*! - -JSZip v3.10.1 - A JavaScript class for generating and reading zip files - - -(c) 2009-2016 Stuart Knightley -Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. - -JSZip uses the library pako released under the MIT license : -https://github.com/nodeca/pako/blob/main/LICENSE -*/ - -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JSZip = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o> 2; - enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); - enc3 = remainingBytes > 1 ? (((chr2 & 15) << 2) | (chr3 >> 6)) : 64; - enc4 = remainingBytes > 2 ? (chr3 & 63) : 64; - - output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4)); - - } - - return output.join(""); -}; - -// public method for decoding -exports.decode = function(input) { - var chr1, chr2, chr3; - var enc1, enc2, enc3, enc4; - var i = 0, resultIndex = 0; - - var dataUrlPrefix = "data:"; - - if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) { - // This is a common error: people give a data url - // (data:image/png;base64,iVBOR...) with a {base64: true} and - // wonders why things don't work. - // We can detect that the string input looks like a data url but we - // *can't* be sure it is one: removing everything up to the comma would - // be too dangerous. - throw new Error("Invalid base64 input, it looks like a data url."); - } - - input = input.replace(/[^A-Za-z0-9+/=]/g, ""); - - var totalLength = input.length * 3 / 4; - if(input.charAt(input.length - 1) === _keyStr.charAt(64)) { - totalLength--; - } - if(input.charAt(input.length - 2) === _keyStr.charAt(64)) { - totalLength--; - } - if (totalLength % 1 !== 0) { - // totalLength is not an integer, the length does not match a valid - // base64 content. That can happen if: - // - the input is not a base64 content - // - the input is *almost* a base64 content, with a extra chars at the - // beginning or at the end - // - the input uses a base64 variant (base64url for example) - throw new Error("Invalid base64 input, bad content length."); - } - var output; - if (support.uint8array) { - output = new Uint8Array(totalLength|0); - } else { - output = new Array(totalLength|0); - } - - while (i < input.length) { - - enc1 = _keyStr.indexOf(input.charAt(i++)); - enc2 = _keyStr.indexOf(input.charAt(i++)); - enc3 = _keyStr.indexOf(input.charAt(i++)); - enc4 = _keyStr.indexOf(input.charAt(i++)); - - chr1 = (enc1 << 2) | (enc2 >> 4); - chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); - chr3 = ((enc3 & 3) << 6) | enc4; - - output[resultIndex++] = chr1; - - if (enc3 !== 64) { - output[resultIndex++] = chr2; - } - if (enc4 !== 64) { - output[resultIndex++] = chr3; - } - - } - - return output; -}; - -},{"./support":30,"./utils":32}],2:[function(require,module,exports){ -"use strict"; - -var external = require("./external"); -var DataWorker = require("./stream/DataWorker"); -var Crc32Probe = require("./stream/Crc32Probe"); -var DataLengthProbe = require("./stream/DataLengthProbe"); - -/** - * Represent a compressed object, with everything needed to decompress it. - * @constructor - * @param {number} compressedSize the size of the data compressed. - * @param {number} uncompressedSize the size of the data after decompression. - * @param {number} crc32 the crc32 of the decompressed file. - * @param {object} compression the type of compression, see lib/compressions.js. - * @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data. - */ -function CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) { - this.compressedSize = compressedSize; - this.uncompressedSize = uncompressedSize; - this.crc32 = crc32; - this.compression = compression; - this.compressedContent = data; -} - -CompressedObject.prototype = { - /** - * Create a worker to get the uncompressed content. - * @return {GenericWorker} the worker. - */ - getContentWorker: function () { - var worker = new DataWorker(external.Promise.resolve(this.compressedContent)) - .pipe(this.compression.uncompressWorker()) - .pipe(new DataLengthProbe("data_length")); - - var that = this; - worker.on("end", function () { - if (this.streamInfo["data_length"] !== that.uncompressedSize) { - throw new Error("Bug : uncompressed data size mismatch"); - } - }); - return worker; - }, - /** - * Create a worker to get the compressed content. - * @return {GenericWorker} the worker. - */ - getCompressedWorker: function () { - return new DataWorker(external.Promise.resolve(this.compressedContent)) - .withStreamInfo("compressedSize", this.compressedSize) - .withStreamInfo("uncompressedSize", this.uncompressedSize) - .withStreamInfo("crc32", this.crc32) - .withStreamInfo("compression", this.compression) - ; - } -}; - -/** - * Chain the given worker with other workers to compress the content with the - * given compression. - * @param {GenericWorker} uncompressedWorker the worker to pipe. - * @param {Object} compression the compression object. - * @param {Object} compressionOptions the options to use when compressing. - * @return {GenericWorker} the new worker compressing the content. - */ -CompressedObject.createWorkerFrom = function (uncompressedWorker, compression, compressionOptions) { - return uncompressedWorker - .pipe(new Crc32Probe()) - .pipe(new DataLengthProbe("uncompressedSize")) - .pipe(compression.compressWorker(compressionOptions)) - .pipe(new DataLengthProbe("compressedSize")) - .withStreamInfo("compression", compression); -}; - -module.exports = CompressedObject; - -},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(require,module,exports){ -"use strict"; - -var GenericWorker = require("./stream/GenericWorker"); - -exports.STORE = { - magic: "\x00\x00", - compressWorker : function () { - return new GenericWorker("STORE compression"); - }, - uncompressWorker : function () { - return new GenericWorker("STORE decompression"); - } -}; -exports.DEFLATE = require("./flate"); - -},{"./flate":7,"./stream/GenericWorker":28}],4:[function(require,module,exports){ -"use strict"; - -var utils = require("./utils"); - -/** - * The following functions come from pako, from pako/lib/zlib/crc32.js - * released under the MIT license, see pako https://github.com/nodeca/pako/ - */ - -// Use ordinary array, since untyped makes no boost here -function makeTable() { - var c, table = []; - - for(var n =0; n < 256; n++){ - c = n; - for(var k =0; k < 8; k++){ - c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); - } - table[n] = c; - } - - return table; -} - -// Create table on load. Just 255 signed longs. Not a problem. -var crcTable = makeTable(); - - -function crc32(crc, buf, len, pos) { - var t = crcTable, end = pos + len; - - crc = crc ^ (-1); - - for (var i = pos; i < end; i++ ) { - crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; - } - - return (crc ^ (-1)); // >>> 0; -} - -// That's all for the pako functions. - -/** - * Compute the crc32 of a string. - * This is almost the same as the function crc32, but for strings. Using the - * same function for the two use cases leads to horrible performances. - * @param {Number} crc the starting value of the crc. - * @param {String} str the string to use. - * @param {Number} len the length of the string. - * @param {Number} pos the starting position for the crc32 computation. - * @return {Number} the computed crc32. - */ -function crc32str(crc, str, len, pos) { - var t = crcTable, end = pos + len; - - crc = crc ^ (-1); - - for (var i = pos; i < end; i++ ) { - crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF]; - } - - return (crc ^ (-1)); // >>> 0; -} - -module.exports = function crc32wrapper(input, crc) { - if (typeof input === "undefined" || !input.length) { - return 0; - } - - var isArray = utils.getTypeOf(input) !== "string"; - - if(isArray) { - return crc32(crc|0, input, input.length, 0); - } else { - return crc32str(crc|0, input, input.length, 0); - } -}; - -},{"./utils":32}],5:[function(require,module,exports){ -"use strict"; -exports.base64 = false; -exports.binary = false; -exports.dir = false; -exports.createFolders = true; -exports.date = null; -exports.compression = null; -exports.compressionOptions = null; -exports.comment = null; -exports.unixPermissions = null; -exports.dosPermissions = null; - -},{}],6:[function(require,module,exports){ -"use strict"; - -// load the global object first: -// - it should be better integrated in the system (unhandledRejection in node) -// - the environment may have a custom Promise implementation (see zone.js) -var ES6Promise = null; -if (typeof Promise !== "undefined") { - ES6Promise = Promise; -} else { - ES6Promise = require("lie"); -} - -/** - * Let the user use/change some implementations. - */ -module.exports = { - Promise: ES6Promise -}; - -},{"lie":37}],7:[function(require,module,exports){ -"use strict"; -var USE_TYPEDARRAY = (typeof Uint8Array !== "undefined") && (typeof Uint16Array !== "undefined") && (typeof Uint32Array !== "undefined"); - -var pako = require("pako"); -var utils = require("./utils"); -var GenericWorker = require("./stream/GenericWorker"); - -var ARRAY_TYPE = USE_TYPEDARRAY ? "uint8array" : "array"; - -exports.magic = "\x08\x00"; - -/** - * Create a worker that uses pako to inflate/deflate. - * @constructor - * @param {String} action the name of the pako function to call : either "Deflate" or "Inflate". - * @param {Object} options the options to use when (de)compressing. - */ -function FlateWorker(action, options) { - GenericWorker.call(this, "FlateWorker/" + action); - - this._pako = null; - this._pakoAction = action; - this._pakoOptions = options; - // the `meta` object from the last chunk received - // this allow this worker to pass around metadata - this.meta = {}; -} - -utils.inherits(FlateWorker, GenericWorker); - -/** - * @see GenericWorker.processChunk - */ -FlateWorker.prototype.processChunk = function (chunk) { - this.meta = chunk.meta; - if (this._pako === null) { - this._createPako(); - } - this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false); -}; - -/** - * @see GenericWorker.flush - */ -FlateWorker.prototype.flush = function () { - GenericWorker.prototype.flush.call(this); - if (this._pako === null) { - this._createPako(); - } - this._pako.push([], true); -}; -/** - * @see GenericWorker.cleanUp - */ -FlateWorker.prototype.cleanUp = function () { - GenericWorker.prototype.cleanUp.call(this); - this._pako = null; -}; - -/** - * Create the _pako object. - * TODO: lazy-loading this object isn't the best solution but it's the - * quickest. The best solution is to lazy-load the worker list. See also the - * issue #446. - */ -FlateWorker.prototype._createPako = function () { - this._pako = new pako[this._pakoAction]({ - raw: true, - level: this._pakoOptions.level || -1 // default compression - }); - var self = this; - this._pako.onData = function(data) { - self.push({ - data : data, - meta : self.meta - }); - }; -}; - -exports.compressWorker = function (compressionOptions) { - return new FlateWorker("Deflate", compressionOptions); -}; -exports.uncompressWorker = function () { - return new FlateWorker("Inflate", {}); -}; - -},{"./stream/GenericWorker":28,"./utils":32,"pako":38}],8:[function(require,module,exports){ -"use strict"; - -var utils = require("../utils"); -var GenericWorker = require("../stream/GenericWorker"); -var utf8 = require("../utf8"); -var crc32 = require("../crc32"); -var signature = require("../signature"); - -/** - * Transform an integer into a string in hexadecimal. - * @private - * @param {number} dec the number to convert. - * @param {number} bytes the number of bytes to generate. - * @returns {string} the result. - */ -var decToHex = function(dec, bytes) { - var hex = "", i; - for (i = 0; i < bytes; i++) { - hex += String.fromCharCode(dec & 0xff); - dec = dec >>> 8; - } - return hex; -}; - -/** - * Generate the UNIX part of the external file attributes. - * @param {Object} unixPermissions the unix permissions or null. - * @param {Boolean} isDir true if the entry is a directory, false otherwise. - * @return {Number} a 32 bit integer. - * - * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute : - * - * TTTTsstrwxrwxrwx0000000000ADVSHR - * ^^^^____________________________ file type, see zipinfo.c (UNX_*) - * ^^^_________________________ setuid, setgid, sticky - * ^^^^^^^^^________________ permissions - * ^^^^^^^^^^______ not used ? - * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only - */ -var generateUnixExternalFileAttr = function (unixPermissions, isDir) { - - var result = unixPermissions; - if (!unixPermissions) { - // I can't use octal values in strict mode, hence the hexa. - // 040775 => 0x41fd - // 0100664 => 0x81b4 - result = isDir ? 0x41fd : 0x81b4; - } - return (result & 0xFFFF) << 16; -}; - -/** - * Generate the DOS part of the external file attributes. - * @param {Object} dosPermissions the dos permissions or null. - * @param {Boolean} isDir true if the entry is a directory, false otherwise. - * @return {Number} a 32 bit integer. - * - * Bit 0 Read-Only - * Bit 1 Hidden - * Bit 2 System - * Bit 3 Volume Label - * Bit 4 Directory - * Bit 5 Archive - */ -var generateDosExternalFileAttr = function (dosPermissions) { - // the dir flag is already set for compatibility - return (dosPermissions || 0) & 0x3F; -}; - -/** - * Generate the various parts used in the construction of the final zip file. - * @param {Object} streamInfo the hash with information about the compressed file. - * @param {Boolean} streamedContent is the content streamed ? - * @param {Boolean} streamingEnded is the stream finished ? - * @param {number} offset the current offset from the start of the zip file. - * @param {String} platform let's pretend we are this platform (change platform dependents fields) - * @param {Function} encodeFileName the function to encode the file name / comment. - * @return {Object} the zip parts. - */ -var generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) { - var file = streamInfo["file"], - compression = streamInfo["compression"], - useCustomEncoding = encodeFileName !== utf8.utf8encode, - encodedFileName = utils.transformTo("string", encodeFileName(file.name)), - utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)), - comment = file.comment, - encodedComment = utils.transformTo("string", encodeFileName(comment)), - utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)), - useUTF8ForFileName = utfEncodedFileName.length !== file.name.length, - useUTF8ForComment = utfEncodedComment.length !== comment.length, - dosTime, - dosDate, - extraFields = "", - unicodePathExtraField = "", - unicodeCommentExtraField = "", - dir = file.dir, - date = file.date; - - - var dataInfo = { - crc32 : 0, - compressedSize : 0, - uncompressedSize : 0 - }; - - // if the content is streamed, the sizes/crc32 are only available AFTER - // the end of the stream. - if (!streamedContent || streamingEnded) { - dataInfo.crc32 = streamInfo["crc32"]; - dataInfo.compressedSize = streamInfo["compressedSize"]; - dataInfo.uncompressedSize = streamInfo["uncompressedSize"]; - } - - var bitflag = 0; - if (streamedContent) { - // Bit 3: the sizes/crc32 are set to zero in the local header. - // The correct values are put in the data descriptor immediately - // following the compressed data. - bitflag |= 0x0008; - } - if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) { - // Bit 11: Language encoding flag (EFS). - bitflag |= 0x0800; - } - - - var extFileAttr = 0; - var versionMadeBy = 0; - if (dir) { - // dos or unix, we set the dos dir flag - extFileAttr |= 0x00010; - } - if(platform === "UNIX") { - versionMadeBy = 0x031E; // UNIX, version 3.0 - extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir); - } else { // DOS or other, fallback to DOS - versionMadeBy = 0x0014; // DOS, version 2.0 - extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir); - } - - // date - // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html - // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html - // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html - - dosTime = date.getUTCHours(); - dosTime = dosTime << 6; - dosTime = dosTime | date.getUTCMinutes(); - dosTime = dosTime << 5; - dosTime = dosTime | date.getUTCSeconds() / 2; - - dosDate = date.getUTCFullYear() - 1980; - dosDate = dosDate << 4; - dosDate = dosDate | (date.getUTCMonth() + 1); - dosDate = dosDate << 5; - dosDate = dosDate | date.getUTCDate(); - - if (useUTF8ForFileName) { - // set the unicode path extra field. unzip needs at least one extra - // field to correctly handle unicode path, so using the path is as good - // as any other information. This could improve the situation with - // other archive managers too. - // This field is usually used without the utf8 flag, with a non - // unicode path in the header (winrar, winzip). This helps (a bit) - // with the messy Windows' default compressed folders feature but - // breaks on p7zip which doesn't seek the unicode path extra field. - // So for now, UTF-8 everywhere ! - unicodePathExtraField = - // Version - decToHex(1, 1) + - // NameCRC32 - decToHex(crc32(encodedFileName), 4) + - // UnicodeName - utfEncodedFileName; - - extraFields += - // Info-ZIP Unicode Path Extra Field - "\x75\x70" + - // size - decToHex(unicodePathExtraField.length, 2) + - // content - unicodePathExtraField; - } - - if(useUTF8ForComment) { - - unicodeCommentExtraField = - // Version - decToHex(1, 1) + - // CommentCRC32 - decToHex(crc32(encodedComment), 4) + - // UnicodeName - utfEncodedComment; - - extraFields += - // Info-ZIP Unicode Path Extra Field - "\x75\x63" + - // size - decToHex(unicodeCommentExtraField.length, 2) + - // content - unicodeCommentExtraField; - } - - var header = ""; - - // version needed to extract - header += "\x0A\x00"; - // general purpose bit flag - header += decToHex(bitflag, 2); - // compression method - header += compression.magic; - // last mod file time - header += decToHex(dosTime, 2); - // last mod file date - header += decToHex(dosDate, 2); - // crc-32 - header += decToHex(dataInfo.crc32, 4); - // compressed size - header += decToHex(dataInfo.compressedSize, 4); - // uncompressed size - header += decToHex(dataInfo.uncompressedSize, 4); - // file name length - header += decToHex(encodedFileName.length, 2); - // extra field length - header += decToHex(extraFields.length, 2); - - - var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields; - - var dirRecord = signature.CENTRAL_FILE_HEADER + - // version made by (00: DOS) - decToHex(versionMadeBy, 2) + - // file header (common to file and central directory) - header + - // file comment length - decToHex(encodedComment.length, 2) + - // disk number start - "\x00\x00" + - // internal file attributes TODO - "\x00\x00" + - // external file attributes - decToHex(extFileAttr, 4) + - // relative offset of local header - decToHex(offset, 4) + - // file name - encodedFileName + - // extra field - extraFields + - // file comment - encodedComment; - - return { - fileRecord: fileRecord, - dirRecord: dirRecord - }; -}; - -/** - * Generate the EOCD record. - * @param {Number} entriesCount the number of entries in the zip file. - * @param {Number} centralDirLength the length (in bytes) of the central dir. - * @param {Number} localDirLength the length (in bytes) of the local dir. - * @param {String} comment the zip file comment as a binary string. - * @param {Function} encodeFileName the function to encode the comment. - * @return {String} the EOCD record. - */ -var generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) { - var dirEnd = ""; - var encodedComment = utils.transformTo("string", encodeFileName(comment)); - - // end of central dir signature - dirEnd = signature.CENTRAL_DIRECTORY_END + - // number of this disk - "\x00\x00" + - // number of the disk with the start of the central directory - "\x00\x00" + - // total number of entries in the central directory on this disk - decToHex(entriesCount, 2) + - // total number of entries in the central directory - decToHex(entriesCount, 2) + - // size of the central directory 4 bytes - decToHex(centralDirLength, 4) + - // offset of start of central directory with respect to the starting disk number - decToHex(localDirLength, 4) + - // .ZIP file comment length - decToHex(encodedComment.length, 2) + - // .ZIP file comment - encodedComment; - - return dirEnd; -}; - -/** - * Generate data descriptors for a file entry. - * @param {Object} streamInfo the hash generated by a worker, containing information - * on the file entry. - * @return {String} the data descriptors. - */ -var generateDataDescriptors = function (streamInfo) { - var descriptor = ""; - descriptor = signature.DATA_DESCRIPTOR + - // crc-32 4 bytes - decToHex(streamInfo["crc32"], 4) + - // compressed size 4 bytes - decToHex(streamInfo["compressedSize"], 4) + - // uncompressed size 4 bytes - decToHex(streamInfo["uncompressedSize"], 4); - - return descriptor; -}; - - -/** - * A worker to concatenate other workers to create a zip file. - * @param {Boolean} streamFiles `true` to stream the content of the files, - * `false` to accumulate it. - * @param {String} comment the comment to use. - * @param {String} platform the platform to use, "UNIX" or "DOS". - * @param {Function} encodeFileName the function to encode file names and comments. - */ -function ZipFileWorker(streamFiles, comment, platform, encodeFileName) { - GenericWorker.call(this, "ZipFileWorker"); - // The number of bytes written so far. This doesn't count accumulated chunks. - this.bytesWritten = 0; - // The comment of the zip file - this.zipComment = comment; - // The platform "generating" the zip file. - this.zipPlatform = platform; - // the function to encode file names and comments. - this.encodeFileName = encodeFileName; - // Should we stream the content of the files ? - this.streamFiles = streamFiles; - // If `streamFiles` is false, we will need to accumulate the content of the - // files to calculate sizes / crc32 (and write them *before* the content). - // This boolean indicates if we are accumulating chunks (it will change a lot - // during the lifetime of this worker). - this.accumulate = false; - // The buffer receiving chunks when accumulating content. - this.contentBuffer = []; - // The list of generated directory records. - this.dirRecords = []; - // The offset (in bytes) from the beginning of the zip file for the current source. - this.currentSourceOffset = 0; - // The total number of entries in this zip file. - this.entriesCount = 0; - // the name of the file currently being added, null when handling the end of the zip file. - // Used for the emitted metadata. - this.currentFile = null; - - - - this._sources = []; -} -utils.inherits(ZipFileWorker, GenericWorker); - -/** - * @see GenericWorker.push - */ -ZipFileWorker.prototype.push = function (chunk) { - - var currentFilePercent = chunk.meta.percent || 0; - var entriesCount = this.entriesCount; - var remainingFiles = this._sources.length; - - if(this.accumulate) { - this.contentBuffer.push(chunk); - } else { - this.bytesWritten += chunk.data.length; - - GenericWorker.prototype.push.call(this, { - data : chunk.data, - meta : { - currentFile : this.currentFile, - percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100 - } - }); - } -}; - -/** - * The worker started a new source (an other worker). - * @param {Object} streamInfo the streamInfo object from the new source. - */ -ZipFileWorker.prototype.openedSource = function (streamInfo) { - this.currentSourceOffset = this.bytesWritten; - this.currentFile = streamInfo["file"].name; - - var streamedContent = this.streamFiles && !streamInfo["file"].dir; - - // don't stream folders (because they don't have any content) - if(streamedContent) { - var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); - this.push({ - data : record.fileRecord, - meta : {percent:0} - }); - } else { - // we need to wait for the whole file before pushing anything - this.accumulate = true; - } -}; - -/** - * The worker finished a source (an other worker). - * @param {Object} streamInfo the streamInfo object from the finished source. - */ -ZipFileWorker.prototype.closedSource = function (streamInfo) { - this.accumulate = false; - var streamedContent = this.streamFiles && !streamInfo["file"].dir; - var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName); - - this.dirRecords.push(record.dirRecord); - if(streamedContent) { - // after the streamed file, we put data descriptors - this.push({ - data : generateDataDescriptors(streamInfo), - meta : {percent:100} - }); - } else { - // the content wasn't streamed, we need to push everything now - // first the file record, then the content - this.push({ - data : record.fileRecord, - meta : {percent:0} - }); - while(this.contentBuffer.length) { - this.push(this.contentBuffer.shift()); - } - } - this.currentFile = null; -}; - -/** - * @see GenericWorker.flush - */ -ZipFileWorker.prototype.flush = function () { - - var localDirLength = this.bytesWritten; - for(var i = 0; i < this.dirRecords.length; i++) { - this.push({ - data : this.dirRecords[i], - meta : {percent:100} - }); - } - var centralDirLength = this.bytesWritten - localDirLength; - - var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName); - - this.push({ - data : dirEnd, - meta : {percent:100} - }); -}; - -/** - * Prepare the next source to be read. - */ -ZipFileWorker.prototype.prepareNextSource = function () { - this.previous = this._sources.shift(); - this.openedSource(this.previous.streamInfo); - if (this.isPaused) { - this.previous.pause(); - } else { - this.previous.resume(); - } -}; - -/** - * @see GenericWorker.registerPrevious - */ -ZipFileWorker.prototype.registerPrevious = function (previous) { - this._sources.push(previous); - var self = this; - - previous.on("data", function (chunk) { - self.processChunk(chunk); - }); - previous.on("end", function () { - self.closedSource(self.previous.streamInfo); - if(self._sources.length) { - self.prepareNextSource(); - } else { - self.end(); - } - }); - previous.on("error", function (e) { - self.error(e); - }); - return this; -}; - -/** - * @see GenericWorker.resume - */ -ZipFileWorker.prototype.resume = function () { - if(!GenericWorker.prototype.resume.call(this)) { - return false; - } - - if (!this.previous && this._sources.length) { - this.prepareNextSource(); - return true; - } - if (!this.previous && !this._sources.length && !this.generatedError) { - this.end(); - return true; - } -}; - -/** - * @see GenericWorker.error - */ -ZipFileWorker.prototype.error = function (e) { - var sources = this._sources; - if(!GenericWorker.prototype.error.call(this, e)) { - return false; - } - for(var i = 0; i < sources.length; i++) { - try { - sources[i].error(e); - } catch(e) { - // the `error` exploded, nothing to do - } - } - return true; -}; - -/** - * @see GenericWorker.lock - */ -ZipFileWorker.prototype.lock = function () { - GenericWorker.prototype.lock.call(this); - var sources = this._sources; - for(var i = 0; i < sources.length; i++) { - sources[i].lock(); - } -}; - -module.exports = ZipFileWorker; - -},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(require,module,exports){ -"use strict"; - -var compressions = require("../compressions"); -var ZipFileWorker = require("./ZipFileWorker"); - -/** - * Find the compression to use. - * @param {String} fileCompression the compression defined at the file level, if any. - * @param {String} zipCompression the compression defined at the load() level. - * @return {Object} the compression object to use. - */ -var getCompression = function (fileCompression, zipCompression) { - - var compressionName = fileCompression || zipCompression; - var compression = compressions[compressionName]; - if (!compression) { - throw new Error(compressionName + " is not a valid compression method !"); - } - return compression; -}; - -/** - * Create a worker to generate a zip file. - * @param {JSZip} zip the JSZip instance at the right root level. - * @param {Object} options to generate the zip file. - * @param {String} comment the comment to use. - */ -exports.generateWorker = function (zip, options, comment) { - - var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName); - var entriesCount = 0; - try { - - zip.forEach(function (relativePath, file) { - entriesCount++; - var compression = getCompression(file.options.compression, options.compression); - var compressionOptions = file.options.compressionOptions || options.compressionOptions || {}; - var dir = file.dir, date = file.date; - - file._compressWorker(compression, compressionOptions) - .withStreamInfo("file", { - name : relativePath, - dir : dir, - date : date, - comment : file.comment || "", - unixPermissions : file.unixPermissions, - dosPermissions : file.dosPermissions - }) - .pipe(zipFileWorker); - }); - zipFileWorker.entriesCount = entriesCount; - } catch (e) { - zipFileWorker.error(e); - } - - return zipFileWorker; -}; - -},{"../compressions":3,"./ZipFileWorker":8}],10:[function(require,module,exports){ -"use strict"; - -/** - * Representation a of zip file in js - * @constructor - */ -function JSZip() { - // if this constructor is used without `new`, it adds `new` before itself: - if(!(this instanceof JSZip)) { - return new JSZip(); - } - - if(arguments.length) { - throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide."); - } - - // object containing the files : - // { - // "folder/" : {...}, - // "folder/data.txt" : {...} - // } - // NOTE: we use a null prototype because we do not - // want filenames like "toString" coming from a zip file - // to overwrite methods and attributes in a normal Object. - this.files = Object.create(null); - - this.comment = null; - - // Where we are in the hierarchy - this.root = ""; - this.clone = function() { - var newObj = new JSZip(); - for (var i in this) { - if (typeof this[i] !== "function") { - newObj[i] = this[i]; - } - } - return newObj; - }; -} -JSZip.prototype = require("./object"); -JSZip.prototype.loadAsync = require("./load"); -JSZip.support = require("./support"); -JSZip.defaults = require("./defaults"); - -// TODO find a better way to handle this version, -// a require('package.json').version doesn't work with webpack, see #327 -JSZip.version = "3.10.1"; - -JSZip.loadAsync = function (content, options) { - return new JSZip().loadAsync(content, options); -}; - -JSZip.external = require("./external"); -module.exports = JSZip; - -},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(require,module,exports){ -"use strict"; -var utils = require("./utils"); -var external = require("./external"); -var utf8 = require("./utf8"); -var ZipEntries = require("./zipEntries"); -var Crc32Probe = require("./stream/Crc32Probe"); -var nodejsUtils = require("./nodejsUtils"); - -/** - * Check the CRC32 of an entry. - * @param {ZipEntry} zipEntry the zip entry to check. - * @return {Promise} the result. - */ -function checkEntryCRC32(zipEntry) { - return new external.Promise(function (resolve, reject) { - var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe()); - worker.on("error", function (e) { - reject(e); - }) - .on("end", function () { - if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) { - reject(new Error("Corrupted zip : CRC32 mismatch")); - } else { - resolve(); - } - }) - .resume(); - }); -} - -module.exports = function (data, options) { - var zip = this; - options = utils.extend(options || {}, { - base64: false, - checkCRC32: false, - optimizedBinaryString: false, - createFolders: false, - decodeFileName: utf8.utf8decode - }); - - if (nodejsUtils.isNode && nodejsUtils.isStream(data)) { - return external.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")); - } - - return utils.prepareContent("the loaded zip file", data, true, options.optimizedBinaryString, options.base64) - .then(function (data) { - var zipEntries = new ZipEntries(options); - zipEntries.load(data); - return zipEntries; - }).then(function checkCRC32(zipEntries) { - var promises = [external.Promise.resolve(zipEntries)]; - var files = zipEntries.files; - if (options.checkCRC32) { - for (var i = 0; i < files.length; i++) { - promises.push(checkEntryCRC32(files[i])); - } - } - return external.Promise.all(promises); - }).then(function addFiles(results) { - var zipEntries = results.shift(); - var files = zipEntries.files; - for (var i = 0; i < files.length; i++) { - var input = files[i]; - - var unsafeName = input.fileNameStr; - var safeName = utils.resolve(input.fileNameStr); - - zip.file(safeName, input.decompressed, { - binary: true, - optimizedBinaryString: true, - date: input.date, - dir: input.dir, - comment: input.fileCommentStr.length ? input.fileCommentStr : null, - unixPermissions: input.unixPermissions, - dosPermissions: input.dosPermissions, - createFolders: options.createFolders - }); - if (!input.dir) { - zip.file(safeName).unsafeOriginalName = unsafeName; - } - } - if (zipEntries.zipComment.length) { - zip.comment = zipEntries.zipComment; - } - - return zip; - }); -}; - -},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(require,module,exports){ -"use strict"; - -var utils = require("../utils"); -var GenericWorker = require("../stream/GenericWorker"); - -/** - * A worker that use a nodejs stream as source. - * @constructor - * @param {String} filename the name of the file entry for this stream. - * @param {Readable} stream the nodejs stream. - */ -function NodejsStreamInputAdapter(filename, stream) { - GenericWorker.call(this, "Nodejs stream input adapter for " + filename); - this._upstreamEnded = false; - this._bindStream(stream); -} - -utils.inherits(NodejsStreamInputAdapter, GenericWorker); - -/** - * Prepare the stream and bind the callbacks on it. - * Do this ASAP on node 0.10 ! A lazy binding doesn't always work. - * @param {Stream} stream the nodejs stream to use. - */ -NodejsStreamInputAdapter.prototype._bindStream = function (stream) { - var self = this; - this._stream = stream; - stream.pause(); - stream - .on("data", function (chunk) { - self.push({ - data: chunk, - meta : { - percent : 0 - } - }); - }) - .on("error", function (e) { - if(self.isPaused) { - this.generatedError = e; - } else { - self.error(e); - } - }) - .on("end", function () { - if(self.isPaused) { - self._upstreamEnded = true; - } else { - self.end(); - } - }); -}; -NodejsStreamInputAdapter.prototype.pause = function () { - if(!GenericWorker.prototype.pause.call(this)) { - return false; - } - this._stream.pause(); - return true; -}; -NodejsStreamInputAdapter.prototype.resume = function () { - if(!GenericWorker.prototype.resume.call(this)) { - return false; - } - - if(this._upstreamEnded) { - this.end(); - } else { - this._stream.resume(); - } - - return true; -}; - -module.exports = NodejsStreamInputAdapter; - -},{"../stream/GenericWorker":28,"../utils":32}],13:[function(require,module,exports){ -"use strict"; - -var Readable = require("readable-stream").Readable; - -var utils = require("../utils"); -utils.inherits(NodejsStreamOutputAdapter, Readable); - -/** -* A nodejs stream using a worker as source. -* @see the SourceWrapper in http://nodejs.org/api/stream.html -* @constructor -* @param {StreamHelper} helper the helper wrapping the worker -* @param {Object} options the nodejs stream options -* @param {Function} updateCb the update callback. -*/ -function NodejsStreamOutputAdapter(helper, options, updateCb) { - Readable.call(this, options); - this._helper = helper; - - var self = this; - helper.on("data", function (data, meta) { - if (!self.push(data)) { - self._helper.pause(); - } - if(updateCb) { - updateCb(meta); - } - }) - .on("error", function(e) { - self.emit("error", e); - }) - .on("end", function () { - self.push(null); - }); -} - - -NodejsStreamOutputAdapter.prototype._read = function() { - this._helper.resume(); -}; - -module.exports = NodejsStreamOutputAdapter; - -},{"../utils":32,"readable-stream":16}],14:[function(require,module,exports){ -"use strict"; - -module.exports = { - /** - * True if this is running in Nodejs, will be undefined in a browser. - * In a browser, browserify won't include this file and the whole module - * will be resolved an empty object. - */ - isNode : typeof Buffer !== "undefined", - /** - * Create a new nodejs Buffer from an existing content. - * @param {Object} data the data to pass to the constructor. - * @param {String} encoding the encoding to use. - * @return {Buffer} a new Buffer. - */ - newBufferFrom: function(data, encoding) { - if (Buffer.from && Buffer.from !== Uint8Array.from) { - return Buffer.from(data, encoding); - } else { - if (typeof data === "number") { - // Safeguard for old Node.js versions. On newer versions, - // Buffer.from(number) / Buffer(number, encoding) already throw. - throw new Error("The \"data\" argument must not be a number"); - } - return new Buffer(data, encoding); - } - }, - /** - * Create a new nodejs Buffer with the specified size. - * @param {Integer} size the size of the buffer. - * @return {Buffer} a new Buffer. - */ - allocBuffer: function (size) { - if (Buffer.alloc) { - return Buffer.alloc(size); - } else { - var buf = new Buffer(size); - buf.fill(0); - return buf; - } - }, - /** - * Find out if an object is a Buffer. - * @param {Object} b the object to test. - * @return {Boolean} true if the object is a Buffer, false otherwise. - */ - isBuffer : function(b){ - return Buffer.isBuffer(b); - }, - - isStream : function (obj) { - return obj && - typeof obj.on === "function" && - typeof obj.pause === "function" && - typeof obj.resume === "function"; - } -}; - -},{}],15:[function(require,module,exports){ -"use strict"; -var utf8 = require("./utf8"); -var utils = require("./utils"); -var GenericWorker = require("./stream/GenericWorker"); -var StreamHelper = require("./stream/StreamHelper"); -var defaults = require("./defaults"); -var CompressedObject = require("./compressedObject"); -var ZipObject = require("./zipObject"); -var generate = require("./generate"); -var nodejsUtils = require("./nodejsUtils"); -var NodejsStreamInputAdapter = require("./nodejs/NodejsStreamInputAdapter"); - - -/** - * Add a file in the current folder. - * @private - * @param {string} name the name of the file - * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file - * @param {Object} originalOptions the options of the file - * @return {Object} the new file. - */ -var fileAdd = function(name, data, originalOptions) { - // be sure sub folders exist - var dataType = utils.getTypeOf(data), - parent; - - - /* - * Correct options. - */ - - var o = utils.extend(originalOptions || {}, defaults); - o.date = o.date || new Date(); - if (o.compression !== null) { - o.compression = o.compression.toUpperCase(); - } - - if (typeof o.unixPermissions === "string") { - o.unixPermissions = parseInt(o.unixPermissions, 8); - } - - // UNX_IFDIR 0040000 see zipinfo.c - if (o.unixPermissions && (o.unixPermissions & 0x4000)) { - o.dir = true; - } - // Bit 4 Directory - if (o.dosPermissions && (o.dosPermissions & 0x0010)) { - o.dir = true; - } - - if (o.dir) { - name = forceTrailingSlash(name); - } - if (o.createFolders && (parent = parentFolder(name))) { - folderAdd.call(this, parent, true); - } - - var isUnicodeString = dataType === "string" && o.binary === false && o.base64 === false; - if (!originalOptions || typeof originalOptions.binary === "undefined") { - o.binary = !isUnicodeString; - } - - - var isCompressedEmpty = (data instanceof CompressedObject) && data.uncompressedSize === 0; - - if (isCompressedEmpty || o.dir || !data || data.length === 0) { - o.base64 = false; - o.binary = true; - data = ""; - o.compression = "STORE"; - dataType = "string"; - } - - /* - * Convert content to fit. - */ - - var zipObjectContent = null; - if (data instanceof CompressedObject || data instanceof GenericWorker) { - zipObjectContent = data; - } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) { - zipObjectContent = new NodejsStreamInputAdapter(name, data); - } else { - zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64); - } - - var object = new ZipObject(name, zipObjectContent, o); - this.files[name] = object; - /* - TODO: we can't throw an exception because we have async promises - (we can have a promise of a Date() for example) but returning a - promise is useless because file(name, data) returns the JSZip - object for chaining. Should we break that to allow the user - to catch the error ? - - return external.Promise.resolve(zipObjectContent) - .then(function () { - return object; - }); - */ -}; - -/** - * Find the parent folder of the path. - * @private - * @param {string} path the path to use - * @return {string} the parent folder, or "" - */ -var parentFolder = function (path) { - if (path.slice(-1) === "/") { - path = path.substring(0, path.length - 1); - } - var lastSlash = path.lastIndexOf("/"); - return (lastSlash > 0) ? path.substring(0, lastSlash) : ""; -}; - -/** - * Returns the path with a slash at the end. - * @private - * @param {String} path the path to check. - * @return {String} the path with a trailing slash. - */ -var forceTrailingSlash = function(path) { - // Check the name ends with a / - if (path.slice(-1) !== "/") { - path += "/"; // IE doesn't like substr(-1) - } - return path; -}; - -/** - * Add a (sub) folder in the current folder. - * @private - * @param {string} name the folder's name - * @param {boolean=} [createFolders] If true, automatically create sub - * folders. Defaults to false. - * @return {Object} the new folder. - */ -var folderAdd = function(name, createFolders) { - createFolders = (typeof createFolders !== "undefined") ? createFolders : defaults.createFolders; - - name = forceTrailingSlash(name); - - // Does this folder already exist? - if (!this.files[name]) { - fileAdd.call(this, name, null, { - dir: true, - createFolders: createFolders - }); - } - return this.files[name]; -}; - -/** -* Cross-window, cross-Node-context regular expression detection -* @param {Object} object Anything -* @return {Boolean} true if the object is a regular expression, -* false otherwise -*/ -function isRegExp(object) { - return Object.prototype.toString.call(object) === "[object RegExp]"; -} - -// return the actual prototype of JSZip -var out = { - /** - * @see loadAsync - */ - load: function() { - throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); - }, - - - /** - * Call a callback function for each entry at this folder level. - * @param {Function} cb the callback function: - * function (relativePath, file) {...} - * It takes 2 arguments : the relative path and the file. - */ - forEach: function(cb) { - var filename, relativePath, file; - // ignore warning about unwanted properties because this.files is a null prototype object - /* eslint-disable-next-line guard-for-in */ - for (filename in this.files) { - file = this.files[filename]; - relativePath = filename.slice(this.root.length, filename.length); - if (relativePath && filename.slice(0, this.root.length) === this.root) { // the file is in the current root - cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn... - } - } - }, - - /** - * Filter nested files/folders with the specified function. - * @param {Function} search the predicate to use : - * function (relativePath, file) {...} - * It takes 2 arguments : the relative path and the file. - * @return {Array} An array of matching elements. - */ - filter: function(search) { - var result = []; - this.forEach(function (relativePath, entry) { - if (search(relativePath, entry)) { // the file matches the function - result.push(entry); - } - - }); - return result; - }, - - /** - * Add a file to the zip file, or search a file. - * @param {string|RegExp} name The name of the file to add (if data is defined), - * the name of the file to find (if no data) or a regex to match files. - * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded - * @param {Object} o File options - * @return {JSZip|Object|Array} this JSZip object (when adding a file), - * a file (when searching by string) or an array of files (when searching by regex). - */ - file: function(name, data, o) { - if (arguments.length === 1) { - if (isRegExp(name)) { - var regexp = name; - return this.filter(function(relativePath, file) { - return !file.dir && regexp.test(relativePath); - }); - } - else { // text - var obj = this.files[this.root + name]; - if (obj && !obj.dir) { - return obj; - } else { - return null; - } - } - } - else { // more than one argument : we have data ! - name = this.root + name; - fileAdd.call(this, name, data, o); - } - return this; - }, - - /** - * Add a directory to the zip file, or search. - * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders. - * @return {JSZip} an object with the new directory as the root, or an array containing matching folders. - */ - folder: function(arg) { - if (!arg) { - return this; - } - - if (isRegExp(arg)) { - return this.filter(function(relativePath, file) { - return file.dir && arg.test(relativePath); - }); - } - - // else, name is a new folder - var name = this.root + arg; - var newFolder = folderAdd.call(this, name); - - // Allow chaining by returning a new object with this folder as the root - var ret = this.clone(); - ret.root = newFolder.name; - return ret; - }, - - /** - * Delete a file, or a directory and all sub-files, from the zip - * @param {string} name the name of the file to delete - * @return {JSZip} this JSZip object - */ - remove: function(name) { - name = this.root + name; - var file = this.files[name]; - if (!file) { - // Look for any folders - if (name.slice(-1) !== "/") { - name += "/"; - } - file = this.files[name]; - } - - if (file && !file.dir) { - // file - delete this.files[name]; - } else { - // maybe a folder, delete recursively - var kids = this.filter(function(relativePath, file) { - return file.name.slice(0, name.length) === name; - }); - for (var i = 0; i < kids.length; i++) { - delete this.files[kids[i].name]; - } - } - - return this; - }, - - /** - * @deprecated This method has been removed in JSZip 3.0, please check the upgrade guide. - */ - generate: function() { - throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); - }, - - /** - * Generate the complete zip file as an internal stream. - * @param {Object} options the options to generate the zip file : - * - compression, "STORE" by default. - * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob. - * @return {StreamHelper} the streamed zip file. - */ - generateInternalStream: function(options) { - var worker, opts = {}; - try { - opts = utils.extend(options || {}, { - streamFiles: false, - compression: "STORE", - compressionOptions : null, - type: "", - platform: "DOS", - comment: null, - mimeType: "application/zip", - encodeFileName: utf8.utf8encode - }); - - opts.type = opts.type.toLowerCase(); - opts.compression = opts.compression.toUpperCase(); - - // "binarystring" is preferred but the internals use "string". - if(opts.type === "binarystring") { - opts.type = "string"; - } - - if (!opts.type) { - throw new Error("No output type specified."); - } - - utils.checkSupport(opts.type); - - // accept nodejs `process.platform` - if( - opts.platform === "darwin" || - opts.platform === "freebsd" || - opts.platform === "linux" || - opts.platform === "sunos" - ) { - opts.platform = "UNIX"; - } - if (opts.platform === "win32") { - opts.platform = "DOS"; - } - - var comment = opts.comment || this.comment || ""; - worker = generate.generateWorker(this, opts, comment); - } catch (e) { - worker = new GenericWorker("error"); - worker.error(e); - } - return new StreamHelper(worker, opts.type || "string", opts.mimeType); - }, - /** - * Generate the complete zip file asynchronously. - * @see generateInternalStream - */ - generateAsync: function(options, onUpdate) { - return this.generateInternalStream(options).accumulate(onUpdate); - }, - /** - * Generate the complete zip file asynchronously. - * @see generateInternalStream - */ - generateNodeStream: function(options, onUpdate) { - options = options || {}; - if (!options.type) { - options.type = "nodebuffer"; - } - return this.generateInternalStream(options).toNodejsStream(onUpdate); - } -}; -module.exports = out; - -},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(require,module,exports){ -"use strict"; -/* - * This file is used by module bundlers (browserify/webpack/etc) when - * including a stream implementation. We use "readable-stream" to get a - * consistent behavior between nodejs versions but bundlers often have a shim - * for "stream". Using this shim greatly improve the compatibility and greatly - * reduce the final size of the bundle (only one stream implementation, not - * two). - */ -module.exports = require("stream"); - -},{"stream":undefined}],17:[function(require,module,exports){ -"use strict"; -var DataReader = require("./DataReader"); -var utils = require("../utils"); - -function ArrayReader(data) { - DataReader.call(this, data); - for(var i = 0; i < this.data.length; i++) { - data[i] = data[i] & 0xFF; - } -} -utils.inherits(ArrayReader, DataReader); -/** - * @see DataReader.byteAt - */ -ArrayReader.prototype.byteAt = function(i) { - return this.data[this.zero + i]; -}; -/** - * @see DataReader.lastIndexOfSignature - */ -ArrayReader.prototype.lastIndexOfSignature = function(sig) { - var sig0 = sig.charCodeAt(0), - sig1 = sig.charCodeAt(1), - sig2 = sig.charCodeAt(2), - sig3 = sig.charCodeAt(3); - for (var i = this.length - 4; i >= 0; --i) { - if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) { - return i - this.zero; - } - } - - return -1; -}; -/** - * @see DataReader.readAndCheckSignature - */ -ArrayReader.prototype.readAndCheckSignature = function (sig) { - var sig0 = sig.charCodeAt(0), - sig1 = sig.charCodeAt(1), - sig2 = sig.charCodeAt(2), - sig3 = sig.charCodeAt(3), - data = this.readData(4); - return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3]; -}; -/** - * @see DataReader.readData - */ -ArrayReader.prototype.readData = function(size) { - this.checkOffset(size); - if(size === 0) { - return []; - } - var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); - this.index += size; - return result; -}; -module.exports = ArrayReader; - -},{"../utils":32,"./DataReader":18}],18:[function(require,module,exports){ -"use strict"; -var utils = require("../utils"); - -function DataReader(data) { - this.data = data; // type : see implementation - this.length = data.length; - this.index = 0; - this.zero = 0; -} -DataReader.prototype = { - /** - * Check that the offset will not go too far. - * @param {string} offset the additional offset to check. - * @throws {Error} an Error if the offset is out of bounds. - */ - checkOffset: function(offset) { - this.checkIndex(this.index + offset); - }, - /** - * Check that the specified index will not be too far. - * @param {string} newIndex the index to check. - * @throws {Error} an Error if the index is out of bounds. - */ - checkIndex: function(newIndex) { - if (this.length < this.zero + newIndex || newIndex < 0) { - throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?"); - } - }, - /** - * Change the index. - * @param {number} newIndex The new index. - * @throws {Error} if the new index is out of the data. - */ - setIndex: function(newIndex) { - this.checkIndex(newIndex); - this.index = newIndex; - }, - /** - * Skip the next n bytes. - * @param {number} n the number of bytes to skip. - * @throws {Error} if the new index is out of the data. - */ - skip: function(n) { - this.setIndex(this.index + n); - }, - /** - * Get the byte at the specified index. - * @param {number} i the index to use. - * @return {number} a byte. - */ - byteAt: function() { - // see implementations - }, - /** - * Get the next number with a given byte size. - * @param {number} size the number of bytes to read. - * @return {number} the corresponding number. - */ - readInt: function(size) { - var result = 0, - i; - this.checkOffset(size); - for (i = this.index + size - 1; i >= this.index; i--) { - result = (result << 8) + this.byteAt(i); - } - this.index += size; - return result; - }, - /** - * Get the next string with a given byte size. - * @param {number} size the number of bytes to read. - * @return {string} the corresponding string. - */ - readString: function(size) { - return utils.transformTo("string", this.readData(size)); - }, - /** - * Get raw data without conversion, bytes. - * @param {number} size the number of bytes to read. - * @return {Object} the raw data, implementation specific. - */ - readData: function() { - // see implementations - }, - /** - * Find the last occurrence of a zip signature (4 bytes). - * @param {string} sig the signature to find. - * @return {number} the index of the last occurrence, -1 if not found. - */ - lastIndexOfSignature: function() { - // see implementations - }, - /** - * Read the signature (4 bytes) at the current position and compare it with sig. - * @param {string} sig the expected signature - * @return {boolean} true if the signature matches, false otherwise. - */ - readAndCheckSignature: function() { - // see implementations - }, - /** - * Get the next date. - * @return {Date} the date. - */ - readDate: function() { - var dostime = this.readInt(4); - return new Date(Date.UTC( - ((dostime >> 25) & 0x7f) + 1980, // year - ((dostime >> 21) & 0x0f) - 1, // month - (dostime >> 16) & 0x1f, // day - (dostime >> 11) & 0x1f, // hour - (dostime >> 5) & 0x3f, // minute - (dostime & 0x1f) << 1)); // second - } -}; -module.exports = DataReader; - -},{"../utils":32}],19:[function(require,module,exports){ -"use strict"; -var Uint8ArrayReader = require("./Uint8ArrayReader"); -var utils = require("../utils"); - -function NodeBufferReader(data) { - Uint8ArrayReader.call(this, data); -} -utils.inherits(NodeBufferReader, Uint8ArrayReader); - -/** - * @see DataReader.readData - */ -NodeBufferReader.prototype.readData = function(size) { - this.checkOffset(size); - var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); - this.index += size; - return result; -}; -module.exports = NodeBufferReader; - -},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(require,module,exports){ -"use strict"; -var DataReader = require("./DataReader"); -var utils = require("../utils"); - -function StringReader(data) { - DataReader.call(this, data); -} -utils.inherits(StringReader, DataReader); -/** - * @see DataReader.byteAt - */ -StringReader.prototype.byteAt = function(i) { - return this.data.charCodeAt(this.zero + i); -}; -/** - * @see DataReader.lastIndexOfSignature - */ -StringReader.prototype.lastIndexOfSignature = function(sig) { - return this.data.lastIndexOf(sig) - this.zero; -}; -/** - * @see DataReader.readAndCheckSignature - */ -StringReader.prototype.readAndCheckSignature = function (sig) { - var data = this.readData(4); - return sig === data; -}; -/** - * @see DataReader.readData - */ -StringReader.prototype.readData = function(size) { - this.checkOffset(size); - // this will work because the constructor applied the "& 0xff" mask. - var result = this.data.slice(this.zero + this.index, this.zero + this.index + size); - this.index += size; - return result; -}; -module.exports = StringReader; - -},{"../utils":32,"./DataReader":18}],21:[function(require,module,exports){ -"use strict"; -var ArrayReader = require("./ArrayReader"); -var utils = require("../utils"); - -function Uint8ArrayReader(data) { - ArrayReader.call(this, data); -} -utils.inherits(Uint8ArrayReader, ArrayReader); -/** - * @see DataReader.readData - */ -Uint8ArrayReader.prototype.readData = function(size) { - this.checkOffset(size); - if(size === 0) { - // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of []. - return new Uint8Array(0); - } - var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size); - this.index += size; - return result; -}; -module.exports = Uint8ArrayReader; - -},{"../utils":32,"./ArrayReader":17}],22:[function(require,module,exports){ -"use strict"; - -var utils = require("../utils"); -var support = require("../support"); -var ArrayReader = require("./ArrayReader"); -var StringReader = require("./StringReader"); -var NodeBufferReader = require("./NodeBufferReader"); -var Uint8ArrayReader = require("./Uint8ArrayReader"); - -/** - * Create a reader adapted to the data. - * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read. - * @return {DataReader} the data reader. - */ -module.exports = function (data) { - var type = utils.getTypeOf(data); - utils.checkSupport(type); - if (type === "string" && !support.uint8array) { - return new StringReader(data); - } - if (type === "nodebuffer") { - return new NodeBufferReader(data); - } - if (support.uint8array) { - return new Uint8ArrayReader(utils.transformTo("uint8array", data)); - } - return new ArrayReader(utils.transformTo("array", data)); -}; - -},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(require,module,exports){ -"use strict"; -exports.LOCAL_FILE_HEADER = "PK\x03\x04"; -exports.CENTRAL_FILE_HEADER = "PK\x01\x02"; -exports.CENTRAL_DIRECTORY_END = "PK\x05\x06"; -exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07"; -exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06"; -exports.DATA_DESCRIPTOR = "PK\x07\x08"; - -},{}],24:[function(require,module,exports){ -"use strict"; - -var GenericWorker = require("./GenericWorker"); -var utils = require("../utils"); - -/** - * A worker which convert chunks to a specified type. - * @constructor - * @param {String} destType the destination type. - */ -function ConvertWorker(destType) { - GenericWorker.call(this, "ConvertWorker to " + destType); - this.destType = destType; -} -utils.inherits(ConvertWorker, GenericWorker); - -/** - * @see GenericWorker.processChunk - */ -ConvertWorker.prototype.processChunk = function (chunk) { - this.push({ - data : utils.transformTo(this.destType, chunk.data), - meta : chunk.meta - }); -}; -module.exports = ConvertWorker; - -},{"../utils":32,"./GenericWorker":28}],25:[function(require,module,exports){ -"use strict"; - -var GenericWorker = require("./GenericWorker"); -var crc32 = require("../crc32"); -var utils = require("../utils"); - -/** - * A worker which calculate the crc32 of the data flowing through. - * @constructor - */ -function Crc32Probe() { - GenericWorker.call(this, "Crc32Probe"); - this.withStreamInfo("crc32", 0); -} -utils.inherits(Crc32Probe, GenericWorker); - -/** - * @see GenericWorker.processChunk - */ -Crc32Probe.prototype.processChunk = function (chunk) { - this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0); - this.push(chunk); -}; -module.exports = Crc32Probe; - -},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(require,module,exports){ -"use strict"; - -var utils = require("../utils"); -var GenericWorker = require("./GenericWorker"); - -/** - * A worker which calculate the total length of the data flowing through. - * @constructor - * @param {String} propName the name used to expose the length - */ -function DataLengthProbe(propName) { - GenericWorker.call(this, "DataLengthProbe for " + propName); - this.propName = propName; - this.withStreamInfo(propName, 0); -} -utils.inherits(DataLengthProbe, GenericWorker); - -/** - * @see GenericWorker.processChunk - */ -DataLengthProbe.prototype.processChunk = function (chunk) { - if(chunk) { - var length = this.streamInfo[this.propName] || 0; - this.streamInfo[this.propName] = length + chunk.data.length; - } - GenericWorker.prototype.processChunk.call(this, chunk); -}; -module.exports = DataLengthProbe; - - -},{"../utils":32,"./GenericWorker":28}],27:[function(require,module,exports){ -"use strict"; - -var utils = require("../utils"); -var GenericWorker = require("./GenericWorker"); - -// the size of the generated chunks -// TODO expose this as a public variable -var DEFAULT_BLOCK_SIZE = 16 * 1024; - -/** - * A worker that reads a content and emits chunks. - * @constructor - * @param {Promise} dataP the promise of the data to split - */ -function DataWorker(dataP) { - GenericWorker.call(this, "DataWorker"); - var self = this; - this.dataIsReady = false; - this.index = 0; - this.max = 0; - this.data = null; - this.type = ""; - - this._tickScheduled = false; - - dataP.then(function (data) { - self.dataIsReady = true; - self.data = data; - self.max = data && data.length || 0; - self.type = utils.getTypeOf(data); - if(!self.isPaused) { - self._tickAndRepeat(); - } - }, function (e) { - self.error(e); - }); -} - -utils.inherits(DataWorker, GenericWorker); - -/** - * @see GenericWorker.cleanUp - */ -DataWorker.prototype.cleanUp = function () { - GenericWorker.prototype.cleanUp.call(this); - this.data = null; -}; - -/** - * @see GenericWorker.resume - */ -DataWorker.prototype.resume = function () { - if(!GenericWorker.prototype.resume.call(this)) { - return false; - } - - if (!this._tickScheduled && this.dataIsReady) { - this._tickScheduled = true; - utils.delay(this._tickAndRepeat, [], this); - } - return true; -}; - -/** - * Trigger a tick a schedule an other call to this function. - */ -DataWorker.prototype._tickAndRepeat = function() { - this._tickScheduled = false; - if(this.isPaused || this.isFinished) { - return; - } - this._tick(); - if(!this.isFinished) { - utils.delay(this._tickAndRepeat, [], this); - this._tickScheduled = true; - } -}; - -/** - * Read and push a chunk. - */ -DataWorker.prototype._tick = function() { - - if(this.isPaused || this.isFinished) { - return false; - } - - var size = DEFAULT_BLOCK_SIZE; - var data = null, nextIndex = Math.min(this.max, this.index + size); - if (this.index >= this.max) { - // EOF - return this.end(); - } else { - switch(this.type) { - case "string": - data = this.data.substring(this.index, nextIndex); - break; - case "uint8array": - data = this.data.subarray(this.index, nextIndex); - break; - case "array": - case "nodebuffer": - data = this.data.slice(this.index, nextIndex); - break; - } - this.index = nextIndex; - return this.push({ - data : data, - meta : { - percent : this.max ? this.index / this.max * 100 : 0 - } - }); - } -}; - -module.exports = DataWorker; - -},{"../utils":32,"./GenericWorker":28}],28:[function(require,module,exports){ -"use strict"; - -/** - * A worker that does nothing but passing chunks to the next one. This is like - * a nodejs stream but with some differences. On the good side : - * - it works on IE 6-9 without any issue / polyfill - * - it weights less than the full dependencies bundled with browserify - * - it forwards errors (no need to declare an error handler EVERYWHERE) - * - * A chunk is an object with 2 attributes : `meta` and `data`. The former is an - * object containing anything (`percent` for example), see each worker for more - * details. The latter is the real data (String, Uint8Array, etc). - * - * @constructor - * @param {String} name the name of the stream (mainly used for debugging purposes) - */ -function GenericWorker(name) { - // the name of the worker - this.name = name || "default"; - // an object containing metadata about the workers chain - this.streamInfo = {}; - // an error which happened when the worker was paused - this.generatedError = null; - // an object containing metadata to be merged by this worker into the general metadata - this.extraStreamInfo = {}; - // true if the stream is paused (and should not do anything), false otherwise - this.isPaused = true; - // true if the stream is finished (and should not do anything), false otherwise - this.isFinished = false; - // true if the stream is locked to prevent further structure updates (pipe), false otherwise - this.isLocked = false; - // the event listeners - this._listeners = { - "data":[], - "end":[], - "error":[] - }; - // the previous worker, if any - this.previous = null; -} - -GenericWorker.prototype = { - /** - * Push a chunk to the next workers. - * @param {Object} chunk the chunk to push - */ - push : function (chunk) { - this.emit("data", chunk); - }, - /** - * End the stream. - * @return {Boolean} true if this call ended the worker, false otherwise. - */ - end : function () { - if (this.isFinished) { - return false; - } - - this.flush(); - try { - this.emit("end"); - this.cleanUp(); - this.isFinished = true; - } catch (e) { - this.emit("error", e); - } - return true; - }, - /** - * End the stream with an error. - * @param {Error} e the error which caused the premature end. - * @return {Boolean} true if this call ended the worker with an error, false otherwise. - */ - error : function (e) { - if (this.isFinished) { - return false; - } - - if(this.isPaused) { - this.generatedError = e; - } else { - this.isFinished = true; - - this.emit("error", e); - - // in the workers chain exploded in the middle of the chain, - // the error event will go downward but we also need to notify - // workers upward that there has been an error. - if(this.previous) { - this.previous.error(e); - } - - this.cleanUp(); - } - return true; - }, - /** - * Add a callback on an event. - * @param {String} name the name of the event (data, end, error) - * @param {Function} listener the function to call when the event is triggered - * @return {GenericWorker} the current object for chainability - */ - on : function (name, listener) { - this._listeners[name].push(listener); - return this; - }, - /** - * Clean any references when a worker is ending. - */ - cleanUp : function () { - this.streamInfo = this.generatedError = this.extraStreamInfo = null; - this._listeners = []; - }, - /** - * Trigger an event. This will call registered callback with the provided arg. - * @param {String} name the name of the event (data, end, error) - * @param {Object} arg the argument to call the callback with. - */ - emit : function (name, arg) { - if (this._listeners[name]) { - for(var i = 0; i < this._listeners[name].length; i++) { - this._listeners[name][i].call(this, arg); - } - } - }, - /** - * Chain a worker with an other. - * @param {Worker} next the worker receiving events from the current one. - * @return {worker} the next worker for chainability - */ - pipe : function (next) { - return next.registerPrevious(this); - }, - /** - * Same as `pipe` in the other direction. - * Using an API with `pipe(next)` is very easy. - * Implementing the API with the point of view of the next one registering - * a source is easier, see the ZipFileWorker. - * @param {Worker} previous the previous worker, sending events to this one - * @return {Worker} the current worker for chainability - */ - registerPrevious : function (previous) { - if (this.isLocked) { - throw new Error("The stream '" + this + "' has already been used."); - } - - // sharing the streamInfo... - this.streamInfo = previous.streamInfo; - // ... and adding our own bits - this.mergeStreamInfo(); - this.previous = previous; - var self = this; - previous.on("data", function (chunk) { - self.processChunk(chunk); - }); - previous.on("end", function () { - self.end(); - }); - previous.on("error", function (e) { - self.error(e); - }); - return this; - }, - /** - * Pause the stream so it doesn't send events anymore. - * @return {Boolean} true if this call paused the worker, false otherwise. - */ - pause : function () { - if(this.isPaused || this.isFinished) { - return false; - } - this.isPaused = true; - - if(this.previous) { - this.previous.pause(); - } - return true; - }, - /** - * Resume a paused stream. - * @return {Boolean} true if this call resumed the worker, false otherwise. - */ - resume : function () { - if(!this.isPaused || this.isFinished) { - return false; - } - this.isPaused = false; - - // if true, the worker tried to resume but failed - var withError = false; - if(this.generatedError) { - this.error(this.generatedError); - withError = true; - } - if(this.previous) { - this.previous.resume(); - } - - return !withError; - }, - /** - * Flush any remaining bytes as the stream is ending. - */ - flush : function () {}, - /** - * Process a chunk. This is usually the method overridden. - * @param {Object} chunk the chunk to process. - */ - processChunk : function(chunk) { - this.push(chunk); - }, - /** - * Add a key/value to be added in the workers chain streamInfo once activated. - * @param {String} key the key to use - * @param {Object} value the associated value - * @return {Worker} the current worker for chainability - */ - withStreamInfo : function (key, value) { - this.extraStreamInfo[key] = value; - this.mergeStreamInfo(); - return this; - }, - /** - * Merge this worker's streamInfo into the chain's streamInfo. - */ - mergeStreamInfo : function () { - for(var key in this.extraStreamInfo) { - if (!Object.prototype.hasOwnProperty.call(this.extraStreamInfo, key)) { - continue; - } - this.streamInfo[key] = this.extraStreamInfo[key]; - } - }, - - /** - * Lock the stream to prevent further updates on the workers chain. - * After calling this method, all calls to pipe will fail. - */ - lock: function () { - if (this.isLocked) { - throw new Error("The stream '" + this + "' has already been used."); - } - this.isLocked = true; - if (this.previous) { - this.previous.lock(); - } - }, - - /** - * - * Pretty print the workers chain. - */ - toString : function () { - var me = "Worker " + this.name; - if (this.previous) { - return this.previous + " -> " + me; - } else { - return me; - } - } -}; - -module.exports = GenericWorker; - -},{}],29:[function(require,module,exports){ -"use strict"; - -var utils = require("../utils"); -var ConvertWorker = require("./ConvertWorker"); -var GenericWorker = require("./GenericWorker"); -var base64 = require("../base64"); -var support = require("../support"); -var external = require("../external"); - -var NodejsStreamOutputAdapter = null; -if (support.nodestream) { - try { - NodejsStreamOutputAdapter = require("../nodejs/NodejsStreamOutputAdapter"); - } catch(e) { - // ignore - } -} - -/** - * Apply the final transformation of the data. If the user wants a Blob for - * example, it's easier to work with an U8intArray and finally do the - * ArrayBuffer/Blob conversion. - * @param {String} type the name of the final type - * @param {String|Uint8Array|Buffer} content the content to transform - * @param {String} mimeType the mime type of the content, if applicable. - * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format. - */ -function transformZipOutput(type, content, mimeType) { - switch(type) { - case "blob" : - return utils.newBlob(utils.transformTo("arraybuffer", content), mimeType); - case "base64" : - return base64.encode(content); - default : - return utils.transformTo(type, content); - } -} - -/** - * Concatenate an array of data of the given type. - * @param {String} type the type of the data in the given array. - * @param {Array} dataArray the array containing the data chunks to concatenate - * @return {String|Uint8Array|Buffer} the concatenated data - * @throws Error if the asked type is unsupported - */ -function concat (type, dataArray) { - var i, index = 0, res = null, totalLength = 0; - for(i = 0; i < dataArray.length; i++) { - totalLength += dataArray[i].length; - } - switch(type) { - case "string": - return dataArray.join(""); - case "array": - return Array.prototype.concat.apply([], dataArray); - case "uint8array": - res = new Uint8Array(totalLength); - for(i = 0; i < dataArray.length; i++) { - res.set(dataArray[i], index); - index += dataArray[i].length; - } - return res; - case "nodebuffer": - return Buffer.concat(dataArray); - default: - throw new Error("concat : unsupported type '" + type + "'"); - } -} - -/** - * Listen a StreamHelper, accumulate its content and concatenate it into a - * complete block. - * @param {StreamHelper} helper the helper to use. - * @param {Function} updateCallback a callback called on each update. Called - * with one arg : - * - the metadata linked to the update received. - * @return Promise the promise for the accumulation. - */ -function accumulate(helper, updateCallback) { - return new external.Promise(function (resolve, reject){ - var dataArray = []; - var chunkType = helper._internalType, - resultType = helper._outputType, - mimeType = helper._mimeType; - helper - .on("data", function (data, meta) { - dataArray.push(data); - if(updateCallback) { - updateCallback(meta); - } - }) - .on("error", function(err) { - dataArray = []; - reject(err); - }) - .on("end", function (){ - try { - var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType); - resolve(result); - } catch (e) { - reject(e); - } - dataArray = []; - }) - .resume(); - }); -} - -/** - * An helper to easily use workers outside of JSZip. - * @constructor - * @param {Worker} worker the worker to wrap - * @param {String} outputType the type of data expected by the use - * @param {String} mimeType the mime type of the content, if applicable. - */ -function StreamHelper(worker, outputType, mimeType) { - var internalType = outputType; - switch(outputType) { - case "blob": - case "arraybuffer": - internalType = "uint8array"; - break; - case "base64": - internalType = "string"; - break; - } - - try { - // the type used internally - this._internalType = internalType; - // the type used to output results - this._outputType = outputType; - // the mime type - this._mimeType = mimeType; - utils.checkSupport(internalType); - this._worker = worker.pipe(new ConvertWorker(internalType)); - // the last workers can be rewired without issues but we need to - // prevent any updates on previous workers. - worker.lock(); - } catch(e) { - this._worker = new GenericWorker("error"); - this._worker.error(e); - } -} - -StreamHelper.prototype = { - /** - * Listen a StreamHelper, accumulate its content and concatenate it into a - * complete block. - * @param {Function} updateCb the update callback. - * @return Promise the promise for the accumulation. - */ - accumulate : function (updateCb) { - return accumulate(this, updateCb); - }, - /** - * Add a listener on an event triggered on a stream. - * @param {String} evt the name of the event - * @param {Function} fn the listener - * @return {StreamHelper} the current helper. - */ - on : function (evt, fn) { - var self = this; - - if(evt === "data") { - this._worker.on(evt, function (chunk) { - fn.call(self, chunk.data, chunk.meta); - }); - } else { - this._worker.on(evt, function () { - utils.delay(fn, arguments, self); - }); - } - return this; - }, - /** - * Resume the flow of chunks. - * @return {StreamHelper} the current helper. - */ - resume : function () { - utils.delay(this._worker.resume, [], this._worker); - return this; - }, - /** - * Pause the flow of chunks. - * @return {StreamHelper} the current helper. - */ - pause : function () { - this._worker.pause(); - return this; - }, - /** - * Return a nodejs stream for this helper. - * @param {Function} updateCb the update callback. - * @return {NodejsStreamOutputAdapter} the nodejs stream. - */ - toNodejsStream : function (updateCb) { - utils.checkSupport("nodestream"); - if (this._outputType !== "nodebuffer") { - // an object stream containing blob/arraybuffer/uint8array/string - // is strange and I don't know if it would be useful. - // I you find this comment and have a good usecase, please open a - // bug report ! - throw new Error(this._outputType + " is not supported by this method"); - } - - return new NodejsStreamOutputAdapter(this, { - objectMode : this._outputType !== "nodebuffer" - }, updateCb); - } -}; - - -module.exports = StreamHelper; - -},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(require,module,exports){ -"use strict"; - -exports.base64 = true; -exports.array = true; -exports.string = true; -exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined"; -exports.nodebuffer = typeof Buffer !== "undefined"; -// contains true if JSZip can read/generate Uint8Array, false otherwise. -exports.uint8array = typeof Uint8Array !== "undefined"; - -if (typeof ArrayBuffer === "undefined") { - exports.blob = false; -} -else { - var buffer = new ArrayBuffer(0); - try { - exports.blob = new Blob([buffer], { - type: "application/zip" - }).size === 0; - } - catch (e) { - try { - var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder; - var builder = new Builder(); - builder.append(buffer); - exports.blob = builder.getBlob("application/zip").size === 0; - } - catch (e) { - exports.blob = false; - } - } -} - -try { - exports.nodestream = !!require("readable-stream").Readable; -} catch(e) { - exports.nodestream = false; -} - -},{"readable-stream":16}],31:[function(require,module,exports){ -"use strict"; - -var utils = require("./utils"); -var support = require("./support"); -var nodejsUtils = require("./nodejsUtils"); -var GenericWorker = require("./stream/GenericWorker"); - -/** - * The following functions come from pako, from pako/lib/utils/strings - * released under the MIT license, see pako https://github.com/nodeca/pako/ - */ - -// Table with utf8 lengths (calculated by first byte of sequence) -// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, -// because max possible codepoint is 0x10ffff -var _utf8len = new Array(256); -for (var i=0; i<256; i++) { - _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1); -} -_utf8len[254]=_utf8len[254]=1; // Invalid sequence start - -// convert string to array (typed, when possible) -var string2buf = function (str) { - var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; - - // count binary size - for (m_pos = 0; m_pos < str_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { - c2 = str.charCodeAt(m_pos+1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); - m_pos++; - } - } - buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; - } - - // allocate buffer - if (support.uint8array) { - buf = new Uint8Array(buf_len); - } else { - buf = new Array(buf_len); - } - - // convert - for (i=0, m_pos = 0; i < buf_len; m_pos++) { - c = str.charCodeAt(m_pos); - if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { - c2 = str.charCodeAt(m_pos+1); - if ((c2 & 0xfc00) === 0xdc00) { - c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); - m_pos++; - } - } - if (c < 0x80) { - /* one byte */ - buf[i++] = c; - } else if (c < 0x800) { - /* two bytes */ - buf[i++] = 0xC0 | (c >>> 6); - buf[i++] = 0x80 | (c & 0x3f); - } else if (c < 0x10000) { - /* three bytes */ - buf[i++] = 0xE0 | (c >>> 12); - buf[i++] = 0x80 | (c >>> 6 & 0x3f); - buf[i++] = 0x80 | (c & 0x3f); - } else { - /* four bytes */ - buf[i++] = 0xf0 | (c >>> 18); - buf[i++] = 0x80 | (c >>> 12 & 0x3f); - buf[i++] = 0x80 | (c >>> 6 & 0x3f); - buf[i++] = 0x80 | (c & 0x3f); - } - } - - return buf; -}; - -// Calculate max possible position in utf8 buffer, -// that will not break sequence. If that's not possible -// - (very small limits) return max size as is. -// -// buf[] - utf8 bytes array -// max - length limit (mandatory); -var utf8border = function(buf, max) { - var pos; - - max = max || buf.length; - if (max > buf.length) { max = buf.length; } - - // go back from last position, until start of sequence found - pos = max-1; - while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } - - // Fuckup - very small and broken sequence, - // return max, because we should return something anyway. - if (pos < 0) { return max; } - - // If we came to start of buffer - that means vuffer is too small, - // return max too. - if (pos === 0) { return max; } - - return (pos + _utf8len[buf[pos]] > max) ? pos : max; -}; - -// convert array to string -var buf2string = function (buf) { - var i, out, c, c_len; - var len = buf.length; - - // Reserve max possible length (2 words per char) - // NB: by unknown reasons, Array is significantly faster for - // String.fromCharCode.apply than Uint16Array. - var utf16buf = new Array(len*2); - - for (out=0, i=0; i 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } - - // apply mask on first byte - c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; - // join the rest - while (c_len > 1 && i < len) { - c = (c << 6) | (buf[i++] & 0x3f); - c_len--; - } - - // terminated by end of string? - if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } - - if (c < 0x10000) { - utf16buf[out++] = c; - } else { - c -= 0x10000; - utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); - utf16buf[out++] = 0xdc00 | (c & 0x3ff); - } - } - - // shrinkBuf(utf16buf, out) - if (utf16buf.length !== out) { - if(utf16buf.subarray) { - utf16buf = utf16buf.subarray(0, out); - } else { - utf16buf.length = out; - } - } - - // return String.fromCharCode.apply(null, utf16buf); - return utils.applyFromCharCode(utf16buf); -}; - - -// That's all for the pako functions. - - -/** - * Transform a javascript string into an array (typed if possible) of bytes, - * UTF-8 encoded. - * @param {String} str the string to encode - * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string. - */ -exports.utf8encode = function utf8encode(str) { - if (support.nodebuffer) { - return nodejsUtils.newBufferFrom(str, "utf-8"); - } - - return string2buf(str); -}; - - -/** - * Transform a bytes array (or a representation) representing an UTF-8 encoded - * string into a javascript string. - * @param {Array|Uint8Array|Buffer} buf the data de decode - * @return {String} the decoded string. - */ -exports.utf8decode = function utf8decode(buf) { - if (support.nodebuffer) { - return utils.transformTo("nodebuffer", buf).toString("utf-8"); - } - - buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf); - - return buf2string(buf); -}; - -/** - * A worker to decode utf8 encoded binary chunks into string chunks. - * @constructor - */ -function Utf8DecodeWorker() { - GenericWorker.call(this, "utf-8 decode"); - // the last bytes if a chunk didn't end with a complete codepoint. - this.leftOver = null; -} -utils.inherits(Utf8DecodeWorker, GenericWorker); - -/** - * @see GenericWorker.processChunk - */ -Utf8DecodeWorker.prototype.processChunk = function (chunk) { - - var data = utils.transformTo(support.uint8array ? "uint8array" : "array", chunk.data); - - // 1st step, re-use what's left of the previous chunk - if (this.leftOver && this.leftOver.length) { - if(support.uint8array) { - var previousData = data; - data = new Uint8Array(previousData.length + this.leftOver.length); - data.set(this.leftOver, 0); - data.set(previousData, this.leftOver.length); - } else { - data = this.leftOver.concat(data); - } - this.leftOver = null; - } - - var nextBoundary = utf8border(data); - var usableData = data; - if (nextBoundary !== data.length) { - if (support.uint8array) { - usableData = data.subarray(0, nextBoundary); - this.leftOver = data.subarray(nextBoundary, data.length); - } else { - usableData = data.slice(0, nextBoundary); - this.leftOver = data.slice(nextBoundary, data.length); - } - } - - this.push({ - data : exports.utf8decode(usableData), - meta : chunk.meta - }); -}; - -/** - * @see GenericWorker.flush - */ -Utf8DecodeWorker.prototype.flush = function () { - if(this.leftOver && this.leftOver.length) { - this.push({ - data : exports.utf8decode(this.leftOver), - meta : {} - }); - this.leftOver = null; - } -}; -exports.Utf8DecodeWorker = Utf8DecodeWorker; - -/** - * A worker to endcode string chunks into utf8 encoded binary chunks. - * @constructor - */ -function Utf8EncodeWorker() { - GenericWorker.call(this, "utf-8 encode"); -} -utils.inherits(Utf8EncodeWorker, GenericWorker); - -/** - * @see GenericWorker.processChunk - */ -Utf8EncodeWorker.prototype.processChunk = function (chunk) { - this.push({ - data : exports.utf8encode(chunk.data), - meta : chunk.meta - }); -}; -exports.Utf8EncodeWorker = Utf8EncodeWorker; - -},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(require,module,exports){ -"use strict"; - -var support = require("./support"); -var base64 = require("./base64"); -var nodejsUtils = require("./nodejsUtils"); -var external = require("./external"); -require("setimmediate"); - - -/** - * Convert a string that pass as a "binary string": it should represent a byte - * array but may have > 255 char codes. Be sure to take only the first byte - * and returns the byte array. - * @param {String} str the string to transform. - * @return {Array|Uint8Array} the string in a binary format. - */ -function string2binary(str) { - var result = null; - if (support.uint8array) { - result = new Uint8Array(str.length); - } else { - result = new Array(str.length); - } - return stringToArrayLike(str, result); -} - -/** - * Create a new blob with the given content and the given type. - * @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use - * an Uint8Array because the stock browser of android 4 won't accept it (it - * will be silently converted to a string, "[object Uint8Array]"). - * - * Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge: - * when a large amount of Array is used to create the Blob, the amount of - * memory consumed is nearly 100 times the original data amount. - * - * @param {String} type the mime type of the blob. - * @return {Blob} the created blob. - */ -exports.newBlob = function(part, type) { - exports.checkSupport("blob"); - - try { - // Blob constructor - return new Blob([part], { - type: type - }); - } - catch (e) { - - try { - // deprecated, browser only, old way - var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder; - var builder = new Builder(); - builder.append(part); - return builder.getBlob(type); - } - catch (e) { - - // well, fuck ?! - throw new Error("Bug : can't construct the Blob."); - } - } - - -}; -/** - * The identity function. - * @param {Object} input the input. - * @return {Object} the same input. - */ -function identity(input) { - return input; -} - -/** - * Fill in an array with a string. - * @param {String} str the string to use. - * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated). - * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array. - */ -function stringToArrayLike(str, array) { - for (var i = 0; i < str.length; ++i) { - array[i] = str.charCodeAt(i) & 0xFF; - } - return array; -} - -/** - * An helper for the function arrayLikeToString. - * This contains static information and functions that - * can be optimized by the browser JIT compiler. - */ -var arrayToStringHelper = { - /** - * Transform an array of int into a string, chunk by chunk. - * See the performances notes on arrayLikeToString. - * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. - * @param {String} type the type of the array. - * @param {Integer} chunk the chunk size. - * @return {String} the resulting string. - * @throws Error if the chunk is too big for the stack. - */ - stringifyByChunk: function(array, type, chunk) { - var result = [], k = 0, len = array.length; - // shortcut - if (len <= chunk) { - return String.fromCharCode.apply(null, array); - } - while (k < len) { - if (type === "array" || type === "nodebuffer") { - result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len)))); - } - else { - result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len)))); - } - k += chunk; - } - return result.join(""); - }, - /** - * Call String.fromCharCode on every item in the array. - * This is the naive implementation, which generate A LOT of intermediate string. - * This should be used when everything else fail. - * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. - * @return {String} the result. - */ - stringifyByChar: function(array){ - var resultStr = ""; - for(var i = 0; i < array.length; i++) { - resultStr += String.fromCharCode(array[i]); - } - return resultStr; - }, - applyCanBeUsed : { - /** - * true if the browser accepts to use String.fromCharCode on Uint8Array - */ - uint8array : (function () { - try { - return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1; - } catch (e) { - return false; - } - })(), - /** - * true if the browser accepts to use String.fromCharCode on nodejs Buffer. - */ - nodebuffer : (function () { - try { - return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1; - } catch (e) { - return false; - } - })() - } -}; - -/** - * Transform an array-like object to a string. - * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. - * @return {String} the result. - */ -function arrayLikeToString(array) { - // Performances notes : - // -------------------- - // String.fromCharCode.apply(null, array) is the fastest, see - // see http://jsperf.com/converting-a-uint8array-to-a-string/2 - // but the stack is limited (and we can get huge arrays !). - // - // result += String.fromCharCode(array[i]); generate too many strings ! - // - // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2 - // TODO : we now have workers that split the work. Do we still need that ? - var chunk = 65536, - type = exports.getTypeOf(array), - canUseApply = true; - if (type === "uint8array") { - canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array; - } else if (type === "nodebuffer") { - canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer; - } - - if (canUseApply) { - while (chunk > 1) { - try { - return arrayToStringHelper.stringifyByChunk(array, type, chunk); - } catch (e) { - chunk = Math.floor(chunk / 2); - } - } - } - - // no apply or chunk error : slow and painful algorithm - // default browser on android 4.* - return arrayToStringHelper.stringifyByChar(array); -} - -exports.applyFromCharCode = arrayLikeToString; - - -/** - * Copy the data from an array-like to an other array-like. - * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array. - * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated. - * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array. - */ -function arrayLikeToArrayLike(arrayFrom, arrayTo) { - for (var i = 0; i < arrayFrom.length; i++) { - arrayTo[i] = arrayFrom[i]; - } - return arrayTo; -} - -// a matrix containing functions to transform everything into everything. -var transform = {}; - -// string to ? -transform["string"] = { - "string": identity, - "array": function(input) { - return stringToArrayLike(input, new Array(input.length)); - }, - "arraybuffer": function(input) { - return transform["string"]["uint8array"](input).buffer; - }, - "uint8array": function(input) { - return stringToArrayLike(input, new Uint8Array(input.length)); - }, - "nodebuffer": function(input) { - return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length)); - } -}; - -// array to ? -transform["array"] = { - "string": arrayLikeToString, - "array": identity, - "arraybuffer": function(input) { - return (new Uint8Array(input)).buffer; - }, - "uint8array": function(input) { - return new Uint8Array(input); - }, - "nodebuffer": function(input) { - return nodejsUtils.newBufferFrom(input); - } -}; - -// arraybuffer to ? -transform["arraybuffer"] = { - "string": function(input) { - return arrayLikeToString(new Uint8Array(input)); - }, - "array": function(input) { - return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength)); - }, - "arraybuffer": identity, - "uint8array": function(input) { - return new Uint8Array(input); - }, - "nodebuffer": function(input) { - return nodejsUtils.newBufferFrom(new Uint8Array(input)); - } -}; - -// uint8array to ? -transform["uint8array"] = { - "string": arrayLikeToString, - "array": function(input) { - return arrayLikeToArrayLike(input, new Array(input.length)); - }, - "arraybuffer": function(input) { - return input.buffer; - }, - "uint8array": identity, - "nodebuffer": function(input) { - return nodejsUtils.newBufferFrom(input); - } -}; - -// nodebuffer to ? -transform["nodebuffer"] = { - "string": arrayLikeToString, - "array": function(input) { - return arrayLikeToArrayLike(input, new Array(input.length)); - }, - "arraybuffer": function(input) { - return transform["nodebuffer"]["uint8array"](input).buffer; - }, - "uint8array": function(input) { - return arrayLikeToArrayLike(input, new Uint8Array(input.length)); - }, - "nodebuffer": identity -}; - -/** - * Transform an input into any type. - * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer. - * If no output type is specified, the unmodified input will be returned. - * @param {String} outputType the output type. - * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert. - * @throws {Error} an Error if the browser doesn't support the requested output type. - */ -exports.transformTo = function(outputType, input) { - if (!input) { - // undefined, null, etc - // an empty string won't harm. - input = ""; - } - if (!outputType) { - return input; - } - exports.checkSupport(outputType); - var inputType = exports.getTypeOf(input); - var result = transform[inputType][outputType](input); - return result; -}; - -/** - * Resolve all relative path components, "." and "..", in a path. If these relative components - * traverse above the root then the resulting path will only contain the final path component. - * - * All empty components, e.g. "//", are removed. - * @param {string} path A path with / or \ separators - * @returns {string} The path with all relative path components resolved. - */ -exports.resolve = function(path) { - var parts = path.split("/"); - var result = []; - for (var index = 0; index < parts.length; index++) { - var part = parts[index]; - // Allow the first and last component to be empty for trailing slashes. - if (part === "." || (part === "" && index !== 0 && index !== parts.length - 1)) { - continue; - } else if (part === "..") { - result.pop(); - } else { - result.push(part); - } - } - return result.join("/"); -}; - -/** - * Return the type of the input. - * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer. - * @param {Object} input the input to identify. - * @return {String} the (lowercase) type of the input. - */ -exports.getTypeOf = function(input) { - if (typeof input === "string") { - return "string"; - } - if (Object.prototype.toString.call(input) === "[object Array]") { - return "array"; - } - if (support.nodebuffer && nodejsUtils.isBuffer(input)) { - return "nodebuffer"; - } - if (support.uint8array && input instanceof Uint8Array) { - return "uint8array"; - } - if (support.arraybuffer && input instanceof ArrayBuffer) { - return "arraybuffer"; - } -}; - -/** - * Throw an exception if the type is not supported. - * @param {String} type the type to check. - * @throws {Error} an Error if the browser doesn't support the requested type. - */ -exports.checkSupport = function(type) { - var supported = support[type.toLowerCase()]; - if (!supported) { - throw new Error(type + " is not supported by this platform"); - } -}; - -exports.MAX_VALUE_16BITS = 65535; -exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1 - -/** - * Prettify a string read as binary. - * @param {string} str the string to prettify. - * @return {string} a pretty string. - */ -exports.pretty = function(str) { - var res = "", - code, i; - for (i = 0; i < (str || "").length; i++) { - code = str.charCodeAt(i); - res += "\\x" + (code < 16 ? "0" : "") + code.toString(16).toUpperCase(); - } - return res; -}; - -/** - * Defer the call of a function. - * @param {Function} callback the function to call asynchronously. - * @param {Array} args the arguments to give to the callback. - */ -exports.delay = function(callback, args, self) { - setImmediate(function () { - callback.apply(self || null, args || []); - }); -}; - -/** - * Extends a prototype with an other, without calling a constructor with - * side effects. Inspired by nodejs' `utils.inherits` - * @param {Function} ctor the constructor to augment - * @param {Function} superCtor the parent constructor to use - */ -exports.inherits = function (ctor, superCtor) { - var Obj = function() {}; - Obj.prototype = superCtor.prototype; - ctor.prototype = new Obj(); -}; - -/** - * Merge the objects passed as parameters into a new one. - * @private - * @param {...Object} var_args All objects to merge. - * @return {Object} a new object with the data of the others. - */ -exports.extend = function() { - var result = {}, i, attr; - for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers - for (attr in arguments[i]) { - if (Object.prototype.hasOwnProperty.call(arguments[i], attr) && typeof result[attr] === "undefined") { - result[attr] = arguments[i][attr]; - } - } - } - return result; -}; - -/** - * Transform arbitrary content into a Promise. - * @param {String} name a name for the content being processed. - * @param {Object} inputData the content to process. - * @param {Boolean} isBinary true if the content is not an unicode string - * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character. - * @param {Boolean} isBase64 true if the string content is encoded with base64. - * @return {Promise} a promise in a format usable by JSZip. - */ -exports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) { - - // if inputData is already a promise, this flatten it. - var promise = external.Promise.resolve(inputData).then(function(data) { - - - var isBlob = support.blob && (data instanceof Blob || ["[object File]", "[object Blob]"].indexOf(Object.prototype.toString.call(data)) !== -1); - - if (isBlob && typeof FileReader !== "undefined") { - return new external.Promise(function (resolve, reject) { - var reader = new FileReader(); - - reader.onload = function(e) { - resolve(e.target.result); - }; - reader.onerror = function(e) { - reject(e.target.error); - }; - reader.readAsArrayBuffer(data); - }); - } else { - return data; - } - }); - - return promise.then(function(data) { - var dataType = exports.getTypeOf(data); - - if (!dataType) { - return external.Promise.reject( - new Error("Can't read the data of '" + name + "'. Is it " + - "in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?") - ); - } - // special case : it's way easier to work with Uint8Array than with ArrayBuffer - if (dataType === "arraybuffer") { - data = exports.transformTo("uint8array", data); - } else if (dataType === "string") { - if (isBase64) { - data = base64.decode(data); - } - else if (isBinary) { - // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask - if (isOptimizedBinaryString !== true) { - // this is a string, not in a base64 format. - // Be sure that this is a correct "binary string" - data = string2binary(data); - } - } - } - return data; - }); -}; - -},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,"setimmediate":54}],33:[function(require,module,exports){ -"use strict"; -var readerFor = require("./reader/readerFor"); -var utils = require("./utils"); -var sig = require("./signature"); -var ZipEntry = require("./zipEntry"); -var support = require("./support"); -// class ZipEntries {{{ -/** - * All the entries in the zip file. - * @constructor - * @param {Object} loadOptions Options for loading the stream. - */ -function ZipEntries(loadOptions) { - this.files = []; - this.loadOptions = loadOptions; -} -ZipEntries.prototype = { - /** - * Check that the reader is on the specified signature. - * @param {string} expectedSignature the expected signature. - * @throws {Error} if it is an other signature. - */ - checkSignature: function(expectedSignature) { - if (!this.reader.readAndCheckSignature(expectedSignature)) { - this.reader.index -= 4; - var signature = this.reader.readString(4); - throw new Error("Corrupted zip or bug: unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")"); - } - }, - /** - * Check if the given signature is at the given index. - * @param {number} askedIndex the index to check. - * @param {string} expectedSignature the signature to expect. - * @return {boolean} true if the signature is here, false otherwise. - */ - isSignature: function(askedIndex, expectedSignature) { - var currentIndex = this.reader.index; - this.reader.setIndex(askedIndex); - var signature = this.reader.readString(4); - var result = signature === expectedSignature; - this.reader.setIndex(currentIndex); - return result; - }, - /** - * Read the end of the central directory. - */ - readBlockEndOfCentral: function() { - this.diskNumber = this.reader.readInt(2); - this.diskWithCentralDirStart = this.reader.readInt(2); - this.centralDirRecordsOnThisDisk = this.reader.readInt(2); - this.centralDirRecords = this.reader.readInt(2); - this.centralDirSize = this.reader.readInt(4); - this.centralDirOffset = this.reader.readInt(4); - - this.zipCommentLength = this.reader.readInt(2); - // warning : the encoding depends of the system locale - // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded. - // On a windows machine, this field is encoded with the localized windows code page. - var zipComment = this.reader.readData(this.zipCommentLength); - var decodeParamType = support.uint8array ? "uint8array" : "array"; - // To get consistent behavior with the generation part, we will assume that - // this is utf8 encoded unless specified otherwise. - var decodeContent = utils.transformTo(decodeParamType, zipComment); - this.zipComment = this.loadOptions.decodeFileName(decodeContent); - }, - /** - * Read the end of the Zip 64 central directory. - * Not merged with the method readEndOfCentral : - * The end of central can coexist with its Zip64 brother, - * I don't want to read the wrong number of bytes ! - */ - readBlockZip64EndOfCentral: function() { - this.zip64EndOfCentralSize = this.reader.readInt(8); - this.reader.skip(4); - // this.versionMadeBy = this.reader.readString(2); - // this.versionNeeded = this.reader.readInt(2); - this.diskNumber = this.reader.readInt(4); - this.diskWithCentralDirStart = this.reader.readInt(4); - this.centralDirRecordsOnThisDisk = this.reader.readInt(8); - this.centralDirRecords = this.reader.readInt(8); - this.centralDirSize = this.reader.readInt(8); - this.centralDirOffset = this.reader.readInt(8); - - this.zip64ExtensibleData = {}; - var extraDataSize = this.zip64EndOfCentralSize - 44, - index = 0, - extraFieldId, - extraFieldLength, - extraFieldValue; - while (index < extraDataSize) { - extraFieldId = this.reader.readInt(2); - extraFieldLength = this.reader.readInt(4); - extraFieldValue = this.reader.readData(extraFieldLength); - this.zip64ExtensibleData[extraFieldId] = { - id: extraFieldId, - length: extraFieldLength, - value: extraFieldValue - }; - } - }, - /** - * Read the end of the Zip 64 central directory locator. - */ - readBlockZip64EndOfCentralLocator: function() { - this.diskWithZip64CentralDirStart = this.reader.readInt(4); - this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8); - this.disksCount = this.reader.readInt(4); - if (this.disksCount > 1) { - throw new Error("Multi-volumes zip are not supported"); - } - }, - /** - * Read the local files, based on the offset read in the central part. - */ - readLocalFiles: function() { - var i, file; - for (i = 0; i < this.files.length; i++) { - file = this.files[i]; - this.reader.setIndex(file.localHeaderOffset); - this.checkSignature(sig.LOCAL_FILE_HEADER); - file.readLocalPart(this.reader); - file.handleUTF8(); - file.processAttributes(); - } - }, - /** - * Read the central directory. - */ - readCentralDir: function() { - var file; - - this.reader.setIndex(this.centralDirOffset); - while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) { - file = new ZipEntry({ - zip64: this.zip64 - }, this.loadOptions); - file.readCentralPart(this.reader); - this.files.push(file); - } - - if (this.centralDirRecords !== this.files.length) { - if (this.centralDirRecords !== 0 && this.files.length === 0) { - // We expected some records but couldn't find ANY. - // This is really suspicious, as if something went wrong. - throw new Error("Corrupted zip or bug: expected " + this.centralDirRecords + " records in central dir, got " + this.files.length); - } else { - // We found some records but not all. - // Something is wrong but we got something for the user: no error here. - // console.warn("expected", this.centralDirRecords, "records in central dir, got", this.files.length); - } - } - }, - /** - * Read the end of central directory. - */ - readEndOfCentral: function() { - var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END); - if (offset < 0) { - // Check if the content is a truncated zip or complete garbage. - // A "LOCAL_FILE_HEADER" is not required at the beginning (auto - // extractible zip for example) but it can give a good hint. - // If an ajax request was used without responseType, we will also - // get unreadable data. - var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER); - - if (isGarbage) { - throw new Error("Can't find end of central directory : is this a zip file ? " + - "If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"); - } else { - throw new Error("Corrupted zip: can't find end of central directory"); - } - - } - this.reader.setIndex(offset); - var endOfCentralDirOffset = offset; - this.checkSignature(sig.CENTRAL_DIRECTORY_END); - this.readBlockEndOfCentral(); - - - /* extract from the zip spec : - 4) If one of the fields in the end of central directory - record is too small to hold required data, the field - should be set to -1 (0xFFFF or 0xFFFFFFFF) and the - ZIP64 format record should be created. - 5) The end of central directory record and the - Zip64 end of central directory locator record must - reside on the same disk when splitting or spanning - an archive. - */ - if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) { - this.zip64 = true; - - /* - Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from - the zip file can fit into a 32bits integer. This cannot be solved : JavaScript represents - all numbers as 64-bit double precision IEEE 754 floating point numbers. - So, we have 53bits for integers and bitwise operations treat everything as 32bits. - see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators - and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5 - */ - - // should look for a zip64 EOCD locator - offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); - if (offset < 0) { - throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator"); - } - this.reader.setIndex(offset); - this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR); - this.readBlockZip64EndOfCentralLocator(); - - // now the zip64 EOCD record - if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) { - // console.warn("ZIP64 end of central directory not where expected."); - this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); - if (this.relativeOffsetEndOfZip64CentralDir < 0) { - throw new Error("Corrupted zip: can't find the ZIP64 end of central directory"); - } - } - this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir); - this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END); - this.readBlockZip64EndOfCentral(); - } - - var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize; - if (this.zip64) { - expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator - expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize; - } - - var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset; - - if (extraBytes > 0) { - // console.warn(extraBytes, "extra bytes at beginning or within zipfile"); - if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) { - // The offsets seem wrong, but we have something at the specified offset. - // So… we keep it. - } else { - // the offset is wrong, update the "zero" of the reader - // this happens if data has been prepended (crx files for example) - this.reader.zero = extraBytes; - } - } else if (extraBytes < 0) { - throw new Error("Corrupted zip: missing " + Math.abs(extraBytes) + " bytes."); - } - }, - prepareReader: function(data) { - this.reader = readerFor(data); - }, - /** - * Read a zip file and create ZipEntries. - * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file. - */ - load: function(data) { - this.prepareReader(data); - this.readEndOfCentral(); - this.readCentralDir(); - this.readLocalFiles(); - } -}; -// }}} end of ZipEntries -module.exports = ZipEntries; - -},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(require,module,exports){ -"use strict"; -var readerFor = require("./reader/readerFor"); -var utils = require("./utils"); -var CompressedObject = require("./compressedObject"); -var crc32fn = require("./crc32"); -var utf8 = require("./utf8"); -var compressions = require("./compressions"); -var support = require("./support"); - -var MADE_BY_DOS = 0x00; -var MADE_BY_UNIX = 0x03; - -/** - * Find a compression registered in JSZip. - * @param {string} compressionMethod the method magic to find. - * @return {Object|null} the JSZip compression object, null if none found. - */ -var findCompression = function(compressionMethod) { - for (var method in compressions) { - if (!Object.prototype.hasOwnProperty.call(compressions, method)) { - continue; - } - if (compressions[method].magic === compressionMethod) { - return compressions[method]; - } - } - return null; -}; - -// class ZipEntry {{{ -/** - * An entry in the zip file. - * @constructor - * @param {Object} options Options of the current file. - * @param {Object} loadOptions Options for loading the stream. - */ -function ZipEntry(options, loadOptions) { - this.options = options; - this.loadOptions = loadOptions; -} -ZipEntry.prototype = { - /** - * say if the file is encrypted. - * @return {boolean} true if the file is encrypted, false otherwise. - */ - isEncrypted: function() { - // bit 1 is set - return (this.bitFlag & 0x0001) === 0x0001; - }, - /** - * say if the file has utf-8 filename/comment. - * @return {boolean} true if the filename/comment is in utf-8, false otherwise. - */ - useUTF8: function() { - // bit 11 is set - return (this.bitFlag & 0x0800) === 0x0800; - }, - /** - * Read the local part of a zip file and add the info in this object. - * @param {DataReader} reader the reader to use. - */ - readLocalPart: function(reader) { - var compression, localExtraFieldsLength; - - // we already know everything from the central dir ! - // If the central dir data are false, we are doomed. - // On the bright side, the local part is scary : zip64, data descriptors, both, etc. - // The less data we get here, the more reliable this should be. - // Let's skip the whole header and dash to the data ! - reader.skip(22); - // in some zip created on windows, the filename stored in the central dir contains \ instead of /. - // Strangely, the filename here is OK. - // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes - // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators... - // Search "unzip mismatching "local" filename continuing with "central" filename version" on - // the internet. - // - // I think I see the logic here : the central directory is used to display - // content and the local directory is used to extract the files. Mixing / and \ - // may be used to display \ to windows users and use / when extracting the files. - // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394 - this.fileNameLength = reader.readInt(2); - localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir - // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding. - this.fileName = reader.readData(this.fileNameLength); - reader.skip(localExtraFieldsLength); - - if (this.compressedSize === -1 || this.uncompressedSize === -1) { - throw new Error("Bug or corrupted zip : didn't get enough information from the central directory " + "(compressedSize === -1 || uncompressedSize === -1)"); - } - - compression = findCompression(this.compressionMethod); - if (compression === null) { // no compression found - throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + utils.transformTo("string", this.fileName) + ")"); - } - this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize)); - }, - - /** - * Read the central part of a zip file and add the info in this object. - * @param {DataReader} reader the reader to use. - */ - readCentralPart: function(reader) { - this.versionMadeBy = reader.readInt(2); - reader.skip(2); - // this.versionNeeded = reader.readInt(2); - this.bitFlag = reader.readInt(2); - this.compressionMethod = reader.readString(2); - this.date = reader.readDate(); - this.crc32 = reader.readInt(4); - this.compressedSize = reader.readInt(4); - this.uncompressedSize = reader.readInt(4); - var fileNameLength = reader.readInt(2); - this.extraFieldsLength = reader.readInt(2); - this.fileCommentLength = reader.readInt(2); - this.diskNumberStart = reader.readInt(2); - this.internalFileAttributes = reader.readInt(2); - this.externalFileAttributes = reader.readInt(4); - this.localHeaderOffset = reader.readInt(4); - - if (this.isEncrypted()) { - throw new Error("Encrypted zip are not supported"); - } - - // will be read in the local part, see the comments there - reader.skip(fileNameLength); - this.readExtraFields(reader); - this.parseZIP64ExtraField(reader); - this.fileComment = reader.readData(this.fileCommentLength); - }, - - /** - * Parse the external file attributes and get the unix/dos permissions. - */ - processAttributes: function () { - this.unixPermissions = null; - this.dosPermissions = null; - var madeBy = this.versionMadeBy >> 8; - - // Check if we have the DOS directory flag set. - // We look for it in the DOS and UNIX permissions - // but some unknown platform could set it as a compatibility flag. - this.dir = this.externalFileAttributes & 0x0010 ? true : false; - - if(madeBy === MADE_BY_DOS) { - // first 6 bits (0 to 5) - this.dosPermissions = this.externalFileAttributes & 0x3F; - } - - if(madeBy === MADE_BY_UNIX) { - this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF; - // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8); - } - - // fail safe : if the name ends with a / it probably means a folder - if (!this.dir && this.fileNameStr.slice(-1) === "/") { - this.dir = true; - } - }, - - /** - * Parse the ZIP64 extra field and merge the info in the current ZipEntry. - * @param {DataReader} reader the reader to use. - */ - parseZIP64ExtraField: function() { - if (!this.extraFields[0x0001]) { - return; - } - - // should be something, preparing the extra reader - var extraReader = readerFor(this.extraFields[0x0001].value); - - // I really hope that these 64bits integer can fit in 32 bits integer, because js - // won't let us have more. - if (this.uncompressedSize === utils.MAX_VALUE_32BITS) { - this.uncompressedSize = extraReader.readInt(8); - } - if (this.compressedSize === utils.MAX_VALUE_32BITS) { - this.compressedSize = extraReader.readInt(8); - } - if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) { - this.localHeaderOffset = extraReader.readInt(8); - } - if (this.diskNumberStart === utils.MAX_VALUE_32BITS) { - this.diskNumberStart = extraReader.readInt(4); - } - }, - /** - * Read the central part of a zip file and add the info in this object. - * @param {DataReader} reader the reader to use. - */ - readExtraFields: function(reader) { - var end = reader.index + this.extraFieldsLength, - extraFieldId, - extraFieldLength, - extraFieldValue; - - if (!this.extraFields) { - this.extraFields = {}; - } - - while (reader.index + 4 < end) { - extraFieldId = reader.readInt(2); - extraFieldLength = reader.readInt(2); - extraFieldValue = reader.readData(extraFieldLength); - - this.extraFields[extraFieldId] = { - id: extraFieldId, - length: extraFieldLength, - value: extraFieldValue - }; - } - - reader.setIndex(end); - }, - /** - * Apply an UTF8 transformation if needed. - */ - handleUTF8: function() { - var decodeParamType = support.uint8array ? "uint8array" : "array"; - if (this.useUTF8()) { - this.fileNameStr = utf8.utf8decode(this.fileName); - this.fileCommentStr = utf8.utf8decode(this.fileComment); - } else { - var upath = this.findExtraFieldUnicodePath(); - if (upath !== null) { - this.fileNameStr = upath; - } else { - // ASCII text or unsupported code page - var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName); - this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray); - } - - var ucomment = this.findExtraFieldUnicodeComment(); - if (ucomment !== null) { - this.fileCommentStr = ucomment; - } else { - // ASCII text or unsupported code page - var commentByteArray = utils.transformTo(decodeParamType, this.fileComment); - this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray); - } - } - }, - - /** - * Find the unicode path declared in the extra field, if any. - * @return {String} the unicode path, null otherwise. - */ - findExtraFieldUnicodePath: function() { - var upathField = this.extraFields[0x7075]; - if (upathField) { - var extraReader = readerFor(upathField.value); - - // wrong version - if (extraReader.readInt(1) !== 1) { - return null; - } - - // the crc of the filename changed, this field is out of date. - if (crc32fn(this.fileName) !== extraReader.readInt(4)) { - return null; - } - - return utf8.utf8decode(extraReader.readData(upathField.length - 5)); - } - return null; - }, - - /** - * Find the unicode comment declared in the extra field, if any. - * @return {String} the unicode comment, null otherwise. - */ - findExtraFieldUnicodeComment: function() { - var ucommentField = this.extraFields[0x6375]; - if (ucommentField) { - var extraReader = readerFor(ucommentField.value); - - // wrong version - if (extraReader.readInt(1) !== 1) { - return null; - } - - // the crc of the comment changed, this field is out of date. - if (crc32fn(this.fileComment) !== extraReader.readInt(4)) { - return null; - } - - return utf8.utf8decode(extraReader.readData(ucommentField.length - 5)); - } - return null; - } -}; -module.exports = ZipEntry; - -},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(require,module,exports){ -"use strict"; - -var StreamHelper = require("./stream/StreamHelper"); -var DataWorker = require("./stream/DataWorker"); -var utf8 = require("./utf8"); -var CompressedObject = require("./compressedObject"); -var GenericWorker = require("./stream/GenericWorker"); - -/** - * A simple object representing a file in the zip file. - * @constructor - * @param {string} name the name of the file - * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data - * @param {Object} options the options of the file - */ -var ZipObject = function(name, data, options) { - this.name = name; - this.dir = options.dir; - this.date = options.date; - this.comment = options.comment; - this.unixPermissions = options.unixPermissions; - this.dosPermissions = options.dosPermissions; - - this._data = data; - this._dataBinary = options.binary; - // keep only the compression - this.options = { - compression : options.compression, - compressionOptions : options.compressionOptions - }; -}; - -ZipObject.prototype = { - /** - * Create an internal stream for the content of this object. - * @param {String} type the type of each chunk. - * @return StreamHelper the stream. - */ - internalStream: function (type) { - var result = null, outputType = "string"; - try { - if (!type) { - throw new Error("No output type specified."); - } - outputType = type.toLowerCase(); - var askUnicodeString = outputType === "string" || outputType === "text"; - if (outputType === "binarystring" || outputType === "text") { - outputType = "string"; - } - result = this._decompressWorker(); - - var isUnicodeString = !this._dataBinary; - - if (isUnicodeString && !askUnicodeString) { - result = result.pipe(new utf8.Utf8EncodeWorker()); - } - if (!isUnicodeString && askUnicodeString) { - result = result.pipe(new utf8.Utf8DecodeWorker()); - } - } catch (e) { - result = new GenericWorker("error"); - result.error(e); - } - - return new StreamHelper(result, outputType, ""); - }, - - /** - * Prepare the content in the asked type. - * @param {String} type the type of the result. - * @param {Function} onUpdate a function to call on each internal update. - * @return Promise the promise of the result. - */ - async: function (type, onUpdate) { - return this.internalStream(type).accumulate(onUpdate); - }, - - /** - * Prepare the content as a nodejs stream. - * @param {String} type the type of each chunk. - * @param {Function} onUpdate a function to call on each internal update. - * @return Stream the stream. - */ - nodeStream: function (type, onUpdate) { - return this.internalStream(type || "nodebuffer").toNodejsStream(onUpdate); - }, - - /** - * Return a worker for the compressed content. - * @private - * @param {Object} compression the compression object to use. - * @param {Object} compressionOptions the options to use when compressing. - * @return Worker the worker. - */ - _compressWorker: function (compression, compressionOptions) { - if ( - this._data instanceof CompressedObject && - this._data.compression.magic === compression.magic - ) { - return this._data.getCompressedWorker(); - } else { - var result = this._decompressWorker(); - if(!this._dataBinary) { - result = result.pipe(new utf8.Utf8EncodeWorker()); - } - return CompressedObject.createWorkerFrom(result, compression, compressionOptions); - } - }, - /** - * Return a worker for the decompressed content. - * @private - * @return Worker the worker. - */ - _decompressWorker : function () { - if (this._data instanceof CompressedObject) { - return this._data.getContentWorker(); - } else if (this._data instanceof GenericWorker) { - return this._data; - } else { - return new DataWorker(this._data); - } - } -}; - -var removedMethods = ["asText", "asBinary", "asNodeBuffer", "asUint8Array", "asArrayBuffer"]; -var removedFn = function () { - throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide."); -}; - -for(var i = 0; i < removedMethods.length; i++) { - ZipObject.prototype[removedMethods[i]] = removedFn; -} -module.exports = ZipObject; - -},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(require,module,exports){ -(function (global){ -'use strict'; -var Mutation = global.MutationObserver || global.WebKitMutationObserver; - -var scheduleDrain; - -{ - if (Mutation) { - var called = 0; - var observer = new Mutation(nextTick); - var element = global.document.createTextNode(''); - observer.observe(element, { - characterData: true - }); - scheduleDrain = function () { - element.data = (called = ++called % 2); - }; - } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') { - var channel = new global.MessageChannel(); - channel.port1.onmessage = nextTick; - scheduleDrain = function () { - channel.port2.postMessage(0); - }; - } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) { - scheduleDrain = function () { - - // Create a