feat: add scripts/build.sh, test.sh, check.sh
This commit is contained in:
parent
2f02db00f5
commit
2f1b822e20
|
|
@ -0,0 +1,5 @@
|
|||
export * from './types';
|
||||
export { VerstakPluginAPI, createPluginAPI } from './plugin-api';
|
||||
export { RPCServer, RPCClient } from './rpc';
|
||||
export { createTestManifest, createTestPluginState, createMockPluginAPI, validateManifest, } from './test-utils';
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,cAAc,SAAS,CAAC;AACxB,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,cAAc,CAAC"}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
// Verstak Plugin SDK — Public API
|
||||
export * from './types';
|
||||
export { VerstakPluginAPI, createPluginAPI } from './plugin-api';
|
||||
export { RPCServer, RPCClient } from './rpc';
|
||||
export { createTestManifest, createTestPluginState, createMockPluginAPI, validateManifest, } from './test-utils';
|
||||
//# sourceMappingURL=index.js.map
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAElC,cAAc,SAAS,CAAC;AACxB,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAC7C,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,mBAAmB,EACnB,gBAAgB,GACjB,MAAM,cAAc,CAAC"}
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
import type { PluginSettings } from './types';
|
||||
/**
|
||||
* VerstakPluginAPI — единственный способ для frontend плагина
|
||||
* общаться с core платформы.
|
||||
*
|
||||
* Экземпляр API передаётся плагину при активации через глобальную
|
||||
* переменную `window.__VERSTAK_PLUGIN_API__`.
|
||||
*/
|
||||
export declare class VerstakPluginAPI {
|
||||
private pluginId;
|
||||
private capabilities;
|
||||
constructor(pluginId: string);
|
||||
/**
|
||||
* Инициализация API — вызывается core после загрузки frontend bundle.
|
||||
* @internal
|
||||
*/
|
||||
_init(capabilities: string[]): void;
|
||||
/**
|
||||
* Зарегистрировать view для отображения в UI Shell.
|
||||
*/
|
||||
registerView(id: string, component: unknown): void;
|
||||
/**
|
||||
* Зарегистрировать панель настроек плагина.
|
||||
*/
|
||||
registerSettingsPanel(id: string, title: string, component: unknown): void;
|
||||
/**
|
||||
* Зарегистрировать команду для command palette.
|
||||
*/
|
||||
registerCommand(id: string, title: string, handler: () => void, keybinding?: string): void;
|
||||
/**
|
||||
* Зарегистрировать действия для файлов.
|
||||
*/
|
||||
registerFileAction(id: string, label: string, handler: (filePath: string) => void, capability?: string): void;
|
||||
/**
|
||||
* Зарегистрировать действия для заметок.
|
||||
*/
|
||||
registerNoteAction(id: string, label: string, handler: (noteId: string) => void, capability?: string): void;
|
||||
/**
|
||||
* Зарегистрировать provider поиска.
|
||||
*/
|
||||
registerSearchProvider(id: string, label: string, handler: (query: string) => unknown[]): void;
|
||||
/**
|
||||
* Проверить, доступна ли capability.
|
||||
*/
|
||||
hasCapability(name: string): boolean;
|
||||
/**
|
||||
* Получить список всех доступных capabilities.
|
||||
*/
|
||||
getAvailableCapabilities(): string[];
|
||||
/**
|
||||
* Вызвать backend метод плагина через RPC.
|
||||
*/
|
||||
callBackend(method: string, args?: unknown[]): Promise<unknown>;
|
||||
/**
|
||||
* Прочитать настройки плагина.
|
||||
*/
|
||||
readSettings(): Promise<PluginSettings>;
|
||||
/**
|
||||
* Записать настройки плагина.
|
||||
*/
|
||||
writeSettings(settings: PluginSettings): Promise<void>;
|
||||
/**
|
||||
* Подписаться на событие event bus.
|
||||
*/
|
||||
subscribe(event: string, handler: (payload: unknown) => void): void;
|
||||
/**
|
||||
* Опубликовать событие в event bus.
|
||||
*/
|
||||
publish(event: string, payload: unknown): void;
|
||||
private _postMessage;
|
||||
private _rpcCall;
|
||||
}
|
||||
/**
|
||||
* Создать экземпляр VerstakPluginAPI.
|
||||
* Core вызывает эту функцию после загрузки frontend bundle,
|
||||
* передавая pluginId и список доступных capabilities.
|
||||
*/
|
||||
export declare function createPluginAPI(pluginId: string): VerstakPluginAPI;
|
||||
//# sourceMappingURL=plugin-api.d.ts.map
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"plugin-api.d.ts","sourceRoot":"","sources":["../src/plugin-api.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAE9C;;;;;;GAMG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,YAAY,CAAqB;gBAE7B,QAAQ,EAAE,MAAM;IAI5B;;;OAGG;IACH,KAAK,CAAC,YAAY,EAAE,MAAM,EAAE,GAAG,IAAI;IAMnC;;OAEG;IACH,YAAY,CAAC,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,GAAG,IAAI;IAIlD;;OAEG;IACH,qBAAqB,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,GAAG,IAAI;IAI1E;;OAEG;IACH,eAAe,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,IAAI,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI;IAI1F;;OAEG;IACH,kBAAkB,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI;IAI7G;;OAEG;IACH,kBAAkB,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI;IAI3G;;OAEG;IACH,sBAAsB,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,EAAE,GAAG,IAAI;IAM9F;;OAEG;IACH,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAIpC;;OAEG;IACH,wBAAwB,IAAI,MAAM,EAAE;IAMpC;;OAEG;IACG,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,GAAE,OAAO,EAAO,GAAG,OAAO,CAAC,OAAO,CAAC;IAMzE;;OAEG;IACG,YAAY,IAAI,OAAO,CAAC,cAAc,CAAC;IAK7C;;OAEG;IACG,aAAa,CAAC,QAAQ,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAM5D;;OAEG;IACH,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,GAAG,IAAI;IAInE;;OAEG;IACH,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI;IAM9C,OAAO,CAAC,YAAY;YAMN,QAAQ;CAiBvB;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,gBAAgB,CAGlE"}
|
||||
|
|
@ -0,0 +1,141 @@
|
|||
// Verstak Plugin SDK — VerstakPluginAPI
|
||||
// The official runtime API available to all plugins in the frontend context.
|
||||
/**
|
||||
* VerstakPluginAPI — единственный способ для frontend плагина
|
||||
* общаться с core платформы.
|
||||
*
|
||||
* Экземпляр API передаётся плагину при активации через глобальную
|
||||
* переменную `window.__VERSTAK_PLUGIN_API__`.
|
||||
*/
|
||||
export class VerstakPluginAPI {
|
||||
pluginId;
|
||||
capabilities = new Set();
|
||||
constructor(pluginId) {
|
||||
this.pluginId = pluginId;
|
||||
}
|
||||
/**
|
||||
* Инициализация API — вызывается core после загрузки frontend bundle.
|
||||
* @internal
|
||||
*/
|
||||
_init(capabilities) {
|
||||
this.capabilities = new Set(capabilities);
|
||||
}
|
||||
// ─── View Registration ─────────────────────────────────────
|
||||
/**
|
||||
* Зарегистрировать view для отображения в UI Shell.
|
||||
*/
|
||||
registerView(id, component) {
|
||||
this._postMessage('register.view', { id, component });
|
||||
}
|
||||
/**
|
||||
* Зарегистрировать панель настроек плагина.
|
||||
*/
|
||||
registerSettingsPanel(id, title, component) {
|
||||
this._postMessage('register.settingsPanel', { id, title, component });
|
||||
}
|
||||
/**
|
||||
* Зарегистрировать команду для command palette.
|
||||
*/
|
||||
registerCommand(id, title, handler, keybinding) {
|
||||
this._postMessage('register.command', { id, title, keybinding, handler: handler.toString() });
|
||||
}
|
||||
/**
|
||||
* Зарегистрировать действия для файлов.
|
||||
*/
|
||||
registerFileAction(id, label, handler, capability) {
|
||||
this._postMessage('register.fileAction', { id, label, handler: handler.toString(), capability });
|
||||
}
|
||||
/**
|
||||
* Зарегистрировать действия для заметок.
|
||||
*/
|
||||
registerNoteAction(id, label, handler, capability) {
|
||||
this._postMessage('register.noteAction', { id, label, handler: handler.toString(), capability });
|
||||
}
|
||||
/**
|
||||
* Зарегистрировать provider поиска.
|
||||
*/
|
||||
registerSearchProvider(id, label, handler) {
|
||||
this._postMessage('register.searchProvider', { id, label, handler: handler.toString() });
|
||||
}
|
||||
// ─── Capabilities ──────────────────────────────────────────
|
||||
/**
|
||||
* Проверить, доступна ли capability.
|
||||
*/
|
||||
hasCapability(name) {
|
||||
return this.capabilities.has(name);
|
||||
}
|
||||
/**
|
||||
* Получить список всех доступных capabilities.
|
||||
*/
|
||||
getAvailableCapabilities() {
|
||||
return Array.from(this.capabilities);
|
||||
}
|
||||
// ─── Backend Communication ─────────────────────────────────
|
||||
/**
|
||||
* Вызвать backend метод плагина через RPC.
|
||||
*/
|
||||
async callBackend(method, args = []) {
|
||||
return this._rpcCall(method, args);
|
||||
}
|
||||
// ─── Settings ──────────────────────────────────────────────
|
||||
/**
|
||||
* Прочитать настройки плагина.
|
||||
*/
|
||||
async readSettings() {
|
||||
const result = await this._rpcCall('readSettings', []);
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Записать настройки плагина.
|
||||
*/
|
||||
async writeSettings(settings) {
|
||||
await this._rpcCall('writeSettings', [settings]);
|
||||
}
|
||||
// ─── Event Bus ─────────────────────────────────────────────
|
||||
/**
|
||||
* Подписаться на событие event bus.
|
||||
*/
|
||||
subscribe(event, handler) {
|
||||
this._postMessage('subscribe', { event, handler: handler.toString() });
|
||||
}
|
||||
/**
|
||||
* Опубликовать событие в event bus.
|
||||
*/
|
||||
publish(event, payload) {
|
||||
this._postMessage('publish', { event, payload });
|
||||
}
|
||||
// ─── Internal ──────────────────────────────────────────────
|
||||
_postMessage(type, data) {
|
||||
window.dispatchEvent(new CustomEvent('verstak:plugin', {
|
||||
detail: { pluginId: this.pluginId, type, data }
|
||||
}));
|
||||
}
|
||||
async _rpcCall(method, args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const callId = `${this.pluginId}:${Date.now()}:${Math.random()}`;
|
||||
const handler = (event) => {
|
||||
if (event.detail.callId === callId) {
|
||||
window.removeEventListener('verstak:rpc:response', handler);
|
||||
if (event.detail.error) {
|
||||
reject(new Error(event.detail.error));
|
||||
}
|
||||
else {
|
||||
resolve(event.detail.result);
|
||||
}
|
||||
}
|
||||
};
|
||||
window.addEventListener('verstak:rpc:response', handler);
|
||||
this._postMessage('rpc', { callId, method, args });
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Создать экземпляр VerstakPluginAPI.
|
||||
* Core вызывает эту функцию после загрузки frontend bundle,
|
||||
* передавая pluginId и список доступных capabilities.
|
||||
*/
|
||||
export function createPluginAPI(pluginId) {
|
||||
const api = new VerstakPluginAPI(pluginId);
|
||||
return api;
|
||||
}
|
||||
//# sourceMappingURL=plugin-api.js.map
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"plugin-api.js","sourceRoot":"","sources":["../src/plugin-api.ts"],"names":[],"mappings":"AAAA,wCAAwC;AACxC,6EAA6E;AAI7E;;;;;;GAMG;AACH,MAAM,OAAO,gBAAgB;IACnB,QAAQ,CAAS;IACjB,YAAY,GAAG,IAAI,GAAG,EAAU,CAAC;IAEzC,YAAY,QAAgB;QAC1B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,YAAsB;QAC1B,IAAI,CAAC,YAAY,GAAG,IAAI,GAAG,CAAC,YAAY,CAAC,CAAC;IAC5C,CAAC;IAED,8DAA8D;IAE9D;;OAEG;IACH,YAAY,CAAC,EAAU,EAAE,SAAkB;QACzC,IAAI,CAAC,YAAY,CAAC,eAAe,EAAE,EAAE,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC;IACxD,CAAC;IAED;;OAEG;IACH,qBAAqB,CAAC,EAAU,EAAE,KAAa,EAAE,SAAkB;QACjE,IAAI,CAAC,YAAY,CAAC,wBAAwB,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;IACxE,CAAC;IAED;;OAEG;IACH,eAAe,CAAC,EAAU,EAAE,KAAa,EAAE,OAAmB,EAAE,UAAmB;QACjF,IAAI,CAAC,YAAY,CAAC,kBAAkB,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAChG,CAAC;IAED;;OAEG;IACH,kBAAkB,CAAC,EAAU,EAAE,KAAa,EAAE,OAAmC,EAAE,UAAmB;QACpG,IAAI,CAAC,YAAY,CAAC,qBAAqB,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,QAAQ,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;IACnG,CAAC;IAED;;OAEG;IACH,kBAAkB,CAAC,EAAU,EAAE,KAAa,EAAE,OAAiC,EAAE,UAAmB;QAClG,IAAI,CAAC,YAAY,CAAC,qBAAqB,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,QAAQ,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;IACnG,CAAC;IAED;;OAEG;IACH,sBAAsB,CAAC,EAAU,EAAE,KAAa,EAAE,OAAqC;QACrF,IAAI,CAAC,YAAY,CAAC,yBAAyB,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IAC3F,CAAC;IAED,8DAA8D;IAE9D;;OAEG;IACH,aAAa,CAAC,IAAY;QACxB,OAAO,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACrC,CAAC;IAED;;OAEG;IACH,wBAAwB;QACtB,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACvC,CAAC;IAED,8DAA8D;IAE9D;;OAEG;IACH,KAAK,CAAC,WAAW,CAAC,MAAc,EAAE,OAAkB,EAAE;QACpD,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IACrC,CAAC;IAED,8DAA8D;IAE9D;;OAEG;IACH,KAAK,CAAC,YAAY;QAChB,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,cAAc,EAAE,EAAE,CAAC,CAAC;QACvD,OAAO,MAAwB,CAAC;IAClC,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,aAAa,CAAC,QAAwB;QAC1C,MAAM,IAAI,CAAC,QAAQ,CAAC,eAAe,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC;IACnD,CAAC;IAED,8DAA8D;IAE9D;;OAEG;IACH,SAAS,CAAC,KAAa,EAAE,OAAmC;QAC1D,IAAI,CAAC,YAAY,CAAC,WAAW,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IACzE,CAAC;IAED;;OAEG;IACH,OAAO,CAAC,KAAa,EAAE,OAAgB;QACrC,IAAI,CAAC,YAAY,CAAC,SAAS,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;IACnD,CAAC;IAED,8DAA8D;IAEtD,YAAY,CAAC,IAAY,EAAE,IAA6B;QAC9D,MAAM,CAAC,aAAa,CAAC,IAAI,WAAW,CAAC,gBAAgB,EAAE;YACrD,MAAM,EAAE,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE;SAChD,CAAC,CAAC,CAAC;IACN,CAAC;IAEO,KAAK,CAAC,QAAQ,CAAC,MAAc,EAAE,IAAe;QACpD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,MAAM,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC;YACjE,MAAM,OAAO,GAAG,CAAC,KAAkB,EAAE,EAAE;gBACrC,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,KAAK,MAAM,EAAE,CAAC;oBACnC,MAAM,CAAC,mBAAmB,CAAC,sBAAsB,EAAE,OAAwB,CAAC,CAAC;oBAC7E,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;wBACvB,MAAM,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;oBACxC,CAAC;yBAAM,CAAC;wBACN,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;oBAC/B,CAAC;gBACH,CAAC;YACH,CAAC,CAAC;YACF,MAAM,CAAC,gBAAgB,CAAC,sBAAsB,EAAE,OAAwB,CAAC,CAAC;YAC1E,IAAI,CAAC,YAAY,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QACrD,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAED;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,QAAgB;IAC9C,MAAM,GAAG,GAAG,IAAI,gBAAgB,CAAC,QAAQ,CAAC,CAAC;IAC3C,OAAO,GAAG,CAAC;AACb,CAAC"}
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
export type RPCTransport = 'stdio' | 'tcp';
|
||||
export interface RPCRequest {
|
||||
jsonrpc: '2.0';
|
||||
id: string;
|
||||
method: string;
|
||||
params: unknown[];
|
||||
}
|
||||
export interface RPCResponse {
|
||||
jsonrpc: '2.0';
|
||||
id: string;
|
||||
result?: unknown;
|
||||
error?: RPCError;
|
||||
}
|
||||
export interface RPCError {
|
||||
code: number;
|
||||
message: string;
|
||||
data?: unknown;
|
||||
}
|
||||
/**
|
||||
* RPC клиент для общения backend sidecar с core платформы.
|
||||
* Использует JSON-RPC 2.0 протокол.
|
||||
*/
|
||||
export declare class RPCServer {
|
||||
private handlers;
|
||||
constructor();
|
||||
/**
|
||||
* Зарегистрировать обработчик RPC метода.
|
||||
*/
|
||||
registerMethod(method: string, handler: (params: unknown[]) => Promise<unknown>): void;
|
||||
/**
|
||||
* Обработать входящий RPC запрос.
|
||||
*/
|
||||
handleRequest(request: RPCRequest): Promise<RPCResponse>;
|
||||
/**
|
||||
* Создать RPC запрос.
|
||||
*/
|
||||
createRequest(method: string, params?: unknown[]): RPCRequest;
|
||||
/**
|
||||
* Разобрать RPC ответ.
|
||||
*/
|
||||
parseResponse(data: string): RPCResponse;
|
||||
}
|
||||
/**
|
||||
* RPC клиент (для core, вызывает методы sidecar).
|
||||
*/
|
||||
export declare class RPCClient {
|
||||
private requestId;
|
||||
/**
|
||||
* Создать JSON-RPC запрос.
|
||||
*/
|
||||
call(method: string, params?: unknown[]): string;
|
||||
/**
|
||||
* Разобрать ответ.
|
||||
*/
|
||||
parseResponse(data: string): RPCResponse;
|
||||
}
|
||||
//# sourceMappingURL=rpc.d.ts.map
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"rpc.d.ts","sourceRoot":"","sources":["../src/rpc.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,YAAY,GAAG,OAAO,GAAG,KAAK,CAAC;AAE3C,MAAM,WAAW,UAAU;IACzB,OAAO,EAAE,KAAK,CAAC;IACf,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,OAAO,EAAE,CAAC;CACnB;AAED,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,KAAK,CAAC;IACf,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,QAAQ,CAAC;CAClB;AAED,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,OAAO,CAAC;CAChB;AAED;;;GAGG;AACH,qBAAa,SAAS;IACpB,OAAO,CAAC,QAAQ,CAA8D;;IAK9E;;OAEG;IACH,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI;IAItF;;OAEG;IACG,aAAa,CAAC,OAAO,EAAE,UAAU,GAAG,OAAO,CAAC,WAAW,CAAC;IAsB9D;;OAEG;IACH,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,GAAE,OAAO,EAAO,GAAG,UAAU;IASjE;;OAEG;IACH,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW;CAGzC;AAED;;GAEG;AACH,qBAAa,SAAS;IACpB,OAAO,CAAC,SAAS,CAAK;IAEtB;;OAEG;IACH,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,GAAE,OAAO,EAAO,GAAG,MAAM;IAUpD;;OAEG;IACH,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW;CAGzC"}
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
// Verstak Plugin SDK — RPC Client for Sidecar Communication
|
||||
/**
|
||||
* RPC клиент для общения backend sidecar с core платформы.
|
||||
* Использует JSON-RPC 2.0 протокол.
|
||||
*/
|
||||
export class RPCServer {
|
||||
handlers = new Map();
|
||||
constructor() {
|
||||
}
|
||||
/**
|
||||
* Зарегистрировать обработчик RPC метода.
|
||||
*/
|
||||
registerMethod(method, handler) {
|
||||
this.handlers.set(method, handler);
|
||||
}
|
||||
/**
|
||||
* Обработать входящий RPC запрос.
|
||||
*/
|
||||
async handleRequest(request) {
|
||||
const handler = this.handlers.get(request.method);
|
||||
if (!handler) {
|
||||
return {
|
||||
jsonrpc: '2.0',
|
||||
id: request.id,
|
||||
error: { code: -32601, message: `Method not found: ${request.method}` }
|
||||
};
|
||||
}
|
||||
try {
|
||||
const result = await handler(request.params);
|
||||
return { jsonrpc: '2.0', id: request.id, result };
|
||||
}
|
||||
catch (err) {
|
||||
return {
|
||||
jsonrpc: '2.0',
|
||||
id: request.id,
|
||||
error: { code: -32000, message: err instanceof Error ? err.message : String(err) }
|
||||
};
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Создать RPC запрос.
|
||||
*/
|
||||
createRequest(method, params = []) {
|
||||
return {
|
||||
jsonrpc: '2.0',
|
||||
id: `${Date.now()}:${Math.random()}`,
|
||||
method,
|
||||
params
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Разобрать RPC ответ.
|
||||
*/
|
||||
parseResponse(data) {
|
||||
return JSON.parse(data);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* RPC клиент (для core, вызывает методы sidecar).
|
||||
*/
|
||||
export class RPCClient {
|
||||
requestId = 0;
|
||||
/**
|
||||
* Создать JSON-RPC запрос.
|
||||
*/
|
||||
call(method, params = []) {
|
||||
const request = {
|
||||
jsonrpc: '2.0',
|
||||
id: `${++this.requestId}`,
|
||||
method,
|
||||
params
|
||||
};
|
||||
return JSON.stringify(request) + '\n';
|
||||
}
|
||||
/**
|
||||
* Разобрать ответ.
|
||||
*/
|
||||
parseResponse(data) {
|
||||
return JSON.parse(data.trim());
|
||||
}
|
||||
}
|
||||
//# sourceMappingURL=rpc.js.map
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"rpc.js","sourceRoot":"","sources":["../src/rpc.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAwB5D;;;GAGG;AACH,MAAM,OAAO,SAAS;IACZ,QAAQ,GAAG,IAAI,GAAG,EAAmD,CAAC;IAE9E;IACA,CAAC;IAED;;OAEG;IACH,cAAc,CAAC,MAAc,EAAE,OAAgD;QAC7E,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACrC,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,aAAa,CAAC,OAAmB;QACrC,MAAM,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAClD,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,EAAE,EAAE,OAAO,CAAC,EAAE;gBACd,KAAK,EAAE,EAAE,IAAI,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,qBAAqB,OAAO,CAAC,MAAM,EAAE,EAAE;aACxE,CAAC;QACJ,CAAC;QAED,IAAI,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YAC7C,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,OAAO,CAAC,EAAE,EAAE,MAAM,EAAE,CAAC;QACpD,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,EAAE,EAAE,OAAO,CAAC,EAAE;gBACd,KAAK,EAAE,EAAE,IAAI,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE;aACnF,CAAC;QACJ,CAAC;IACH,CAAC;IAED;;OAEG;IACH,aAAa,CAAC,MAAc,EAAE,SAAoB,EAAE;QAClD,OAAO;YACL,OAAO,EAAE,KAAK;YACd,EAAE,EAAE,GAAG,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,EAAE;YACpC,MAAM;YACN,MAAM;SACP,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,aAAa,CAAC,IAAY;QACxB,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAgB,CAAC;IACzC,CAAC;CACF;AAED;;GAEG;AACH,MAAM,OAAO,SAAS;IACZ,SAAS,GAAG,CAAC,CAAC;IAEtB;;OAEG;IACH,IAAI,CAAC,MAAc,EAAE,SAAoB,EAAE;QACzC,MAAM,OAAO,GAAe;YAC1B,OAAO,EAAE,KAAK;YACd,EAAE,EAAE,GAAG,EAAE,IAAI,CAAC,SAAS,EAAE;YACzB,MAAM;YACN,MAAM;SACP,CAAC;QACF,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;IACxC,CAAC;IAED;;OAEG;IACH,aAAa,CAAC,IAAY;QACxB,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,CAAgB,CAAC;IAChD,CAAC;CACF"}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
import type { PluginManifest, PluginState } from './types';
|
||||
/**
|
||||
* Создать тестовый manifest для unit-тестов.
|
||||
*/
|
||||
export declare function createTestManifest(overrides?: Partial<PluginManifest>): PluginManifest;
|
||||
/**
|
||||
* Создать тестовое состояние плагина.
|
||||
*/
|
||||
export declare function createTestPluginState(overrides?: Partial<PluginState>): PluginState;
|
||||
/**
|
||||
* Создать заглушку VerstakPluginAPI для тестов.
|
||||
*/
|
||||
export declare function createMockPluginAPI(): {
|
||||
registerView: ReturnType<typeof vi.fn>;
|
||||
registerCommand: ReturnType<typeof vi.fn>;
|
||||
registerSettingsPanel: ReturnType<typeof vi.fn>;
|
||||
hasCapability: ReturnType<typeof vi.fn>;
|
||||
callBackend: ReturnType<typeof vi.fn>;
|
||||
subscribe: ReturnType<typeof vi.fn>;
|
||||
publish: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
/**
|
||||
* Валидатор plugin manifest.
|
||||
*/
|
||||
export declare function validateManifest(manifest: unknown): {
|
||||
valid: boolean;
|
||||
errors: string[];
|
||||
};
|
||||
import { vi } from 'vitest';
|
||||
export { vi };
|
||||
//# sourceMappingURL=test-utils.d.ts.map
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"test-utils.d.ts","sourceRoot":"","sources":["../src/test-utils.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAE3D;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,GAAG,cAAc,CAetF;AAED;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC,WAAW,CAAC,GAAG,WAAW,CASnF;AAED;;GAEG;AACH,wBAAgB,mBAAmB,IAAI;IACrC,YAAY,EAAE,UAAU,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC;IACvC,eAAe,EAAE,UAAU,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC;IAC1C,qBAAqB,EAAE,UAAU,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC;IAChD,aAAa,EAAE,UAAU,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC;IACxC,WAAW,EAAE,UAAU,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC;IACtC,SAAS,EAAE,UAAU,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC;IACpC,OAAO,EAAE,UAAU,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC;CACnC,CAUA;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,OAAO,GAAG;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,CAgCxF;AAGD,OAAO,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,EAAE,EAAE,CAAC"}
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
// Verstak Plugin SDK — Test Utilities
|
||||
/**
|
||||
* Создать тестовый manifest для unit-тестов.
|
||||
*/
|
||||
export function createTestManifest(overrides) {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
id: 'test.plugin',
|
||||
name: 'Test Plugin',
|
||||
version: '0.1.0',
|
||||
apiVersion: '1',
|
||||
description: 'A test plugin for platform verification',
|
||||
source: 'local',
|
||||
provides: ['test.capability'],
|
||||
requires: [],
|
||||
optionalRequires: [],
|
||||
permissions: ['events.publish', 'events.subscribe'],
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Создать тестовое состояние плагина.
|
||||
*/
|
||||
export function createTestPluginState(overrides) {
|
||||
return {
|
||||
id: 'test.plugin',
|
||||
manifest: createTestManifest(),
|
||||
status: 'loaded',
|
||||
enabled: true,
|
||||
loadedAt: new Date().toISOString(),
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Создать заглушку VerstakPluginAPI для тестов.
|
||||
*/
|
||||
export function createMockPluginAPI() {
|
||||
return {
|
||||
registerView: vi.fn(),
|
||||
registerCommand: vi.fn(),
|
||||
registerSettingsPanel: vi.fn(),
|
||||
hasCapability: vi.fn().mockReturnValue(false),
|
||||
callBackend: vi.fn().mockResolvedValue(undefined),
|
||||
subscribe: vi.fn(),
|
||||
publish: vi.fn(),
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Валидатор plugin manifest.
|
||||
*/
|
||||
export function validateManifest(manifest) {
|
||||
const errors = [];
|
||||
if (!manifest || typeof manifest !== 'object') {
|
||||
return { valid: false, errors: ['Manifest must be an object'] };
|
||||
}
|
||||
const m = manifest;
|
||||
if (m.schemaVersion !== 1) {
|
||||
errors.push(`schemaVersion must be 1, got ${m.schemaVersion}`);
|
||||
}
|
||||
if (typeof m.id !== 'string' || !m.id) {
|
||||
errors.push('id must be a non-empty string');
|
||||
}
|
||||
if (typeof m.name !== 'string' || !m.name) {
|
||||
errors.push('name must be a non-empty string');
|
||||
}
|
||||
if (typeof m.version !== 'string' || !/^\d+\.\d+\.\d+/.test(m.version)) {
|
||||
errors.push('version must be a valid semver (e.g. 0.1.0)');
|
||||
}
|
||||
if (typeof m.apiVersion !== 'string' || !m.apiVersion) {
|
||||
errors.push('apiVersion must be a non-empty string');
|
||||
}
|
||||
if (!Array.isArray(m.provides) || m.provides.length === 0) {
|
||||
errors.push('provides must be a non-empty array');
|
||||
}
|
||||
if (!Array.isArray(m.permissions) || m.permissions.length === 0) {
|
||||
errors.push('permissions must be a non-empty array');
|
||||
}
|
||||
return { valid: errors.length === 0, errors };
|
||||
}
|
||||
// Re-export vi for test files
|
||||
import { vi } from 'vitest';
|
||||
export { vi };
|
||||
//# sourceMappingURL=test-utils.js.map
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"test-utils.js","sourceRoot":"","sources":["../src/test-utils.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAItC;;GAEG;AACH,MAAM,UAAU,kBAAkB,CAAC,SAAmC;IACpE,OAAO;QACL,aAAa,EAAE,CAAC;QAChB,EAAE,EAAE,aAAa;QACjB,IAAI,EAAE,aAAa;QACnB,OAAO,EAAE,OAAO;QAChB,UAAU,EAAE,GAAG;QACf,WAAW,EAAE,yCAAyC;QACtD,MAAM,EAAE,OAAO;QACf,QAAQ,EAAE,CAAC,iBAAiB,CAAC;QAC7B,QAAQ,EAAE,EAAE;QACZ,gBAAgB,EAAE,EAAE;QACpB,WAAW,EAAE,CAAC,gBAAgB,EAAE,kBAAkB,CAAC;QACnD,GAAG,SAAS;KACb,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,qBAAqB,CAAC,SAAgC;IACpE,OAAO;QACL,EAAE,EAAE,aAAa;QACjB,QAAQ,EAAE,kBAAkB,EAAE;QAC9B,MAAM,EAAE,QAAQ;QAChB,OAAO,EAAE,IAAI;QACb,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QAClC,GAAG,SAAS;KACb,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB;IASjC,OAAO;QACL,YAAY,EAAE,EAAE,CAAC,EAAE,EAAE;QACrB,eAAe,EAAE,EAAE,CAAC,EAAE,EAAE;QACxB,qBAAqB,EAAE,EAAE,CAAC,EAAE,EAAE;QAC9B,aAAa,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,eAAe,CAAC,KAAK,CAAC;QAC7C,WAAW,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,iBAAiB,CAAC,SAAS,CAAC;QACjD,SAAS,EAAE,EAAE,CAAC,EAAE,EAAE;QAClB,OAAO,EAAE,EAAE,CAAC,EAAE,EAAE;KACjB,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,gBAAgB,CAAC,QAAiB;IAChD,MAAM,MAAM,GAAa,EAAE,CAAC;IAE5B,IAAI,CAAC,QAAQ,IAAI,OAAO,QAAQ,KAAK,QAAQ,EAAE,CAAC;QAC9C,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,4BAA4B,CAAC,EAAE,CAAC;IAClE,CAAC;IAED,MAAM,CAAC,GAAG,QAAmC,CAAC;IAE9C,IAAI,CAAC,CAAC,aAAa,KAAK,CAAC,EAAE,CAAC;QAC1B,MAAM,CAAC,IAAI,CAAC,gCAAgC,CAAC,CAAC,aAAa,EAAE,CAAC,CAAC;IACjE,CAAC;IACD,IAAI,OAAO,CAAC,CAAC,EAAE,KAAK,QAAQ,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;QACtC,MAAM,CAAC,IAAI,CAAC,+BAA+B,CAAC,CAAC;IAC/C,CAAC;IACD,IAAI,OAAO,CAAC,CAAC,IAAI,KAAK,QAAQ,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QAC1C,MAAM,CAAC,IAAI,CAAC,iCAAiC,CAAC,CAAC;IACjD,CAAC;IACD,IAAI,OAAO,CAAC,CAAC,OAAO,KAAK,QAAQ,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,OAAiB,CAAC,EAAE,CAAC;QACjF,MAAM,CAAC,IAAI,CAAC,6CAA6C,CAAC,CAAC;IAC7D,CAAC;IACD,IAAI,OAAO,CAAC,CAAC,UAAU,KAAK,QAAQ,IAAI,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC;QACtD,MAAM,CAAC,IAAI,CAAC,uCAAuC,CAAC,CAAC;IACvD,CAAC;IACD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1D,MAAM,CAAC,IAAI,CAAC,oCAAoC,CAAC,CAAC;IACpD,CAAC;IACD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAChE,MAAM,CAAC,IAAI,CAAC,uCAAuC,CAAC,CAAC;IACvD,CAAC;IAED,OAAO,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;AAChD,CAAC;AAED,8BAA8B;AAC9B,OAAO,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,EAAE,EAAE,CAAC"}
|
||||
|
|
@ -0,0 +1,263 @@
|
|||
export type PluginSource = 'official' | 'local' | 'third-party';
|
||||
export interface PluginManifest {
|
||||
schemaVersion: 1;
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
apiVersion: string;
|
||||
description?: string;
|
||||
source?: PluginSource;
|
||||
icon?: string;
|
||||
provides: string[];
|
||||
requires?: string[];
|
||||
optionalRequires?: string[];
|
||||
permissions: Permission[];
|
||||
frontend?: FrontendConfig;
|
||||
backend?: BackendConfig;
|
||||
migrations?: MigrationConfig;
|
||||
contributes?: ContributionPoints;
|
||||
sync?: SyncConfig;
|
||||
}
|
||||
export interface FrontendConfig {
|
||||
entry: string;
|
||||
style?: string;
|
||||
}
|
||||
export interface BackendConfig {
|
||||
type: 'sidecar';
|
||||
entry: Record<string, string>;
|
||||
healthCheck?: HealthCheckConfig;
|
||||
}
|
||||
export interface HealthCheckConfig {
|
||||
type?: 'rpc' | 'stdio' | 'tcp';
|
||||
timeout?: number;
|
||||
}
|
||||
export interface MigrationConfig {
|
||||
path: string;
|
||||
}
|
||||
export interface SyncConfig {
|
||||
namespaces?: string[];
|
||||
participate?: boolean;
|
||||
}
|
||||
export type CapabilityName = string;
|
||||
export interface CapabilityEntry {
|
||||
name: CapabilityName;
|
||||
description: string;
|
||||
status: 'stable' | 'draft' | 'deprecated';
|
||||
}
|
||||
export type Permission = 'vault.read' | 'vault.write' | 'vault.watch' | 'storage.namespace' | 'storage.migrations' | 'events.publish' | 'events.subscribe' | 'ui.register' | 'commands.register' | 'network.local' | 'network.remote' | 'process.spawn' | 'secrets.read' | 'secrets.write' | 'sync.participate';
|
||||
export interface PermissionEntry {
|
||||
name: Permission;
|
||||
description: string;
|
||||
dangerous: boolean;
|
||||
}
|
||||
export interface ContributionPoints {
|
||||
views?: ContributionView[];
|
||||
commands?: ContributionCommand[];
|
||||
settingsPanels?: ContributionSettingsPanel[];
|
||||
sidebarItems?: ContributionSidebarItem[];
|
||||
fileActions?: ContributionAction[];
|
||||
noteActions?: ContributionAction[];
|
||||
contextMenuEntries?: ContributionContextMenuEntry[];
|
||||
searchProviders?: ContributionSearchProvider[];
|
||||
activityProviders?: ContributionActivityProvider[];
|
||||
statusBarItems?: ContributionStatusBarItem[];
|
||||
}
|
||||
export interface ContributionView {
|
||||
id: string;
|
||||
title: string;
|
||||
icon?: string;
|
||||
component: string;
|
||||
}
|
||||
export interface ContributionCommand {
|
||||
id: string;
|
||||
title: string;
|
||||
keybinding?: string;
|
||||
icon?: string;
|
||||
handler?: string;
|
||||
}
|
||||
export interface ContributionSettingsPanel {
|
||||
id: string;
|
||||
title: string;
|
||||
component: string;
|
||||
icon?: string;
|
||||
}
|
||||
export interface ContributionSidebarItem {
|
||||
id: string;
|
||||
title: string;
|
||||
icon?: string;
|
||||
view: string;
|
||||
position?: number;
|
||||
}
|
||||
export interface ContributionAction {
|
||||
id: string;
|
||||
label: string;
|
||||
icon?: string;
|
||||
capability?: CapabilityName;
|
||||
handler?: string;
|
||||
}
|
||||
export interface ContributionContextMenuEntry {
|
||||
id: string;
|
||||
label: string;
|
||||
context: 'file' | 'note' | 'case' | 'folder';
|
||||
group?: string;
|
||||
capability?: CapabilityName;
|
||||
handler?: string;
|
||||
}
|
||||
export interface ContributionSearchProvider {
|
||||
id: string;
|
||||
label: string;
|
||||
handler: string;
|
||||
}
|
||||
export interface ContributionActivityProvider {
|
||||
id: string;
|
||||
events?: string[];
|
||||
handler: string;
|
||||
}
|
||||
export interface ContributionStatusBarItem {
|
||||
id: string;
|
||||
label: string;
|
||||
position?: 'left' | 'right';
|
||||
handler?: string;
|
||||
}
|
||||
export type PluginStatus = 'discovered' | 'disabled' | 'loading' | 'loaded' | 'degraded' | 'failed' | 'incompatible' | 'missing-required-capability';
|
||||
export interface PluginState {
|
||||
id: string;
|
||||
manifest: PluginManifest;
|
||||
status: PluginStatus;
|
||||
error?: string;
|
||||
enabled: boolean;
|
||||
loadedAt?: string;
|
||||
}
|
||||
export interface VerstakEvent {
|
||||
name: string;
|
||||
timestamp: string;
|
||||
payload: Record<string, unknown>;
|
||||
}
|
||||
export interface BrowserCapturePageEvent extends VerstakEvent {
|
||||
name: 'browser.capture.page';
|
||||
payload: {
|
||||
url: string;
|
||||
title: string;
|
||||
html?: string;
|
||||
text?: string;
|
||||
capturedAt: string;
|
||||
domain?: string;
|
||||
};
|
||||
}
|
||||
export interface BrowserCaptureSelectionEvent extends VerstakEvent {
|
||||
name: 'browser.capture.selection';
|
||||
payload: {
|
||||
url: string;
|
||||
title: string;
|
||||
text: string;
|
||||
capturedAt: string;
|
||||
domain?: string;
|
||||
};
|
||||
}
|
||||
export interface BrowserCaptureLinkEvent extends VerstakEvent {
|
||||
name: 'browser.capture.link';
|
||||
payload: {
|
||||
url: string;
|
||||
title?: string;
|
||||
capturedAt: string;
|
||||
domain?: string;
|
||||
};
|
||||
}
|
||||
export interface VaultOpenedEvent extends VerstakEvent {
|
||||
name: 'vault.opened';
|
||||
payload: {
|
||||
path: string;
|
||||
version?: string;
|
||||
openedAt: string;
|
||||
};
|
||||
}
|
||||
export interface CaseSelectedEvent extends VerstakEvent {
|
||||
name: 'case.selected';
|
||||
payload: {
|
||||
caseId: string;
|
||||
casePath: string;
|
||||
caseType?: string;
|
||||
selectedAt: string;
|
||||
};
|
||||
}
|
||||
export interface FileChangedEvent extends VerstakEvent {
|
||||
name: 'file.changed';
|
||||
payload: {
|
||||
path: string;
|
||||
size?: number;
|
||||
changedAt: string;
|
||||
};
|
||||
}
|
||||
export interface NoteSavedEvent extends VerstakEvent {
|
||||
name: 'note.saved';
|
||||
payload: {
|
||||
noteId: string;
|
||||
title?: string;
|
||||
path: string;
|
||||
caseId?: string;
|
||||
savedAt: string;
|
||||
};
|
||||
}
|
||||
export interface PluginEnabledEvent extends VerstakEvent {
|
||||
name: 'plugin.enabled';
|
||||
payload: {
|
||||
pluginId: string;
|
||||
version?: string;
|
||||
enabledAt: string;
|
||||
};
|
||||
}
|
||||
export interface PluginDisabledEvent extends VerstakEvent {
|
||||
name: 'plugin.disabled';
|
||||
payload: {
|
||||
pluginId: string;
|
||||
disabledAt: string;
|
||||
};
|
||||
}
|
||||
export type SyncOpType = 'add' | 'modify' | 'delete' | 'rename';
|
||||
export type SyncEntityType = 'file' | 'note' | 'plugin_state' | 'vault_meta';
|
||||
export interface SyncOperation {
|
||||
op: SyncOpType;
|
||||
id: string;
|
||||
timestamp: string;
|
||||
deviceId?: string;
|
||||
entityType?: SyncEntityType;
|
||||
entityPath?: string;
|
||||
hash?: string;
|
||||
size?: number;
|
||||
mimeType?: string;
|
||||
pluginNamespace?: string;
|
||||
oldPath?: string;
|
||||
metadata?: Record<string, string>;
|
||||
}
|
||||
export interface SyncBatch {
|
||||
batchId: string;
|
||||
deviceId: string;
|
||||
operations: SyncOperation[];
|
||||
timestamp: string;
|
||||
lastSyncTimestamp?: string;
|
||||
sequence?: number;
|
||||
}
|
||||
export interface SyncManifestEntry {
|
||||
path: string;
|
||||
hash: string;
|
||||
size?: number;
|
||||
updatedAt: string;
|
||||
deleted?: boolean;
|
||||
}
|
||||
export interface SyncManifest {
|
||||
deviceId: string;
|
||||
entries: SyncManifestEntry[];
|
||||
}
|
||||
export interface Conflict {
|
||||
entityPath: string;
|
||||
localHash: string;
|
||||
remoteHash: string;
|
||||
localTimestamp: string;
|
||||
remoteTimestamp: string;
|
||||
resolution?: 'local_wins' | 'remote_wins' | 'manual';
|
||||
resolvedAt?: string;
|
||||
}
|
||||
export interface PluginSettings {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
//# sourceMappingURL=types.d.ts.map
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,3 @@
|
|||
// Verstak Plugin SDK — Core TypeScript Types
|
||||
export {};
|
||||
//# sourceMappingURL=types.js.map
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,6CAA6C"}
|
||||
|
|
@ -0,0 +1 @@
|
|||
../acorn/bin/acorn
|
||||
|
|
@ -0,0 +1 @@
|
|||
../esbuild/bin/esbuild
|
||||
|
|
@ -0,0 +1 @@
|
|||
../nanoid/bin/nanoid.cjs
|
||||
|
|
@ -0,0 +1 @@
|
|||
../which/bin/node-which
|
||||
|
|
@ -0,0 +1 @@
|
|||
../rollup/dist/bin/rollup
|
||||
|
|
@ -0,0 +1 @@
|
|||
../typescript/bin/tsc
|
||||
|
|
@ -0,0 +1 @@
|
|||
../typescript/bin/tsserver
|
||||
|
|
@ -0,0 +1 @@
|
|||
../vite/bin/vite.js
|
||||
|
|
@ -0,0 +1 @@
|
|||
../vite-node/vite-node.mjs
|
||||
|
|
@ -0,0 +1 @@
|
|||
../vitest/vitest.mjs
|
||||
|
|
@ -0,0 +1 @@
|
|||
../why-is-node-running/cli.js
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,3 @@
|
|||
# esbuild
|
||||
|
||||
This is the Linux 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details.
|
||||
Binary file not shown.
|
|
@ -0,0 +1,20 @@
|
|||
{
|
||||
"name": "@esbuild/linux-x64",
|
||||
"version": "0.21.5",
|
||||
"description": "The Linux 64-bit binary for esbuild, a JavaScript bundler.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/evanw/esbuild.git"
|
||||
},
|
||||
"license": "MIT",
|
||||
"preferUnplugged": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
|
||||
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.
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
# `@jest/schemas`
|
||||
|
||||
Experimental and currently incomplete module for JSON schemas for [Jest's](https://jestjs.io/) configuration.
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
import {Static} from '@sinclair/typebox';
|
||||
import {TBoolean} from '@sinclair/typebox';
|
||||
import {TNull} from '@sinclair/typebox';
|
||||
import {TNumber} from '@sinclair/typebox';
|
||||
import {TObject} from '@sinclair/typebox';
|
||||
import {TReadonlyOptional} from '@sinclair/typebox';
|
||||
import {TString} from '@sinclair/typebox';
|
||||
|
||||
declare const RawSnapshotFormat: TObject<{
|
||||
callToJSON: TReadonlyOptional<TBoolean>;
|
||||
compareKeys: TReadonlyOptional<TNull>;
|
||||
escapeRegex: TReadonlyOptional<TBoolean>;
|
||||
escapeString: TReadonlyOptional<TBoolean>;
|
||||
highlight: TReadonlyOptional<TBoolean>;
|
||||
indent: TReadonlyOptional<TNumber>;
|
||||
maxDepth: TReadonlyOptional<TNumber>;
|
||||
maxWidth: TReadonlyOptional<TNumber>;
|
||||
min: TReadonlyOptional<TBoolean>;
|
||||
printBasicPrototype: TReadonlyOptional<TBoolean>;
|
||||
printFunctionName: TReadonlyOptional<TBoolean>;
|
||||
theme: TReadonlyOptional<
|
||||
TObject<{
|
||||
comment: TReadonlyOptional<TString<string>>;
|
||||
content: TReadonlyOptional<TString<string>>;
|
||||
prop: TReadonlyOptional<TString<string>>;
|
||||
tag: TReadonlyOptional<TString<string>>;
|
||||
value: TReadonlyOptional<TString<string>>;
|
||||
}>
|
||||
>;
|
||||
}>;
|
||||
|
||||
export declare const SnapshotFormat: TObject<{
|
||||
callToJSON: TReadonlyOptional<TBoolean>;
|
||||
compareKeys: TReadonlyOptional<TNull>;
|
||||
escapeRegex: TReadonlyOptional<TBoolean>;
|
||||
escapeString: TReadonlyOptional<TBoolean>;
|
||||
highlight: TReadonlyOptional<TBoolean>;
|
||||
indent: TReadonlyOptional<TNumber>;
|
||||
maxDepth: TReadonlyOptional<TNumber>;
|
||||
maxWidth: TReadonlyOptional<TNumber>;
|
||||
min: TReadonlyOptional<TBoolean>;
|
||||
printBasicPrototype: TReadonlyOptional<TBoolean>;
|
||||
printFunctionName: TReadonlyOptional<TBoolean>;
|
||||
theme: TReadonlyOptional<
|
||||
TObject<{
|
||||
comment: TReadonlyOptional<TString<string>>;
|
||||
content: TReadonlyOptional<TString<string>>;
|
||||
prop: TReadonlyOptional<TString<string>>;
|
||||
tag: TReadonlyOptional<TString<string>>;
|
||||
value: TReadonlyOptional<TString<string>>;
|
||||
}>
|
||||
>;
|
||||
}>;
|
||||
|
||||
export declare type SnapshotFormat = Static<typeof RawSnapshotFormat>;
|
||||
|
||||
export {};
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', {
|
||||
value: true
|
||||
});
|
||||
exports.SnapshotFormat = void 0;
|
||||
function _typebox() {
|
||||
const data = require('@sinclair/typebox');
|
||||
_typebox = function () {
|
||||
return data;
|
||||
};
|
||||
return data;
|
||||
}
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
const RawSnapshotFormat = _typebox().Type.Partial(
|
||||
_typebox().Type.Object({
|
||||
callToJSON: _typebox().Type.Readonly(_typebox().Type.Boolean()),
|
||||
compareKeys: _typebox().Type.Readonly(_typebox().Type.Null()),
|
||||
escapeRegex: _typebox().Type.Readonly(_typebox().Type.Boolean()),
|
||||
escapeString: _typebox().Type.Readonly(_typebox().Type.Boolean()),
|
||||
highlight: _typebox().Type.Readonly(_typebox().Type.Boolean()),
|
||||
indent: _typebox().Type.Readonly(
|
||||
_typebox().Type.Number({
|
||||
minimum: 0
|
||||
})
|
||||
),
|
||||
maxDepth: _typebox().Type.Readonly(
|
||||
_typebox().Type.Number({
|
||||
minimum: 0
|
||||
})
|
||||
),
|
||||
maxWidth: _typebox().Type.Readonly(
|
||||
_typebox().Type.Number({
|
||||
minimum: 0
|
||||
})
|
||||
),
|
||||
min: _typebox().Type.Readonly(_typebox().Type.Boolean()),
|
||||
printBasicPrototype: _typebox().Type.Readonly(_typebox().Type.Boolean()),
|
||||
printFunctionName: _typebox().Type.Readonly(_typebox().Type.Boolean()),
|
||||
theme: _typebox().Type.Readonly(
|
||||
_typebox().Type.Partial(
|
||||
_typebox().Type.Object({
|
||||
comment: _typebox().Type.Readonly(_typebox().Type.String()),
|
||||
content: _typebox().Type.Readonly(_typebox().Type.String()),
|
||||
prop: _typebox().Type.Readonly(_typebox().Type.String()),
|
||||
tag: _typebox().Type.Readonly(_typebox().Type.String()),
|
||||
value: _typebox().Type.Readonly(_typebox().Type.String())
|
||||
})
|
||||
)
|
||||
)
|
||||
})
|
||||
);
|
||||
const SnapshotFormat = _typebox().Type.Strict(RawSnapshotFormat);
|
||||
exports.SnapshotFormat = SnapshotFormat;
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
{
|
||||
"name": "@jest/schemas",
|
||||
"version": "29.6.3",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/jestjs/jest.git",
|
||||
"directory": "packages/jest-schemas"
|
||||
},
|
||||
"license": "MIT",
|
||||
"main": "./build/index.js",
|
||||
"types": "./build/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./build/index.d.ts",
|
||||
"default": "./build/index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@sinclair/typebox": "^0.27.8"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"gitHead": "fb7d95c8af6e0d65a8b65348433d8a0ea0725b5b"
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
Copyright 2024 Justin Ridgewell <justin@ridgewell.name>
|
||||
|
||||
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.
|
||||
|
|
@ -0,0 +1,264 @@
|
|||
# @jridgewell/sourcemap-codec
|
||||
|
||||
Encode/decode the `mappings` property of a [sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit).
|
||||
|
||||
|
||||
## Why?
|
||||
|
||||
Sourcemaps are difficult to generate and manipulate, because the `mappings` property – the part that actually links the generated code back to the original source – is encoded using an obscure method called [Variable-length quantity](https://en.wikipedia.org/wiki/Variable-length_quantity). On top of that, each segment in the mapping contains offsets rather than absolute indices, which means that you can't look at a segment in isolation – you have to understand the whole sourcemap.
|
||||
|
||||
This package makes the process slightly easier.
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @jridgewell/sourcemap-codec
|
||||
```
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
import { encode, decode } from '@jridgewell/sourcemap-codec';
|
||||
|
||||
var decoded = decode( ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' );
|
||||
|
||||
assert.deepEqual( decoded, [
|
||||
// the first line (of the generated code) has no mappings,
|
||||
// as shown by the starting semi-colon (which separates lines)
|
||||
[],
|
||||
|
||||
// the second line contains four (comma-separated) segments
|
||||
[
|
||||
// segments are encoded as you'd expect:
|
||||
// [ generatedCodeColumn, sourceIndex, sourceCodeLine, sourceCodeColumn, nameIndex ]
|
||||
|
||||
// i.e. the first segment begins at column 2, and maps back to the second column
|
||||
// of the second line (both zero-based) of the 0th source, and uses the 0th
|
||||
// name in the `map.names` array
|
||||
[ 2, 0, 2, 2, 0 ],
|
||||
|
||||
// the remaining segments are 4-length rather than 5-length,
|
||||
// because they don't map a name
|
||||
[ 4, 0, 2, 4 ],
|
||||
[ 6, 0, 2, 5 ],
|
||||
[ 7, 0, 2, 7 ]
|
||||
],
|
||||
|
||||
// the final line contains two segments
|
||||
[
|
||||
[ 2, 1, 10, 19 ],
|
||||
[ 12, 1, 11, 20 ]
|
||||
]
|
||||
]);
|
||||
|
||||
var encoded = encode( decoded );
|
||||
assert.equal( encoded, ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' );
|
||||
```
|
||||
|
||||
## Benchmarks
|
||||
|
||||
```
|
||||
node v20.10.0
|
||||
|
||||
amp.js.map - 45120 segments
|
||||
|
||||
Decode Memory Usage:
|
||||
local code 5815135 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 5868160 bytes
|
||||
sourcemap-codec 5492584 bytes
|
||||
source-map-0.6.1 13569984 bytes
|
||||
source-map-0.8.0 6390584 bytes
|
||||
chrome dev tools 8011136 bytes
|
||||
Smallest memory usage is sourcemap-codec
|
||||
|
||||
Decode speed:
|
||||
decode: local code x 492 ops/sec ±1.22% (90 runs sampled)
|
||||
decode: @jridgewell/sourcemap-codec 1.4.15 x 499 ops/sec ±1.16% (89 runs sampled)
|
||||
decode: sourcemap-codec x 376 ops/sec ±1.66% (89 runs sampled)
|
||||
decode: source-map-0.6.1 x 34.99 ops/sec ±0.94% (48 runs sampled)
|
||||
decode: source-map-0.8.0 x 351 ops/sec ±0.07% (95 runs sampled)
|
||||
chrome dev tools x 165 ops/sec ±0.91% (86 runs sampled)
|
||||
Fastest is decode: @jridgewell/sourcemap-codec 1.4.15
|
||||
|
||||
Encode Memory Usage:
|
||||
local code 444248 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 623024 bytes
|
||||
sourcemap-codec 8696280 bytes
|
||||
source-map-0.6.1 8745176 bytes
|
||||
source-map-0.8.0 8736624 bytes
|
||||
Smallest memory usage is local code
|
||||
|
||||
Encode speed:
|
||||
encode: local code x 796 ops/sec ±0.11% (97 runs sampled)
|
||||
encode: @jridgewell/sourcemap-codec 1.4.15 x 795 ops/sec ±0.25% (98 runs sampled)
|
||||
encode: sourcemap-codec x 231 ops/sec ±0.83% (86 runs sampled)
|
||||
encode: source-map-0.6.1 x 166 ops/sec ±0.57% (86 runs sampled)
|
||||
encode: source-map-0.8.0 x 203 ops/sec ±0.45% (88 runs sampled)
|
||||
Fastest is encode: local code,encode: @jridgewell/sourcemap-codec 1.4.15
|
||||
|
||||
|
||||
***
|
||||
|
||||
|
||||
babel.min.js.map - 347793 segments
|
||||
|
||||
Decode Memory Usage:
|
||||
local code 35424960 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 35424696 bytes
|
||||
sourcemap-codec 36033464 bytes
|
||||
source-map-0.6.1 62253704 bytes
|
||||
source-map-0.8.0 43843920 bytes
|
||||
chrome dev tools 45111400 bytes
|
||||
Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15
|
||||
|
||||
Decode speed:
|
||||
decode: local code x 38.18 ops/sec ±5.44% (52 runs sampled)
|
||||
decode: @jridgewell/sourcemap-codec 1.4.15 x 38.36 ops/sec ±5.02% (52 runs sampled)
|
||||
decode: sourcemap-codec x 34.05 ops/sec ±4.45% (47 runs sampled)
|
||||
decode: source-map-0.6.1 x 4.31 ops/sec ±2.76% (15 runs sampled)
|
||||
decode: source-map-0.8.0 x 55.60 ops/sec ±0.13% (73 runs sampled)
|
||||
chrome dev tools x 16.94 ops/sec ±3.78% (46 runs sampled)
|
||||
Fastest is decode: source-map-0.8.0
|
||||
|
||||
Encode Memory Usage:
|
||||
local code 2606016 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 2626440 bytes
|
||||
sourcemap-codec 21152576 bytes
|
||||
source-map-0.6.1 25023928 bytes
|
||||
source-map-0.8.0 25256448 bytes
|
||||
Smallest memory usage is local code
|
||||
|
||||
Encode speed:
|
||||
encode: local code x 127 ops/sec ±0.18% (83 runs sampled)
|
||||
encode: @jridgewell/sourcemap-codec 1.4.15 x 128 ops/sec ±0.26% (83 runs sampled)
|
||||
encode: sourcemap-codec x 29.31 ops/sec ±2.55% (53 runs sampled)
|
||||
encode: source-map-0.6.1 x 18.85 ops/sec ±3.19% (36 runs sampled)
|
||||
encode: source-map-0.8.0 x 19.34 ops/sec ±1.97% (36 runs sampled)
|
||||
Fastest is encode: @jridgewell/sourcemap-codec 1.4.15
|
||||
|
||||
|
||||
***
|
||||
|
||||
|
||||
preact.js.map - 1992 segments
|
||||
|
||||
Decode Memory Usage:
|
||||
local code 261696 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 244296 bytes
|
||||
sourcemap-codec 302816 bytes
|
||||
source-map-0.6.1 939176 bytes
|
||||
source-map-0.8.0 336 bytes
|
||||
chrome dev tools 587368 bytes
|
||||
Smallest memory usage is source-map-0.8.0
|
||||
|
||||
Decode speed:
|
||||
decode: local code x 17,782 ops/sec ±0.32% (97 runs sampled)
|
||||
decode: @jridgewell/sourcemap-codec 1.4.15 x 17,863 ops/sec ±0.40% (100 runs sampled)
|
||||
decode: sourcemap-codec x 12,453 ops/sec ±0.27% (101 runs sampled)
|
||||
decode: source-map-0.6.1 x 1,288 ops/sec ±1.05% (96 runs sampled)
|
||||
decode: source-map-0.8.0 x 9,289 ops/sec ±0.27% (101 runs sampled)
|
||||
chrome dev tools x 4,769 ops/sec ±0.18% (100 runs sampled)
|
||||
Fastest is decode: @jridgewell/sourcemap-codec 1.4.15
|
||||
|
||||
Encode Memory Usage:
|
||||
local code 262944 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 25544 bytes
|
||||
sourcemap-codec 323048 bytes
|
||||
source-map-0.6.1 507808 bytes
|
||||
source-map-0.8.0 507480 bytes
|
||||
Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15
|
||||
|
||||
Encode speed:
|
||||
encode: local code x 24,207 ops/sec ±0.79% (95 runs sampled)
|
||||
encode: @jridgewell/sourcemap-codec 1.4.15 x 24,288 ops/sec ±0.48% (96 runs sampled)
|
||||
encode: sourcemap-codec x 6,761 ops/sec ±0.21% (100 runs sampled)
|
||||
encode: source-map-0.6.1 x 5,374 ops/sec ±0.17% (99 runs sampled)
|
||||
encode: source-map-0.8.0 x 5,633 ops/sec ±0.32% (99 runs sampled)
|
||||
Fastest is encode: @jridgewell/sourcemap-codec 1.4.15,encode: local code
|
||||
|
||||
|
||||
***
|
||||
|
||||
|
||||
react.js.map - 5726 segments
|
||||
|
||||
Decode Memory Usage:
|
||||
local code 678816 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 678816 bytes
|
||||
sourcemap-codec 816400 bytes
|
||||
source-map-0.6.1 2288864 bytes
|
||||
source-map-0.8.0 721360 bytes
|
||||
chrome dev tools 1012512 bytes
|
||||
Smallest memory usage is local code
|
||||
|
||||
Decode speed:
|
||||
decode: local code x 6,178 ops/sec ±0.19% (98 runs sampled)
|
||||
decode: @jridgewell/sourcemap-codec 1.4.15 x 6,261 ops/sec ±0.22% (100 runs sampled)
|
||||
decode: sourcemap-codec x 4,472 ops/sec ±0.90% (99 runs sampled)
|
||||
decode: source-map-0.6.1 x 449 ops/sec ±0.31% (95 runs sampled)
|
||||
decode: source-map-0.8.0 x 3,219 ops/sec ±0.13% (100 runs sampled)
|
||||
chrome dev tools x 1,743 ops/sec ±0.20% (99 runs sampled)
|
||||
Fastest is decode: @jridgewell/sourcemap-codec 1.4.15
|
||||
|
||||
Encode Memory Usage:
|
||||
local code 140960 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 159808 bytes
|
||||
sourcemap-codec 969304 bytes
|
||||
source-map-0.6.1 930520 bytes
|
||||
source-map-0.8.0 930248 bytes
|
||||
Smallest memory usage is local code
|
||||
|
||||
Encode speed:
|
||||
encode: local code x 8,013 ops/sec ±0.19% (100 runs sampled)
|
||||
encode: @jridgewell/sourcemap-codec 1.4.15 x 7,989 ops/sec ±0.20% (101 runs sampled)
|
||||
encode: sourcemap-codec x 2,472 ops/sec ±0.21% (99 runs sampled)
|
||||
encode: source-map-0.6.1 x 2,200 ops/sec ±0.17% (99 runs sampled)
|
||||
encode: source-map-0.8.0 x 2,220 ops/sec ±0.37% (99 runs sampled)
|
||||
Fastest is encode: local code
|
||||
|
||||
|
||||
***
|
||||
|
||||
|
||||
vscode.map - 2141001 segments
|
||||
|
||||
Decode Memory Usage:
|
||||
local code 198955264 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 199175352 bytes
|
||||
sourcemap-codec 199102688 bytes
|
||||
source-map-0.6.1 386323432 bytes
|
||||
source-map-0.8.0 244116432 bytes
|
||||
chrome dev tools 293734280 bytes
|
||||
Smallest memory usage is local code
|
||||
|
||||
Decode speed:
|
||||
decode: local code x 3.90 ops/sec ±22.21% (15 runs sampled)
|
||||
decode: @jridgewell/sourcemap-codec 1.4.15 x 3.95 ops/sec ±23.53% (15 runs sampled)
|
||||
decode: sourcemap-codec x 3.82 ops/sec ±17.94% (14 runs sampled)
|
||||
decode: source-map-0.6.1 x 0.61 ops/sec ±7.81% (6 runs sampled)
|
||||
decode: source-map-0.8.0 x 9.54 ops/sec ±0.28% (28 runs sampled)
|
||||
chrome dev tools x 2.18 ops/sec ±10.58% (10 runs sampled)
|
||||
Fastest is decode: source-map-0.8.0
|
||||
|
||||
Encode Memory Usage:
|
||||
local code 13509880 bytes
|
||||
@jridgewell/sourcemap-codec 1.4.15 13537648 bytes
|
||||
sourcemap-codec 32540104 bytes
|
||||
source-map-0.6.1 127531040 bytes
|
||||
source-map-0.8.0 127535312 bytes
|
||||
Smallest memory usage is local code
|
||||
|
||||
Encode speed:
|
||||
encode: local code x 20.10 ops/sec ±0.19% (38 runs sampled)
|
||||
encode: @jridgewell/sourcemap-codec 1.4.15 x 20.26 ops/sec ±0.32% (38 runs sampled)
|
||||
encode: sourcemap-codec x 5.44 ops/sec ±1.64% (18 runs sampled)
|
||||
encode: source-map-0.6.1 x 2.30 ops/sec ±4.79% (10 runs sampled)
|
||||
encode: source-map-0.8.0 x 2.46 ops/sec ±6.53% (10 runs sampled)
|
||||
Fastest is encode: @jridgewell/sourcemap-codec 1.4.15
|
||||
```
|
||||
|
||||
# License
|
||||
|
||||
MIT
|
||||
423
node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
generated
vendored
Normal file
423
node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
generated
vendored
Normal file
|
|
@ -0,0 +1,423 @@
|
|||
// src/vlq.ts
|
||||
var comma = ",".charCodeAt(0);
|
||||
var semicolon = ";".charCodeAt(0);
|
||||
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
var intToChar = new Uint8Array(64);
|
||||
var charToInt = new Uint8Array(128);
|
||||
for (let i = 0; i < chars.length; i++) {
|
||||
const c = chars.charCodeAt(i);
|
||||
intToChar[i] = c;
|
||||
charToInt[c] = i;
|
||||
}
|
||||
function decodeInteger(reader, relative) {
|
||||
let value = 0;
|
||||
let shift = 0;
|
||||
let integer = 0;
|
||||
do {
|
||||
const c = reader.next();
|
||||
integer = charToInt[c];
|
||||
value |= (integer & 31) << shift;
|
||||
shift += 5;
|
||||
} while (integer & 32);
|
||||
const shouldNegate = value & 1;
|
||||
value >>>= 1;
|
||||
if (shouldNegate) {
|
||||
value = -2147483648 | -value;
|
||||
}
|
||||
return relative + value;
|
||||
}
|
||||
function encodeInteger(builder, num, relative) {
|
||||
let delta = num - relative;
|
||||
delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
|
||||
do {
|
||||
let clamped = delta & 31;
|
||||
delta >>>= 5;
|
||||
if (delta > 0) clamped |= 32;
|
||||
builder.write(intToChar[clamped]);
|
||||
} while (delta > 0);
|
||||
return num;
|
||||
}
|
||||
function hasMoreVlq(reader, max) {
|
||||
if (reader.pos >= max) return false;
|
||||
return reader.peek() !== comma;
|
||||
}
|
||||
|
||||
// src/strings.ts
|
||||
var bufLength = 1024 * 16;
|
||||
var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
|
||||
decode(buf) {
|
||||
const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||
return out.toString();
|
||||
}
|
||||
} : {
|
||||
decode(buf) {
|
||||
let out = "";
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
out += String.fromCharCode(buf[i]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
};
|
||||
var StringWriter = class {
|
||||
constructor() {
|
||||
this.pos = 0;
|
||||
this.out = "";
|
||||
this.buffer = new Uint8Array(bufLength);
|
||||
}
|
||||
write(v) {
|
||||
const { buffer } = this;
|
||||
buffer[this.pos++] = v;
|
||||
if (this.pos === bufLength) {
|
||||
this.out += td.decode(buffer);
|
||||
this.pos = 0;
|
||||
}
|
||||
}
|
||||
flush() {
|
||||
const { buffer, out, pos } = this;
|
||||
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
|
||||
}
|
||||
};
|
||||
var StringReader = class {
|
||||
constructor(buffer) {
|
||||
this.pos = 0;
|
||||
this.buffer = buffer;
|
||||
}
|
||||
next() {
|
||||
return this.buffer.charCodeAt(this.pos++);
|
||||
}
|
||||
peek() {
|
||||
return this.buffer.charCodeAt(this.pos);
|
||||
}
|
||||
indexOf(char) {
|
||||
const { buffer, pos } = this;
|
||||
const idx = buffer.indexOf(char, pos);
|
||||
return idx === -1 ? buffer.length : idx;
|
||||
}
|
||||
};
|
||||
|
||||
// src/scopes.ts
|
||||
var EMPTY = [];
|
||||
function decodeOriginalScopes(input) {
|
||||
const { length } = input;
|
||||
const reader = new StringReader(input);
|
||||
const scopes = [];
|
||||
const stack = [];
|
||||
let line = 0;
|
||||
for (; reader.pos < length; reader.pos++) {
|
||||
line = decodeInteger(reader, line);
|
||||
const column = decodeInteger(reader, 0);
|
||||
if (!hasMoreVlq(reader, length)) {
|
||||
const last = stack.pop();
|
||||
last[2] = line;
|
||||
last[3] = column;
|
||||
continue;
|
||||
}
|
||||
const kind = decodeInteger(reader, 0);
|
||||
const fields = decodeInteger(reader, 0);
|
||||
const hasName = fields & 1;
|
||||
const scope = hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind];
|
||||
let vars = EMPTY;
|
||||
if (hasMoreVlq(reader, length)) {
|
||||
vars = [];
|
||||
do {
|
||||
const varsIndex = decodeInteger(reader, 0);
|
||||
vars.push(varsIndex);
|
||||
} while (hasMoreVlq(reader, length));
|
||||
}
|
||||
scope.vars = vars;
|
||||
scopes.push(scope);
|
||||
stack.push(scope);
|
||||
}
|
||||
return scopes;
|
||||
}
|
||||
function encodeOriginalScopes(scopes) {
|
||||
const writer = new StringWriter();
|
||||
for (let i = 0; i < scopes.length; ) {
|
||||
i = _encodeOriginalScopes(scopes, i, writer, [0]);
|
||||
}
|
||||
return writer.flush();
|
||||
}
|
||||
function _encodeOriginalScopes(scopes, index, writer, state) {
|
||||
const scope = scopes[index];
|
||||
const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;
|
||||
if (index > 0) writer.write(comma);
|
||||
state[0] = encodeInteger(writer, startLine, state[0]);
|
||||
encodeInteger(writer, startColumn, 0);
|
||||
encodeInteger(writer, kind, 0);
|
||||
const fields = scope.length === 6 ? 1 : 0;
|
||||
encodeInteger(writer, fields, 0);
|
||||
if (scope.length === 6) encodeInteger(writer, scope[5], 0);
|
||||
for (const v of vars) {
|
||||
encodeInteger(writer, v, 0);
|
||||
}
|
||||
for (index++; index < scopes.length; ) {
|
||||
const next = scopes[index];
|
||||
const { 0: l, 1: c } = next;
|
||||
if (l > endLine || l === endLine && c >= endColumn) {
|
||||
break;
|
||||
}
|
||||
index = _encodeOriginalScopes(scopes, index, writer, state);
|
||||
}
|
||||
writer.write(comma);
|
||||
state[0] = encodeInteger(writer, endLine, state[0]);
|
||||
encodeInteger(writer, endColumn, 0);
|
||||
return index;
|
||||
}
|
||||
function decodeGeneratedRanges(input) {
|
||||
const { length } = input;
|
||||
const reader = new StringReader(input);
|
||||
const ranges = [];
|
||||
const stack = [];
|
||||
let genLine = 0;
|
||||
let definitionSourcesIndex = 0;
|
||||
let definitionScopeIndex = 0;
|
||||
let callsiteSourcesIndex = 0;
|
||||
let callsiteLine = 0;
|
||||
let callsiteColumn = 0;
|
||||
let bindingLine = 0;
|
||||
let bindingColumn = 0;
|
||||
do {
|
||||
const semi = reader.indexOf(";");
|
||||
let genColumn = 0;
|
||||
for (; reader.pos < semi; reader.pos++) {
|
||||
genColumn = decodeInteger(reader, genColumn);
|
||||
if (!hasMoreVlq(reader, semi)) {
|
||||
const last = stack.pop();
|
||||
last[2] = genLine;
|
||||
last[3] = genColumn;
|
||||
continue;
|
||||
}
|
||||
const fields = decodeInteger(reader, 0);
|
||||
const hasDefinition = fields & 1;
|
||||
const hasCallsite = fields & 2;
|
||||
const hasScope = fields & 4;
|
||||
let callsite = null;
|
||||
let bindings = EMPTY;
|
||||
let range;
|
||||
if (hasDefinition) {
|
||||
const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);
|
||||
definitionScopeIndex = decodeInteger(
|
||||
reader,
|
||||
definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0
|
||||
);
|
||||
definitionSourcesIndex = defSourcesIndex;
|
||||
range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex];
|
||||
} else {
|
||||
range = [genLine, genColumn, 0, 0];
|
||||
}
|
||||
range.isScope = !!hasScope;
|
||||
if (hasCallsite) {
|
||||
const prevCsi = callsiteSourcesIndex;
|
||||
const prevLine = callsiteLine;
|
||||
callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);
|
||||
const sameSource = prevCsi === callsiteSourcesIndex;
|
||||
callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);
|
||||
callsiteColumn = decodeInteger(
|
||||
reader,
|
||||
sameSource && prevLine === callsiteLine ? callsiteColumn : 0
|
||||
);
|
||||
callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];
|
||||
}
|
||||
range.callsite = callsite;
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
bindings = [];
|
||||
do {
|
||||
bindingLine = genLine;
|
||||
bindingColumn = genColumn;
|
||||
const expressionsCount = decodeInteger(reader, 0);
|
||||
let expressionRanges;
|
||||
if (expressionsCount < -1) {
|
||||
expressionRanges = [[decodeInteger(reader, 0)]];
|
||||
for (let i = -1; i > expressionsCount; i--) {
|
||||
const prevBl = bindingLine;
|
||||
bindingLine = decodeInteger(reader, bindingLine);
|
||||
bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);
|
||||
const expression = decodeInteger(reader, 0);
|
||||
expressionRanges.push([expression, bindingLine, bindingColumn]);
|
||||
}
|
||||
} else {
|
||||
expressionRanges = [[expressionsCount]];
|
||||
}
|
||||
bindings.push(expressionRanges);
|
||||
} while (hasMoreVlq(reader, semi));
|
||||
}
|
||||
range.bindings = bindings;
|
||||
ranges.push(range);
|
||||
stack.push(range);
|
||||
}
|
||||
genLine++;
|
||||
reader.pos = semi + 1;
|
||||
} while (reader.pos < length);
|
||||
return ranges;
|
||||
}
|
||||
function encodeGeneratedRanges(ranges) {
|
||||
if (ranges.length === 0) return "";
|
||||
const writer = new StringWriter();
|
||||
for (let i = 0; i < ranges.length; ) {
|
||||
i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);
|
||||
}
|
||||
return writer.flush();
|
||||
}
|
||||
function _encodeGeneratedRanges(ranges, index, writer, state) {
|
||||
const range = ranges[index];
|
||||
const {
|
||||
0: startLine,
|
||||
1: startColumn,
|
||||
2: endLine,
|
||||
3: endColumn,
|
||||
isScope,
|
||||
callsite,
|
||||
bindings
|
||||
} = range;
|
||||
if (state[0] < startLine) {
|
||||
catchupLine(writer, state[0], startLine);
|
||||
state[0] = startLine;
|
||||
state[1] = 0;
|
||||
} else if (index > 0) {
|
||||
writer.write(comma);
|
||||
}
|
||||
state[1] = encodeInteger(writer, range[1], state[1]);
|
||||
const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0);
|
||||
encodeInteger(writer, fields, 0);
|
||||
if (range.length === 6) {
|
||||
const { 4: sourcesIndex, 5: scopesIndex } = range;
|
||||
if (sourcesIndex !== state[2]) {
|
||||
state[3] = 0;
|
||||
}
|
||||
state[2] = encodeInteger(writer, sourcesIndex, state[2]);
|
||||
state[3] = encodeInteger(writer, scopesIndex, state[3]);
|
||||
}
|
||||
if (callsite) {
|
||||
const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite;
|
||||
if (sourcesIndex !== state[4]) {
|
||||
state[5] = 0;
|
||||
state[6] = 0;
|
||||
} else if (callLine !== state[5]) {
|
||||
state[6] = 0;
|
||||
}
|
||||
state[4] = encodeInteger(writer, sourcesIndex, state[4]);
|
||||
state[5] = encodeInteger(writer, callLine, state[5]);
|
||||
state[6] = encodeInteger(writer, callColumn, state[6]);
|
||||
}
|
||||
if (bindings) {
|
||||
for (const binding of bindings) {
|
||||
if (binding.length > 1) encodeInteger(writer, -binding.length, 0);
|
||||
const expression = binding[0][0];
|
||||
encodeInteger(writer, expression, 0);
|
||||
let bindingStartLine = startLine;
|
||||
let bindingStartColumn = startColumn;
|
||||
for (let i = 1; i < binding.length; i++) {
|
||||
const expRange = binding[i];
|
||||
bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine);
|
||||
bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn);
|
||||
encodeInteger(writer, expRange[0], 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (index++; index < ranges.length; ) {
|
||||
const next = ranges[index];
|
||||
const { 0: l, 1: c } = next;
|
||||
if (l > endLine || l === endLine && c >= endColumn) {
|
||||
break;
|
||||
}
|
||||
index = _encodeGeneratedRanges(ranges, index, writer, state);
|
||||
}
|
||||
if (state[0] < endLine) {
|
||||
catchupLine(writer, state[0], endLine);
|
||||
state[0] = endLine;
|
||||
state[1] = 0;
|
||||
} else {
|
||||
writer.write(comma);
|
||||
}
|
||||
state[1] = encodeInteger(writer, endColumn, state[1]);
|
||||
return index;
|
||||
}
|
||||
function catchupLine(writer, lastLine, line) {
|
||||
do {
|
||||
writer.write(semicolon);
|
||||
} while (++lastLine < line);
|
||||
}
|
||||
|
||||
// src/sourcemap-codec.ts
|
||||
function decode(mappings) {
|
||||
const { length } = mappings;
|
||||
const reader = new StringReader(mappings);
|
||||
const decoded = [];
|
||||
let genColumn = 0;
|
||||
let sourcesIndex = 0;
|
||||
let sourceLine = 0;
|
||||
let sourceColumn = 0;
|
||||
let namesIndex = 0;
|
||||
do {
|
||||
const semi = reader.indexOf(";");
|
||||
const line = [];
|
||||
let sorted = true;
|
||||
let lastCol = 0;
|
||||
genColumn = 0;
|
||||
while (reader.pos < semi) {
|
||||
let seg;
|
||||
genColumn = decodeInteger(reader, genColumn);
|
||||
if (genColumn < lastCol) sorted = false;
|
||||
lastCol = genColumn;
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
sourcesIndex = decodeInteger(reader, sourcesIndex);
|
||||
sourceLine = decodeInteger(reader, sourceLine);
|
||||
sourceColumn = decodeInteger(reader, sourceColumn);
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
namesIndex = decodeInteger(reader, namesIndex);
|
||||
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
|
||||
} else {
|
||||
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
|
||||
}
|
||||
} else {
|
||||
seg = [genColumn];
|
||||
}
|
||||
line.push(seg);
|
||||
reader.pos++;
|
||||
}
|
||||
if (!sorted) sort(line);
|
||||
decoded.push(line);
|
||||
reader.pos = semi + 1;
|
||||
} while (reader.pos <= length);
|
||||
return decoded;
|
||||
}
|
||||
function sort(line) {
|
||||
line.sort(sortComparator);
|
||||
}
|
||||
function sortComparator(a, b) {
|
||||
return a[0] - b[0];
|
||||
}
|
||||
function encode(decoded) {
|
||||
const writer = new StringWriter();
|
||||
let sourcesIndex = 0;
|
||||
let sourceLine = 0;
|
||||
let sourceColumn = 0;
|
||||
let namesIndex = 0;
|
||||
for (let i = 0; i < decoded.length; i++) {
|
||||
const line = decoded[i];
|
||||
if (i > 0) writer.write(semicolon);
|
||||
if (line.length === 0) continue;
|
||||
let genColumn = 0;
|
||||
for (let j = 0; j < line.length; j++) {
|
||||
const segment = line[j];
|
||||
if (j > 0) writer.write(comma);
|
||||
genColumn = encodeInteger(writer, segment[0], genColumn);
|
||||
if (segment.length === 1) continue;
|
||||
sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
|
||||
sourceLine = encodeInteger(writer, segment[2], sourceLine);
|
||||
sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
|
||||
if (segment.length === 4) continue;
|
||||
namesIndex = encodeInteger(writer, segment[4], namesIndex);
|
||||
}
|
||||
}
|
||||
return writer.flush();
|
||||
}
|
||||
export {
|
||||
decode,
|
||||
decodeGeneratedRanges,
|
||||
decodeOriginalScopes,
|
||||
encode,
|
||||
encodeGeneratedRanges,
|
||||
encodeOriginalScopes
|
||||
};
|
||||
//# sourceMappingURL=sourcemap-codec.mjs.map
|
||||
6
node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map
generated
vendored
Normal file
6
node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
464
node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js
generated
vendored
Normal file
464
node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js
generated
vendored
Normal file
|
|
@ -0,0 +1,464 @@
|
|||
(function (global, factory) {
|
||||
if (typeof exports === 'object' && typeof module !== 'undefined') {
|
||||
factory(module);
|
||||
module.exports = def(module);
|
||||
} else if (typeof define === 'function' && define.amd) {
|
||||
define(['module'], function(mod) {
|
||||
factory.apply(this, arguments);
|
||||
mod.exports = def(mod);
|
||||
});
|
||||
} else {
|
||||
const mod = { exports: {} };
|
||||
factory(mod);
|
||||
global = typeof globalThis !== 'undefined' ? globalThis : global || self;
|
||||
global.sourcemapCodec = def(mod);
|
||||
}
|
||||
function def(m) { return 'default' in m.exports ? m.exports.default : m.exports; }
|
||||
})(this, (function (module) {
|
||||
"use strict";
|
||||
var __defProp = Object.defineProperty;
|
||||
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||
var __export = (target, all) => {
|
||||
for (var name in all)
|
||||
__defProp(target, name, { get: all[name], enumerable: true });
|
||||
};
|
||||
var __copyProps = (to, from, except, desc) => {
|
||||
if (from && typeof from === "object" || typeof from === "function") {
|
||||
for (let key of __getOwnPropNames(from))
|
||||
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||
}
|
||||
return to;
|
||||
};
|
||||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||
|
||||
// src/sourcemap-codec.ts
|
||||
var sourcemap_codec_exports = {};
|
||||
__export(sourcemap_codec_exports, {
|
||||
decode: () => decode,
|
||||
decodeGeneratedRanges: () => decodeGeneratedRanges,
|
||||
decodeOriginalScopes: () => decodeOriginalScopes,
|
||||
encode: () => encode,
|
||||
encodeGeneratedRanges: () => encodeGeneratedRanges,
|
||||
encodeOriginalScopes: () => encodeOriginalScopes
|
||||
});
|
||||
module.exports = __toCommonJS(sourcemap_codec_exports);
|
||||
|
||||
// src/vlq.ts
|
||||
var comma = ",".charCodeAt(0);
|
||||
var semicolon = ";".charCodeAt(0);
|
||||
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
var intToChar = new Uint8Array(64);
|
||||
var charToInt = new Uint8Array(128);
|
||||
for (let i = 0; i < chars.length; i++) {
|
||||
const c = chars.charCodeAt(i);
|
||||
intToChar[i] = c;
|
||||
charToInt[c] = i;
|
||||
}
|
||||
function decodeInteger(reader, relative) {
|
||||
let value = 0;
|
||||
let shift = 0;
|
||||
let integer = 0;
|
||||
do {
|
||||
const c = reader.next();
|
||||
integer = charToInt[c];
|
||||
value |= (integer & 31) << shift;
|
||||
shift += 5;
|
||||
} while (integer & 32);
|
||||
const shouldNegate = value & 1;
|
||||
value >>>= 1;
|
||||
if (shouldNegate) {
|
||||
value = -2147483648 | -value;
|
||||
}
|
||||
return relative + value;
|
||||
}
|
||||
function encodeInteger(builder, num, relative) {
|
||||
let delta = num - relative;
|
||||
delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
|
||||
do {
|
||||
let clamped = delta & 31;
|
||||
delta >>>= 5;
|
||||
if (delta > 0) clamped |= 32;
|
||||
builder.write(intToChar[clamped]);
|
||||
} while (delta > 0);
|
||||
return num;
|
||||
}
|
||||
function hasMoreVlq(reader, max) {
|
||||
if (reader.pos >= max) return false;
|
||||
return reader.peek() !== comma;
|
||||
}
|
||||
|
||||
// src/strings.ts
|
||||
var bufLength = 1024 * 16;
|
||||
var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
|
||||
decode(buf) {
|
||||
const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||
return out.toString();
|
||||
}
|
||||
} : {
|
||||
decode(buf) {
|
||||
let out = "";
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
out += String.fromCharCode(buf[i]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
};
|
||||
var StringWriter = class {
|
||||
constructor() {
|
||||
this.pos = 0;
|
||||
this.out = "";
|
||||
this.buffer = new Uint8Array(bufLength);
|
||||
}
|
||||
write(v) {
|
||||
const { buffer } = this;
|
||||
buffer[this.pos++] = v;
|
||||
if (this.pos === bufLength) {
|
||||
this.out += td.decode(buffer);
|
||||
this.pos = 0;
|
||||
}
|
||||
}
|
||||
flush() {
|
||||
const { buffer, out, pos } = this;
|
||||
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
|
||||
}
|
||||
};
|
||||
var StringReader = class {
|
||||
constructor(buffer) {
|
||||
this.pos = 0;
|
||||
this.buffer = buffer;
|
||||
}
|
||||
next() {
|
||||
return this.buffer.charCodeAt(this.pos++);
|
||||
}
|
||||
peek() {
|
||||
return this.buffer.charCodeAt(this.pos);
|
||||
}
|
||||
indexOf(char) {
|
||||
const { buffer, pos } = this;
|
||||
const idx = buffer.indexOf(char, pos);
|
||||
return idx === -1 ? buffer.length : idx;
|
||||
}
|
||||
};
|
||||
|
||||
// src/scopes.ts
|
||||
var EMPTY = [];
|
||||
function decodeOriginalScopes(input) {
|
||||
const { length } = input;
|
||||
const reader = new StringReader(input);
|
||||
const scopes = [];
|
||||
const stack = [];
|
||||
let line = 0;
|
||||
for (; reader.pos < length; reader.pos++) {
|
||||
line = decodeInteger(reader, line);
|
||||
const column = decodeInteger(reader, 0);
|
||||
if (!hasMoreVlq(reader, length)) {
|
||||
const last = stack.pop();
|
||||
last[2] = line;
|
||||
last[3] = column;
|
||||
continue;
|
||||
}
|
||||
const kind = decodeInteger(reader, 0);
|
||||
const fields = decodeInteger(reader, 0);
|
||||
const hasName = fields & 1;
|
||||
const scope = hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind];
|
||||
let vars = EMPTY;
|
||||
if (hasMoreVlq(reader, length)) {
|
||||
vars = [];
|
||||
do {
|
||||
const varsIndex = decodeInteger(reader, 0);
|
||||
vars.push(varsIndex);
|
||||
} while (hasMoreVlq(reader, length));
|
||||
}
|
||||
scope.vars = vars;
|
||||
scopes.push(scope);
|
||||
stack.push(scope);
|
||||
}
|
||||
return scopes;
|
||||
}
|
||||
function encodeOriginalScopes(scopes) {
|
||||
const writer = new StringWriter();
|
||||
for (let i = 0; i < scopes.length; ) {
|
||||
i = _encodeOriginalScopes(scopes, i, writer, [0]);
|
||||
}
|
||||
return writer.flush();
|
||||
}
|
||||
function _encodeOriginalScopes(scopes, index, writer, state) {
|
||||
const scope = scopes[index];
|
||||
const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;
|
||||
if (index > 0) writer.write(comma);
|
||||
state[0] = encodeInteger(writer, startLine, state[0]);
|
||||
encodeInteger(writer, startColumn, 0);
|
||||
encodeInteger(writer, kind, 0);
|
||||
const fields = scope.length === 6 ? 1 : 0;
|
||||
encodeInteger(writer, fields, 0);
|
||||
if (scope.length === 6) encodeInteger(writer, scope[5], 0);
|
||||
for (const v of vars) {
|
||||
encodeInteger(writer, v, 0);
|
||||
}
|
||||
for (index++; index < scopes.length; ) {
|
||||
const next = scopes[index];
|
||||
const { 0: l, 1: c } = next;
|
||||
if (l > endLine || l === endLine && c >= endColumn) {
|
||||
break;
|
||||
}
|
||||
index = _encodeOriginalScopes(scopes, index, writer, state);
|
||||
}
|
||||
writer.write(comma);
|
||||
state[0] = encodeInteger(writer, endLine, state[0]);
|
||||
encodeInteger(writer, endColumn, 0);
|
||||
return index;
|
||||
}
|
||||
function decodeGeneratedRanges(input) {
|
||||
const { length } = input;
|
||||
const reader = new StringReader(input);
|
||||
const ranges = [];
|
||||
const stack = [];
|
||||
let genLine = 0;
|
||||
let definitionSourcesIndex = 0;
|
||||
let definitionScopeIndex = 0;
|
||||
let callsiteSourcesIndex = 0;
|
||||
let callsiteLine = 0;
|
||||
let callsiteColumn = 0;
|
||||
let bindingLine = 0;
|
||||
let bindingColumn = 0;
|
||||
do {
|
||||
const semi = reader.indexOf(";");
|
||||
let genColumn = 0;
|
||||
for (; reader.pos < semi; reader.pos++) {
|
||||
genColumn = decodeInteger(reader, genColumn);
|
||||
if (!hasMoreVlq(reader, semi)) {
|
||||
const last = stack.pop();
|
||||
last[2] = genLine;
|
||||
last[3] = genColumn;
|
||||
continue;
|
||||
}
|
||||
const fields = decodeInteger(reader, 0);
|
||||
const hasDefinition = fields & 1;
|
||||
const hasCallsite = fields & 2;
|
||||
const hasScope = fields & 4;
|
||||
let callsite = null;
|
||||
let bindings = EMPTY;
|
||||
let range;
|
||||
if (hasDefinition) {
|
||||
const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);
|
||||
definitionScopeIndex = decodeInteger(
|
||||
reader,
|
||||
definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0
|
||||
);
|
||||
definitionSourcesIndex = defSourcesIndex;
|
||||
range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex];
|
||||
} else {
|
||||
range = [genLine, genColumn, 0, 0];
|
||||
}
|
||||
range.isScope = !!hasScope;
|
||||
if (hasCallsite) {
|
||||
const prevCsi = callsiteSourcesIndex;
|
||||
const prevLine = callsiteLine;
|
||||
callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);
|
||||
const sameSource = prevCsi === callsiteSourcesIndex;
|
||||
callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);
|
||||
callsiteColumn = decodeInteger(
|
||||
reader,
|
||||
sameSource && prevLine === callsiteLine ? callsiteColumn : 0
|
||||
);
|
||||
callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];
|
||||
}
|
||||
range.callsite = callsite;
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
bindings = [];
|
||||
do {
|
||||
bindingLine = genLine;
|
||||
bindingColumn = genColumn;
|
||||
const expressionsCount = decodeInteger(reader, 0);
|
||||
let expressionRanges;
|
||||
if (expressionsCount < -1) {
|
||||
expressionRanges = [[decodeInteger(reader, 0)]];
|
||||
for (let i = -1; i > expressionsCount; i--) {
|
||||
const prevBl = bindingLine;
|
||||
bindingLine = decodeInteger(reader, bindingLine);
|
||||
bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);
|
||||
const expression = decodeInteger(reader, 0);
|
||||
expressionRanges.push([expression, bindingLine, bindingColumn]);
|
||||
}
|
||||
} else {
|
||||
expressionRanges = [[expressionsCount]];
|
||||
}
|
||||
bindings.push(expressionRanges);
|
||||
} while (hasMoreVlq(reader, semi));
|
||||
}
|
||||
range.bindings = bindings;
|
||||
ranges.push(range);
|
||||
stack.push(range);
|
||||
}
|
||||
genLine++;
|
||||
reader.pos = semi + 1;
|
||||
} while (reader.pos < length);
|
||||
return ranges;
|
||||
}
|
||||
function encodeGeneratedRanges(ranges) {
|
||||
if (ranges.length === 0) return "";
|
||||
const writer = new StringWriter();
|
||||
for (let i = 0; i < ranges.length; ) {
|
||||
i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);
|
||||
}
|
||||
return writer.flush();
|
||||
}
|
||||
function _encodeGeneratedRanges(ranges, index, writer, state) {
|
||||
const range = ranges[index];
|
||||
const {
|
||||
0: startLine,
|
||||
1: startColumn,
|
||||
2: endLine,
|
||||
3: endColumn,
|
||||
isScope,
|
||||
callsite,
|
||||
bindings
|
||||
} = range;
|
||||
if (state[0] < startLine) {
|
||||
catchupLine(writer, state[0], startLine);
|
||||
state[0] = startLine;
|
||||
state[1] = 0;
|
||||
} else if (index > 0) {
|
||||
writer.write(comma);
|
||||
}
|
||||
state[1] = encodeInteger(writer, range[1], state[1]);
|
||||
const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0);
|
||||
encodeInteger(writer, fields, 0);
|
||||
if (range.length === 6) {
|
||||
const { 4: sourcesIndex, 5: scopesIndex } = range;
|
||||
if (sourcesIndex !== state[2]) {
|
||||
state[3] = 0;
|
||||
}
|
||||
state[2] = encodeInteger(writer, sourcesIndex, state[2]);
|
||||
state[3] = encodeInteger(writer, scopesIndex, state[3]);
|
||||
}
|
||||
if (callsite) {
|
||||
const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite;
|
||||
if (sourcesIndex !== state[4]) {
|
||||
state[5] = 0;
|
||||
state[6] = 0;
|
||||
} else if (callLine !== state[5]) {
|
||||
state[6] = 0;
|
||||
}
|
||||
state[4] = encodeInteger(writer, sourcesIndex, state[4]);
|
||||
state[5] = encodeInteger(writer, callLine, state[5]);
|
||||
state[6] = encodeInteger(writer, callColumn, state[6]);
|
||||
}
|
||||
if (bindings) {
|
||||
for (const binding of bindings) {
|
||||
if (binding.length > 1) encodeInteger(writer, -binding.length, 0);
|
||||
const expression = binding[0][0];
|
||||
encodeInteger(writer, expression, 0);
|
||||
let bindingStartLine = startLine;
|
||||
let bindingStartColumn = startColumn;
|
||||
for (let i = 1; i < binding.length; i++) {
|
||||
const expRange = binding[i];
|
||||
bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine);
|
||||
bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn);
|
||||
encodeInteger(writer, expRange[0], 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (index++; index < ranges.length; ) {
|
||||
const next = ranges[index];
|
||||
const { 0: l, 1: c } = next;
|
||||
if (l > endLine || l === endLine && c >= endColumn) {
|
||||
break;
|
||||
}
|
||||
index = _encodeGeneratedRanges(ranges, index, writer, state);
|
||||
}
|
||||
if (state[0] < endLine) {
|
||||
catchupLine(writer, state[0], endLine);
|
||||
state[0] = endLine;
|
||||
state[1] = 0;
|
||||
} else {
|
||||
writer.write(comma);
|
||||
}
|
||||
state[1] = encodeInteger(writer, endColumn, state[1]);
|
||||
return index;
|
||||
}
|
||||
function catchupLine(writer, lastLine, line) {
|
||||
do {
|
||||
writer.write(semicolon);
|
||||
} while (++lastLine < line);
|
||||
}
|
||||
|
||||
// src/sourcemap-codec.ts
|
||||
function decode(mappings) {
|
||||
const { length } = mappings;
|
||||
const reader = new StringReader(mappings);
|
||||
const decoded = [];
|
||||
let genColumn = 0;
|
||||
let sourcesIndex = 0;
|
||||
let sourceLine = 0;
|
||||
let sourceColumn = 0;
|
||||
let namesIndex = 0;
|
||||
do {
|
||||
const semi = reader.indexOf(";");
|
||||
const line = [];
|
||||
let sorted = true;
|
||||
let lastCol = 0;
|
||||
genColumn = 0;
|
||||
while (reader.pos < semi) {
|
||||
let seg;
|
||||
genColumn = decodeInteger(reader, genColumn);
|
||||
if (genColumn < lastCol) sorted = false;
|
||||
lastCol = genColumn;
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
sourcesIndex = decodeInteger(reader, sourcesIndex);
|
||||
sourceLine = decodeInteger(reader, sourceLine);
|
||||
sourceColumn = decodeInteger(reader, sourceColumn);
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
namesIndex = decodeInteger(reader, namesIndex);
|
||||
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
|
||||
} else {
|
||||
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
|
||||
}
|
||||
} else {
|
||||
seg = [genColumn];
|
||||
}
|
||||
line.push(seg);
|
||||
reader.pos++;
|
||||
}
|
||||
if (!sorted) sort(line);
|
||||
decoded.push(line);
|
||||
reader.pos = semi + 1;
|
||||
} while (reader.pos <= length);
|
||||
return decoded;
|
||||
}
|
||||
function sort(line) {
|
||||
line.sort(sortComparator);
|
||||
}
|
||||
function sortComparator(a, b) {
|
||||
return a[0] - b[0];
|
||||
}
|
||||
function encode(decoded) {
|
||||
const writer = new StringWriter();
|
||||
let sourcesIndex = 0;
|
||||
let sourceLine = 0;
|
||||
let sourceColumn = 0;
|
||||
let namesIndex = 0;
|
||||
for (let i = 0; i < decoded.length; i++) {
|
||||
const line = decoded[i];
|
||||
if (i > 0) writer.write(semicolon);
|
||||
if (line.length === 0) continue;
|
||||
let genColumn = 0;
|
||||
for (let j = 0; j < line.length; j++) {
|
||||
const segment = line[j];
|
||||
if (j > 0) writer.write(comma);
|
||||
genColumn = encodeInteger(writer, segment[0], genColumn);
|
||||
if (segment.length === 1) continue;
|
||||
sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
|
||||
sourceLine = encodeInteger(writer, segment[2], sourceLine);
|
||||
sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
|
||||
if (segment.length === 4) continue;
|
||||
namesIndex = encodeInteger(writer, segment[4], namesIndex);
|
||||
}
|
||||
}
|
||||
return writer.flush();
|
||||
}
|
||||
}));
|
||||
//# sourceMappingURL=sourcemap-codec.umd.js.map
|
||||
6
node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map
generated
vendored
Normal file
6
node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,63 @@
|
|||
{
|
||||
"name": "@jridgewell/sourcemap-codec",
|
||||
"version": "1.5.5",
|
||||
"description": "Encode/decode sourcemap mappings",
|
||||
"keywords": [
|
||||
"sourcemap",
|
||||
"vlq"
|
||||
],
|
||||
"main": "dist/sourcemap-codec.umd.js",
|
||||
"module": "dist/sourcemap-codec.mjs",
|
||||
"types": "types/sourcemap-codec.d.cts",
|
||||
"files": [
|
||||
"dist",
|
||||
"src",
|
||||
"types"
|
||||
],
|
||||
"exports": {
|
||||
".": [
|
||||
{
|
||||
"import": {
|
||||
"types": "./types/sourcemap-codec.d.mts",
|
||||
"default": "./dist/sourcemap-codec.mjs"
|
||||
},
|
||||
"default": {
|
||||
"types": "./types/sourcemap-codec.d.cts",
|
||||
"default": "./dist/sourcemap-codec.umd.js"
|
||||
}
|
||||
},
|
||||
"./dist/sourcemap-codec.umd.js"
|
||||
],
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"scripts": {
|
||||
"benchmark": "run-s build:code benchmark:*",
|
||||
"benchmark:install": "cd benchmark && npm install",
|
||||
"benchmark:only": "node --expose-gc benchmark/index.js",
|
||||
"build": "run-s -n build:code build:types",
|
||||
"build:code": "node ../../esbuild.mjs sourcemap-codec.ts",
|
||||
"build:types": "run-s build:types:force build:types:emit build:types:mts",
|
||||
"build:types:force": "rimraf tsconfig.build.tsbuildinfo",
|
||||
"build:types:emit": "tsc --project tsconfig.build.json",
|
||||
"build:types:mts": "node ../../mts-types.mjs",
|
||||
"clean": "run-s -n clean:code clean:types",
|
||||
"clean:code": "tsc --build --clean tsconfig.build.json",
|
||||
"clean:types": "rimraf dist types",
|
||||
"test": "run-s -n test:types test:only test:format",
|
||||
"test:format": "prettier --check '{src,test}/**/*.ts'",
|
||||
"test:only": "mocha",
|
||||
"test:types": "eslint '{src,test}/**/*.ts'",
|
||||
"lint": "run-s -n lint:types lint:format",
|
||||
"lint:format": "npm run test:format -- --write",
|
||||
"lint:types": "npm run test:types -- --fix",
|
||||
"prepublishOnly": "npm run-s -n build test"
|
||||
},
|
||||
"homepage": "https://github.com/jridgewell/sourcemaps/tree/main/packages/sourcemap-codec",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/jridgewell/sourcemaps.git",
|
||||
"directory": "packages/sourcemap-codec"
|
||||
},
|
||||
"author": "Justin Ridgewell <justin@ridgewell.name>",
|
||||
"license": "MIT"
|
||||
}
|
||||
|
|
@ -0,0 +1,345 @@
|
|||
import { StringReader, StringWriter } from './strings';
|
||||
import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq';
|
||||
|
||||
const EMPTY: any[] = [];
|
||||
|
||||
type Line = number;
|
||||
type Column = number;
|
||||
type Kind = number;
|
||||
type Name = number;
|
||||
type Var = number;
|
||||
type SourcesIndex = number;
|
||||
type ScopesIndex = number;
|
||||
|
||||
type Mix<A, B, O> = (A & O) | (B & O);
|
||||
|
||||
export type OriginalScope = Mix<
|
||||
[Line, Column, Line, Column, Kind],
|
||||
[Line, Column, Line, Column, Kind, Name],
|
||||
{ vars: Var[] }
|
||||
>;
|
||||
|
||||
export type GeneratedRange = Mix<
|
||||
[Line, Column, Line, Column],
|
||||
[Line, Column, Line, Column, SourcesIndex, ScopesIndex],
|
||||
{
|
||||
callsite: CallSite | null;
|
||||
bindings: Binding[];
|
||||
isScope: boolean;
|
||||
}
|
||||
>;
|
||||
export type CallSite = [SourcesIndex, Line, Column];
|
||||
type Binding = BindingExpressionRange[];
|
||||
export type BindingExpressionRange = [Name] | [Name, Line, Column];
|
||||
|
||||
export function decodeOriginalScopes(input: string): OriginalScope[] {
|
||||
const { length } = input;
|
||||
const reader = new StringReader(input);
|
||||
const scopes: OriginalScope[] = [];
|
||||
const stack: OriginalScope[] = [];
|
||||
let line = 0;
|
||||
|
||||
for (; reader.pos < length; reader.pos++) {
|
||||
line = decodeInteger(reader, line);
|
||||
const column = decodeInteger(reader, 0);
|
||||
|
||||
if (!hasMoreVlq(reader, length)) {
|
||||
const last = stack.pop()!;
|
||||
last[2] = line;
|
||||
last[3] = column;
|
||||
continue;
|
||||
}
|
||||
|
||||
const kind = decodeInteger(reader, 0);
|
||||
const fields = decodeInteger(reader, 0);
|
||||
const hasName = fields & 0b0001;
|
||||
|
||||
const scope: OriginalScope = (
|
||||
hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]
|
||||
) as OriginalScope;
|
||||
|
||||
let vars: Var[] = EMPTY;
|
||||
if (hasMoreVlq(reader, length)) {
|
||||
vars = [];
|
||||
do {
|
||||
const varsIndex = decodeInteger(reader, 0);
|
||||
vars.push(varsIndex);
|
||||
} while (hasMoreVlq(reader, length));
|
||||
}
|
||||
scope.vars = vars;
|
||||
|
||||
scopes.push(scope);
|
||||
stack.push(scope);
|
||||
}
|
||||
|
||||
return scopes;
|
||||
}
|
||||
|
||||
export function encodeOriginalScopes(scopes: OriginalScope[]): string {
|
||||
const writer = new StringWriter();
|
||||
|
||||
for (let i = 0; i < scopes.length; ) {
|
||||
i = _encodeOriginalScopes(scopes, i, writer, [0]);
|
||||
}
|
||||
|
||||
return writer.flush();
|
||||
}
|
||||
|
||||
function _encodeOriginalScopes(
|
||||
scopes: OriginalScope[],
|
||||
index: number,
|
||||
writer: StringWriter,
|
||||
state: [
|
||||
number, // GenColumn
|
||||
],
|
||||
): number {
|
||||
const scope = scopes[index];
|
||||
const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;
|
||||
|
||||
if (index > 0) writer.write(comma);
|
||||
|
||||
state[0] = encodeInteger(writer, startLine, state[0]);
|
||||
encodeInteger(writer, startColumn, 0);
|
||||
encodeInteger(writer, kind, 0);
|
||||
|
||||
const fields = scope.length === 6 ? 0b0001 : 0;
|
||||
encodeInteger(writer, fields, 0);
|
||||
if (scope.length === 6) encodeInteger(writer, scope[5], 0);
|
||||
|
||||
for (const v of vars) {
|
||||
encodeInteger(writer, v, 0);
|
||||
}
|
||||
|
||||
for (index++; index < scopes.length; ) {
|
||||
const next = scopes[index];
|
||||
const { 0: l, 1: c } = next;
|
||||
if (l > endLine || (l === endLine && c >= endColumn)) {
|
||||
break;
|
||||
}
|
||||
index = _encodeOriginalScopes(scopes, index, writer, state);
|
||||
}
|
||||
|
||||
writer.write(comma);
|
||||
state[0] = encodeInteger(writer, endLine, state[0]);
|
||||
encodeInteger(writer, endColumn, 0);
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
export function decodeGeneratedRanges(input: string): GeneratedRange[] {
|
||||
const { length } = input;
|
||||
const reader = new StringReader(input);
|
||||
const ranges: GeneratedRange[] = [];
|
||||
const stack: GeneratedRange[] = [];
|
||||
|
||||
let genLine = 0;
|
||||
let definitionSourcesIndex = 0;
|
||||
let definitionScopeIndex = 0;
|
||||
let callsiteSourcesIndex = 0;
|
||||
let callsiteLine = 0;
|
||||
let callsiteColumn = 0;
|
||||
let bindingLine = 0;
|
||||
let bindingColumn = 0;
|
||||
|
||||
do {
|
||||
const semi = reader.indexOf(';');
|
||||
let genColumn = 0;
|
||||
|
||||
for (; reader.pos < semi; reader.pos++) {
|
||||
genColumn = decodeInteger(reader, genColumn);
|
||||
|
||||
if (!hasMoreVlq(reader, semi)) {
|
||||
const last = stack.pop()!;
|
||||
last[2] = genLine;
|
||||
last[3] = genColumn;
|
||||
continue;
|
||||
}
|
||||
|
||||
const fields = decodeInteger(reader, 0);
|
||||
const hasDefinition = fields & 0b0001;
|
||||
const hasCallsite = fields & 0b0010;
|
||||
const hasScope = fields & 0b0100;
|
||||
|
||||
let callsite: CallSite | null = null;
|
||||
let bindings: Binding[] = EMPTY;
|
||||
let range: GeneratedRange;
|
||||
if (hasDefinition) {
|
||||
const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);
|
||||
definitionScopeIndex = decodeInteger(
|
||||
reader,
|
||||
definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0,
|
||||
);
|
||||
|
||||
definitionSourcesIndex = defSourcesIndex;
|
||||
range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex] as GeneratedRange;
|
||||
} else {
|
||||
range = [genLine, genColumn, 0, 0] as GeneratedRange;
|
||||
}
|
||||
|
||||
range.isScope = !!hasScope;
|
||||
|
||||
if (hasCallsite) {
|
||||
const prevCsi = callsiteSourcesIndex;
|
||||
const prevLine = callsiteLine;
|
||||
callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);
|
||||
const sameSource = prevCsi === callsiteSourcesIndex;
|
||||
callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);
|
||||
callsiteColumn = decodeInteger(
|
||||
reader,
|
||||
sameSource && prevLine === callsiteLine ? callsiteColumn : 0,
|
||||
);
|
||||
|
||||
callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];
|
||||
}
|
||||
range.callsite = callsite;
|
||||
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
bindings = [];
|
||||
do {
|
||||
bindingLine = genLine;
|
||||
bindingColumn = genColumn;
|
||||
const expressionsCount = decodeInteger(reader, 0);
|
||||
let expressionRanges: BindingExpressionRange[];
|
||||
if (expressionsCount < -1) {
|
||||
expressionRanges = [[decodeInteger(reader, 0)]];
|
||||
for (let i = -1; i > expressionsCount; i--) {
|
||||
const prevBl = bindingLine;
|
||||
bindingLine = decodeInteger(reader, bindingLine);
|
||||
bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);
|
||||
const expression = decodeInteger(reader, 0);
|
||||
expressionRanges.push([expression, bindingLine, bindingColumn]);
|
||||
}
|
||||
} else {
|
||||
expressionRanges = [[expressionsCount]];
|
||||
}
|
||||
bindings.push(expressionRanges);
|
||||
} while (hasMoreVlq(reader, semi));
|
||||
}
|
||||
range.bindings = bindings;
|
||||
|
||||
ranges.push(range);
|
||||
stack.push(range);
|
||||
}
|
||||
|
||||
genLine++;
|
||||
reader.pos = semi + 1;
|
||||
} while (reader.pos < length);
|
||||
|
||||
return ranges;
|
||||
}
|
||||
|
||||
export function encodeGeneratedRanges(ranges: GeneratedRange[]): string {
|
||||
if (ranges.length === 0) return '';
|
||||
|
||||
const writer = new StringWriter();
|
||||
|
||||
for (let i = 0; i < ranges.length; ) {
|
||||
i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);
|
||||
}
|
||||
|
||||
return writer.flush();
|
||||
}
|
||||
|
||||
function _encodeGeneratedRanges(
|
||||
ranges: GeneratedRange[],
|
||||
index: number,
|
||||
writer: StringWriter,
|
||||
state: [
|
||||
number, // GenLine
|
||||
number, // GenColumn
|
||||
number, // DefSourcesIndex
|
||||
number, // DefScopesIndex
|
||||
number, // CallSourcesIndex
|
||||
number, // CallLine
|
||||
number, // CallColumn
|
||||
],
|
||||
): number {
|
||||
const range = ranges[index];
|
||||
const {
|
||||
0: startLine,
|
||||
1: startColumn,
|
||||
2: endLine,
|
||||
3: endColumn,
|
||||
isScope,
|
||||
callsite,
|
||||
bindings,
|
||||
} = range;
|
||||
|
||||
if (state[0] < startLine) {
|
||||
catchupLine(writer, state[0], startLine);
|
||||
state[0] = startLine;
|
||||
state[1] = 0;
|
||||
} else if (index > 0) {
|
||||
writer.write(comma);
|
||||
}
|
||||
|
||||
state[1] = encodeInteger(writer, range[1], state[1]);
|
||||
|
||||
const fields =
|
||||
(range.length === 6 ? 0b0001 : 0) | (callsite ? 0b0010 : 0) | (isScope ? 0b0100 : 0);
|
||||
encodeInteger(writer, fields, 0);
|
||||
|
||||
if (range.length === 6) {
|
||||
const { 4: sourcesIndex, 5: scopesIndex } = range;
|
||||
if (sourcesIndex !== state[2]) {
|
||||
state[3] = 0;
|
||||
}
|
||||
state[2] = encodeInteger(writer, sourcesIndex, state[2]);
|
||||
state[3] = encodeInteger(writer, scopesIndex, state[3]);
|
||||
}
|
||||
|
||||
if (callsite) {
|
||||
const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite!;
|
||||
if (sourcesIndex !== state[4]) {
|
||||
state[5] = 0;
|
||||
state[6] = 0;
|
||||
} else if (callLine !== state[5]) {
|
||||
state[6] = 0;
|
||||
}
|
||||
state[4] = encodeInteger(writer, sourcesIndex, state[4]);
|
||||
state[5] = encodeInteger(writer, callLine, state[5]);
|
||||
state[6] = encodeInteger(writer, callColumn, state[6]);
|
||||
}
|
||||
|
||||
if (bindings) {
|
||||
for (const binding of bindings) {
|
||||
if (binding.length > 1) encodeInteger(writer, -binding.length, 0);
|
||||
const expression = binding[0][0];
|
||||
encodeInteger(writer, expression, 0);
|
||||
let bindingStartLine = startLine;
|
||||
let bindingStartColumn = startColumn;
|
||||
for (let i = 1; i < binding.length; i++) {
|
||||
const expRange = binding[i];
|
||||
bindingStartLine = encodeInteger(writer, expRange[1]!, bindingStartLine);
|
||||
bindingStartColumn = encodeInteger(writer, expRange[2]!, bindingStartColumn);
|
||||
encodeInteger(writer, expRange[0]!, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (index++; index < ranges.length; ) {
|
||||
const next = ranges[index];
|
||||
const { 0: l, 1: c } = next;
|
||||
if (l > endLine || (l === endLine && c >= endColumn)) {
|
||||
break;
|
||||
}
|
||||
index = _encodeGeneratedRanges(ranges, index, writer, state);
|
||||
}
|
||||
|
||||
if (state[0] < endLine) {
|
||||
catchupLine(writer, state[0], endLine);
|
||||
state[0] = endLine;
|
||||
state[1] = 0;
|
||||
} else {
|
||||
writer.write(comma);
|
||||
}
|
||||
state[1] = encodeInteger(writer, endColumn, state[1]);
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
function catchupLine(writer: StringWriter, lastLine: number, line: number) {
|
||||
do {
|
||||
writer.write(semicolon);
|
||||
} while (++lastLine < line);
|
||||
}
|
||||
|
|
@ -0,0 +1,111 @@
|
|||
import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq';
|
||||
import { StringWriter, StringReader } from './strings';
|
||||
|
||||
export {
|
||||
decodeOriginalScopes,
|
||||
encodeOriginalScopes,
|
||||
decodeGeneratedRanges,
|
||||
encodeGeneratedRanges,
|
||||
} from './scopes';
|
||||
export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes';
|
||||
|
||||
export type SourceMapSegment =
|
||||
| [number]
|
||||
| [number, number, number, number]
|
||||
| [number, number, number, number, number];
|
||||
export type SourceMapLine = SourceMapSegment[];
|
||||
export type SourceMapMappings = SourceMapLine[];
|
||||
|
||||
export function decode(mappings: string): SourceMapMappings {
|
||||
const { length } = mappings;
|
||||
const reader = new StringReader(mappings);
|
||||
const decoded: SourceMapMappings = [];
|
||||
let genColumn = 0;
|
||||
let sourcesIndex = 0;
|
||||
let sourceLine = 0;
|
||||
let sourceColumn = 0;
|
||||
let namesIndex = 0;
|
||||
|
||||
do {
|
||||
const semi = reader.indexOf(';');
|
||||
const line: SourceMapLine = [];
|
||||
let sorted = true;
|
||||
let lastCol = 0;
|
||||
genColumn = 0;
|
||||
|
||||
while (reader.pos < semi) {
|
||||
let seg: SourceMapSegment;
|
||||
|
||||
genColumn = decodeInteger(reader, genColumn);
|
||||
if (genColumn < lastCol) sorted = false;
|
||||
lastCol = genColumn;
|
||||
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
sourcesIndex = decodeInteger(reader, sourcesIndex);
|
||||
sourceLine = decodeInteger(reader, sourceLine);
|
||||
sourceColumn = decodeInteger(reader, sourceColumn);
|
||||
|
||||
if (hasMoreVlq(reader, semi)) {
|
||||
namesIndex = decodeInteger(reader, namesIndex);
|
||||
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
|
||||
} else {
|
||||
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
|
||||
}
|
||||
} else {
|
||||
seg = [genColumn];
|
||||
}
|
||||
|
||||
line.push(seg);
|
||||
reader.pos++;
|
||||
}
|
||||
|
||||
if (!sorted) sort(line);
|
||||
decoded.push(line);
|
||||
reader.pos = semi + 1;
|
||||
} while (reader.pos <= length);
|
||||
|
||||
return decoded;
|
||||
}
|
||||
|
||||
function sort(line: SourceMapSegment[]) {
|
||||
line.sort(sortComparator);
|
||||
}
|
||||
|
||||
function sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {
|
||||
return a[0] - b[0];
|
||||
}
|
||||
|
||||
export function encode(decoded: SourceMapMappings): string;
|
||||
export function encode(decoded: Readonly<SourceMapMappings>): string;
|
||||
export function encode(decoded: Readonly<SourceMapMappings>): string {
|
||||
const writer = new StringWriter();
|
||||
let sourcesIndex = 0;
|
||||
let sourceLine = 0;
|
||||
let sourceColumn = 0;
|
||||
let namesIndex = 0;
|
||||
|
||||
for (let i = 0; i < decoded.length; i++) {
|
||||
const line = decoded[i];
|
||||
if (i > 0) writer.write(semicolon);
|
||||
if (line.length === 0) continue;
|
||||
|
||||
let genColumn = 0;
|
||||
|
||||
for (let j = 0; j < line.length; j++) {
|
||||
const segment = line[j];
|
||||
if (j > 0) writer.write(comma);
|
||||
|
||||
genColumn = encodeInteger(writer, segment[0], genColumn);
|
||||
|
||||
if (segment.length === 1) continue;
|
||||
sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
|
||||
sourceLine = encodeInteger(writer, segment[2], sourceLine);
|
||||
sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
|
||||
|
||||
if (segment.length === 4) continue;
|
||||
namesIndex = encodeInteger(writer, segment[4], namesIndex);
|
||||
}
|
||||
}
|
||||
|
||||
return writer.flush();
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
const bufLength = 1024 * 16;
|
||||
|
||||
// Provide a fallback for older environments.
|
||||
const td =
|
||||
typeof TextDecoder !== 'undefined'
|
||||
? /* #__PURE__ */ new TextDecoder()
|
||||
: typeof Buffer !== 'undefined'
|
||||
? {
|
||||
decode(buf: Uint8Array): string {
|
||||
const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||
return out.toString();
|
||||
},
|
||||
}
|
||||
: {
|
||||
decode(buf: Uint8Array): string {
|
||||
let out = '';
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
out += String.fromCharCode(buf[i]);
|
||||
}
|
||||
return out;
|
||||
},
|
||||
};
|
||||
|
||||
export class StringWriter {
|
||||
pos = 0;
|
||||
private out = '';
|
||||
private buffer = new Uint8Array(bufLength);
|
||||
|
||||
write(v: number): void {
|
||||
const { buffer } = this;
|
||||
buffer[this.pos++] = v;
|
||||
if (this.pos === bufLength) {
|
||||
this.out += td.decode(buffer);
|
||||
this.pos = 0;
|
||||
}
|
||||
}
|
||||
|
||||
flush(): string {
|
||||
const { buffer, out, pos } = this;
|
||||
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
|
||||
}
|
||||
}
|
||||
|
||||
export class StringReader {
|
||||
pos = 0;
|
||||
declare private buffer: string;
|
||||
|
||||
constructor(buffer: string) {
|
||||
this.buffer = buffer;
|
||||
}
|
||||
|
||||
next(): number {
|
||||
return this.buffer.charCodeAt(this.pos++);
|
||||
}
|
||||
|
||||
peek(): number {
|
||||
return this.buffer.charCodeAt(this.pos);
|
||||
}
|
||||
|
||||
indexOf(char: string): number {
|
||||
const { buffer, pos } = this;
|
||||
const idx = buffer.indexOf(char, pos);
|
||||
return idx === -1 ? buffer.length : idx;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
import type { StringReader, StringWriter } from './strings';
|
||||
|
||||
export const comma = ','.charCodeAt(0);
|
||||
export const semicolon = ';'.charCodeAt(0);
|
||||
|
||||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
||||
const intToChar = new Uint8Array(64); // 64 possible chars.
|
||||
const charToInt = new Uint8Array(128); // z is 122 in ASCII
|
||||
|
||||
for (let i = 0; i < chars.length; i++) {
|
||||
const c = chars.charCodeAt(i);
|
||||
intToChar[i] = c;
|
||||
charToInt[c] = i;
|
||||
}
|
||||
|
||||
export function decodeInteger(reader: StringReader, relative: number): number {
|
||||
let value = 0;
|
||||
let shift = 0;
|
||||
let integer = 0;
|
||||
|
||||
do {
|
||||
const c = reader.next();
|
||||
integer = charToInt[c];
|
||||
value |= (integer & 31) << shift;
|
||||
shift += 5;
|
||||
} while (integer & 32);
|
||||
|
||||
const shouldNegate = value & 1;
|
||||
value >>>= 1;
|
||||
|
||||
if (shouldNegate) {
|
||||
value = -0x80000000 | -value;
|
||||
}
|
||||
|
||||
return relative + value;
|
||||
}
|
||||
|
||||
export function encodeInteger(builder: StringWriter, num: number, relative: number): number {
|
||||
let delta = num - relative;
|
||||
|
||||
delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;
|
||||
do {
|
||||
let clamped = delta & 0b011111;
|
||||
delta >>>= 5;
|
||||
if (delta > 0) clamped |= 0b100000;
|
||||
builder.write(intToChar[clamped]);
|
||||
} while (delta > 0);
|
||||
|
||||
return num;
|
||||
}
|
||||
|
||||
export function hasMoreVlq(reader: StringReader, max: number) {
|
||||
if (reader.pos >= max) return false;
|
||||
return reader.peek() !== comma;
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
type Line = number;
|
||||
type Column = number;
|
||||
type Kind = number;
|
||||
type Name = number;
|
||||
type Var = number;
|
||||
type SourcesIndex = number;
|
||||
type ScopesIndex = number;
|
||||
type Mix<A, B, O> = (A & O) | (B & O);
|
||||
export type OriginalScope = Mix<[
|
||||
Line,
|
||||
Column,
|
||||
Line,
|
||||
Column,
|
||||
Kind
|
||||
], [
|
||||
Line,
|
||||
Column,
|
||||
Line,
|
||||
Column,
|
||||
Kind,
|
||||
Name
|
||||
], {
|
||||
vars: Var[];
|
||||
}>;
|
||||
export type GeneratedRange = Mix<[
|
||||
Line,
|
||||
Column,
|
||||
Line,
|
||||
Column
|
||||
], [
|
||||
Line,
|
||||
Column,
|
||||
Line,
|
||||
Column,
|
||||
SourcesIndex,
|
||||
ScopesIndex
|
||||
], {
|
||||
callsite: CallSite | null;
|
||||
bindings: Binding[];
|
||||
isScope: boolean;
|
||||
}>;
|
||||
export type CallSite = [SourcesIndex, Line, Column];
|
||||
type Binding = BindingExpressionRange[];
|
||||
export type BindingExpressionRange = [Name] | [Name, Line, Column];
|
||||
export declare function decodeOriginalScopes(input: string): OriginalScope[];
|
||||
export declare function encodeOriginalScopes(scopes: OriginalScope[]): string;
|
||||
export declare function decodeGeneratedRanges(input: string): GeneratedRange[];
|
||||
export declare function encodeGeneratedRanges(ranges: GeneratedRange[]): string;
|
||||
export {};
|
||||
//# sourceMappingURL=scopes.d.ts.map
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../src/scopes.ts"],"names":[],"mappings":"AAKA,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,MAAM,GAAG,MAAM,CAAC;AACrB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,GAAG,GAAG,MAAM,CAAC;AAClB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,WAAW,GAAG,MAAM,CAAC;AAE1B,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAEtC,MAAM,MAAM,aAAa,GAAG,GAAG,CAC7B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;CAAC,EAClC;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,IAAI;CAAC,EACxC;IAAE,IAAI,EAAE,GAAG,EAAE,CAAA;CAAE,CAChB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,GAAG,CAC9B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;CAAC,EAC5B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,YAAY;IAAE,WAAW;CAAC,EACvD;IACE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;CAClB,CACF,CAAC;AACF,MAAM,MAAM,QAAQ,GAAG,CAAC,YAAY,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AACpD,KAAK,OAAO,GAAG,sBAAsB,EAAE,CAAC;AACxC,MAAM,MAAM,sBAAsB,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAEnE,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,EAAE,CAyCnE;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,CAQpE;AA2CD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,EAAE,CAoGrE;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,CAUtE"}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
type Line = number;
|
||||
type Column = number;
|
||||
type Kind = number;
|
||||
type Name = number;
|
||||
type Var = number;
|
||||
type SourcesIndex = number;
|
||||
type ScopesIndex = number;
|
||||
type Mix<A, B, O> = (A & O) | (B & O);
|
||||
export type OriginalScope = Mix<[
|
||||
Line,
|
||||
Column,
|
||||
Line,
|
||||
Column,
|
||||
Kind
|
||||
], [
|
||||
Line,
|
||||
Column,
|
||||
Line,
|
||||
Column,
|
||||
Kind,
|
||||
Name
|
||||
], {
|
||||
vars: Var[];
|
||||
}>;
|
||||
export type GeneratedRange = Mix<[
|
||||
Line,
|
||||
Column,
|
||||
Line,
|
||||
Column
|
||||
], [
|
||||
Line,
|
||||
Column,
|
||||
Line,
|
||||
Column,
|
||||
SourcesIndex,
|
||||
ScopesIndex
|
||||
], {
|
||||
callsite: CallSite | null;
|
||||
bindings: Binding[];
|
||||
isScope: boolean;
|
||||
}>;
|
||||
export type CallSite = [SourcesIndex, Line, Column];
|
||||
type Binding = BindingExpressionRange[];
|
||||
export type BindingExpressionRange = [Name] | [Name, Line, Column];
|
||||
export declare function decodeOriginalScopes(input: string): OriginalScope[];
|
||||
export declare function encodeOriginalScopes(scopes: OriginalScope[]): string;
|
||||
export declare function decodeGeneratedRanges(input: string): GeneratedRange[];
|
||||
export declare function encodeGeneratedRanges(ranges: GeneratedRange[]): string;
|
||||
export {};
|
||||
//# sourceMappingURL=scopes.d.ts.map
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../src/scopes.ts"],"names":[],"mappings":"AAKA,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,MAAM,GAAG,MAAM,CAAC;AACrB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,GAAG,GAAG,MAAM,CAAC;AAClB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,WAAW,GAAG,MAAM,CAAC;AAE1B,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAEtC,MAAM,MAAM,aAAa,GAAG,GAAG,CAC7B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;CAAC,EAClC;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,IAAI;CAAC,EACxC;IAAE,IAAI,EAAE,GAAG,EAAE,CAAA;CAAE,CAChB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,GAAG,CAC9B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;CAAC,EAC5B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,YAAY;IAAE,WAAW;CAAC,EACvD;IACE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;CAClB,CACF,CAAC;AACF,MAAM,MAAM,QAAQ,GAAG,CAAC,YAAY,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AACpD,KAAK,OAAO,GAAG,sBAAsB,EAAE,CAAC;AACxC,MAAM,MAAM,sBAAsB,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAEnE,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,EAAE,CAyCnE;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,CAQpE;AA2CD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,EAAE,CAoGrE;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,CAUtE"}
|
||||
9
node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts
generated
vendored
Normal file
9
node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts
generated
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
export { decodeOriginalScopes, encodeOriginalScopes, decodeGeneratedRanges, encodeGeneratedRanges, } from './scopes.cts';
|
||||
export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes.cts';
|
||||
export type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number];
|
||||
export type SourceMapLine = SourceMapSegment[];
|
||||
export type SourceMapMappings = SourceMapLine[];
|
||||
export declare function decode(mappings: string): SourceMapMappings;
|
||||
export declare function encode(decoded: SourceMapMappings): string;
|
||||
export declare function encode(decoded: Readonly<SourceMapMappings>): string;
|
||||
//# sourceMappingURL=sourcemap-codec.d.ts.map
|
||||
1
node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map
generated
vendored
Normal file
1
node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"sourcemap-codec.d.ts","sourceRoot":"","sources":["../src/sourcemap-codec.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,UAAU,CAAC;AAClB,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAEhG,MAAM,MAAM,gBAAgB,GACxB,CAAC,MAAM,CAAC,GACR,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,GAChC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAC7C,MAAM,MAAM,aAAa,GAAG,gBAAgB,EAAE,CAAC;AAC/C,MAAM,MAAM,iBAAiB,GAAG,aAAa,EAAE,CAAC;AAEhD,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB,CAiD1D;AAUD,wBAAgB,MAAM,CAAC,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAAC;AAC3D,wBAAgB,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,iBAAiB,CAAC,GAAG,MAAM,CAAC"}
|
||||
9
node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts
generated
vendored
Normal file
9
node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts
generated
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
export { decodeOriginalScopes, encodeOriginalScopes, decodeGeneratedRanges, encodeGeneratedRanges, } from './scopes.mts';
|
||||
export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes.mts';
|
||||
export type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number];
|
||||
export type SourceMapLine = SourceMapSegment[];
|
||||
export type SourceMapMappings = SourceMapLine[];
|
||||
export declare function decode(mappings: string): SourceMapMappings;
|
||||
export declare function encode(decoded: SourceMapMappings): string;
|
||||
export declare function encode(decoded: Readonly<SourceMapMappings>): string;
|
||||
//# sourceMappingURL=sourcemap-codec.d.ts.map
|
||||
1
node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map
generated
vendored
Normal file
1
node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map
generated
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"sourcemap-codec.d.ts","sourceRoot":"","sources":["../src/sourcemap-codec.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,UAAU,CAAC;AAClB,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAEhG,MAAM,MAAM,gBAAgB,GACxB,CAAC,MAAM,CAAC,GACR,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,GAChC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAC7C,MAAM,MAAM,aAAa,GAAG,gBAAgB,EAAE,CAAC;AAC/C,MAAM,MAAM,iBAAiB,GAAG,aAAa,EAAE,CAAC;AAEhD,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB,CAiD1D;AAUD,wBAAgB,MAAM,CAAC,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAAC;AAC3D,wBAAgB,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,iBAAiB,CAAC,GAAG,MAAM,CAAC"}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
export declare class StringWriter {
|
||||
pos: number;
|
||||
private out;
|
||||
private buffer;
|
||||
write(v: number): void;
|
||||
flush(): string;
|
||||
}
|
||||
export declare class StringReader {
|
||||
pos: number;
|
||||
private buffer;
|
||||
constructor(buffer: string);
|
||||
next(): number;
|
||||
peek(): number;
|
||||
indexOf(char: string): number;
|
||||
}
|
||||
//# sourceMappingURL=strings.d.ts.map
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"strings.d.ts","sourceRoot":"","sources":["../src/strings.ts"],"names":[],"mappings":"AAuBA,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,MAAM,CAA6B;IAE3C,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI;IAStB,KAAK,IAAI,MAAM;CAIhB;AAED,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,QAAgB,MAAM,CAAS;gBAEnB,MAAM,EAAE,MAAM;IAI1B,IAAI,IAAI,MAAM;IAId,IAAI,IAAI,MAAM;IAId,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAK9B"}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
export declare class StringWriter {
|
||||
pos: number;
|
||||
private out;
|
||||
private buffer;
|
||||
write(v: number): void;
|
||||
flush(): string;
|
||||
}
|
||||
export declare class StringReader {
|
||||
pos: number;
|
||||
private buffer;
|
||||
constructor(buffer: string);
|
||||
next(): number;
|
||||
peek(): number;
|
||||
indexOf(char: string): number;
|
||||
}
|
||||
//# sourceMappingURL=strings.d.ts.map
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"strings.d.ts","sourceRoot":"","sources":["../src/strings.ts"],"names":[],"mappings":"AAuBA,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,MAAM,CAA6B;IAE3C,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI;IAStB,KAAK,IAAI,MAAM;CAIhB;AAED,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,QAAgB,MAAM,CAAS;gBAEnB,MAAM,EAAE,MAAM;IAI1B,IAAI,IAAI,MAAM;IAId,IAAI,IAAI,MAAM;IAId,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAK9B"}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import type { StringReader, StringWriter } from './strings.cts';
|
||||
export declare const comma: number;
|
||||
export declare const semicolon: number;
|
||||
export declare function decodeInteger(reader: StringReader, relative: number): number;
|
||||
export declare function encodeInteger(builder: StringWriter, num: number, relative: number): number;
|
||||
export declare function hasMoreVlq(reader: StringReader, max: number): boolean;
|
||||
//# sourceMappingURL=vlq.d.ts.map
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"vlq.d.ts","sourceRoot":"","sources":["../src/vlq.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5D,eAAO,MAAM,KAAK,QAAoB,CAAC;AACvC,eAAO,MAAM,SAAS,QAAoB,CAAC;AAY3C,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAoB5E;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAY1F;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,WAG3D"}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import type { StringReader, StringWriter } from './strings.mts';
|
||||
export declare const comma: number;
|
||||
export declare const semicolon: number;
|
||||
export declare function decodeInteger(reader: StringReader, relative: number): number;
|
||||
export declare function encodeInteger(builder: StringWriter, num: number, relative: number): number;
|
||||
export declare function hasMoreVlq(reader: StringReader, max: number): boolean;
|
||||
//# sourceMappingURL=vlq.d.ts.map
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"vlq.d.ts","sourceRoot":"","sources":["../src/vlq.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5D,eAAO,MAAM,KAAK,QAAoB,CAAC;AACvC,eAAO,MAAM,SAAS,QAAoB,CAAC;AAY3C,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAoB5E;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAY1F;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,WAG3D"}
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
# `@rollup/rollup-linux-x64-gnu`
|
||||
|
||||
This is the **x86_64-unknown-linux-gnu** binary for `rollup`
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
{
|
||||
"name": "@rollup/rollup-linux-x64-gnu",
|
||||
"version": "4.62.0",
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"files": [
|
||||
"rollup.linux-x64-gnu.node"
|
||||
],
|
||||
"description": "Native bindings for Rollup",
|
||||
"author": "Lukas Taegert-Atkinson",
|
||||
"homepage": "https://rollupjs.org/",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/rollup/rollup.git"
|
||||
},
|
||||
"libc": [
|
||||
"glibc"
|
||||
],
|
||||
"main": "./rollup.linux-x64-gnu.node"
|
||||
}
|
||||
BIN
node_modules/@rollup/rollup-linux-x64-gnu/rollup.linux-x64-gnu.node
generated
vendored
Normal file
BIN
node_modules/@rollup/rollup-linux-x64-gnu/rollup.linux-x64-gnu.node
generated
vendored
Normal file
Binary file not shown.
|
|
@ -0,0 +1,3 @@
|
|||
# `@rollup/rollup-linux-x64-musl`
|
||||
|
||||
This is the **x86_64-unknown-linux-musl** binary for `rollup`
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
{
|
||||
"name": "@rollup/rollup-linux-x64-musl",
|
||||
"version": "4.62.0",
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"files": [
|
||||
"rollup.linux-x64-musl.node"
|
||||
],
|
||||
"description": "Native bindings for Rollup",
|
||||
"author": "Lukas Taegert-Atkinson",
|
||||
"homepage": "https://rollupjs.org/",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/rollup/rollup.git"
|
||||
},
|
||||
"libc": [
|
||||
"musl"
|
||||
],
|
||||
"main": "./rollup.linux-x64-musl.node"
|
||||
}
|
||||
BIN
node_modules/@rollup/rollup-linux-x64-musl/rollup.linux-x64-musl.node
generated
vendored
Normal file
BIN
node_modules/@rollup/rollup-linux-x64-musl/rollup.linux-x64-musl.node
generated
vendored
Normal file
Binary file not shown.
|
|
@ -0,0 +1,35 @@
|
|||
import * as Types from '../typebox';
|
||||
import { ValueErrorIterator } from '../errors/index';
|
||||
export type CheckFunction = (value: unknown) => boolean;
|
||||
export declare class TypeCheck<T extends Types.TSchema> {
|
||||
private readonly schema;
|
||||
private readonly references;
|
||||
private readonly checkFunc;
|
||||
private readonly code;
|
||||
constructor(schema: T, references: Types.TSchema[], checkFunc: CheckFunction, code: string);
|
||||
/** Returns the generated assertion code used to validate this type. */
|
||||
Code(): string;
|
||||
/** Returns an iterator for each error in this value. */
|
||||
Errors(value: unknown): ValueErrorIterator;
|
||||
/** Returns true if the value matches the compiled type. */
|
||||
Check(value: unknown): value is Types.Static<T>;
|
||||
}
|
||||
export declare class TypeCompilerUnknownTypeError extends Error {
|
||||
readonly schema: Types.TSchema;
|
||||
constructor(schema: Types.TSchema);
|
||||
}
|
||||
export declare class TypeCompilerDereferenceError extends Error {
|
||||
readonly schema: Types.TRef;
|
||||
constructor(schema: Types.TRef);
|
||||
}
|
||||
export declare class TypeCompilerTypeGuardError extends Error {
|
||||
readonly schema: Types.TSchema;
|
||||
constructor(schema: Types.TSchema);
|
||||
}
|
||||
/** Compiles Types for Runtime Type Checking */
|
||||
export declare namespace TypeCompiler {
|
||||
/** Returns the generated assertion code used to validate this type. */
|
||||
function Code<T extends Types.TSchema>(schema: T, references?: Types.TSchema[]): string;
|
||||
/** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
|
||||
function Compile<T extends Types.TSchema>(schema: T, references?: Types.TSchema[]): TypeCheck<T>;
|
||||
}
|
||||
|
|
@ -0,0 +1,577 @@
|
|||
"use strict";
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/compiler
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.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.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.TypeCompiler = exports.TypeCompilerTypeGuardError = exports.TypeCompilerDereferenceError = exports.TypeCompilerUnknownTypeError = exports.TypeCheck = void 0;
|
||||
const Types = require("../typebox");
|
||||
const index_1 = require("../errors/index");
|
||||
const index_2 = require("../system/index");
|
||||
const hash_1 = require("../value/hash");
|
||||
// -------------------------------------------------------------------
|
||||
// TypeCheck
|
||||
// -------------------------------------------------------------------
|
||||
class TypeCheck {
|
||||
constructor(schema, references, checkFunc, code) {
|
||||
this.schema = schema;
|
||||
this.references = references;
|
||||
this.checkFunc = checkFunc;
|
||||
this.code = code;
|
||||
}
|
||||
/** Returns the generated assertion code used to validate this type. */
|
||||
Code() {
|
||||
return this.code;
|
||||
}
|
||||
/** Returns an iterator for each error in this value. */
|
||||
Errors(value) {
|
||||
return index_1.ValueErrors.Errors(this.schema, this.references, value);
|
||||
}
|
||||
/** Returns true if the value matches the compiled type. */
|
||||
Check(value) {
|
||||
return this.checkFunc(value);
|
||||
}
|
||||
}
|
||||
exports.TypeCheck = TypeCheck;
|
||||
// -------------------------------------------------------------------
|
||||
// Character
|
||||
// -------------------------------------------------------------------
|
||||
var Character;
|
||||
(function (Character) {
|
||||
function DollarSign(code) {
|
||||
return code === 36;
|
||||
}
|
||||
Character.DollarSign = DollarSign;
|
||||
function IsUnderscore(code) {
|
||||
return code === 95;
|
||||
}
|
||||
Character.IsUnderscore = IsUnderscore;
|
||||
function IsAlpha(code) {
|
||||
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
|
||||
}
|
||||
Character.IsAlpha = IsAlpha;
|
||||
function IsNumeric(code) {
|
||||
return code >= 48 && code <= 57;
|
||||
}
|
||||
Character.IsNumeric = IsNumeric;
|
||||
})(Character || (Character = {}));
|
||||
// -------------------------------------------------------------------
|
||||
// MemberExpression
|
||||
// -------------------------------------------------------------------
|
||||
var MemberExpression;
|
||||
(function (MemberExpression) {
|
||||
function IsFirstCharacterNumeric(value) {
|
||||
if (value.length === 0)
|
||||
return false;
|
||||
return Character.IsNumeric(value.charCodeAt(0));
|
||||
}
|
||||
function IsAccessor(value) {
|
||||
if (IsFirstCharacterNumeric(value))
|
||||
return false;
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
const code = value.charCodeAt(i);
|
||||
const check = Character.IsAlpha(code) || Character.IsNumeric(code) || Character.DollarSign(code) || Character.IsUnderscore(code);
|
||||
if (!check)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function EscapeHyphen(key) {
|
||||
return key.replace(/'/g, "\\'");
|
||||
}
|
||||
function Encode(object, key) {
|
||||
return IsAccessor(key) ? `${object}.${key}` : `${object}['${EscapeHyphen(key)}']`;
|
||||
}
|
||||
MemberExpression.Encode = Encode;
|
||||
})(MemberExpression || (MemberExpression = {}));
|
||||
// -------------------------------------------------------------------
|
||||
// Identifier
|
||||
// -------------------------------------------------------------------
|
||||
var Identifier;
|
||||
(function (Identifier) {
|
||||
function Encode($id) {
|
||||
const buffer = [];
|
||||
for (let i = 0; i < $id.length; i++) {
|
||||
const code = $id.charCodeAt(i);
|
||||
if (Character.IsNumeric(code) || Character.IsAlpha(code)) {
|
||||
buffer.push($id.charAt(i));
|
||||
}
|
||||
else {
|
||||
buffer.push(`_${code}_`);
|
||||
}
|
||||
}
|
||||
return buffer.join('').replace(/__/g, '_');
|
||||
}
|
||||
Identifier.Encode = Encode;
|
||||
})(Identifier || (Identifier = {}));
|
||||
// -------------------------------------------------------------------
|
||||
// TypeCompiler
|
||||
// -------------------------------------------------------------------
|
||||
class TypeCompilerUnknownTypeError extends Error {
|
||||
constructor(schema) {
|
||||
super('TypeCompiler: Unknown type');
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.TypeCompilerUnknownTypeError = TypeCompilerUnknownTypeError;
|
||||
class TypeCompilerDereferenceError extends Error {
|
||||
constructor(schema) {
|
||||
super(`TypeCompiler: Unable to dereference schema with $id '${schema.$ref}'`);
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.TypeCompilerDereferenceError = TypeCompilerDereferenceError;
|
||||
class TypeCompilerTypeGuardError extends Error {
|
||||
constructor(schema) {
|
||||
super('TypeCompiler: Preflight validation check failed to guard for the given schema');
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.TypeCompilerTypeGuardError = TypeCompilerTypeGuardError;
|
||||
/** Compiles Types for Runtime Type Checking */
|
||||
var TypeCompiler;
|
||||
(function (TypeCompiler) {
|
||||
// -------------------------------------------------------------------
|
||||
// Guards
|
||||
// -------------------------------------------------------------------
|
||||
function IsBigInt(value) {
|
||||
return typeof value === 'bigint';
|
||||
}
|
||||
function IsNumber(value) {
|
||||
return typeof value === 'number' && globalThis.Number.isFinite(value);
|
||||
}
|
||||
function IsString(value) {
|
||||
return typeof value === 'string';
|
||||
}
|
||||
// -------------------------------------------------------------------
|
||||
// Polices
|
||||
// -------------------------------------------------------------------
|
||||
function IsExactOptionalProperty(value, key, expression) {
|
||||
return index_2.TypeSystem.ExactOptionalPropertyTypes ? `('${key}' in ${value} ? ${expression} : true)` : `(${MemberExpression.Encode(value, key)} !== undefined ? ${expression} : true)`;
|
||||
}
|
||||
function IsObjectCheck(value) {
|
||||
return !index_2.TypeSystem.AllowArrayObjects ? `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))` : `(typeof ${value} === 'object' && ${value} !== null)`;
|
||||
}
|
||||
function IsRecordCheck(value) {
|
||||
return !index_2.TypeSystem.AllowArrayObjects
|
||||
? `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}) && !(${value} instanceof Date) && !(${value} instanceof Uint8Array))`
|
||||
: `(typeof ${value} === 'object' && ${value} !== null && !(${value} instanceof Date) && !(${value} instanceof Uint8Array))`;
|
||||
}
|
||||
function IsNumberCheck(value) {
|
||||
return !index_2.TypeSystem.AllowNaN ? `(typeof ${value} === 'number' && Number.isFinite(${value}))` : `typeof ${value} === 'number'`;
|
||||
}
|
||||
function IsVoidCheck(value) {
|
||||
return index_2.TypeSystem.AllowVoidNull ? `(${value} === undefined || ${value} === null)` : `${value} === undefined`;
|
||||
}
|
||||
// -------------------------------------------------------------------
|
||||
// Types
|
||||
// -------------------------------------------------------------------
|
||||
function* Any(schema, references, value) {
|
||||
yield 'true';
|
||||
}
|
||||
function* Array(schema, references, value) {
|
||||
const expression = CreateExpression(schema.items, references, 'value');
|
||||
yield `Array.isArray(${value}) && ${value}.every(value => ${expression})`;
|
||||
if (IsNumber(schema.minItems))
|
||||
yield `${value}.length >= ${schema.minItems}`;
|
||||
if (IsNumber(schema.maxItems))
|
||||
yield `${value}.length <= ${schema.maxItems}`;
|
||||
if (schema.uniqueItems === true)
|
||||
yield `((function() { const set = new Set(); for(const element of ${value}) { const hashed = hash(element); if(set.has(hashed)) { return false } else { set.add(hashed) } } return true })())`;
|
||||
}
|
||||
function* BigInt(schema, references, value) {
|
||||
yield `(typeof ${value} === 'bigint')`;
|
||||
if (IsBigInt(schema.multipleOf))
|
||||
yield `(${value} % BigInt(${schema.multipleOf})) === 0`;
|
||||
if (IsBigInt(schema.exclusiveMinimum))
|
||||
yield `${value} > BigInt(${schema.exclusiveMinimum})`;
|
||||
if (IsBigInt(schema.exclusiveMaximum))
|
||||
yield `${value} < BigInt(${schema.exclusiveMaximum})`;
|
||||
if (IsBigInt(schema.minimum))
|
||||
yield `${value} >= BigInt(${schema.minimum})`;
|
||||
if (IsBigInt(schema.maximum))
|
||||
yield `${value} <= BigInt(${schema.maximum})`;
|
||||
}
|
||||
function* Boolean(schema, references, value) {
|
||||
yield `typeof ${value} === 'boolean'`;
|
||||
}
|
||||
function* Constructor(schema, references, value) {
|
||||
yield* Visit(schema.returns, references, `${value}.prototype`);
|
||||
}
|
||||
function* Date(schema, references, value) {
|
||||
yield `(${value} instanceof Date) && Number.isFinite(${value}.getTime())`;
|
||||
if (IsNumber(schema.exclusiveMinimumTimestamp))
|
||||
yield `${value}.getTime() > ${schema.exclusiveMinimumTimestamp}`;
|
||||
if (IsNumber(schema.exclusiveMaximumTimestamp))
|
||||
yield `${value}.getTime() < ${schema.exclusiveMaximumTimestamp}`;
|
||||
if (IsNumber(schema.minimumTimestamp))
|
||||
yield `${value}.getTime() >= ${schema.minimumTimestamp}`;
|
||||
if (IsNumber(schema.maximumTimestamp))
|
||||
yield `${value}.getTime() <= ${schema.maximumTimestamp}`;
|
||||
}
|
||||
function* Function(schema, references, value) {
|
||||
yield `typeof ${value} === 'function'`;
|
||||
}
|
||||
function* Integer(schema, references, value) {
|
||||
yield `(typeof ${value} === 'number' && Number.isInteger(${value}))`;
|
||||
if (IsNumber(schema.multipleOf))
|
||||
yield `(${value} % ${schema.multipleOf}) === 0`;
|
||||
if (IsNumber(schema.exclusiveMinimum))
|
||||
yield `${value} > ${schema.exclusiveMinimum}`;
|
||||
if (IsNumber(schema.exclusiveMaximum))
|
||||
yield `${value} < ${schema.exclusiveMaximum}`;
|
||||
if (IsNumber(schema.minimum))
|
||||
yield `${value} >= ${schema.minimum}`;
|
||||
if (IsNumber(schema.maximum))
|
||||
yield `${value} <= ${schema.maximum}`;
|
||||
}
|
||||
function* Intersect(schema, references, value) {
|
||||
if (schema.unevaluatedProperties === undefined) {
|
||||
const expressions = schema.allOf.map((schema) => CreateExpression(schema, references, value));
|
||||
yield `${expressions.join(' && ')}`;
|
||||
}
|
||||
else if (schema.unevaluatedProperties === false) {
|
||||
// prettier-ignore
|
||||
const schemaKeys = Types.KeyResolver.Resolve(schema).map((key) => `'${key}'`).join(', ');
|
||||
const expressions = schema.allOf.map((schema) => CreateExpression(schema, references, value));
|
||||
const expression1 = `Object.getOwnPropertyNames(${value}).every(key => [${schemaKeys}].includes(key))`;
|
||||
yield `${expressions.join(' && ')} && ${expression1}`;
|
||||
}
|
||||
else if (typeof schema.unevaluatedProperties === 'object') {
|
||||
// prettier-ignore
|
||||
const schemaKeys = Types.KeyResolver.Resolve(schema).map((key) => `'${key}'`).join(', ');
|
||||
const expressions = schema.allOf.map((schema) => CreateExpression(schema, references, value));
|
||||
const expression1 = CreateExpression(schema.unevaluatedProperties, references, 'value[key]');
|
||||
const expression2 = `Object.getOwnPropertyNames(${value}).every(key => [${schemaKeys}].includes(key) || ${expression1})`;
|
||||
yield `${expressions.join(' && ')} && ${expression2}`;
|
||||
}
|
||||
}
|
||||
function* Literal(schema, references, value) {
|
||||
if (typeof schema.const === 'number' || typeof schema.const === 'boolean') {
|
||||
yield `${value} === ${schema.const}`;
|
||||
}
|
||||
else {
|
||||
yield `${value} === '${schema.const}'`;
|
||||
}
|
||||
}
|
||||
function* Never(schema, references, value) {
|
||||
yield `false`;
|
||||
}
|
||||
function* Not(schema, references, value) {
|
||||
const left = CreateExpression(schema.allOf[0].not, references, value);
|
||||
const right = CreateExpression(schema.allOf[1], references, value);
|
||||
yield `!${left} && ${right}`;
|
||||
}
|
||||
function* Null(schema, references, value) {
|
||||
yield `${value} === null`;
|
||||
}
|
||||
function* Number(schema, references, value) {
|
||||
yield IsNumberCheck(value);
|
||||
if (IsNumber(schema.multipleOf))
|
||||
yield `(${value} % ${schema.multipleOf}) === 0`;
|
||||
if (IsNumber(schema.exclusiveMinimum))
|
||||
yield `${value} > ${schema.exclusiveMinimum}`;
|
||||
if (IsNumber(schema.exclusiveMaximum))
|
||||
yield `${value} < ${schema.exclusiveMaximum}`;
|
||||
if (IsNumber(schema.minimum))
|
||||
yield `${value} >= ${schema.minimum}`;
|
||||
if (IsNumber(schema.maximum))
|
||||
yield `${value} <= ${schema.maximum}`;
|
||||
}
|
||||
function* Object(schema, references, value) {
|
||||
yield IsObjectCheck(value);
|
||||
if (IsNumber(schema.minProperties))
|
||||
yield `Object.getOwnPropertyNames(${value}).length >= ${schema.minProperties}`;
|
||||
if (IsNumber(schema.maxProperties))
|
||||
yield `Object.getOwnPropertyNames(${value}).length <= ${schema.maxProperties}`;
|
||||
const knownKeys = globalThis.Object.getOwnPropertyNames(schema.properties);
|
||||
for (const knownKey of knownKeys) {
|
||||
const memberExpression = MemberExpression.Encode(value, knownKey);
|
||||
const property = schema.properties[knownKey];
|
||||
if (schema.required && schema.required.includes(knownKey)) {
|
||||
yield* Visit(property, references, memberExpression);
|
||||
if (Types.ExtendsUndefined.Check(property))
|
||||
yield `('${knownKey}' in ${value})`;
|
||||
}
|
||||
else {
|
||||
const expression = CreateExpression(property, references, memberExpression);
|
||||
yield IsExactOptionalProperty(value, knownKey, expression);
|
||||
}
|
||||
}
|
||||
if (schema.additionalProperties === false) {
|
||||
if (schema.required && schema.required.length === knownKeys.length) {
|
||||
yield `Object.getOwnPropertyNames(${value}).length === ${knownKeys.length}`;
|
||||
}
|
||||
else {
|
||||
const keys = `[${knownKeys.map((key) => `'${key}'`).join(', ')}]`;
|
||||
yield `Object.getOwnPropertyNames(${value}).every(key => ${keys}.includes(key))`;
|
||||
}
|
||||
}
|
||||
if (typeof schema.additionalProperties === 'object') {
|
||||
const expression = CreateExpression(schema.additionalProperties, references, 'value[key]');
|
||||
const keys = `[${knownKeys.map((key) => `'${key}'`).join(', ')}]`;
|
||||
yield `(Object.getOwnPropertyNames(${value}).every(key => ${keys}.includes(key) || ${expression}))`;
|
||||
}
|
||||
}
|
||||
function* Promise(schema, references, value) {
|
||||
yield `(typeof value === 'object' && typeof ${value}.then === 'function')`;
|
||||
}
|
||||
function* Record(schema, references, value) {
|
||||
yield IsRecordCheck(value);
|
||||
if (IsNumber(schema.minProperties))
|
||||
yield `Object.getOwnPropertyNames(${value}).length >= ${schema.minProperties}`;
|
||||
if (IsNumber(schema.maxProperties))
|
||||
yield `Object.getOwnPropertyNames(${value}).length <= ${schema.maxProperties}`;
|
||||
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
|
||||
const local = PushLocal(`new RegExp(/${keyPattern}/)`);
|
||||
yield `(Object.getOwnPropertyNames(${value}).every(key => ${local}.test(key)))`;
|
||||
const expression = CreateExpression(valueSchema, references, 'value');
|
||||
yield `Object.values(${value}).every(value => ${expression})`;
|
||||
}
|
||||
function* Ref(schema, references, value) {
|
||||
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
|
||||
if (index === -1)
|
||||
throw new TypeCompilerDereferenceError(schema);
|
||||
const target = references[index];
|
||||
// Reference: If we have seen this reference before we can just yield and return
|
||||
// the function call. If this isn't the case we defer to visit to generate and
|
||||
// set the function for subsequent passes. Consider for refactor.
|
||||
if (state_local_function_names.has(schema.$ref))
|
||||
return yield `${CreateFunctionName(schema.$ref)}(${value})`;
|
||||
yield* Visit(target, references, value);
|
||||
}
|
||||
function* String(schema, references, value) {
|
||||
yield `(typeof ${value} === 'string')`;
|
||||
if (IsNumber(schema.minLength))
|
||||
yield `${value}.length >= ${schema.minLength}`;
|
||||
if (IsNumber(schema.maxLength))
|
||||
yield `${value}.length <= ${schema.maxLength}`;
|
||||
if (schema.pattern !== undefined) {
|
||||
const local = PushLocal(`${new RegExp(schema.pattern)};`);
|
||||
yield `${local}.test(${value})`;
|
||||
}
|
||||
if (schema.format !== undefined) {
|
||||
yield `format('${schema.format}', ${value})`;
|
||||
}
|
||||
}
|
||||
function* Symbol(schema, references, value) {
|
||||
yield `(typeof ${value} === 'symbol')`;
|
||||
}
|
||||
function* TemplateLiteral(schema, references, value) {
|
||||
yield `(typeof ${value} === 'string')`;
|
||||
const local = PushLocal(`${new RegExp(schema.pattern)};`);
|
||||
yield `${local}.test(${value})`;
|
||||
}
|
||||
function* This(schema, references, value) {
|
||||
const func = CreateFunctionName(schema.$ref);
|
||||
yield `${func}(${value})`;
|
||||
}
|
||||
function* Tuple(schema, references, value) {
|
||||
yield `(Array.isArray(${value}))`;
|
||||
if (schema.items === undefined)
|
||||
return yield `${value}.length === 0`;
|
||||
yield `(${value}.length === ${schema.maxItems})`;
|
||||
for (let i = 0; i < schema.items.length; i++) {
|
||||
const expression = CreateExpression(schema.items[i], references, `${value}[${i}]`);
|
||||
yield `${expression}`;
|
||||
}
|
||||
}
|
||||
function* Undefined(schema, references, value) {
|
||||
yield `${value} === undefined`;
|
||||
}
|
||||
function* Union(schema, references, value) {
|
||||
const expressions = schema.anyOf.map((schema) => CreateExpression(schema, references, value));
|
||||
yield `(${expressions.join(' || ')})`;
|
||||
}
|
||||
function* Uint8Array(schema, references, value) {
|
||||
yield `${value} instanceof Uint8Array`;
|
||||
if (IsNumber(schema.maxByteLength))
|
||||
yield `(${value}.length <= ${schema.maxByteLength})`;
|
||||
if (IsNumber(schema.minByteLength))
|
||||
yield `(${value}.length >= ${schema.minByteLength})`;
|
||||
}
|
||||
function* Unknown(schema, references, value) {
|
||||
yield 'true';
|
||||
}
|
||||
function* Void(schema, references, value) {
|
||||
yield IsVoidCheck(value);
|
||||
}
|
||||
function* UserDefined(schema, references, value) {
|
||||
const schema_key = `schema_key_${state_remote_custom_types.size}`;
|
||||
state_remote_custom_types.set(schema_key, schema);
|
||||
yield `custom('${schema[Types.Kind]}', '${schema_key}', ${value})`;
|
||||
}
|
||||
function* Visit(schema, references, value) {
|
||||
const references_ = IsString(schema.$id) ? [...references, schema] : references;
|
||||
const schema_ = schema;
|
||||
// Reference: Referenced schemas can originate from either additional schemas
|
||||
// or inline in the schema itself. Ideally the recursive path should align to
|
||||
// reference path. Consider for refactor.
|
||||
if (IsString(schema.$id) && !state_local_function_names.has(schema.$id)) {
|
||||
state_local_function_names.add(schema.$id);
|
||||
const name = CreateFunctionName(schema.$id);
|
||||
const body = CreateFunction(name, schema, references, 'value');
|
||||
PushFunction(body);
|
||||
yield `${name}(${value})`;
|
||||
return;
|
||||
}
|
||||
switch (schema_[Types.Kind]) {
|
||||
case 'Any':
|
||||
return yield* Any(schema_, references_, value);
|
||||
case 'Array':
|
||||
return yield* Array(schema_, references_, value);
|
||||
case 'BigInt':
|
||||
return yield* BigInt(schema_, references_, value);
|
||||
case 'Boolean':
|
||||
return yield* Boolean(schema_, references_, value);
|
||||
case 'Constructor':
|
||||
return yield* Constructor(schema_, references_, value);
|
||||
case 'Date':
|
||||
return yield* Date(schema_, references_, value);
|
||||
case 'Function':
|
||||
return yield* Function(schema_, references_, value);
|
||||
case 'Integer':
|
||||
return yield* Integer(schema_, references_, value);
|
||||
case 'Intersect':
|
||||
return yield* Intersect(schema_, references_, value);
|
||||
case 'Literal':
|
||||
return yield* Literal(schema_, references_, value);
|
||||
case 'Never':
|
||||
return yield* Never(schema_, references_, value);
|
||||
case 'Not':
|
||||
return yield* Not(schema_, references_, value);
|
||||
case 'Null':
|
||||
return yield* Null(schema_, references_, value);
|
||||
case 'Number':
|
||||
return yield* Number(schema_, references_, value);
|
||||
case 'Object':
|
||||
return yield* Object(schema_, references_, value);
|
||||
case 'Promise':
|
||||
return yield* Promise(schema_, references_, value);
|
||||
case 'Record':
|
||||
return yield* Record(schema_, references_, value);
|
||||
case 'Ref':
|
||||
return yield* Ref(schema_, references_, value);
|
||||
case 'String':
|
||||
return yield* String(schema_, references_, value);
|
||||
case 'Symbol':
|
||||
return yield* Symbol(schema_, references_, value);
|
||||
case 'TemplateLiteral':
|
||||
return yield* TemplateLiteral(schema_, references_, value);
|
||||
case 'This':
|
||||
return yield* This(schema_, references_, value);
|
||||
case 'Tuple':
|
||||
return yield* Tuple(schema_, references_, value);
|
||||
case 'Undefined':
|
||||
return yield* Undefined(schema_, references_, value);
|
||||
case 'Union':
|
||||
return yield* Union(schema_, references_, value);
|
||||
case 'Uint8Array':
|
||||
return yield* Uint8Array(schema_, references_, value);
|
||||
case 'Unknown':
|
||||
return yield* Unknown(schema_, references_, value);
|
||||
case 'Void':
|
||||
return yield* Void(schema_, references_, value);
|
||||
default:
|
||||
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
|
||||
throw new TypeCompilerUnknownTypeError(schema);
|
||||
return yield* UserDefined(schema_, references_, value);
|
||||
}
|
||||
}
|
||||
// -------------------------------------------------------------------
|
||||
// Compiler State
|
||||
// -------------------------------------------------------------------
|
||||
const state_local_variables = new Set(); // local variables and functions
|
||||
const state_local_function_names = new Set(); // local function names used call ref validators
|
||||
const state_remote_custom_types = new Map(); // remote custom types used during compilation
|
||||
function ResetCompiler() {
|
||||
state_local_variables.clear();
|
||||
state_local_function_names.clear();
|
||||
state_remote_custom_types.clear();
|
||||
}
|
||||
function CreateExpression(schema, references, value) {
|
||||
return `(${[...Visit(schema, references, value)].join(' && ')})`;
|
||||
}
|
||||
function CreateFunctionName($id) {
|
||||
return `check_${Identifier.Encode($id)}`;
|
||||
}
|
||||
function CreateFunction(name, schema, references, value) {
|
||||
const expression = [...Visit(schema, references, value)].map((condition) => ` ${condition}`).join(' &&\n');
|
||||
return `function ${name}(value) {\n return (\n${expression}\n )\n}`;
|
||||
}
|
||||
function PushFunction(functionBody) {
|
||||
state_local_variables.add(functionBody);
|
||||
}
|
||||
function PushLocal(expression) {
|
||||
const local = `local_${state_local_variables.size}`;
|
||||
state_local_variables.add(`const ${local} = ${expression}`);
|
||||
return local;
|
||||
}
|
||||
function GetLocals() {
|
||||
return [...state_local_variables.values()];
|
||||
}
|
||||
// -------------------------------------------------------------------
|
||||
// Compile
|
||||
// -------------------------------------------------------------------
|
||||
function Build(schema, references) {
|
||||
ResetCompiler();
|
||||
const check = CreateFunction('check', schema, references, 'value');
|
||||
const locals = GetLocals();
|
||||
return `${locals.join('\n')}\nreturn ${check}`;
|
||||
}
|
||||
/** Returns the generated assertion code used to validate this type. */
|
||||
function Code(schema, references = []) {
|
||||
if (!Types.TypeGuard.TSchema(schema))
|
||||
throw new TypeCompilerTypeGuardError(schema);
|
||||
for (const schema of references)
|
||||
if (!Types.TypeGuard.TSchema(schema))
|
||||
throw new TypeCompilerTypeGuardError(schema);
|
||||
return Build(schema, references);
|
||||
}
|
||||
TypeCompiler.Code = Code;
|
||||
/** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
|
||||
function Compile(schema, references = []) {
|
||||
const code = Code(schema, references);
|
||||
const custom_schemas = new Map(state_remote_custom_types);
|
||||
const compiledFunction = globalThis.Function('custom', 'format', 'hash', code);
|
||||
const checkFunction = compiledFunction((kind, schema_key, value) => {
|
||||
if (!Types.TypeRegistry.Has(kind) || !custom_schemas.has(schema_key))
|
||||
return false;
|
||||
const schema = custom_schemas.get(schema_key);
|
||||
const func = Types.TypeRegistry.Get(kind);
|
||||
return func(schema, value);
|
||||
}, (format, value) => {
|
||||
if (!Types.FormatRegistry.Has(format))
|
||||
return false;
|
||||
const func = Types.FormatRegistry.Get(format);
|
||||
return func(value);
|
||||
}, (value) => {
|
||||
return hash_1.ValueHash.Create(value);
|
||||
});
|
||||
return new TypeCheck(schema, references, checkFunction, code);
|
||||
}
|
||||
TypeCompiler.Compile = Compile;
|
||||
})(TypeCompiler = exports.TypeCompiler || (exports.TypeCompiler = {}));
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export { ValueError, ValueErrorType } from '../errors/index';
|
||||
export * from './compiler';
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
"use strict";
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/compiler
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.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.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ValueErrorType = void 0;
|
||||
var index_1 = require("../errors/index");
|
||||
Object.defineProperty(exports, "ValueErrorType", { enumerable: true, get: function () { return index_1.ValueErrorType; } });
|
||||
__exportStar(require("./compiler"), exports);
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
import * as Types from '../typebox';
|
||||
export declare enum ValueErrorType {
|
||||
Array = 0,
|
||||
ArrayMinItems = 1,
|
||||
ArrayMaxItems = 2,
|
||||
ArrayUniqueItems = 3,
|
||||
BigInt = 4,
|
||||
BigIntMultipleOf = 5,
|
||||
BigIntExclusiveMinimum = 6,
|
||||
BigIntExclusiveMaximum = 7,
|
||||
BigIntMinimum = 8,
|
||||
BigIntMaximum = 9,
|
||||
Boolean = 10,
|
||||
Date = 11,
|
||||
DateExclusiveMinimumTimestamp = 12,
|
||||
DateExclusiveMaximumTimestamp = 13,
|
||||
DateMinimumTimestamp = 14,
|
||||
DateMaximumTimestamp = 15,
|
||||
Function = 16,
|
||||
Integer = 17,
|
||||
IntegerMultipleOf = 18,
|
||||
IntegerExclusiveMinimum = 19,
|
||||
IntegerExclusiveMaximum = 20,
|
||||
IntegerMinimum = 21,
|
||||
IntegerMaximum = 22,
|
||||
Intersect = 23,
|
||||
IntersectUnevaluatedProperties = 24,
|
||||
Literal = 25,
|
||||
Never = 26,
|
||||
Not = 27,
|
||||
Null = 28,
|
||||
Number = 29,
|
||||
NumberMultipleOf = 30,
|
||||
NumberExclusiveMinimum = 31,
|
||||
NumberExclusiveMaximum = 32,
|
||||
NumberMinumum = 33,
|
||||
NumberMaximum = 34,
|
||||
Object = 35,
|
||||
ObjectMinProperties = 36,
|
||||
ObjectMaxProperties = 37,
|
||||
ObjectAdditionalProperties = 38,
|
||||
ObjectRequiredProperties = 39,
|
||||
Promise = 40,
|
||||
RecordKeyNumeric = 41,
|
||||
RecordKeyString = 42,
|
||||
String = 43,
|
||||
StringMinLength = 44,
|
||||
StringMaxLength = 45,
|
||||
StringPattern = 46,
|
||||
StringFormatUnknown = 47,
|
||||
StringFormat = 48,
|
||||
Symbol = 49,
|
||||
TupleZeroLength = 50,
|
||||
TupleLength = 51,
|
||||
Undefined = 52,
|
||||
Union = 53,
|
||||
Uint8Array = 54,
|
||||
Uint8ArrayMinByteLength = 55,
|
||||
Uint8ArrayMaxByteLength = 56,
|
||||
Void = 57,
|
||||
Custom = 58
|
||||
}
|
||||
export interface ValueError {
|
||||
type: ValueErrorType;
|
||||
schema: Types.TSchema;
|
||||
path: string;
|
||||
value: unknown;
|
||||
message: string;
|
||||
}
|
||||
export declare class ValueErrorIterator {
|
||||
private readonly iterator;
|
||||
constructor(iterator: IterableIterator<ValueError>);
|
||||
[Symbol.iterator](): IterableIterator<ValueError>;
|
||||
/** Returns the first value error or undefined if no errors */
|
||||
First(): ValueError | undefined;
|
||||
}
|
||||
export declare class ValueErrorsUnknownTypeError extends Error {
|
||||
readonly schema: Types.TSchema;
|
||||
constructor(schema: Types.TSchema);
|
||||
}
|
||||
export declare class ValueErrorsDereferenceError extends Error {
|
||||
readonly schema: Types.TRef | Types.TThis;
|
||||
constructor(schema: Types.TRef | Types.TThis);
|
||||
}
|
||||
/** Provides functionality to generate a sequence of errors against a TypeBox type. */
|
||||
export declare namespace ValueErrors {
|
||||
function Errors<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: any): ValueErrorIterator;
|
||||
}
|
||||
|
|
@ -0,0 +1,609 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ValueErrors = exports.ValueErrorsDereferenceError = exports.ValueErrorsUnknownTypeError = exports.ValueErrorIterator = exports.ValueErrorType = void 0;
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/errors
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.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.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
const Types = require("../typebox");
|
||||
const index_1 = require("../system/index");
|
||||
const hash_1 = require("../value/hash");
|
||||
// -------------------------------------------------------------------
|
||||
// ValueErrorType
|
||||
// -------------------------------------------------------------------
|
||||
var ValueErrorType;
|
||||
(function (ValueErrorType) {
|
||||
ValueErrorType[ValueErrorType["Array"] = 0] = "Array";
|
||||
ValueErrorType[ValueErrorType["ArrayMinItems"] = 1] = "ArrayMinItems";
|
||||
ValueErrorType[ValueErrorType["ArrayMaxItems"] = 2] = "ArrayMaxItems";
|
||||
ValueErrorType[ValueErrorType["ArrayUniqueItems"] = 3] = "ArrayUniqueItems";
|
||||
ValueErrorType[ValueErrorType["BigInt"] = 4] = "BigInt";
|
||||
ValueErrorType[ValueErrorType["BigIntMultipleOf"] = 5] = "BigIntMultipleOf";
|
||||
ValueErrorType[ValueErrorType["BigIntExclusiveMinimum"] = 6] = "BigIntExclusiveMinimum";
|
||||
ValueErrorType[ValueErrorType["BigIntExclusiveMaximum"] = 7] = "BigIntExclusiveMaximum";
|
||||
ValueErrorType[ValueErrorType["BigIntMinimum"] = 8] = "BigIntMinimum";
|
||||
ValueErrorType[ValueErrorType["BigIntMaximum"] = 9] = "BigIntMaximum";
|
||||
ValueErrorType[ValueErrorType["Boolean"] = 10] = "Boolean";
|
||||
ValueErrorType[ValueErrorType["Date"] = 11] = "Date";
|
||||
ValueErrorType[ValueErrorType["DateExclusiveMinimumTimestamp"] = 12] = "DateExclusiveMinimumTimestamp";
|
||||
ValueErrorType[ValueErrorType["DateExclusiveMaximumTimestamp"] = 13] = "DateExclusiveMaximumTimestamp";
|
||||
ValueErrorType[ValueErrorType["DateMinimumTimestamp"] = 14] = "DateMinimumTimestamp";
|
||||
ValueErrorType[ValueErrorType["DateMaximumTimestamp"] = 15] = "DateMaximumTimestamp";
|
||||
ValueErrorType[ValueErrorType["Function"] = 16] = "Function";
|
||||
ValueErrorType[ValueErrorType["Integer"] = 17] = "Integer";
|
||||
ValueErrorType[ValueErrorType["IntegerMultipleOf"] = 18] = "IntegerMultipleOf";
|
||||
ValueErrorType[ValueErrorType["IntegerExclusiveMinimum"] = 19] = "IntegerExclusiveMinimum";
|
||||
ValueErrorType[ValueErrorType["IntegerExclusiveMaximum"] = 20] = "IntegerExclusiveMaximum";
|
||||
ValueErrorType[ValueErrorType["IntegerMinimum"] = 21] = "IntegerMinimum";
|
||||
ValueErrorType[ValueErrorType["IntegerMaximum"] = 22] = "IntegerMaximum";
|
||||
ValueErrorType[ValueErrorType["Intersect"] = 23] = "Intersect";
|
||||
ValueErrorType[ValueErrorType["IntersectUnevaluatedProperties"] = 24] = "IntersectUnevaluatedProperties";
|
||||
ValueErrorType[ValueErrorType["Literal"] = 25] = "Literal";
|
||||
ValueErrorType[ValueErrorType["Never"] = 26] = "Never";
|
||||
ValueErrorType[ValueErrorType["Not"] = 27] = "Not";
|
||||
ValueErrorType[ValueErrorType["Null"] = 28] = "Null";
|
||||
ValueErrorType[ValueErrorType["Number"] = 29] = "Number";
|
||||
ValueErrorType[ValueErrorType["NumberMultipleOf"] = 30] = "NumberMultipleOf";
|
||||
ValueErrorType[ValueErrorType["NumberExclusiveMinimum"] = 31] = "NumberExclusiveMinimum";
|
||||
ValueErrorType[ValueErrorType["NumberExclusiveMaximum"] = 32] = "NumberExclusiveMaximum";
|
||||
ValueErrorType[ValueErrorType["NumberMinumum"] = 33] = "NumberMinumum";
|
||||
ValueErrorType[ValueErrorType["NumberMaximum"] = 34] = "NumberMaximum";
|
||||
ValueErrorType[ValueErrorType["Object"] = 35] = "Object";
|
||||
ValueErrorType[ValueErrorType["ObjectMinProperties"] = 36] = "ObjectMinProperties";
|
||||
ValueErrorType[ValueErrorType["ObjectMaxProperties"] = 37] = "ObjectMaxProperties";
|
||||
ValueErrorType[ValueErrorType["ObjectAdditionalProperties"] = 38] = "ObjectAdditionalProperties";
|
||||
ValueErrorType[ValueErrorType["ObjectRequiredProperties"] = 39] = "ObjectRequiredProperties";
|
||||
ValueErrorType[ValueErrorType["Promise"] = 40] = "Promise";
|
||||
ValueErrorType[ValueErrorType["RecordKeyNumeric"] = 41] = "RecordKeyNumeric";
|
||||
ValueErrorType[ValueErrorType["RecordKeyString"] = 42] = "RecordKeyString";
|
||||
ValueErrorType[ValueErrorType["String"] = 43] = "String";
|
||||
ValueErrorType[ValueErrorType["StringMinLength"] = 44] = "StringMinLength";
|
||||
ValueErrorType[ValueErrorType["StringMaxLength"] = 45] = "StringMaxLength";
|
||||
ValueErrorType[ValueErrorType["StringPattern"] = 46] = "StringPattern";
|
||||
ValueErrorType[ValueErrorType["StringFormatUnknown"] = 47] = "StringFormatUnknown";
|
||||
ValueErrorType[ValueErrorType["StringFormat"] = 48] = "StringFormat";
|
||||
ValueErrorType[ValueErrorType["Symbol"] = 49] = "Symbol";
|
||||
ValueErrorType[ValueErrorType["TupleZeroLength"] = 50] = "TupleZeroLength";
|
||||
ValueErrorType[ValueErrorType["TupleLength"] = 51] = "TupleLength";
|
||||
ValueErrorType[ValueErrorType["Undefined"] = 52] = "Undefined";
|
||||
ValueErrorType[ValueErrorType["Union"] = 53] = "Union";
|
||||
ValueErrorType[ValueErrorType["Uint8Array"] = 54] = "Uint8Array";
|
||||
ValueErrorType[ValueErrorType["Uint8ArrayMinByteLength"] = 55] = "Uint8ArrayMinByteLength";
|
||||
ValueErrorType[ValueErrorType["Uint8ArrayMaxByteLength"] = 56] = "Uint8ArrayMaxByteLength";
|
||||
ValueErrorType[ValueErrorType["Void"] = 57] = "Void";
|
||||
ValueErrorType[ValueErrorType["Custom"] = 58] = "Custom";
|
||||
})(ValueErrorType = exports.ValueErrorType || (exports.ValueErrorType = {}));
|
||||
// -------------------------------------------------------------------
|
||||
// ValueErrorIterator
|
||||
// -------------------------------------------------------------------
|
||||
class ValueErrorIterator {
|
||||
constructor(iterator) {
|
||||
this.iterator = iterator;
|
||||
}
|
||||
[Symbol.iterator]() {
|
||||
return this.iterator;
|
||||
}
|
||||
/** Returns the first value error or undefined if no errors */
|
||||
First() {
|
||||
const next = this.iterator.next();
|
||||
return next.done ? undefined : next.value;
|
||||
}
|
||||
}
|
||||
exports.ValueErrorIterator = ValueErrorIterator;
|
||||
// -------------------------------------------------------------------
|
||||
// ValueErrors
|
||||
// -------------------------------------------------------------------
|
||||
class ValueErrorsUnknownTypeError extends Error {
|
||||
constructor(schema) {
|
||||
super('ValueErrors: Unknown type');
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueErrorsUnknownTypeError = ValueErrorsUnknownTypeError;
|
||||
class ValueErrorsDereferenceError extends Error {
|
||||
constructor(schema) {
|
||||
super(`ValueErrors: Unable to dereference schema with $id '${schema.$ref}'`);
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueErrorsDereferenceError = ValueErrorsDereferenceError;
|
||||
/** Provides functionality to generate a sequence of errors against a TypeBox type. */
|
||||
var ValueErrors;
|
||||
(function (ValueErrors) {
|
||||
// ----------------------------------------------------------------------
|
||||
// Guards
|
||||
// ----------------------------------------------------------------------
|
||||
function IsBigInt(value) {
|
||||
return typeof value === 'bigint';
|
||||
}
|
||||
function IsInteger(value) {
|
||||
return globalThis.Number.isInteger(value);
|
||||
}
|
||||
function IsString(value) {
|
||||
return typeof value === 'string';
|
||||
}
|
||||
function IsDefined(value) {
|
||||
return value !== undefined;
|
||||
}
|
||||
// ----------------------------------------------------------------------
|
||||
// Policies
|
||||
// ----------------------------------------------------------------------
|
||||
function IsExactOptionalProperty(value, key) {
|
||||
return index_1.TypeSystem.ExactOptionalPropertyTypes ? key in value : value[key] !== undefined;
|
||||
}
|
||||
function IsObject(value) {
|
||||
const result = typeof value === 'object' && value !== null;
|
||||
return index_1.TypeSystem.AllowArrayObjects ? result : result && !globalThis.Array.isArray(value);
|
||||
}
|
||||
function IsRecordObject(value) {
|
||||
return IsObject(value) && !(value instanceof globalThis.Date) && !(value instanceof globalThis.Uint8Array);
|
||||
}
|
||||
function IsNumber(value) {
|
||||
const result = typeof value === 'number';
|
||||
return index_1.TypeSystem.AllowNaN ? result : result && globalThis.Number.isFinite(value);
|
||||
}
|
||||
function IsVoid(value) {
|
||||
const result = value === undefined;
|
||||
return index_1.TypeSystem.AllowVoidNull ? result || value === null : result;
|
||||
}
|
||||
// ----------------------------------------------------------------------
|
||||
// Types
|
||||
// ----------------------------------------------------------------------
|
||||
function* Any(schema, references, path, value) { }
|
||||
function* Array(schema, references, path, value) {
|
||||
if (!globalThis.Array.isArray(value)) {
|
||||
return yield { type: ValueErrorType.Array, schema, path, value, message: `Expected array` };
|
||||
}
|
||||
if (IsDefined(schema.minItems) && !(value.length >= schema.minItems)) {
|
||||
yield { type: ValueErrorType.ArrayMinItems, schema, path, value, message: `Expected array length to be greater or equal to ${schema.minItems}` };
|
||||
}
|
||||
if (IsDefined(schema.maxItems) && !(value.length <= schema.maxItems)) {
|
||||
yield { type: ValueErrorType.ArrayMinItems, schema, path, value, message: `Expected array length to be less or equal to ${schema.maxItems}` };
|
||||
}
|
||||
// prettier-ignore
|
||||
if (schema.uniqueItems === true && !((function () { const set = new Set(); for (const element of value) {
|
||||
const hashed = hash_1.ValueHash.Create(element);
|
||||
if (set.has(hashed)) {
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
set.add(hashed);
|
||||
}
|
||||
} return true; })())) {
|
||||
yield { type: ValueErrorType.ArrayUniqueItems, schema, path, value, message: `Expected array elements to be unique` };
|
||||
}
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
yield* Visit(schema.items, references, `${path}/${i}`, value[i]);
|
||||
}
|
||||
}
|
||||
function* BigInt(schema, references, path, value) {
|
||||
if (!IsBigInt(value)) {
|
||||
return yield { type: ValueErrorType.BigInt, schema, path, value, message: `Expected bigint` };
|
||||
}
|
||||
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === globalThis.BigInt(0))) {
|
||||
yield { type: ValueErrorType.BigIntMultipleOf, schema, path, value, message: `Expected bigint to be a multiple of ${schema.multipleOf}` };
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
|
||||
yield { type: ValueErrorType.BigIntExclusiveMinimum, schema, path, value, message: `Expected bigint to be greater than ${schema.exclusiveMinimum}` };
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
|
||||
yield { type: ValueErrorType.BigIntExclusiveMaximum, schema, path, value, message: `Expected bigint to be less than ${schema.exclusiveMaximum}` };
|
||||
}
|
||||
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
|
||||
yield { type: ValueErrorType.BigIntMinimum, schema, path, value, message: `Expected bigint to be greater or equal to ${schema.minimum}` };
|
||||
}
|
||||
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
|
||||
yield { type: ValueErrorType.BigIntMaximum, schema, path, value, message: `Expected bigint to be less or equal to ${schema.maximum}` };
|
||||
}
|
||||
}
|
||||
function* Boolean(schema, references, path, value) {
|
||||
if (!(typeof value === 'boolean')) {
|
||||
return yield { type: ValueErrorType.Boolean, schema, path, value, message: `Expected boolean` };
|
||||
}
|
||||
}
|
||||
function* Constructor(schema, references, path, value) {
|
||||
yield* Visit(schema.returns, references, path, value.prototype);
|
||||
}
|
||||
function* Date(schema, references, path, value) {
|
||||
if (!(value instanceof globalThis.Date)) {
|
||||
return yield { type: ValueErrorType.Date, schema, path, value, message: `Expected Date object` };
|
||||
}
|
||||
if (!globalThis.isFinite(value.getTime())) {
|
||||
return yield { type: ValueErrorType.Date, schema, path, value, message: `Invalid Date` };
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMinimumTimestamp) && !(value.getTime() > schema.exclusiveMinimumTimestamp)) {
|
||||
yield { type: ValueErrorType.DateExclusiveMinimumTimestamp, schema, path, value, message: `Expected Date timestamp to be greater than ${schema.exclusiveMinimum}` };
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMaximumTimestamp) && !(value.getTime() < schema.exclusiveMaximumTimestamp)) {
|
||||
yield { type: ValueErrorType.DateExclusiveMaximumTimestamp, schema, path, value, message: `Expected Date timestamp to be less than ${schema.exclusiveMaximum}` };
|
||||
}
|
||||
if (IsDefined(schema.minimumTimestamp) && !(value.getTime() >= schema.minimumTimestamp)) {
|
||||
yield { type: ValueErrorType.DateMinimumTimestamp, schema, path, value, message: `Expected Date timestamp to be greater or equal to ${schema.minimum}` };
|
||||
}
|
||||
if (IsDefined(schema.maximumTimestamp) && !(value.getTime() <= schema.maximumTimestamp)) {
|
||||
yield { type: ValueErrorType.DateMaximumTimestamp, schema, path, value, message: `Expected Date timestamp to be less or equal to ${schema.maximum}` };
|
||||
}
|
||||
}
|
||||
function* Function(schema, references, path, value) {
|
||||
if (!(typeof value === 'function')) {
|
||||
return yield { type: ValueErrorType.Function, schema, path, value, message: `Expected function` };
|
||||
}
|
||||
}
|
||||
function* Integer(schema, references, path, value) {
|
||||
if (!IsInteger(value)) {
|
||||
return yield { type: ValueErrorType.Integer, schema, path, value, message: `Expected integer` };
|
||||
}
|
||||
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
|
||||
yield { type: ValueErrorType.IntegerMultipleOf, schema, path, value, message: `Expected integer to be a multiple of ${schema.multipleOf}` };
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
|
||||
yield { type: ValueErrorType.IntegerExclusiveMinimum, schema, path, value, message: `Expected integer to be greater than ${schema.exclusiveMinimum}` };
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
|
||||
yield { type: ValueErrorType.IntegerExclusiveMaximum, schema, path, value, message: `Expected integer to be less than ${schema.exclusiveMaximum}` };
|
||||
}
|
||||
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
|
||||
yield { type: ValueErrorType.IntegerMinimum, schema, path, value, message: `Expected integer to be greater or equal to ${schema.minimum}` };
|
||||
}
|
||||
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
|
||||
yield { type: ValueErrorType.IntegerMaximum, schema, path, value, message: `Expected integer to be less or equal to ${schema.maximum}` };
|
||||
}
|
||||
}
|
||||
function* Intersect(schema, references, path, value) {
|
||||
for (const subschema of schema.allOf) {
|
||||
const next = Visit(subschema, references, path, value).next();
|
||||
if (!next.done) {
|
||||
yield next.value;
|
||||
yield { type: ValueErrorType.Intersect, schema, path, value, message: `Expected all sub schemas to be valid` };
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (schema.unevaluatedProperties === false) {
|
||||
const schemaKeys = Types.KeyResolver.Resolve(schema);
|
||||
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
|
||||
for (const valueKey of valueKeys) {
|
||||
if (!schemaKeys.includes(valueKey)) {
|
||||
yield { type: ValueErrorType.IntersectUnevaluatedProperties, schema, path: `${path}/${valueKey}`, value, message: `Unexpected property` };
|
||||
}
|
||||
}
|
||||
}
|
||||
if (typeof schema.unevaluatedProperties === 'object') {
|
||||
const schemaKeys = Types.KeyResolver.Resolve(schema);
|
||||
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
|
||||
for (const valueKey of valueKeys) {
|
||||
if (!schemaKeys.includes(valueKey)) {
|
||||
const next = Visit(schema.unevaluatedProperties, references, `${path}/${valueKey}`, value[valueKey]).next();
|
||||
if (!next.done) {
|
||||
yield next.value;
|
||||
yield { type: ValueErrorType.IntersectUnevaluatedProperties, schema, path: `${path}/${valueKey}`, value, message: `Invalid additional property` };
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function* Literal(schema, references, path, value) {
|
||||
if (!(value === schema.const)) {
|
||||
const error = typeof schema.const === 'string' ? `'${schema.const}'` : schema.const;
|
||||
return yield { type: ValueErrorType.Literal, schema, path, value, message: `Expected ${error}` };
|
||||
}
|
||||
}
|
||||
function* Never(schema, references, path, value) {
|
||||
yield { type: ValueErrorType.Never, schema, path, value, message: `Value cannot be validated` };
|
||||
}
|
||||
function* Not(schema, references, path, value) {
|
||||
if (Visit(schema.allOf[0].not, references, path, value).next().done === true) {
|
||||
yield { type: ValueErrorType.Not, schema, path, value, message: `Value should not validate` };
|
||||
}
|
||||
yield* Visit(schema.allOf[1], references, path, value);
|
||||
}
|
||||
function* Null(schema, references, path, value) {
|
||||
if (!(value === null)) {
|
||||
return yield { type: ValueErrorType.Null, schema, path, value, message: `Expected null` };
|
||||
}
|
||||
}
|
||||
function* Number(schema, references, path, value) {
|
||||
if (!IsNumber(value)) {
|
||||
return yield { type: ValueErrorType.Number, schema, path, value, message: `Expected number` };
|
||||
}
|
||||
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
|
||||
yield { type: ValueErrorType.NumberMultipleOf, schema, path, value, message: `Expected number to be a multiple of ${schema.multipleOf}` };
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
|
||||
yield { type: ValueErrorType.NumberExclusiveMinimum, schema, path, value, message: `Expected number to be greater than ${schema.exclusiveMinimum}` };
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
|
||||
yield { type: ValueErrorType.NumberExclusiveMaximum, schema, path, value, message: `Expected number to be less than ${schema.exclusiveMaximum}` };
|
||||
}
|
||||
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
|
||||
yield { type: ValueErrorType.NumberMaximum, schema, path, value, message: `Expected number to be greater or equal to ${schema.minimum}` };
|
||||
}
|
||||
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
|
||||
yield { type: ValueErrorType.NumberMinumum, schema, path, value, message: `Expected number to be less or equal to ${schema.maximum}` };
|
||||
}
|
||||
}
|
||||
function* Object(schema, references, path, value) {
|
||||
if (!IsObject(value)) {
|
||||
return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected object` };
|
||||
}
|
||||
if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
|
||||
yield { type: ValueErrorType.ObjectMinProperties, schema, path, value, message: `Expected object to have at least ${schema.minProperties} properties` };
|
||||
}
|
||||
if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
|
||||
yield { type: ValueErrorType.ObjectMaxProperties, schema, path, value, message: `Expected object to have less than ${schema.minProperties} properties` };
|
||||
}
|
||||
const requiredKeys = globalThis.Array.isArray(schema.required) ? schema.required : [];
|
||||
const knownKeys = globalThis.Object.getOwnPropertyNames(schema.properties);
|
||||
const unknownKeys = globalThis.Object.getOwnPropertyNames(value);
|
||||
for (const knownKey of knownKeys) {
|
||||
const property = schema.properties[knownKey];
|
||||
if (schema.required && schema.required.includes(knownKey)) {
|
||||
yield* Visit(property, references, `${path}/${knownKey}`, value[knownKey]);
|
||||
if (Types.ExtendsUndefined.Check(schema) && !(knownKey in value)) {
|
||||
yield { type: ValueErrorType.ObjectRequiredProperties, schema: property, path: `${path}/${knownKey}`, value: undefined, message: `Expected required property` };
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (IsExactOptionalProperty(value, knownKey)) {
|
||||
yield* Visit(property, references, `${path}/${knownKey}`, value[knownKey]);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const requiredKey of requiredKeys) {
|
||||
if (unknownKeys.includes(requiredKey))
|
||||
continue;
|
||||
yield { type: ValueErrorType.ObjectRequiredProperties, schema: schema.properties[requiredKey], path: `${path}/${requiredKey}`, value: undefined, message: `Expected required property` };
|
||||
}
|
||||
if (schema.additionalProperties === false) {
|
||||
for (const valueKey of unknownKeys) {
|
||||
if (!knownKeys.includes(valueKey)) {
|
||||
yield { type: ValueErrorType.ObjectAdditionalProperties, schema, path: `${path}/${valueKey}`, value: value[valueKey], message: `Unexpected property` };
|
||||
}
|
||||
}
|
||||
}
|
||||
if (typeof schema.additionalProperties === 'object') {
|
||||
for (const valueKey of unknownKeys) {
|
||||
if (knownKeys.includes(valueKey))
|
||||
continue;
|
||||
yield* Visit(schema.additionalProperties, references, `${path}/${valueKey}`, value[valueKey]);
|
||||
}
|
||||
}
|
||||
}
|
||||
function* Promise(schema, references, path, value) {
|
||||
if (!(typeof value === 'object' && typeof value.then === 'function')) {
|
||||
yield { type: ValueErrorType.Promise, schema, path, value, message: `Expected Promise` };
|
||||
}
|
||||
}
|
||||
function* Record(schema, references, path, value) {
|
||||
if (!IsRecordObject(value)) {
|
||||
return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected record object` };
|
||||
}
|
||||
if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
|
||||
yield { type: ValueErrorType.ObjectMinProperties, schema, path, value, message: `Expected object to have at least ${schema.minProperties} properties` };
|
||||
}
|
||||
if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
|
||||
yield { type: ValueErrorType.ObjectMaxProperties, schema, path, value, message: `Expected object to have less than ${schema.minProperties} properties` };
|
||||
}
|
||||
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
|
||||
const regex = new RegExp(keyPattern);
|
||||
if (!globalThis.Object.getOwnPropertyNames(value).every((key) => regex.test(key))) {
|
||||
const numeric = keyPattern === Types.PatternNumberExact;
|
||||
const type = numeric ? ValueErrorType.RecordKeyNumeric : ValueErrorType.RecordKeyString;
|
||||
const message = numeric ? 'Expected all object property keys to be numeric' : 'Expected all object property keys to be strings';
|
||||
return yield { type, schema, path, value, message };
|
||||
}
|
||||
for (const [propKey, propValue] of globalThis.Object.entries(value)) {
|
||||
yield* Visit(valueSchema, references, `${path}/${propKey}`, propValue);
|
||||
}
|
||||
}
|
||||
function* Ref(schema, references, path, value) {
|
||||
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
|
||||
if (index === -1)
|
||||
throw new ValueErrorsDereferenceError(schema);
|
||||
const target = references[index];
|
||||
yield* Visit(target, references, path, value);
|
||||
}
|
||||
function* String(schema, references, path, value) {
|
||||
if (!IsString(value)) {
|
||||
return yield { type: ValueErrorType.String, schema, path, value, message: 'Expected string' };
|
||||
}
|
||||
if (IsDefined(schema.minLength) && !(value.length >= schema.minLength)) {
|
||||
yield { type: ValueErrorType.StringMinLength, schema, path, value, message: `Expected string length greater or equal to ${schema.minLength}` };
|
||||
}
|
||||
if (IsDefined(schema.maxLength) && !(value.length <= schema.maxLength)) {
|
||||
yield { type: ValueErrorType.StringMaxLength, schema, path, value, message: `Expected string length less or equal to ${schema.maxLength}` };
|
||||
}
|
||||
if (schema.pattern !== undefined) {
|
||||
const regex = new RegExp(schema.pattern);
|
||||
if (!regex.test(value)) {
|
||||
yield { type: ValueErrorType.StringPattern, schema, path, value, message: `Expected string to match pattern ${schema.pattern}` };
|
||||
}
|
||||
}
|
||||
if (schema.format !== undefined) {
|
||||
if (!Types.FormatRegistry.Has(schema.format)) {
|
||||
yield { type: ValueErrorType.StringFormatUnknown, schema, path, value, message: `Unknown string format '${schema.format}'` };
|
||||
}
|
||||
else {
|
||||
const format = Types.FormatRegistry.Get(schema.format);
|
||||
if (!format(value)) {
|
||||
yield { type: ValueErrorType.StringFormat, schema, path, value, message: `Expected string to match format '${schema.format}'` };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function* Symbol(schema, references, path, value) {
|
||||
if (!(typeof value === 'symbol')) {
|
||||
return yield { type: ValueErrorType.Symbol, schema, path, value, message: 'Expected symbol' };
|
||||
}
|
||||
}
|
||||
function* TemplateLiteral(schema, references, path, value) {
|
||||
if (!IsString(value)) {
|
||||
return yield { type: ValueErrorType.String, schema, path, value, message: 'Expected string' };
|
||||
}
|
||||
const regex = new RegExp(schema.pattern);
|
||||
if (!regex.test(value)) {
|
||||
yield { type: ValueErrorType.StringPattern, schema, path, value, message: `Expected string to match pattern ${schema.pattern}` };
|
||||
}
|
||||
}
|
||||
function* This(schema, references, path, value) {
|
||||
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
|
||||
if (index === -1)
|
||||
throw new ValueErrorsDereferenceError(schema);
|
||||
const target = references[index];
|
||||
yield* Visit(target, references, path, value);
|
||||
}
|
||||
function* Tuple(schema, references, path, value) {
|
||||
if (!globalThis.Array.isArray(value)) {
|
||||
return yield { type: ValueErrorType.Array, schema, path, value, message: 'Expected Array' };
|
||||
}
|
||||
if (schema.items === undefined && !(value.length === 0)) {
|
||||
return yield { type: ValueErrorType.TupleZeroLength, schema, path, value, message: 'Expected tuple to have 0 elements' };
|
||||
}
|
||||
if (!(value.length === schema.maxItems)) {
|
||||
yield { type: ValueErrorType.TupleLength, schema, path, value, message: `Expected tuple to have ${schema.maxItems} elements` };
|
||||
}
|
||||
if (!schema.items) {
|
||||
return;
|
||||
}
|
||||
for (let i = 0; i < schema.items.length; i++) {
|
||||
yield* Visit(schema.items[i], references, `${path}/${i}`, value[i]);
|
||||
}
|
||||
}
|
||||
function* Undefined(schema, references, path, value) {
|
||||
if (!(value === undefined)) {
|
||||
yield { type: ValueErrorType.Undefined, schema, path, value, message: `Expected undefined` };
|
||||
}
|
||||
}
|
||||
function* Union(schema, references, path, value) {
|
||||
const errors = [];
|
||||
for (const inner of schema.anyOf) {
|
||||
const variantErrors = [...Visit(inner, references, path, value)];
|
||||
if (variantErrors.length === 0)
|
||||
return;
|
||||
errors.push(...variantErrors);
|
||||
}
|
||||
if (errors.length > 0) {
|
||||
yield { type: ValueErrorType.Union, schema, path, value, message: 'Expected value of union' };
|
||||
}
|
||||
for (const error of errors) {
|
||||
yield error;
|
||||
}
|
||||
}
|
||||
function* Uint8Array(schema, references, path, value) {
|
||||
if (!(value instanceof globalThis.Uint8Array)) {
|
||||
return yield { type: ValueErrorType.Uint8Array, schema, path, value, message: `Expected Uint8Array` };
|
||||
}
|
||||
if (IsDefined(schema.maxByteLength) && !(value.length <= schema.maxByteLength)) {
|
||||
yield { type: ValueErrorType.Uint8ArrayMaxByteLength, schema, path, value, message: `Expected Uint8Array to have a byte length less or equal to ${schema.maxByteLength}` };
|
||||
}
|
||||
if (IsDefined(schema.minByteLength) && !(value.length >= schema.minByteLength)) {
|
||||
yield { type: ValueErrorType.Uint8ArrayMinByteLength, schema, path, value, message: `Expected Uint8Array to have a byte length greater or equal to ${schema.maxByteLength}` };
|
||||
}
|
||||
}
|
||||
function* Unknown(schema, references, path, value) { }
|
||||
function* Void(schema, references, path, value) {
|
||||
if (!IsVoid(value)) {
|
||||
return yield { type: ValueErrorType.Void, schema, path, value, message: `Expected void` };
|
||||
}
|
||||
}
|
||||
function* UserDefined(schema, references, path, value) {
|
||||
const check = Types.TypeRegistry.Get(schema[Types.Kind]);
|
||||
if (!check(schema, value)) {
|
||||
return yield { type: ValueErrorType.Custom, schema, path, value, message: `Expected kind ${schema[Types.Kind]}` };
|
||||
}
|
||||
}
|
||||
function* Visit(schema, references, path, value) {
|
||||
const references_ = IsDefined(schema.$id) ? [...references, schema] : references;
|
||||
const schema_ = schema;
|
||||
switch (schema_[Types.Kind]) {
|
||||
case 'Any':
|
||||
return yield* Any(schema_, references_, path, value);
|
||||
case 'Array':
|
||||
return yield* Array(schema_, references_, path, value);
|
||||
case 'BigInt':
|
||||
return yield* BigInt(schema_, references_, path, value);
|
||||
case 'Boolean':
|
||||
return yield* Boolean(schema_, references_, path, value);
|
||||
case 'Constructor':
|
||||
return yield* Constructor(schema_, references_, path, value);
|
||||
case 'Date':
|
||||
return yield* Date(schema_, references_, path, value);
|
||||
case 'Function':
|
||||
return yield* Function(schema_, references_, path, value);
|
||||
case 'Integer':
|
||||
return yield* Integer(schema_, references_, path, value);
|
||||
case 'Intersect':
|
||||
return yield* Intersect(schema_, references_, path, value);
|
||||
case 'Literal':
|
||||
return yield* Literal(schema_, references_, path, value);
|
||||
case 'Never':
|
||||
return yield* Never(schema_, references_, path, value);
|
||||
case 'Not':
|
||||
return yield* Not(schema_, references_, path, value);
|
||||
case 'Null':
|
||||
return yield* Null(schema_, references_, path, value);
|
||||
case 'Number':
|
||||
return yield* Number(schema_, references_, path, value);
|
||||
case 'Object':
|
||||
return yield* Object(schema_, references_, path, value);
|
||||
case 'Promise':
|
||||
return yield* Promise(schema_, references_, path, value);
|
||||
case 'Record':
|
||||
return yield* Record(schema_, references_, path, value);
|
||||
case 'Ref':
|
||||
return yield* Ref(schema_, references_, path, value);
|
||||
case 'String':
|
||||
return yield* String(schema_, references_, path, value);
|
||||
case 'Symbol':
|
||||
return yield* Symbol(schema_, references_, path, value);
|
||||
case 'TemplateLiteral':
|
||||
return yield* TemplateLiteral(schema_, references_, path, value);
|
||||
case 'This':
|
||||
return yield* This(schema_, references_, path, value);
|
||||
case 'Tuple':
|
||||
return yield* Tuple(schema_, references_, path, value);
|
||||
case 'Undefined':
|
||||
return yield* Undefined(schema_, references_, path, value);
|
||||
case 'Union':
|
||||
return yield* Union(schema_, references_, path, value);
|
||||
case 'Uint8Array':
|
||||
return yield* Uint8Array(schema_, references_, path, value);
|
||||
case 'Unknown':
|
||||
return yield* Unknown(schema_, references_, path, value);
|
||||
case 'Void':
|
||||
return yield* Void(schema_, references_, path, value);
|
||||
default:
|
||||
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
|
||||
throw new ValueErrorsUnknownTypeError(schema);
|
||||
return yield* UserDefined(schema_, references_, path, value);
|
||||
}
|
||||
}
|
||||
function Errors(schema, references, value) {
|
||||
const iterator = Visit(schema, references, '', value);
|
||||
return new ValueErrorIterator(iterator);
|
||||
}
|
||||
ValueErrors.Errors = Errors;
|
||||
})(ValueErrors = exports.ValueErrors || (exports.ValueErrors = {}));
|
||||
|
|
@ -0,0 +1 @@
|
|||
export * from './errors';
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
"use strict";
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/errors
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.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.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
__exportStar(require("./errors"), exports);
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
TypeBox: JSON Schema Type Builder with Static Type Resolution for TypeScript
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.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.
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
{
|
||||
"name": "@sinclair/typebox",
|
||||
"version": "0.27.10",
|
||||
"description": "JSONSchema Type Builder with Static Type Resolution for TypeScript",
|
||||
"keywords": [
|
||||
"typescript",
|
||||
"json-schema",
|
||||
"validate",
|
||||
"typecheck"
|
||||
],
|
||||
"author": "sinclairzx81",
|
||||
"license": "MIT",
|
||||
"main": "./typebox.js",
|
||||
"types": "./typebox.d.ts",
|
||||
"exports": {
|
||||
"./compiler": "./compiler/index.js",
|
||||
"./errors": "./errors/index.js",
|
||||
"./system": "./system/index.js",
|
||||
"./value": "./value/index.js",
|
||||
".": "./typebox.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/sinclairzx81/typebox-legacy"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "hammer task clean",
|
||||
"format": "hammer task format",
|
||||
"start": "hammer task start",
|
||||
"test": "hammer task test",
|
||||
"benchmark": "hammer task benchmark",
|
||||
"build": "hammer task build",
|
||||
"build:native": "hammer task build_native",
|
||||
"publish": "hammer task publish"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@sinclair/hammer": "^0.17.1",
|
||||
"@typescript/native-preview": "^7.0.0-dev.20260203.1",
|
||||
"@types/chai": "^4.3.3",
|
||||
"@types/mocha": "^9.1.1",
|
||||
"@types/node": "^18.19.130",
|
||||
"ajv": "^8.12.0",
|
||||
"ajv-formats": "^2.1.1",
|
||||
"chai": "^4.3.6",
|
||||
"mocha": "^9.2.2",
|
||||
"prettier": "^2.7.1",
|
||||
"typescript": "5.0.2"
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1 @@
|
|||
export * from './system';
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
"use strict";
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/system
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.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.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
__exportStar(require("./system"), exports);
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
import * as Types from '../typebox';
|
||||
export declare class TypeSystemDuplicateTypeKind extends Error {
|
||||
constructor(kind: string);
|
||||
}
|
||||
export declare class TypeSystemDuplicateFormat extends Error {
|
||||
constructor(kind: string);
|
||||
}
|
||||
/** Creates user defined types and formats and provides overrides for value checking behaviours */
|
||||
export declare namespace TypeSystem {
|
||||
/** Sets whether TypeBox should assert optional properties using the TypeScript `exactOptionalPropertyTypes` assertion policy. The default is `false` */
|
||||
let ExactOptionalPropertyTypes: boolean;
|
||||
/** Sets whether arrays should be treated as a kind of objects. The default is `false` */
|
||||
let AllowArrayObjects: boolean;
|
||||
/** Sets whether `NaN` or `Infinity` should be treated as valid numeric values. The default is `false` */
|
||||
let AllowNaN: boolean;
|
||||
/** Sets whether `null` should validate for void types. The default is `false` */
|
||||
let AllowVoidNull: boolean;
|
||||
/** Creates a new type */
|
||||
function Type<Type, Options = object>(kind: string, check: (options: Options, value: unknown) => boolean): (options?: Partial<Options>) => Types.TUnsafe<Type>;
|
||||
/** Creates a new string format */
|
||||
function Format<F extends string>(format: F, check: (value: string) => boolean): F;
|
||||
/** @deprecated Use `TypeSystem.Type()` instead. */
|
||||
function CreateType<Type, Options = object>(kind: string, check: (options: Options, value: unknown) => boolean): (options?: Partial<Options>) => Types.TUnsafe<Type>;
|
||||
/** @deprecated Use `TypeSystem.Format()` instead. */
|
||||
function CreateFormat<F extends string>(format: F, check: (value: string) => boolean): F;
|
||||
}
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
"use strict";
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/system
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.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.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.TypeSystem = exports.TypeSystemDuplicateFormat = exports.TypeSystemDuplicateTypeKind = void 0;
|
||||
const Types = require("../typebox");
|
||||
class TypeSystemDuplicateTypeKind extends Error {
|
||||
constructor(kind) {
|
||||
super(`Duplicate type kind '${kind}' detected`);
|
||||
}
|
||||
}
|
||||
exports.TypeSystemDuplicateTypeKind = TypeSystemDuplicateTypeKind;
|
||||
class TypeSystemDuplicateFormat extends Error {
|
||||
constructor(kind) {
|
||||
super(`Duplicate string format '${kind}' detected`);
|
||||
}
|
||||
}
|
||||
exports.TypeSystemDuplicateFormat = TypeSystemDuplicateFormat;
|
||||
/** Creates user defined types and formats and provides overrides for value checking behaviours */
|
||||
var TypeSystem;
|
||||
(function (TypeSystem) {
|
||||
// ------------------------------------------------------------------------
|
||||
// Assertion Policies
|
||||
// ------------------------------------------------------------------------
|
||||
/** Sets whether TypeBox should assert optional properties using the TypeScript `exactOptionalPropertyTypes` assertion policy. The default is `false` */
|
||||
TypeSystem.ExactOptionalPropertyTypes = false;
|
||||
/** Sets whether arrays should be treated as a kind of objects. The default is `false` */
|
||||
TypeSystem.AllowArrayObjects = false;
|
||||
/** Sets whether `NaN` or `Infinity` should be treated as valid numeric values. The default is `false` */
|
||||
TypeSystem.AllowNaN = false;
|
||||
/** Sets whether `null` should validate for void types. The default is `false` */
|
||||
TypeSystem.AllowVoidNull = false;
|
||||
// ------------------------------------------------------------------------
|
||||
// String Formats and Types
|
||||
// ------------------------------------------------------------------------
|
||||
/** Creates a new type */
|
||||
function Type(kind, check) {
|
||||
if (Types.TypeRegistry.Has(kind))
|
||||
throw new TypeSystemDuplicateTypeKind(kind);
|
||||
Types.TypeRegistry.Set(kind, check);
|
||||
return (options = {}) => Types.Type.Unsafe({ ...options, [Types.Kind]: kind });
|
||||
}
|
||||
TypeSystem.Type = Type;
|
||||
/** Creates a new string format */
|
||||
function Format(format, check) {
|
||||
if (Types.FormatRegistry.Has(format))
|
||||
throw new TypeSystemDuplicateFormat(format);
|
||||
Types.FormatRegistry.Set(format, check);
|
||||
return format;
|
||||
}
|
||||
TypeSystem.Format = Format;
|
||||
// ------------------------------------------------------------------------
|
||||
// Deprecated
|
||||
// ------------------------------------------------------------------------
|
||||
/** @deprecated Use `TypeSystem.Type()` instead. */
|
||||
function CreateType(kind, check) {
|
||||
return Type(kind, check);
|
||||
}
|
||||
TypeSystem.CreateType = CreateType;
|
||||
/** @deprecated Use `TypeSystem.Format()` instead. */
|
||||
function CreateFormat(format, check) {
|
||||
return Format(format, check);
|
||||
}
|
||||
TypeSystem.CreateFormat = CreateFormat;
|
||||
})(TypeSystem = exports.TypeSystem || (exports.TypeSystem = {}));
|
||||
|
|
@ -0,0 +1,717 @@
|
|||
export declare const Modifier: unique symbol;
|
||||
export declare const Hint: unique symbol;
|
||||
export declare const Kind: unique symbol;
|
||||
export declare const PatternBoolean = "(true|false)";
|
||||
export declare const PatternNumber = "(0|[1-9][0-9]*)";
|
||||
export declare const PatternString = "(.*)";
|
||||
export declare const PatternBooleanExact: string;
|
||||
export declare const PatternNumberExact: string;
|
||||
export declare const PatternStringExact: string;
|
||||
export type TupleToIntersect<T extends any[]> = T extends [infer I] ? I : T extends [infer I, ...infer R] ? I & TupleToIntersect<R> : never;
|
||||
export type TupleToUnion<T extends any[]> = {
|
||||
[K in keyof T]: T[K];
|
||||
}[number];
|
||||
export type UnionToIntersect<U> = (U extends unknown ? (arg: U) => 0 : never) extends (arg: infer I) => 0 ? I : never;
|
||||
export type UnionLast<U> = UnionToIntersect<U extends unknown ? (x: U) => 0 : never> extends (x: infer L) => 0 ? L : never;
|
||||
export type UnionToTuple<U, L = UnionLast<U>> = [U] extends [never] ? [] : [...UnionToTuple<Exclude<U, L>>, L];
|
||||
export type Assert<T, E> = T extends E ? T : never;
|
||||
export type Evaluate<T> = T extends infer O ? {
|
||||
[K in keyof O]: O[K];
|
||||
} : never;
|
||||
export type Ensure<T> = T extends infer U ? U : never;
|
||||
export type TModifier = TReadonlyOptional<TSchema> | TOptional<TSchema> | TReadonly<TSchema>;
|
||||
export type TReadonly<T extends TSchema> = T & {
|
||||
[Modifier]: 'Readonly';
|
||||
};
|
||||
export type TOptional<T extends TSchema> = T & {
|
||||
[Modifier]: 'Optional';
|
||||
};
|
||||
export type TReadonlyOptional<T extends TSchema> = T & {
|
||||
[Modifier]: 'ReadonlyOptional';
|
||||
};
|
||||
export interface SchemaOptions {
|
||||
$schema?: string;
|
||||
/** Id for this schema */
|
||||
$id?: string;
|
||||
/** Title of this schema */
|
||||
title?: string;
|
||||
/** Description of this schema */
|
||||
description?: string;
|
||||
/** Default value for this schema */
|
||||
default?: any;
|
||||
/** Example values matching this schema */
|
||||
examples?: any;
|
||||
[prop: string]: any;
|
||||
}
|
||||
export interface TKind {
|
||||
[Kind]: string;
|
||||
}
|
||||
export interface TSchema extends SchemaOptions, TKind {
|
||||
[Modifier]?: string;
|
||||
[Hint]?: string;
|
||||
params: unknown[];
|
||||
static: unknown;
|
||||
}
|
||||
export type TAnySchema = TSchema | TAny | TArray | TBigInt | TBoolean | TConstructor | TDate | TEnum | TFunction | TInteger | TIntersect | TLiteral | TNot | TNull | TNumber | TObject | TPromise | TRecord | TRef | TString | TSymbol | TTemplateLiteral | TThis | TTuple | TUndefined | TUnion | TUint8Array | TUnknown | TVoid;
|
||||
export type TNumeric = TInteger | TNumber;
|
||||
export interface NumericOptions<N extends number | bigint> extends SchemaOptions {
|
||||
exclusiveMaximum?: N;
|
||||
exclusiveMinimum?: N;
|
||||
maximum?: N;
|
||||
minimum?: N;
|
||||
multipleOf?: N;
|
||||
}
|
||||
export interface TAny extends TSchema {
|
||||
[Kind]: 'Any';
|
||||
static: any;
|
||||
}
|
||||
export interface ArrayOptions extends SchemaOptions {
|
||||
uniqueItems?: boolean;
|
||||
minItems?: number;
|
||||
maxItems?: number;
|
||||
}
|
||||
export interface TArray<T extends TSchema = TSchema> extends TSchema, ArrayOptions {
|
||||
[Kind]: 'Array';
|
||||
static: Static<T, this['params']>[];
|
||||
type: 'array';
|
||||
items: T;
|
||||
}
|
||||
export interface TBigInt extends TSchema, NumericOptions<bigint> {
|
||||
[Kind]: 'BigInt';
|
||||
static: bigint;
|
||||
type: 'null';
|
||||
typeOf: 'BigInt';
|
||||
}
|
||||
export interface TBoolean extends TSchema {
|
||||
[Kind]: 'Boolean';
|
||||
static: boolean;
|
||||
type: 'boolean';
|
||||
}
|
||||
export type TConstructorParameters<T extends TConstructor<TSchema[], TSchema>> = TTuple<T['parameters']>;
|
||||
export type TInstanceType<T extends TConstructor<TSchema[], TSchema>> = T['returns'];
|
||||
export type TCompositeEvaluateArray<T extends readonly TSchema[], P extends unknown[]> = {
|
||||
[K in keyof T]: T[K] extends TSchema ? Static<T[K], P> : never;
|
||||
};
|
||||
export type TCompositeArray<T extends readonly TObject[]> = {
|
||||
[K in keyof T]: T[K] extends TObject<infer P> ? P : {};
|
||||
};
|
||||
export type TCompositeProperties<I extends unknown, T extends readonly any[]> = Evaluate<T extends [infer A, ...infer B] ? TCompositeProperties<I & A, B> : I extends object ? I : {}>;
|
||||
export interface TComposite<T extends TObject[] = TObject[]> extends TObject {
|
||||
[Hint]: 'Composite';
|
||||
static: Evaluate<TCompositeProperties<unknown, TCompositeEvaluateArray<T, this['params']>>>;
|
||||
properties: TCompositeProperties<unknown, TCompositeArray<T>>;
|
||||
}
|
||||
export type TConstructorParameterArray<T extends readonly TSchema[], P extends unknown[]> = [...{
|
||||
[K in keyof T]: Static<Assert<T[K], TSchema>, P>;
|
||||
}];
|
||||
export interface TConstructor<T extends TSchema[] = TSchema[], U extends TSchema = TSchema> extends TSchema {
|
||||
[Kind]: 'Constructor';
|
||||
static: new (...param: TConstructorParameterArray<T, this['params']>) => Static<U, this['params']>;
|
||||
type: 'object';
|
||||
instanceOf: 'Constructor';
|
||||
parameters: T;
|
||||
returns: U;
|
||||
}
|
||||
export interface DateOptions extends SchemaOptions {
|
||||
exclusiveMaximumTimestamp?: number;
|
||||
exclusiveMinimumTimestamp?: number;
|
||||
maximumTimestamp?: number;
|
||||
minimumTimestamp?: number;
|
||||
}
|
||||
export interface TDate extends TSchema, DateOptions {
|
||||
[Kind]: 'Date';
|
||||
static: Date;
|
||||
type: 'object';
|
||||
instanceOf: 'Date';
|
||||
}
|
||||
export interface TEnumOption<T> {
|
||||
type: 'number' | 'string';
|
||||
const: T;
|
||||
}
|
||||
export interface TEnum<T extends Record<string, string | number> = Record<string, string | number>> extends TSchema {
|
||||
[Kind]: 'Union';
|
||||
static: T[keyof T];
|
||||
anyOf: TLiteral<string | number>[];
|
||||
}
|
||||
export type TExtends<L extends TSchema, R extends TSchema, T extends TSchema, U extends TSchema> = (Static<L> extends Static<R> ? T : U) extends infer O ? UnionToTuple<O> extends [infer X, infer Y] ? TUnion<[Assert<X, TSchema>, Assert<Y, TSchema>]> : Assert<O, TSchema> : never;
|
||||
export type TExcludeTemplateLiteralResult<T extends string> = TString;
|
||||
export type TExcludeTemplateLiteral<T extends TTemplateLiteral, U extends TSchema> = Exclude<Static<T>, Static<U>> extends infer S ? TExcludeTemplateLiteralResult<Assert<S, string>> : never;
|
||||
export type TExcludeArray<T extends TSchema[], U extends TSchema> = Assert<UnionToTuple<{
|
||||
[K in keyof T]: Static<Assert<T[K], TSchema>> extends Static<U> ? never : T[K];
|
||||
}[number]>, TSchema[]> extends infer R ? TUnionResult<Assert<R, TSchema[]>> : never;
|
||||
export type TExclude<T extends TSchema, U extends TSchema> = T extends TTemplateLiteral ? TExcludeTemplateLiteral<T, U> : T extends TUnion<infer S> ? TExcludeArray<S, U> : T extends U ? TNever : T;
|
||||
export type TExtractTemplateLiteralResult<T extends string> = TString;
|
||||
export type TExtractTemplateLiteral<T extends TTemplateLiteral, U extends TSchema> = Extract<Static<T>, Static<U>> extends infer S ? TExtractTemplateLiteralResult<Assert<S, string>> : never;
|
||||
export type TExtractArray<T extends TSchema[], U extends TSchema> = Assert<UnionToTuple<{
|
||||
[K in keyof T]: Static<Assert<T[K], TSchema>> extends Static<U> ? T[K] : never;
|
||||
}[number]>, TSchema[]> extends infer R ? TUnionResult<Assert<R, TSchema[]>> : never;
|
||||
export type TExtract<T extends TSchema, U extends TSchema> = T extends TTemplateLiteral ? TExtractTemplateLiteral<T, U> : T extends TUnion<infer S> ? TExtractArray<S, U> : T extends U ? T : T;
|
||||
export type TFunctionParameters<T extends readonly TSchema[], P extends unknown[]> = [...{
|
||||
[K in keyof T]: Static<Assert<T[K], TSchema>, P>;
|
||||
}];
|
||||
export interface TFunction<T extends readonly TSchema[] = TSchema[], U extends TSchema = TSchema> extends TSchema {
|
||||
[Kind]: 'Function';
|
||||
static: (...param: TFunctionParameters<T, this['params']>) => Static<U, this['params']>;
|
||||
type: 'object';
|
||||
instanceOf: 'Function';
|
||||
parameters: T;
|
||||
returns: U;
|
||||
}
|
||||
export interface TInteger extends TSchema, NumericOptions<number> {
|
||||
[Kind]: 'Integer';
|
||||
static: number;
|
||||
type: 'integer';
|
||||
}
|
||||
export type TUnevaluatedProperties = undefined | TSchema | boolean;
|
||||
export interface IntersectOptions extends SchemaOptions {
|
||||
unevaluatedProperties?: TUnevaluatedProperties;
|
||||
}
|
||||
export interface TIntersect<T extends TSchema[] = TSchema[]> extends TSchema, IntersectOptions {
|
||||
[Kind]: 'Intersect';
|
||||
static: TupleToIntersect<{
|
||||
[K in keyof T]: Static<Assert<T[K], TSchema>, this['params']>;
|
||||
}>;
|
||||
type?: 'object';
|
||||
allOf: [...T];
|
||||
}
|
||||
export type TKeyOfTuple<T extends TSchema> = {
|
||||
[K in keyof Static<T>]: TLiteral<Assert<K, TLiteralValue>>;
|
||||
} extends infer U ? UnionToTuple<Exclude<{
|
||||
[K in keyof U]: U[K];
|
||||
}[keyof U], undefined>> : never;
|
||||
export type TKeyOf<T extends TSchema = TSchema> = (T extends TRecursive<infer S> ? TKeyOfTuple<S> : T extends TComposite ? TKeyOfTuple<T> : T extends TIntersect ? TKeyOfTuple<T> : T extends TUnion ? TKeyOfTuple<T> : T extends TObject ? TKeyOfTuple<T> : T extends TRecord<infer K> ? [K] : [
|
||||
]) extends infer R ? TUnionResult<Assert<R, TSchema[]>> : never;
|
||||
export type TLiteralValue = string | number | boolean;
|
||||
export interface TLiteral<T extends TLiteralValue = TLiteralValue> extends TSchema {
|
||||
[Kind]: 'Literal';
|
||||
static: T;
|
||||
const: T;
|
||||
}
|
||||
export interface TNever extends TSchema {
|
||||
[Kind]: 'Never';
|
||||
static: never;
|
||||
not: {};
|
||||
}
|
||||
export interface TNot<Not extends TSchema = TSchema, T extends TSchema = TSchema> extends TSchema {
|
||||
[Kind]: 'Not';
|
||||
static: Static<T>;
|
||||
allOf: [{
|
||||
not: Not;
|
||||
}, T];
|
||||
}
|
||||
export interface TNull extends TSchema {
|
||||
[Kind]: 'Null';
|
||||
static: null;
|
||||
type: 'null';
|
||||
}
|
||||
export interface TNumber extends TSchema, NumericOptions<number> {
|
||||
[Kind]: 'Number';
|
||||
static: number;
|
||||
type: 'number';
|
||||
}
|
||||
export type ReadonlyOptionalPropertyKeys<T extends TProperties> = {
|
||||
[K in keyof T]: T[K] extends TReadonlyOptional<TSchema> ? K : never;
|
||||
}[keyof T];
|
||||
export type ReadonlyPropertyKeys<T extends TProperties> = {
|
||||
[K in keyof T]: T[K] extends TReadonly<TSchema> ? K : never;
|
||||
}[keyof T];
|
||||
export type OptionalPropertyKeys<T extends TProperties> = {
|
||||
[K in keyof T]: T[K] extends TOptional<TSchema> ? K : never;
|
||||
}[keyof T];
|
||||
export type RequiredPropertyKeys<T extends TProperties> = keyof Omit<T, ReadonlyOptionalPropertyKeys<T> | ReadonlyPropertyKeys<T> | OptionalPropertyKeys<T>>;
|
||||
export type PropertiesReducer<T extends TProperties, R extends Record<keyof any, unknown>> = Evaluate<(Readonly<Partial<Pick<R, ReadonlyOptionalPropertyKeys<T>>>> & Readonly<Pick<R, ReadonlyPropertyKeys<T>>> & Partial<Pick<R, OptionalPropertyKeys<T>>> & Required<Pick<R, RequiredPropertyKeys<T>>>)>;
|
||||
export type PropertiesReduce<T extends TProperties, P extends unknown[]> = PropertiesReducer<T, {
|
||||
[K in keyof T]: Static<T[K], P>;
|
||||
}>;
|
||||
export type TProperties = Record<keyof any, TSchema>;
|
||||
export type ObjectProperties<T> = T extends TObject<infer U> ? U : never;
|
||||
export type ObjectPropertyKeys<T> = T extends TObject<infer U> ? keyof U : never;
|
||||
export type TAdditionalProperties = undefined | TSchema | boolean;
|
||||
export interface ObjectOptions extends SchemaOptions {
|
||||
additionalProperties?: TAdditionalProperties;
|
||||
minProperties?: number;
|
||||
maxProperties?: number;
|
||||
}
|
||||
export interface TObject<T extends TProperties = TProperties> extends TSchema, ObjectOptions {
|
||||
[Kind]: 'Object';
|
||||
static: PropertiesReduce<T, this['params']>;
|
||||
additionalProperties?: TAdditionalProperties;
|
||||
type: 'object';
|
||||
properties: T;
|
||||
required?: string[];
|
||||
}
|
||||
export type TOmitArray<T extends TSchema[], K extends keyof any> = Assert<{
|
||||
[K2 in keyof T]: TOmit<Assert<T[K2], TSchema>, K>;
|
||||
}, TSchema[]>;
|
||||
export type TOmitProperties<T extends TProperties, K extends keyof any> = Evaluate<Assert<Omit<T, K>, TProperties>>;
|
||||
export type TOmit<T extends TSchema = TSchema, K extends keyof any = keyof any> = T extends TRecursive<infer S> ? TRecursive<TOmit<S, K>> : T extends TComposite<infer S> ? TComposite<TOmitArray<S, K>> : T extends TIntersect<infer S> ? TIntersect<TOmitArray<S, K>> : T extends TUnion<infer S> ? TUnion<TOmitArray<S, K>> : T extends TObject<infer S> ? TObject<TOmitProperties<S, K>> : T;
|
||||
export type TParameters<T extends TFunction> = TTuple<T['parameters']>;
|
||||
export type TPartialObjectArray<T extends TObject[]> = Assert<{
|
||||
[K in keyof T]: TPartial<Assert<T[K], TObject>>;
|
||||
}, TObject[]>;
|
||||
export type TPartialArray<T extends TSchema[]> = Assert<{
|
||||
[K in keyof T]: TPartial<Assert<T[K], TSchema>>;
|
||||
}, TSchema[]>;
|
||||
export type TPartialProperties<T extends TProperties> = Evaluate<Assert<{
|
||||
[K in keyof T]: T[K] extends TReadonlyOptional<infer U> ? TReadonlyOptional<U> : T[K] extends TReadonly<infer U> ? TReadonlyOptional<U> : T[K] extends TOptional<infer U> ? TOptional<U> : TOptional<T[K]>;
|
||||
}, TProperties>>;
|
||||
export type TPartial<T extends TSchema> = T extends TRecursive<infer S> ? TRecursive<TPartial<S>> : T extends TComposite<infer S> ? TComposite<TPartialArray<S>> : T extends TIntersect<infer S> ? TIntersect<TPartialArray<S>> : T extends TUnion<infer S> ? TUnion<TPartialArray<S>> : T extends TObject<infer S> ? TObject<TPartialProperties<S>> : T;
|
||||
export type TPickArray<T extends TSchema[], K extends keyof any> = {
|
||||
[K2 in keyof T]: TPick<Assert<T[K2], TSchema>, K>;
|
||||
};
|
||||
export type TPickProperties<T extends TProperties, K extends keyof any> = Pick<T, Assert<Extract<K, keyof T>, keyof T>> extends infer R ? ({
|
||||
[K in keyof R]: Assert<R[K], TSchema> extends TSchema ? R[K] : never;
|
||||
}) : never;
|
||||
export type TPick<T extends TSchema = TSchema, K extends keyof any = keyof any> = T extends TRecursive<infer S> ? TRecursive<TPick<S, K>> : T extends TComposite<infer S> ? TComposite<TPickArray<S, K>> : T extends TIntersect<infer S> ? TIntersect<TPickArray<S, K>> : T extends TUnion<infer S> ? TUnion<TPickArray<S, K>> : T extends TObject<infer S> ? TObject<TPickProperties<S, K>> : T;
|
||||
export interface TPromise<T extends TSchema = TSchema> extends TSchema {
|
||||
[Kind]: 'Promise';
|
||||
static: Promise<Static<T, this['params']>>;
|
||||
type: 'object';
|
||||
instanceOf: 'Promise';
|
||||
item: TSchema;
|
||||
}
|
||||
export type RecordTemplateLiteralObjectType<K extends TTemplateLiteral, T extends TSchema> = Ensure<TObject<Evaluate<{
|
||||
[_ in Static<K>]: T;
|
||||
}>>>;
|
||||
export type RecordTemplateLiteralType<K extends TTemplateLiteral, T extends TSchema> = IsTemplateLiteralFinite<K> extends true ? RecordTemplateLiteralObjectType<K, T> : TRecord<K, T>;
|
||||
export type RecordUnionLiteralType<K extends TUnion<TLiteral<string | number>[]>, T extends TSchema> = Static<K> extends string ? Ensure<TObject<{
|
||||
[X in Static<K>]: T;
|
||||
}>> : never;
|
||||
export type RecordLiteralType<K extends TLiteral<string | number>, T extends TSchema> = Ensure<TObject<{
|
||||
[K2 in K['const']]: T;
|
||||
}>>;
|
||||
export type RecordNumberType<K extends TInteger | TNumber, T extends TSchema> = Ensure<TRecord<K, T>>;
|
||||
export type RecordStringType<K extends TString, T extends TSchema> = Ensure<TRecord<K, T>>;
|
||||
export type RecordKey = TUnion<TLiteral<string | number>[]> | TLiteral<string | number> | TTemplateLiteral | TInteger | TNumber | TString;
|
||||
export interface TRecord<K extends RecordKey = RecordKey, T extends TSchema = TSchema> extends TSchema {
|
||||
[Kind]: 'Record';
|
||||
static: Record<Static<K>, Static<T, this['params']>>;
|
||||
type: 'object';
|
||||
patternProperties: {
|
||||
[pattern: string]: T;
|
||||
};
|
||||
additionalProperties: false;
|
||||
}
|
||||
export interface TThis extends TSchema {
|
||||
[Kind]: 'This';
|
||||
static: this['params'][0];
|
||||
$ref: string;
|
||||
}
|
||||
export type TRecursiveReduce<T extends TSchema> = Static<T, [TRecursiveReduce<T>]>;
|
||||
export interface TRecursive<T extends TSchema> extends TSchema {
|
||||
[Hint]: 'Recursive';
|
||||
static: TRecursiveReduce<T>;
|
||||
}
|
||||
export interface TRef<T extends TSchema = TSchema> extends TSchema {
|
||||
[Kind]: 'Ref';
|
||||
static: Static<T, this['params']>;
|
||||
$ref: string;
|
||||
}
|
||||
export type TReturnType<T extends TFunction> = T['returns'];
|
||||
export type TRequiredArray<T extends TSchema[]> = Assert<{
|
||||
[K in keyof T]: TRequired<Assert<T[K], TSchema>>;
|
||||
}, TSchema[]>;
|
||||
export type TRequiredProperties<T extends TProperties> = Evaluate<Assert<{
|
||||
[K in keyof T]: T[K] extends TReadonlyOptional<infer U> ? TReadonly<U> : T[K] extends TReadonly<infer U> ? TReadonly<U> : T[K] extends TOptional<infer U> ? U : T[K];
|
||||
}, TProperties>>;
|
||||
export type TRequired<T extends TSchema> = T extends TRecursive<infer S> ? TRecursive<TRequired<S>> : T extends TComposite<infer S> ? TComposite<TRequiredArray<S>> : T extends TIntersect<infer S> ? TIntersect<TRequiredArray<S>> : T extends TUnion<infer S> ? TUnion<TRequiredArray<S>> : T extends TObject<infer S> ? TObject<TRequiredProperties<S>> : T;
|
||||
export type StringFormatOption = 'date-time' | 'time' | 'date' | 'email' | 'idn-email' | 'hostname' | 'idn-hostname' | 'ipv4' | 'ipv6' | 'uri' | 'uri-reference' | 'iri' | 'uuid' | 'iri-reference' | 'uri-template' | 'json-pointer' | 'relative-json-pointer' | 'regex';
|
||||
export interface StringOptions<Format extends string> extends SchemaOptions {
|
||||
minLength?: number;
|
||||
maxLength?: number;
|
||||
pattern?: string;
|
||||
format?: Format;
|
||||
contentEncoding?: '7bit' | '8bit' | 'binary' | 'quoted-printable' | 'base64';
|
||||
contentMediaType?: string;
|
||||
}
|
||||
export interface TString<Format extends string = string> extends TSchema, StringOptions<Format> {
|
||||
[Kind]: 'String';
|
||||
static: string;
|
||||
type: 'string';
|
||||
}
|
||||
export type SymbolValue = string | number | undefined;
|
||||
export interface TSymbol extends TSchema, SchemaOptions {
|
||||
[Kind]: 'Symbol';
|
||||
static: symbol;
|
||||
type: 'null';
|
||||
typeOf: 'Symbol';
|
||||
}
|
||||
export type IsTemplateLiteralFiniteCheck<T> = T extends TTemplateLiteral<infer U> ? IsTemplateLiteralFiniteArray<Assert<U, TTemplateLiteralKind[]>> : T extends TUnion<infer U> ? IsTemplateLiteralFiniteArray<Assert<U, TTemplateLiteralKind[]>> : T extends TString ? false : T extends TBoolean ? false : T extends TNumber ? false : T extends TInteger ? false : T extends TBigInt ? false : T extends TLiteral ? true : false;
|
||||
export type IsTemplateLiteralFiniteArray<T extends TTemplateLiteralKind[]> = T extends [infer L, ...infer R] ? IsTemplateLiteralFiniteCheck<L> extends false ? false : IsTemplateLiteralFiniteArray<Assert<R, TTemplateLiteralKind[]>> : T extends [infer L] ? IsTemplateLiteralFiniteCheck<L> extends false ? false : true : true;
|
||||
export type IsTemplateLiteralFinite<T> = T extends TTemplateLiteral<infer U> ? IsTemplateLiteralFiniteArray<U> : false;
|
||||
export type TTemplateLiteralKind = TUnion | TLiteral | TInteger | TTemplateLiteral | TNumber | TBigInt | TString | TBoolean | TNever;
|
||||
export type TTemplateLiteralConst<T, Acc extends string> = T extends TUnion<infer U> ? {
|
||||
[K in keyof U]: TTemplateLiteralUnion<Assert<[U[K]], TTemplateLiteralKind[]>, Acc>;
|
||||
}[number] : T extends TTemplateLiteral ? `${Static<T>}` : T extends TLiteral<infer U> ? `${U}` : T extends TString ? `${string}` : T extends TNumber ? `${number}` : T extends TBigInt ? `${bigint}` : T extends TBoolean ? `${boolean}` : never;
|
||||
export type TTemplateLiteralUnion<T extends TTemplateLiteralKind[], Acc extends string = ''> = T extends [infer L, ...infer R] ? `${TTemplateLiteralConst<L, Acc>}${TTemplateLiteralUnion<Assert<R, TTemplateLiteralKind[]>, Acc>}` : T extends [infer L] ? `${TTemplateLiteralConst<L, Acc>}${Acc}` : Acc;
|
||||
export interface TTemplateLiteral<T extends TTemplateLiteralKind[] = TTemplateLiteralKind[]> extends TSchema {
|
||||
[Kind]: 'TemplateLiteral';
|
||||
static: TTemplateLiteralUnion<T>;
|
||||
type: 'string';
|
||||
pattern: string;
|
||||
}
|
||||
export type TTupleIntoArray<T extends TTuple<TSchema[]>> = T extends TTuple<infer R> ? Assert<R, TSchema[]> : never;
|
||||
export interface TTuple<T extends TSchema[] = TSchema[]> extends TSchema {
|
||||
[Kind]: 'Tuple';
|
||||
static: {
|
||||
[K in keyof T]: T[K] extends TSchema ? Static<T[K], this['params']> : T[K];
|
||||
};
|
||||
type: 'array';
|
||||
items?: T;
|
||||
additionalItems?: false;
|
||||
minItems: number;
|
||||
maxItems: number;
|
||||
}
|
||||
export interface TUndefined extends TSchema {
|
||||
[Kind]: 'Undefined';
|
||||
static: undefined;
|
||||
type: 'null';
|
||||
typeOf: 'Undefined';
|
||||
}
|
||||
export type TUnionOfLiteralArray<T extends TLiteral<string>[]> = {
|
||||
[K in keyof T]: Assert<T[K], TLiteral>['const'];
|
||||
}[number];
|
||||
export type TUnionOfLiteral<T extends TUnion<TLiteral<string>[]>> = TUnionOfLiteralArray<T['anyOf']>;
|
||||
export type TUnionResult<T extends TSchema[]> = T extends [] ? TNever : T extends [infer S] ? S : TUnion<T>;
|
||||
export type TUnionTemplateLiteral<T extends TTemplateLiteral, S extends string = Static<T>> = (string);
|
||||
export interface TUnion<T extends TSchema[] = TSchema[]> extends TSchema {
|
||||
[Kind]: 'Union';
|
||||
static: {
|
||||
[K in keyof T]: T[K] extends TSchema ? Static<T[K], this['params']> : never;
|
||||
}[number];
|
||||
anyOf: T;
|
||||
}
|
||||
export interface Uint8ArrayOptions extends SchemaOptions {
|
||||
maxByteLength?: number;
|
||||
minByteLength?: number;
|
||||
}
|
||||
export interface TUint8Array extends TSchema, Uint8ArrayOptions {
|
||||
[Kind]: 'Uint8Array';
|
||||
static: Uint8Array;
|
||||
instanceOf: 'Uint8Array';
|
||||
type: 'object';
|
||||
}
|
||||
export interface TUnknown extends TSchema {
|
||||
[Kind]: 'Unknown';
|
||||
static: unknown;
|
||||
}
|
||||
export interface UnsafeOptions extends SchemaOptions {
|
||||
[Kind]?: string;
|
||||
}
|
||||
export interface TUnsafe<T> extends TSchema {
|
||||
[Kind]: string;
|
||||
static: T;
|
||||
}
|
||||
export interface TVoid extends TSchema {
|
||||
[Kind]: 'Void';
|
||||
static: void;
|
||||
type: 'null';
|
||||
typeOf: 'Void';
|
||||
}
|
||||
/** Creates a TypeScript static type from a TypeBox type */
|
||||
export type Static<T extends TSchema, P extends unknown[] = []> = (T & {
|
||||
params: P;
|
||||
})['static'];
|
||||
export type TypeRegistryValidationFunction<TSchema> = (schema: TSchema, value: unknown) => boolean;
|
||||
/** A registry for user defined types */
|
||||
export declare namespace TypeRegistry {
|
||||
/** Returns the entries in this registry */
|
||||
function Entries(): Map<string, TypeRegistryValidationFunction<any>>;
|
||||
/** Clears all user defined types */
|
||||
function Clear(): void;
|
||||
/** Returns true if this registry contains this kind */
|
||||
function Has(kind: string): boolean;
|
||||
/** Sets a validation function for a user defined type */
|
||||
function Set<TSchema = unknown>(kind: string, func: TypeRegistryValidationFunction<TSchema>): void;
|
||||
/** Gets a custom validation function for a user defined type */
|
||||
function Get(kind: string): TypeRegistryValidationFunction<any> | undefined;
|
||||
}
|
||||
export type FormatRegistryValidationFunction = (value: string) => boolean;
|
||||
/** A registry for user defined string formats */
|
||||
export declare namespace FormatRegistry {
|
||||
/** Returns the entries in this registry */
|
||||
function Entries(): Map<string, FormatRegistryValidationFunction>;
|
||||
/** Clears all user defined string formats */
|
||||
function Clear(): void;
|
||||
/** Returns true if the user defined string format exists */
|
||||
function Has(format: string): boolean;
|
||||
/** Sets a validation function for a user defined string format */
|
||||
function Set(format: string, func: FormatRegistryValidationFunction): void;
|
||||
/** Gets a validation function for a user defined string format */
|
||||
function Get(format: string): FormatRegistryValidationFunction | undefined;
|
||||
}
|
||||
export declare class TypeGuardUnknownTypeError extends Error {
|
||||
readonly schema: unknown;
|
||||
constructor(schema: unknown);
|
||||
}
|
||||
/** Provides functions to test if JavaScript values are TypeBox types */
|
||||
export declare namespace TypeGuard {
|
||||
/** Returns true if the given schema is TAny */
|
||||
function TAny(schema: unknown): schema is TAny;
|
||||
/** Returns true if the given schema is TArray */
|
||||
function TArray(schema: unknown): schema is TArray;
|
||||
/** Returns true if the given schema is TBigInt */
|
||||
function TBigInt(schema: unknown): schema is TBigInt;
|
||||
/** Returns true if the given schema is TBoolean */
|
||||
function TBoolean(schema: unknown): schema is TBoolean;
|
||||
/** Returns true if the given schema is TConstructor */
|
||||
function TConstructor(schema: unknown): schema is TConstructor;
|
||||
/** Returns true if the given schema is TDate */
|
||||
function TDate(schema: unknown): schema is TDate;
|
||||
/** Returns true if the given schema is TFunction */
|
||||
function TFunction(schema: unknown): schema is TFunction;
|
||||
/** Returns true if the given schema is TInteger */
|
||||
function TInteger(schema: unknown): schema is TInteger;
|
||||
/** Returns true if the given schema is TIntersect */
|
||||
function TIntersect(schema: unknown): schema is TIntersect;
|
||||
/** Returns true if the given schema is TKind */
|
||||
function TKind(schema: unknown): schema is Record<typeof Kind | string, unknown>;
|
||||
/** Returns true if the given schema is TLiteral */
|
||||
function TLiteral(schema: unknown): schema is TLiteral;
|
||||
/** Returns true if the given schema is TNever */
|
||||
function TNever(schema: unknown): schema is TNever;
|
||||
/** Returns true if the given schema is TNot */
|
||||
function TNot(schema: unknown): schema is TNot;
|
||||
/** Returns true if the given schema is TNull */
|
||||
function TNull(schema: unknown): schema is TNull;
|
||||
/** Returns true if the given schema is TNumber */
|
||||
function TNumber(schema: unknown): schema is TNumber;
|
||||
/** Returns true if the given schema is TObject */
|
||||
function TObject(schema: unknown): schema is TObject;
|
||||
/** Returns true if the given schema is TPromise */
|
||||
function TPromise(schema: unknown): schema is TPromise;
|
||||
/** Returns true if the given schema is TRecord */
|
||||
function TRecord(schema: unknown): schema is TRecord;
|
||||
/** Returns true if the given schema is TRef */
|
||||
function TRef(schema: unknown): schema is TRef;
|
||||
/** Returns true if the given schema is TString */
|
||||
function TString(schema: unknown): schema is TString;
|
||||
/** Returns true if the given schema is TSymbol */
|
||||
function TSymbol(schema: unknown): schema is TSymbol;
|
||||
/** Returns true if the given schema is TTemplateLiteral */
|
||||
function TTemplateLiteral(schema: unknown): schema is TTemplateLiteral;
|
||||
/** Returns true if the given schema is TThis */
|
||||
function TThis(schema: unknown): schema is TThis;
|
||||
/** Returns true if the given schema is TTuple */
|
||||
function TTuple(schema: unknown): schema is TTuple;
|
||||
/** Returns true if the given schema is TUndefined */
|
||||
function TUndefined(schema: unknown): schema is TUndefined;
|
||||
/** Returns true if the given schema is TUnion */
|
||||
function TUnion(schema: unknown): schema is TUnion;
|
||||
/** Returns true if the given schema is TUnion<Literal<string>[]> */
|
||||
function TUnionLiteral(schema: unknown): schema is TUnion<TLiteral<string>[]>;
|
||||
/** Returns true if the given schema is TUint8Array */
|
||||
function TUint8Array(schema: unknown): schema is TUint8Array;
|
||||
/** Returns true if the given schema is TUnknown */
|
||||
function TUnknown(schema: unknown): schema is TUnknown;
|
||||
/** Returns true if the given schema is a raw TUnsafe */
|
||||
function TUnsafe(schema: unknown): schema is TUnsafe<unknown>;
|
||||
/** Returns true if the given schema is TVoid */
|
||||
function TVoid(schema: unknown): schema is TVoid;
|
||||
/** Returns true if this schema has the ReadonlyOptional modifier */
|
||||
function TReadonlyOptional<T extends TSchema>(schema: T): schema is TReadonlyOptional<T>;
|
||||
/** Returns true if this schema has the Readonly modifier */
|
||||
function TReadonly<T extends TSchema>(schema: T): schema is TReadonly<T>;
|
||||
/** Returns true if this schema has the Optional modifier */
|
||||
function TOptional<T extends TSchema>(schema: T): schema is TOptional<T>;
|
||||
/** Returns true if the given schema is TSchema */
|
||||
function TSchema(schema: unknown): schema is TSchema;
|
||||
}
|
||||
/** Fast undefined check used for properties of type undefined */
|
||||
export declare namespace ExtendsUndefined {
|
||||
function Check(schema: TSchema): boolean;
|
||||
}
|
||||
export declare enum TypeExtendsResult {
|
||||
Union = 0,
|
||||
True = 1,
|
||||
False = 2
|
||||
}
|
||||
export declare namespace TypeExtends {
|
||||
function Extends(left: TSchema, right: TSchema): TypeExtendsResult;
|
||||
}
|
||||
/** Specialized Clone for Types */
|
||||
export declare namespace TypeClone {
|
||||
/** Clones a type. */
|
||||
function Clone<T extends TSchema>(schema: T, options: SchemaOptions): T;
|
||||
}
|
||||
export declare namespace ObjectMap {
|
||||
function Map<T = TSchema>(schema: TSchema, callback: (object: TObject) => TObject, options: SchemaOptions): T;
|
||||
}
|
||||
export declare namespace KeyResolver {
|
||||
function Resolve<T extends TSchema>(schema: T): string[];
|
||||
}
|
||||
export declare namespace TemplateLiteralPattern {
|
||||
function Create(kinds: TTemplateLiteralKind[]): string;
|
||||
}
|
||||
export declare namespace TemplateLiteralResolver {
|
||||
function Resolve(template: TTemplateLiteral): TString | TUnion | TLiteral;
|
||||
}
|
||||
export declare class TemplateLiteralParserError extends Error {
|
||||
constructor(message: string);
|
||||
}
|
||||
export declare namespace TemplateLiteralParser {
|
||||
type Expression = And | Or | Const;
|
||||
type Const = {
|
||||
type: 'const';
|
||||
const: string;
|
||||
};
|
||||
type And = {
|
||||
type: 'and';
|
||||
expr: Expression[];
|
||||
};
|
||||
type Or = {
|
||||
type: 'or';
|
||||
expr: Expression[];
|
||||
};
|
||||
/** Parses a pattern and returns an expression tree */
|
||||
function Parse(pattern: string): Expression;
|
||||
/** Parses a pattern and strips forward and trailing ^ and $ */
|
||||
function ParseExact(pattern: string): Expression;
|
||||
}
|
||||
export declare namespace TemplateLiteralFinite {
|
||||
function Check(expression: TemplateLiteralParser.Expression): boolean;
|
||||
}
|
||||
export declare namespace TemplateLiteralGenerator {
|
||||
function Generate(expression: TemplateLiteralParser.Expression): IterableIterator<string>;
|
||||
}
|
||||
export declare class TypeBuilder {
|
||||
/** `[Utility]` Creates a schema without `static` and `params` types */
|
||||
protected Create<T>(schema: Omit<T, 'static' | 'params'>): T;
|
||||
/** `[Standard]` Omits compositing symbols from this schema */
|
||||
Strict<T extends TSchema>(schema: T): T;
|
||||
}
|
||||
export declare class StandardTypeBuilder extends TypeBuilder {
|
||||
/** `[Modifier]` Creates a Optional property */
|
||||
Optional<T extends TSchema>(schema: T): TOptional<T>;
|
||||
/** `[Modifier]` Creates a ReadonlyOptional property */
|
||||
ReadonlyOptional<T extends TSchema>(schema: T): TReadonlyOptional<T>;
|
||||
/** `[Modifier]` Creates a Readonly object or property */
|
||||
Readonly<T extends TSchema>(schema: T): TReadonly<T>;
|
||||
/** `[Standard]` Creates an Any type */
|
||||
Any(options?: SchemaOptions): TAny;
|
||||
/** `[Standard]` Creates an Array type */
|
||||
Array<T extends TSchema>(items: T, options?: ArrayOptions): TArray<T>;
|
||||
/** `[Standard]` Creates a Boolean type */
|
||||
Boolean(options?: SchemaOptions): TBoolean;
|
||||
/** `[Standard]` Creates a Composite object type. */
|
||||
Composite<T extends TObject[]>(objects: [...T], options?: ObjectOptions): TComposite<T>;
|
||||
/** `[Standard]` Creates a Enum type */
|
||||
Enum<T extends Record<string, string | number>>(item: T, options?: SchemaOptions): TEnum<T>;
|
||||
/** `[Standard]` A conditional type expression that will return the true type if the left type extends the right */
|
||||
Extends<L extends TSchema, R extends TSchema, T extends TSchema, U extends TSchema>(left: L, right: R, trueType: T, falseType: U, options?: SchemaOptions): TExtends<L, R, T, U>;
|
||||
/** `[Standard]` Excludes from the left type any type that is not assignable to the right */
|
||||
Exclude<L extends TSchema, R extends TSchema>(left: L, right: R, options?: SchemaOptions): TExclude<L, R>;
|
||||
/** `[Standard]` Extracts from the left type any type that is assignable to the right */
|
||||
Extract<L extends TSchema, R extends TSchema>(left: L, right: R, options?: SchemaOptions): TExtract<L, R>;
|
||||
/** `[Standard]` Creates an Integer type */
|
||||
Integer(options?: NumericOptions<number>): TInteger;
|
||||
/** `[Standard]` Creates a Intersect type */
|
||||
Intersect(allOf: [], options?: SchemaOptions): TNever;
|
||||
/** `[Standard]` Creates a Intersect type */
|
||||
Intersect<T extends [TSchema]>(allOf: [...T], options?: SchemaOptions): T[0];
|
||||
Intersect<T extends TSchema[]>(allOf: [...T], options?: IntersectOptions): TIntersect<T>;
|
||||
/** `[Standard]` Creates a KeyOf type */
|
||||
KeyOf<T extends TSchema>(schema: T, options?: SchemaOptions): TKeyOf<T>;
|
||||
/** `[Standard]` Creates a Literal type */
|
||||
Literal<T extends TLiteralValue>(value: T, options?: SchemaOptions): TLiteral<T>;
|
||||
/** `[Standard]` Creates a Never type */
|
||||
Never(options?: SchemaOptions): TNever;
|
||||
/** `[Standard]` Creates a Not type. The first argument is the disallowed type, the second is the allowed. */
|
||||
Not<N extends TSchema, T extends TSchema>(not: N, schema: T, options?: SchemaOptions): TNot<N, T>;
|
||||
/** `[Standard]` Creates a Null type */
|
||||
Null(options?: SchemaOptions): TNull;
|
||||
/** `[Standard]` Creates a Number type */
|
||||
Number(options?: NumericOptions<number>): TNumber;
|
||||
/** `[Standard]` Creates an Object type */
|
||||
Object<T extends TProperties>(properties: T, options?: ObjectOptions): TObject<T>;
|
||||
/** `[Standard]` Creates a mapped type whose keys are omitted from the given type */
|
||||
Omit<T extends TSchema, K extends (keyof Static<T>)[]>(schema: T, keys: readonly [...K], options?: SchemaOptions): TOmit<T, K[number]>;
|
||||
/** `[Standard]` Creates a mapped type whose keys are omitted from the given type */
|
||||
Omit<T extends TSchema, K extends TUnion<TLiteral<string>[]>>(schema: T, keys: K, options?: SchemaOptions): TOmit<T, TUnionOfLiteral<K>>;
|
||||
/** `[Standard]` Creates a mapped type whose keys are omitted from the given type */
|
||||
Omit<T extends TSchema, K extends TLiteral<string>>(schema: T, key: K, options?: SchemaOptions): TOmit<T, K['const']>;
|
||||
/** `[Standard]` Creates a mapped type whose keys are omitted from the given type */
|
||||
Omit<T extends TSchema, K extends TNever>(schema: T, key: K, options?: SchemaOptions): TOmit<T, never>;
|
||||
/** `[Standard]` Creates a mapped type where all properties are Optional */
|
||||
Partial<T extends TSchema>(schema: T, options?: ObjectOptions): TPartial<T>;
|
||||
/** `[Standard]` Creates a mapped type whose keys are picked from the given type */
|
||||
Pick<T extends TSchema, K extends (keyof Static<T>)[]>(schema: T, keys: readonly [...K], options?: SchemaOptions): TPick<T, K[number]>;
|
||||
/** `[Standard]` Creates a mapped type whose keys are picked from the given type */
|
||||
Pick<T extends TSchema, K extends TUnion<TLiteral<string>[]>>(schema: T, keys: K, options?: SchemaOptions): TPick<T, TUnionOfLiteral<K>>;
|
||||
/** `[Standard]` Creates a mapped type whose keys are picked from the given type */
|
||||
Pick<T extends TSchema, K extends TLiteral<string>>(schema: T, key: K, options?: SchemaOptions): TPick<T, K['const']>;
|
||||
/** `[Standard]` Creates a mapped type whose keys are picked from the given type */
|
||||
Pick<T extends TSchema, K extends TNever>(schema: T, key: K, options?: SchemaOptions): TPick<T, never>;
|
||||
/** `[Standard]` Creates a Record type */
|
||||
Record<K extends TUnion<TLiteral<string | number>[]>, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): RecordUnionLiteralType<K, T>;
|
||||
/** `[Standard]` Creates a Record type */
|
||||
Record<K extends TLiteral<string | number>, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): RecordLiteralType<K, T>;
|
||||
/** `[Standard]` Creates a Record type */
|
||||
Record<K extends TTemplateLiteral, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): RecordTemplateLiteralType<K, T>;
|
||||
/** `[Standard]` Creates a Record type */
|
||||
Record<K extends TInteger | TNumber, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): RecordNumberType<K, T>;
|
||||
/** `[Standard]` Creates a Record type */
|
||||
Record<K extends TString, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): RecordStringType<K, T>;
|
||||
/** `[Standard]` Creates a Recursive type */
|
||||
Recursive<T extends TSchema>(callback: (thisType: TThis) => T, options?: SchemaOptions): TRecursive<T>;
|
||||
/** `[Standard]` Creates a Ref type. The referenced type must contain a $id */
|
||||
Ref<T extends TSchema>(schema: T, options?: SchemaOptions): TRef<T>;
|
||||
/** `[Standard]` Creates a mapped type where all properties are Required */
|
||||
Required<T extends TSchema>(schema: T, options?: SchemaOptions): TRequired<T>;
|
||||
/** `[Standard]` Creates a String type */
|
||||
String<Format extends string>(options?: StringOptions<StringFormatOption | Format>): TString<Format>;
|
||||
/** `[Standard]` Creates a template literal type */
|
||||
TemplateLiteral<T extends TTemplateLiteralKind[]>(kinds: [...T], options?: SchemaOptions): TTemplateLiteral<T>;
|
||||
/** `[Standard]` Creates a Tuple type */
|
||||
Tuple<T extends TSchema[]>(items: [...T], options?: SchemaOptions): TTuple<T>;
|
||||
/** `[Standard]` Creates a Union type */
|
||||
Union(anyOf: [], options?: SchemaOptions): TNever;
|
||||
/** `[Standard]` Creates a Union type */
|
||||
Union<T extends [TSchema]>(anyOf: [...T], options?: SchemaOptions): T[0];
|
||||
/** `[Standard]` Creates a Union type */
|
||||
Union<T extends TSchema[]>(anyOf: [...T], options?: SchemaOptions): TUnion<T>;
|
||||
/** `[Experimental]` Remaps a TemplateLiteral into a Union representation. This function is known to cause TS compiler crashes for finite templates with large generation counts. Use with caution. */
|
||||
Union<T extends TTemplateLiteral>(template: T): TUnionTemplateLiteral<T>;
|
||||
/** `[Standard]` Creates an Unknown type */
|
||||
Unknown(options?: SchemaOptions): TUnknown;
|
||||
/** `[Standard]` Creates a Unsafe type that infers for the generic argument */
|
||||
Unsafe<T>(options?: UnsafeOptions): TUnsafe<T>;
|
||||
}
|
||||
export declare class ExtendedTypeBuilder extends StandardTypeBuilder {
|
||||
/** `[Extended]` Creates a BigInt type */
|
||||
BigInt(options?: NumericOptions<bigint>): TBigInt;
|
||||
/** `[Extended]` Extracts the ConstructorParameters from the given Constructor type */
|
||||
ConstructorParameters<T extends TConstructor<any[], any>>(schema: T, options?: SchemaOptions): TConstructorParameters<T>;
|
||||
/** `[Extended]` Creates a Constructor type */
|
||||
Constructor<T extends TTuple<TSchema[]>, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TConstructor<TTupleIntoArray<T>, U>;
|
||||
/** `[Extended]` Creates a Constructor type */
|
||||
Constructor<T extends TSchema[], U extends TSchema>(parameters: [...T], returns: U, options?: SchemaOptions): TConstructor<T, U>;
|
||||
/** `[Extended]` Creates a Date type */
|
||||
Date(options?: DateOptions): TDate;
|
||||
/** `[Extended]` Creates a Function type */
|
||||
Function<T extends TTuple<TSchema[]>, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TFunction<TTupleIntoArray<T>, U>;
|
||||
/** `[Extended]` Creates a Function type */
|
||||
Function<T extends TSchema[], U extends TSchema>(parameters: [...T], returns: U, options?: SchemaOptions): TFunction<T, U>;
|
||||
/** `[Extended]` Extracts the InstanceType from the given Constructor */
|
||||
InstanceType<T extends TConstructor<any[], any>>(schema: T, options?: SchemaOptions): TInstanceType<T>;
|
||||
/** `[Extended]` Extracts the Parameters from the given Function type */
|
||||
Parameters<T extends TFunction<any[], any>>(schema: T, options?: SchemaOptions): TParameters<T>;
|
||||
/** `[Extended]` Creates a Promise type */
|
||||
Promise<T extends TSchema>(item: T, options?: SchemaOptions): TPromise<T>;
|
||||
/** `[Extended]` Creates a regular expression type */
|
||||
RegEx(regex: RegExp, options?: SchemaOptions): TString;
|
||||
/** `[Extended]` Extracts the ReturnType from the given Function */
|
||||
ReturnType<T extends TFunction<any[], any>>(schema: T, options?: SchemaOptions): TReturnType<T>;
|
||||
/** `[Extended]` Creates a Symbol type */
|
||||
Symbol(options?: SchemaOptions): TSymbol;
|
||||
/** `[Extended]` Creates a Undefined type */
|
||||
Undefined(options?: SchemaOptions): TUndefined;
|
||||
/** `[Extended]` Creates a Uint8Array type */
|
||||
Uint8Array(options?: Uint8ArrayOptions): TUint8Array;
|
||||
/** `[Extended]` Creates a Void type */
|
||||
Void(options?: SchemaOptions): TVoid;
|
||||
}
|
||||
/** JSON Schema TypeBuilder with Static Resolution for TypeScript */
|
||||
export declare const StandardType: StandardTypeBuilder;
|
||||
/** JSON Schema TypeBuilder with Static Resolution for TypeScript */
|
||||
export declare const Type: ExtendedTypeBuilder;
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,30 @@
|
|||
import * as Types from '../typebox';
|
||||
export declare class ValueCastReferenceTypeError extends Error {
|
||||
readonly schema: Types.TRef | Types.TThis;
|
||||
constructor(schema: Types.TRef | Types.TThis);
|
||||
}
|
||||
export declare class ValueCastArrayUniqueItemsTypeError extends Error {
|
||||
readonly schema: Types.TSchema;
|
||||
readonly value: unknown;
|
||||
constructor(schema: Types.TSchema, value: unknown);
|
||||
}
|
||||
export declare class ValueCastNeverTypeError extends Error {
|
||||
readonly schema: Types.TSchema;
|
||||
constructor(schema: Types.TSchema);
|
||||
}
|
||||
export declare class ValueCastRecursiveTypeError extends Error {
|
||||
readonly schema: Types.TSchema;
|
||||
constructor(schema: Types.TSchema);
|
||||
}
|
||||
export declare class ValueCastUnknownTypeError extends Error {
|
||||
readonly schema: Types.TSchema;
|
||||
constructor(schema: Types.TSchema);
|
||||
}
|
||||
export declare class ValueCastDereferenceError extends Error {
|
||||
readonly schema: Types.TRef | Types.TThis;
|
||||
constructor(schema: Types.TRef | Types.TThis);
|
||||
}
|
||||
export declare namespace ValueCast {
|
||||
function Visit(schema: Types.TSchema, references: Types.TSchema[], value: any): any;
|
||||
function Cast<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: any): Types.Static<T>;
|
||||
}
|
||||
|
|
@ -0,0 +1,372 @@
|
|||
"use strict";
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/value
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.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.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ValueCast = exports.ValueCastDereferenceError = exports.ValueCastUnknownTypeError = exports.ValueCastRecursiveTypeError = exports.ValueCastNeverTypeError = exports.ValueCastArrayUniqueItemsTypeError = exports.ValueCastReferenceTypeError = void 0;
|
||||
const Types = require("../typebox");
|
||||
const create_1 = require("./create");
|
||||
const check_1 = require("./check");
|
||||
const clone_1 = require("./clone");
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
// Errors
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
class ValueCastReferenceTypeError extends Error {
|
||||
constructor(schema) {
|
||||
super(`ValueCast: Cannot locate referenced schema with $id '${schema.$ref}'`);
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueCastReferenceTypeError = ValueCastReferenceTypeError;
|
||||
class ValueCastArrayUniqueItemsTypeError extends Error {
|
||||
constructor(schema, value) {
|
||||
super('ValueCast: Array cast produced invalid data due to uniqueItems constraint');
|
||||
this.schema = schema;
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
exports.ValueCastArrayUniqueItemsTypeError = ValueCastArrayUniqueItemsTypeError;
|
||||
class ValueCastNeverTypeError extends Error {
|
||||
constructor(schema) {
|
||||
super('ValueCast: Never types cannot be cast');
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueCastNeverTypeError = ValueCastNeverTypeError;
|
||||
class ValueCastRecursiveTypeError extends Error {
|
||||
constructor(schema) {
|
||||
super('ValueCast.Recursive: Cannot cast recursive schemas');
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueCastRecursiveTypeError = ValueCastRecursiveTypeError;
|
||||
class ValueCastUnknownTypeError extends Error {
|
||||
constructor(schema) {
|
||||
super('ValueCast: Unknown type');
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueCastUnknownTypeError = ValueCastUnknownTypeError;
|
||||
class ValueCastDereferenceError extends Error {
|
||||
constructor(schema) {
|
||||
super(`ValueCast: Unable to dereference schema with $id '${schema.$ref}'`);
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueCastDereferenceError = ValueCastDereferenceError;
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
// The following will score a schema against a value. For objects, the score is the tally of
|
||||
// points awarded for each property of the value. Property points are (1.0 / propertyCount)
|
||||
// to prevent large property counts biasing results. Properties that match literal values are
|
||||
// maximally awarded as literals are typically used as union discriminator fields.
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
var UnionCastCreate;
|
||||
(function (UnionCastCreate) {
|
||||
function Score(schema, references, value) {
|
||||
if (schema[Types.Kind] === 'Object' && typeof value === 'object' && value !== null) {
|
||||
const object = schema;
|
||||
const keys = Object.keys(value);
|
||||
const entries = globalThis.Object.entries(object.properties);
|
||||
const [point, max] = [1 / entries.length, entries.length];
|
||||
return entries.reduce((acc, [key, schema]) => {
|
||||
const literal = schema[Types.Kind] === 'Literal' && schema.const === value[key] ? max : 0;
|
||||
const checks = check_1.ValueCheck.Check(schema, references, value[key]) ? point : 0;
|
||||
const exists = keys.includes(key) ? point : 0;
|
||||
return acc + (literal + checks + exists);
|
||||
}, 0);
|
||||
}
|
||||
else {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
function Select(union, references, value) {
|
||||
let [select, best] = [union.anyOf[0], 0];
|
||||
for (const schema of union.anyOf) {
|
||||
const score = Score(schema, references, value);
|
||||
if (score > best) {
|
||||
select = schema;
|
||||
best = score;
|
||||
}
|
||||
}
|
||||
return select;
|
||||
}
|
||||
function Create(union, references, value) {
|
||||
if (union.default !== undefined) {
|
||||
return union.default;
|
||||
}
|
||||
else {
|
||||
const schema = Select(union, references, value);
|
||||
return ValueCast.Cast(schema, references, value);
|
||||
}
|
||||
}
|
||||
UnionCastCreate.Create = Create;
|
||||
})(UnionCastCreate || (UnionCastCreate = {}));
|
||||
var ValueCast;
|
||||
(function (ValueCast) {
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
// Guards
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
function IsObject(value) {
|
||||
return typeof value === 'object' && value !== null && !globalThis.Array.isArray(value);
|
||||
}
|
||||
function IsArray(value) {
|
||||
return typeof value === 'object' && globalThis.Array.isArray(value);
|
||||
}
|
||||
function IsNumber(value) {
|
||||
return typeof value === 'number' && !isNaN(value);
|
||||
}
|
||||
function IsString(value) {
|
||||
return typeof value === 'string';
|
||||
}
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
// Cast
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
function Any(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function Array(schema, references, value) {
|
||||
if (check_1.ValueCheck.Check(schema, references, value))
|
||||
return clone_1.ValueClone.Clone(value);
|
||||
const created = IsArray(value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
|
||||
const minimum = IsNumber(schema.minItems) && created.length < schema.minItems ? [...created, ...globalThis.Array.from({ length: schema.minItems - created.length }, () => null)] : created;
|
||||
const maximum = IsNumber(schema.maxItems) && minimum.length > schema.maxItems ? minimum.slice(0, schema.maxItems) : minimum;
|
||||
const casted = maximum.map((value) => Visit(schema.items, references, value));
|
||||
if (schema.uniqueItems !== true)
|
||||
return casted;
|
||||
const unique = [...new Set(casted)];
|
||||
if (!check_1.ValueCheck.Check(schema, references, unique))
|
||||
throw new ValueCastArrayUniqueItemsTypeError(schema, unique);
|
||||
return unique;
|
||||
}
|
||||
function BigInt(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function Boolean(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function Constructor(schema, references, value) {
|
||||
if (check_1.ValueCheck.Check(schema, references, value))
|
||||
return create_1.ValueCreate.Create(schema, references);
|
||||
const required = new Set(schema.returns.required || []);
|
||||
const result = function () { };
|
||||
for (const [key, property] of globalThis.Object.entries(schema.returns.properties)) {
|
||||
if (!required.has(key) && value.prototype[key] === undefined)
|
||||
continue;
|
||||
result.prototype[key] = Visit(property, references, value.prototype[key]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function Date(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function Function(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function Integer(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function Intersect(schema, references, value) {
|
||||
const created = create_1.ValueCreate.Create(schema, references);
|
||||
const mapped = IsObject(created) && IsObject(value) ? { ...created, ...value } : value;
|
||||
return check_1.ValueCheck.Check(schema, references, mapped) ? mapped : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function Literal(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function Never(schema, references, value) {
|
||||
throw new ValueCastNeverTypeError(schema);
|
||||
}
|
||||
function Not(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema.allOf[1], references);
|
||||
}
|
||||
function Null(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function Number(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function Object(schema, references, value) {
|
||||
if (check_1.ValueCheck.Check(schema, references, value))
|
||||
return value;
|
||||
if (value === null || typeof value !== 'object')
|
||||
return create_1.ValueCreate.Create(schema, references);
|
||||
const required = new Set(schema.required || []);
|
||||
const result = {};
|
||||
for (const [key, property] of globalThis.Object.entries(schema.properties)) {
|
||||
if (!required.has(key) && value[key] === undefined)
|
||||
continue;
|
||||
result[key] = Visit(property, references, value[key]);
|
||||
}
|
||||
// additional schema properties
|
||||
if (typeof schema.additionalProperties === 'object') {
|
||||
const propertyNames = globalThis.Object.getOwnPropertyNames(schema.properties);
|
||||
for (const propertyName of globalThis.Object.getOwnPropertyNames(value)) {
|
||||
if (propertyNames.includes(propertyName))
|
||||
continue;
|
||||
result[propertyName] = Visit(schema.additionalProperties, references, value[propertyName]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function Promise(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function Record(schema, references, value) {
|
||||
if (check_1.ValueCheck.Check(schema, references, value))
|
||||
return clone_1.ValueClone.Clone(value);
|
||||
if (value === null || typeof value !== 'object' || globalThis.Array.isArray(value) || value instanceof globalThis.Date)
|
||||
return create_1.ValueCreate.Create(schema, references);
|
||||
const subschemaPropertyName = globalThis.Object.getOwnPropertyNames(schema.patternProperties)[0];
|
||||
const subschema = schema.patternProperties[subschemaPropertyName];
|
||||
const result = {};
|
||||
for (const [propKey, propValue] of globalThis.Object.entries(value)) {
|
||||
result[propKey] = Visit(subschema, references, propValue);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function Ref(schema, references, value) {
|
||||
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
|
||||
if (index === -1)
|
||||
throw new ValueCastDereferenceError(schema);
|
||||
const target = references[index];
|
||||
return Visit(target, references, value);
|
||||
}
|
||||
function String(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function Symbol(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function TemplateLiteral(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function This(schema, references, value) {
|
||||
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
|
||||
if (index === -1)
|
||||
throw new ValueCastDereferenceError(schema);
|
||||
const target = references[index];
|
||||
return Visit(target, references, value);
|
||||
}
|
||||
function Tuple(schema, references, value) {
|
||||
if (check_1.ValueCheck.Check(schema, references, value))
|
||||
return clone_1.ValueClone.Clone(value);
|
||||
if (!globalThis.Array.isArray(value))
|
||||
return create_1.ValueCreate.Create(schema, references);
|
||||
if (schema.items === undefined)
|
||||
return [];
|
||||
return schema.items.map((schema, index) => Visit(schema, references, value[index]));
|
||||
}
|
||||
function Undefined(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function Union(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : UnionCastCreate.Create(schema, references, value);
|
||||
}
|
||||
function Uint8Array(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function Unknown(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function Void(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function UserDefined(schema, references, value) {
|
||||
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
|
||||
}
|
||||
function Visit(schema, references, value) {
|
||||
const references_ = IsString(schema.$id) ? [...references, schema] : references;
|
||||
const schema_ = schema;
|
||||
switch (schema[Types.Kind]) {
|
||||
case 'Any':
|
||||
return Any(schema_, references_, value);
|
||||
case 'Array':
|
||||
return Array(schema_, references_, value);
|
||||
case 'BigInt':
|
||||
return BigInt(schema_, references_, value);
|
||||
case 'Boolean':
|
||||
return Boolean(schema_, references_, value);
|
||||
case 'Constructor':
|
||||
return Constructor(schema_, references_, value);
|
||||
case 'Date':
|
||||
return Date(schema_, references_, value);
|
||||
case 'Function':
|
||||
return Function(schema_, references_, value);
|
||||
case 'Integer':
|
||||
return Integer(schema_, references_, value);
|
||||
case 'Intersect':
|
||||
return Intersect(schema_, references_, value);
|
||||
case 'Literal':
|
||||
return Literal(schema_, references_, value);
|
||||
case 'Never':
|
||||
return Never(schema_, references_, value);
|
||||
case 'Not':
|
||||
return Not(schema_, references_, value);
|
||||
case 'Null':
|
||||
return Null(schema_, references_, value);
|
||||
case 'Number':
|
||||
return Number(schema_, references_, value);
|
||||
case 'Object':
|
||||
return Object(schema_, references_, value);
|
||||
case 'Promise':
|
||||
return Promise(schema_, references_, value);
|
||||
case 'Record':
|
||||
return Record(schema_, references_, value);
|
||||
case 'Ref':
|
||||
return Ref(schema_, references_, value);
|
||||
case 'String':
|
||||
return String(schema_, references_, value);
|
||||
case 'Symbol':
|
||||
return Symbol(schema_, references_, value);
|
||||
case 'TemplateLiteral':
|
||||
return TemplateLiteral(schema_, references_, value);
|
||||
case 'This':
|
||||
return This(schema_, references_, value);
|
||||
case 'Tuple':
|
||||
return Tuple(schema_, references_, value);
|
||||
case 'Undefined':
|
||||
return Undefined(schema_, references_, value);
|
||||
case 'Union':
|
||||
return Union(schema_, references_, value);
|
||||
case 'Uint8Array':
|
||||
return Uint8Array(schema_, references_, value);
|
||||
case 'Unknown':
|
||||
return Unknown(schema_, references_, value);
|
||||
case 'Void':
|
||||
return Void(schema_, references_, value);
|
||||
default:
|
||||
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
|
||||
throw new ValueCastUnknownTypeError(schema_);
|
||||
return UserDefined(schema_, references_, value);
|
||||
}
|
||||
}
|
||||
ValueCast.Visit = Visit;
|
||||
function Cast(schema, references, value) {
|
||||
return Visit(schema, references, clone_1.ValueClone.Clone(value));
|
||||
}
|
||||
ValueCast.Cast = Cast;
|
||||
})(ValueCast = exports.ValueCast || (exports.ValueCast = {}));
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
import * as Types from '../typebox';
|
||||
export declare class ValueCheckUnknownTypeError extends Error {
|
||||
readonly schema: Types.TSchema;
|
||||
constructor(schema: Types.TSchema);
|
||||
}
|
||||
export declare class ValueCheckDereferenceError extends Error {
|
||||
readonly schema: Types.TRef | Types.TThis;
|
||||
constructor(schema: Types.TRef | Types.TThis);
|
||||
}
|
||||
export declare namespace ValueCheck {
|
||||
function Check<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: any): boolean;
|
||||
}
|
||||
|
|
@ -0,0 +1,484 @@
|
|||
"use strict";
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/value
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.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.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ValueCheck = exports.ValueCheckDereferenceError = exports.ValueCheckUnknownTypeError = void 0;
|
||||
const Types = require("../typebox");
|
||||
const index_1 = require("../system/index");
|
||||
const hash_1 = require("./hash");
|
||||
// -------------------------------------------------------------------------
|
||||
// Errors
|
||||
// -------------------------------------------------------------------------
|
||||
class ValueCheckUnknownTypeError extends Error {
|
||||
constructor(schema) {
|
||||
super(`ValueCheck: ${schema[Types.Kind] ? `Unknown type '${schema[Types.Kind]}'` : 'Unknown type'}`);
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueCheckUnknownTypeError = ValueCheckUnknownTypeError;
|
||||
class ValueCheckDereferenceError extends Error {
|
||||
constructor(schema) {
|
||||
super(`ValueCheck: Unable to dereference schema with $id '${schema.$ref}'`);
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueCheckDereferenceError = ValueCheckDereferenceError;
|
||||
var ValueCheck;
|
||||
(function (ValueCheck) {
|
||||
// ----------------------------------------------------------------------
|
||||
// Guards
|
||||
// ----------------------------------------------------------------------
|
||||
function IsBigInt(value) {
|
||||
return typeof value === 'bigint';
|
||||
}
|
||||
function IsInteger(value) {
|
||||
return globalThis.Number.isInteger(value);
|
||||
}
|
||||
function IsString(value) {
|
||||
return typeof value === 'string';
|
||||
}
|
||||
function IsDefined(value) {
|
||||
return value !== undefined;
|
||||
}
|
||||
// ----------------------------------------------------------------------
|
||||
// Policies
|
||||
// ----------------------------------------------------------------------
|
||||
function IsExactOptionalProperty(value, key) {
|
||||
return index_1.TypeSystem.ExactOptionalPropertyTypes ? key in value : value[key] !== undefined;
|
||||
}
|
||||
function IsObject(value) {
|
||||
const result = typeof value === 'object' && value !== null;
|
||||
return index_1.TypeSystem.AllowArrayObjects ? result : result && !globalThis.Array.isArray(value);
|
||||
}
|
||||
function IsRecordObject(value) {
|
||||
return IsObject(value) && !(value instanceof globalThis.Date) && !(value instanceof globalThis.Uint8Array);
|
||||
}
|
||||
function IsNumber(value) {
|
||||
const result = typeof value === 'number';
|
||||
return index_1.TypeSystem.AllowNaN ? result : result && globalThis.Number.isFinite(value);
|
||||
}
|
||||
function IsVoid(value) {
|
||||
const result = value === undefined;
|
||||
return index_1.TypeSystem.AllowVoidNull ? result || value === null : result;
|
||||
}
|
||||
// ----------------------------------------------------------------------
|
||||
// Types
|
||||
// ----------------------------------------------------------------------
|
||||
function Any(schema, references, value) {
|
||||
return true;
|
||||
}
|
||||
function Array(schema, references, value) {
|
||||
if (!globalThis.Array.isArray(value)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.minItems) && !(value.length >= schema.minItems)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.maxItems) && !(value.length <= schema.maxItems)) {
|
||||
return false;
|
||||
}
|
||||
// prettier-ignore
|
||||
if (schema.uniqueItems === true && !((function () { const set = new Set(); for (const element of value) {
|
||||
const hashed = hash_1.ValueHash.Create(element);
|
||||
if (set.has(hashed)) {
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
set.add(hashed);
|
||||
}
|
||||
} return true; })())) {
|
||||
return false;
|
||||
}
|
||||
return value.every((value) => Visit(schema.items, references, value));
|
||||
}
|
||||
function BigInt(schema, references, value) {
|
||||
if (!IsBigInt(value)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === globalThis.BigInt(0))) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function Boolean(schema, references, value) {
|
||||
return typeof value === 'boolean';
|
||||
}
|
||||
function Constructor(schema, references, value) {
|
||||
return Visit(schema.returns, references, value.prototype);
|
||||
}
|
||||
function Date(schema, references, value) {
|
||||
if (!(value instanceof globalThis.Date)) {
|
||||
return false;
|
||||
}
|
||||
if (!IsNumber(value.getTime())) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMinimumTimestamp) && !(value.getTime() > schema.exclusiveMinimumTimestamp)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMaximumTimestamp) && !(value.getTime() < schema.exclusiveMaximumTimestamp)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.minimumTimestamp) && !(value.getTime() >= schema.minimumTimestamp)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.maximumTimestamp) && !(value.getTime() <= schema.maximumTimestamp)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function Function(schema, references, value) {
|
||||
return typeof value === 'function';
|
||||
}
|
||||
function Integer(schema, references, value) {
|
||||
if (!IsInteger(value)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function Intersect(schema, references, value) {
|
||||
if (!schema.allOf.every((schema) => Visit(schema, references, value))) {
|
||||
return false;
|
||||
}
|
||||
else if (schema.unevaluatedProperties === false) {
|
||||
const schemaKeys = Types.KeyResolver.Resolve(schema);
|
||||
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
|
||||
return valueKeys.every((key) => schemaKeys.includes(key));
|
||||
}
|
||||
else if (Types.TypeGuard.TSchema(schema.unevaluatedProperties)) {
|
||||
const schemaKeys = Types.KeyResolver.Resolve(schema);
|
||||
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
|
||||
return valueKeys.every((key) => schemaKeys.includes(key) || Visit(schema.unevaluatedProperties, references, value[key]));
|
||||
}
|
||||
else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
function Literal(schema, references, value) {
|
||||
return value === schema.const;
|
||||
}
|
||||
function Never(schema, references, value) {
|
||||
return false;
|
||||
}
|
||||
function Not(schema, references, value) {
|
||||
return !Visit(schema.allOf[0].not, references, value) && Visit(schema.allOf[1], references, value);
|
||||
}
|
||||
function Null(schema, references, value) {
|
||||
return value === null;
|
||||
}
|
||||
function Number(schema, references, value) {
|
||||
if (!IsNumber(value)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function Object(schema, references, value) {
|
||||
if (!IsObject(value)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
|
||||
return false;
|
||||
}
|
||||
const knownKeys = globalThis.Object.getOwnPropertyNames(schema.properties);
|
||||
for (const knownKey of knownKeys) {
|
||||
const property = schema.properties[knownKey];
|
||||
if (schema.required && schema.required.includes(knownKey)) {
|
||||
if (!Visit(property, references, value[knownKey])) {
|
||||
return false;
|
||||
}
|
||||
if (Types.ExtendsUndefined.Check(property)) {
|
||||
return knownKey in value;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (IsExactOptionalProperty(value, knownKey) && !Visit(property, references, value[knownKey])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (schema.additionalProperties === false) {
|
||||
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
|
||||
// optimization: value is valid if schemaKey length matches the valueKey length
|
||||
if (schema.required && schema.required.length === knownKeys.length && valueKeys.length === knownKeys.length) {
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
return valueKeys.every((valueKey) => knownKeys.includes(valueKey));
|
||||
}
|
||||
}
|
||||
else if (typeof schema.additionalProperties === 'object') {
|
||||
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
|
||||
return valueKeys.every((key) => knownKeys.includes(key) || Visit(schema.additionalProperties, references, value[key]));
|
||||
}
|
||||
else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
function Promise(schema, references, value) {
|
||||
return typeof value === 'object' && typeof value.then === 'function';
|
||||
}
|
||||
function Record(schema, references, value) {
|
||||
if (!IsRecordObject(value)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
|
||||
return false;
|
||||
}
|
||||
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
|
||||
const regex = new RegExp(keyPattern);
|
||||
if (!globalThis.Object.getOwnPropertyNames(value).every((key) => regex.test(key))) {
|
||||
return false;
|
||||
}
|
||||
for (const propValue of globalThis.Object.values(value)) {
|
||||
if (!Visit(valueSchema, references, propValue))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function Ref(schema, references, value) {
|
||||
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
|
||||
if (index === -1)
|
||||
throw new ValueCheckDereferenceError(schema);
|
||||
const target = references[index];
|
||||
return Visit(target, references, value);
|
||||
}
|
||||
function String(schema, references, value) {
|
||||
if (!IsString(value)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.minLength)) {
|
||||
if (!(value.length >= schema.minLength))
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.maxLength)) {
|
||||
if (!(value.length <= schema.maxLength))
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.pattern)) {
|
||||
const regex = new RegExp(schema.pattern);
|
||||
if (!regex.test(value))
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.format)) {
|
||||
if (!Types.FormatRegistry.Has(schema.format))
|
||||
return false;
|
||||
const func = Types.FormatRegistry.Get(schema.format);
|
||||
return func(value);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function Symbol(schema, references, value) {
|
||||
if (!(typeof value === 'symbol')) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function TemplateLiteral(schema, references, value) {
|
||||
if (!IsString(value)) {
|
||||
return false;
|
||||
}
|
||||
return new RegExp(schema.pattern).test(value);
|
||||
}
|
||||
function This(schema, references, value) {
|
||||
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
|
||||
if (index === -1)
|
||||
throw new ValueCheckDereferenceError(schema);
|
||||
const target = references[index];
|
||||
return Visit(target, references, value);
|
||||
}
|
||||
function Tuple(schema, references, value) {
|
||||
if (!globalThis.Array.isArray(value)) {
|
||||
return false;
|
||||
}
|
||||
if (schema.items === undefined && !(value.length === 0)) {
|
||||
return false;
|
||||
}
|
||||
if (!(value.length === schema.maxItems)) {
|
||||
return false;
|
||||
}
|
||||
if (!schema.items) {
|
||||
return true;
|
||||
}
|
||||
for (let i = 0; i < schema.items.length; i++) {
|
||||
if (!Visit(schema.items[i], references, value[i]))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function Undefined(schema, references, value) {
|
||||
return value === undefined;
|
||||
}
|
||||
function Union(schema, references, value) {
|
||||
return schema.anyOf.some((inner) => Visit(inner, references, value));
|
||||
}
|
||||
function Uint8Array(schema, references, value) {
|
||||
if (!(value instanceof globalThis.Uint8Array)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.maxByteLength) && !(value.length <= schema.maxByteLength)) {
|
||||
return false;
|
||||
}
|
||||
if (IsDefined(schema.minByteLength) && !(value.length >= schema.minByteLength)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function Unknown(schema, references, value) {
|
||||
return true;
|
||||
}
|
||||
function Void(schema, references, value) {
|
||||
return IsVoid(value);
|
||||
}
|
||||
function UserDefined(schema, references, value) {
|
||||
if (!Types.TypeRegistry.Has(schema[Types.Kind]))
|
||||
return false;
|
||||
const func = Types.TypeRegistry.Get(schema[Types.Kind]);
|
||||
return func(schema, value);
|
||||
}
|
||||
function Visit(schema, references, value) {
|
||||
const references_ = IsDefined(schema.$id) ? [...references, schema] : references;
|
||||
const schema_ = schema;
|
||||
switch (schema_[Types.Kind]) {
|
||||
case 'Any':
|
||||
return Any(schema_, references_, value);
|
||||
case 'Array':
|
||||
return Array(schema_, references_, value);
|
||||
case 'BigInt':
|
||||
return BigInt(schema_, references_, value);
|
||||
case 'Boolean':
|
||||
return Boolean(schema_, references_, value);
|
||||
case 'Constructor':
|
||||
return Constructor(schema_, references_, value);
|
||||
case 'Date':
|
||||
return Date(schema_, references_, value);
|
||||
case 'Function':
|
||||
return Function(schema_, references_, value);
|
||||
case 'Integer':
|
||||
return Integer(schema_, references_, value);
|
||||
case 'Intersect':
|
||||
return Intersect(schema_, references_, value);
|
||||
case 'Literal':
|
||||
return Literal(schema_, references_, value);
|
||||
case 'Never':
|
||||
return Never(schema_, references_, value);
|
||||
case 'Not':
|
||||
return Not(schema_, references_, value);
|
||||
case 'Null':
|
||||
return Null(schema_, references_, value);
|
||||
case 'Number':
|
||||
return Number(schema_, references_, value);
|
||||
case 'Object':
|
||||
return Object(schema_, references_, value);
|
||||
case 'Promise':
|
||||
return Promise(schema_, references_, value);
|
||||
case 'Record':
|
||||
return Record(schema_, references_, value);
|
||||
case 'Ref':
|
||||
return Ref(schema_, references_, value);
|
||||
case 'String':
|
||||
return String(schema_, references_, value);
|
||||
case 'Symbol':
|
||||
return Symbol(schema_, references_, value);
|
||||
case 'TemplateLiteral':
|
||||
return TemplateLiteral(schema_, references_, value);
|
||||
case 'This':
|
||||
return This(schema_, references_, value);
|
||||
case 'Tuple':
|
||||
return Tuple(schema_, references_, value);
|
||||
case 'Undefined':
|
||||
return Undefined(schema_, references_, value);
|
||||
case 'Union':
|
||||
return Union(schema_, references_, value);
|
||||
case 'Uint8Array':
|
||||
return Uint8Array(schema_, references_, value);
|
||||
case 'Unknown':
|
||||
return Unknown(schema_, references_, value);
|
||||
case 'Void':
|
||||
return Void(schema_, references_, value);
|
||||
default:
|
||||
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
|
||||
throw new ValueCheckUnknownTypeError(schema_);
|
||||
return UserDefined(schema_, references_, value);
|
||||
}
|
||||
}
|
||||
// -------------------------------------------------------------------------
|
||||
// Check
|
||||
// -------------------------------------------------------------------------
|
||||
function Check(schema, references, value) {
|
||||
return Visit(schema, references, value);
|
||||
}
|
||||
ValueCheck.Check = Check;
|
||||
})(ValueCheck = exports.ValueCheck || (exports.ValueCheck = {}));
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
export declare namespace ValueClone {
|
||||
function Clone<T extends unknown>(value: T): T;
|
||||
}
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
"use strict";
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/value
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.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.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ValueClone = void 0;
|
||||
const is_1 = require("./is");
|
||||
var ValueClone;
|
||||
(function (ValueClone) {
|
||||
function Array(value) {
|
||||
return value.map((element) => Clone(element));
|
||||
}
|
||||
function Date(value) {
|
||||
return new globalThis.Date(value.toISOString());
|
||||
}
|
||||
function Object(value) {
|
||||
const keys = [...globalThis.Object.keys(value), ...globalThis.Object.getOwnPropertySymbols(value)];
|
||||
return keys.reduce((acc, key) => ({ ...acc, [key]: Clone(value[key]) }), {});
|
||||
}
|
||||
function TypedArray(value) {
|
||||
return value.slice();
|
||||
}
|
||||
function Value(value) {
|
||||
return value;
|
||||
}
|
||||
function Clone(value) {
|
||||
if (is_1.Is.Date(value)) {
|
||||
return Date(value);
|
||||
}
|
||||
else if (is_1.Is.Object(value)) {
|
||||
return Object(value);
|
||||
}
|
||||
else if (is_1.Is.Array(value)) {
|
||||
return Array(value);
|
||||
}
|
||||
else if (is_1.Is.TypedArray(value)) {
|
||||
return TypedArray(value);
|
||||
}
|
||||
else if (is_1.Is.Value(value)) {
|
||||
return Value(value);
|
||||
}
|
||||
else {
|
||||
throw new Error('ValueClone: Unable to clone value');
|
||||
}
|
||||
}
|
||||
ValueClone.Clone = Clone;
|
||||
})(ValueClone = exports.ValueClone || (exports.ValueClone = {}));
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
import * as Types from '../typebox';
|
||||
export declare class ValueConvertUnknownTypeError extends Error {
|
||||
readonly schema: Types.TSchema;
|
||||
constructor(schema: Types.TSchema);
|
||||
}
|
||||
export declare class ValueConvertDereferenceError extends Error {
|
||||
readonly schema: Types.TRef | Types.TThis;
|
||||
constructor(schema: Types.TRef | Types.TThis);
|
||||
}
|
||||
export declare namespace ValueConvert {
|
||||
function Visit(schema: Types.TSchema, references: Types.TSchema[], value: any): unknown;
|
||||
function Convert<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: any): unknown;
|
||||
}
|
||||
|
|
@ -0,0 +1,372 @@
|
|||
"use strict";
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/value
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.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.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ValueConvert = exports.ValueConvertDereferenceError = exports.ValueConvertUnknownTypeError = void 0;
|
||||
const Types = require("../typebox");
|
||||
const clone_1 = require("./clone");
|
||||
const check_1 = require("./check");
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
// Errors
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
class ValueConvertUnknownTypeError extends Error {
|
||||
constructor(schema) {
|
||||
super('ValueConvert: Unknown type');
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueConvertUnknownTypeError = ValueConvertUnknownTypeError;
|
||||
class ValueConvertDereferenceError extends Error {
|
||||
constructor(schema) {
|
||||
super(`ValueConvert: Unable to dereference schema with $id '${schema.$ref}'`);
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueConvertDereferenceError = ValueConvertDereferenceError;
|
||||
var ValueConvert;
|
||||
(function (ValueConvert) {
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
// Guards
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
function IsObject(value) {
|
||||
return typeof value === 'object' && value !== null && !globalThis.Array.isArray(value);
|
||||
}
|
||||
function IsArray(value) {
|
||||
return typeof value === 'object' && globalThis.Array.isArray(value);
|
||||
}
|
||||
function IsDate(value) {
|
||||
return typeof value === 'object' && value instanceof globalThis.Date;
|
||||
}
|
||||
function IsSymbol(value) {
|
||||
return typeof value === 'symbol';
|
||||
}
|
||||
function IsString(value) {
|
||||
return typeof value === 'string';
|
||||
}
|
||||
function IsBoolean(value) {
|
||||
return typeof value === 'boolean';
|
||||
}
|
||||
function IsBigInt(value) {
|
||||
return typeof value === 'bigint';
|
||||
}
|
||||
function IsNumber(value) {
|
||||
return typeof value === 'number' && !isNaN(value);
|
||||
}
|
||||
function IsStringNumeric(value) {
|
||||
return IsString(value) && !isNaN(value) && !isNaN(parseFloat(value));
|
||||
}
|
||||
function IsValueToString(value) {
|
||||
return IsBigInt(value) || IsBoolean(value) || IsNumber(value);
|
||||
}
|
||||
function IsValueTrue(value) {
|
||||
return value === true || (IsNumber(value) && value === 1) || (IsBigInt(value) && value === globalThis.BigInt('1')) || (IsString(value) && (value.toLowerCase() === 'true' || value === '1'));
|
||||
}
|
||||
function IsValueFalse(value) {
|
||||
return value === false || (IsNumber(value) && value === 0) || (IsBigInt(value) && value === globalThis.BigInt('0')) || (IsString(value) && (value.toLowerCase() === 'false' || value === '0'));
|
||||
}
|
||||
function IsTimeStringWithTimeZone(value) {
|
||||
return IsString(value) && /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i.test(value);
|
||||
}
|
||||
function IsTimeStringWithoutTimeZone(value) {
|
||||
return IsString(value) && /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)?$/i.test(value);
|
||||
}
|
||||
function IsDateTimeStringWithTimeZone(value) {
|
||||
return IsString(value) && /^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i.test(value);
|
||||
}
|
||||
function IsDateTimeStringWithoutTimeZone(value) {
|
||||
return IsString(value) && /^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)?$/i.test(value);
|
||||
}
|
||||
function IsDateString(value) {
|
||||
return IsString(value) && /^\d\d\d\d-[0-1]\d-[0-3]\d$/i.test(value);
|
||||
}
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
// Convert
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
function TryConvertLiteralString(value, target) {
|
||||
const conversion = TryConvertString(value);
|
||||
return conversion === target ? conversion : value;
|
||||
}
|
||||
function TryConvertLiteralNumber(value, target) {
|
||||
const conversion = TryConvertNumber(value);
|
||||
return conversion === target ? conversion : value;
|
||||
}
|
||||
function TryConvertLiteralBoolean(value, target) {
|
||||
const conversion = TryConvertBoolean(value);
|
||||
return conversion === target ? conversion : value;
|
||||
}
|
||||
function TryConvertLiteral(schema, value) {
|
||||
if (typeof schema.const === 'string') {
|
||||
return TryConvertLiteralString(value, schema.const);
|
||||
}
|
||||
else if (typeof schema.const === 'number') {
|
||||
return TryConvertLiteralNumber(value, schema.const);
|
||||
}
|
||||
else if (typeof schema.const === 'boolean') {
|
||||
return TryConvertLiteralBoolean(value, schema.const);
|
||||
}
|
||||
else {
|
||||
return clone_1.ValueClone.Clone(value);
|
||||
}
|
||||
}
|
||||
function TryConvertBoolean(value) {
|
||||
return IsValueTrue(value) ? true : IsValueFalse(value) ? false : value;
|
||||
}
|
||||
function TryConvertBigInt(value) {
|
||||
return IsStringNumeric(value) ? globalThis.BigInt(parseInt(value)) : IsNumber(value) ? globalThis.BigInt(value | 0) : IsValueFalse(value) ? 0 : IsValueTrue(value) ? 1 : value;
|
||||
}
|
||||
function TryConvertString(value) {
|
||||
return IsValueToString(value) ? value.toString() : value;
|
||||
}
|
||||
function TryConvertNumber(value) {
|
||||
return IsStringNumeric(value) ? parseFloat(value) : IsValueTrue(value) ? 1 : IsValueFalse(value) ? 0 : value;
|
||||
}
|
||||
function TryConvertInteger(value) {
|
||||
return IsStringNumeric(value) ? parseInt(value) : IsNumber(value) ? value | 0 : IsValueTrue(value) ? 1 : IsValueFalse(value) ? 0 : value;
|
||||
}
|
||||
function TryConvertNull(value) {
|
||||
return IsString(value) && value.toLowerCase() === 'null' ? null : value;
|
||||
}
|
||||
function TryConvertUndefined(value) {
|
||||
return IsString(value) && value === 'undefined' ? undefined : value;
|
||||
}
|
||||
function TryConvertDate(value) {
|
||||
// note: this function may return an invalid dates for the regex tests
|
||||
// above. Invalid dates will however be checked during the casting
|
||||
// function and will return a epoch date if invalid. Consider better
|
||||
// string parsing for the iso dates in future revisions.
|
||||
return IsDate(value)
|
||||
? value
|
||||
: IsNumber(value)
|
||||
? new globalThis.Date(value)
|
||||
: IsValueTrue(value)
|
||||
? new globalThis.Date(1)
|
||||
: IsValueFalse(value)
|
||||
? new globalThis.Date(0)
|
||||
: IsStringNumeric(value)
|
||||
? new globalThis.Date(parseInt(value))
|
||||
: IsTimeStringWithoutTimeZone(value)
|
||||
? new globalThis.Date(`1970-01-01T${value}.000Z`)
|
||||
: IsTimeStringWithTimeZone(value)
|
||||
? new globalThis.Date(`1970-01-01T${value}`)
|
||||
: IsDateTimeStringWithoutTimeZone(value)
|
||||
? new globalThis.Date(`${value}.000Z`)
|
||||
: IsDateTimeStringWithTimeZone(value)
|
||||
? new globalThis.Date(value)
|
||||
: IsDateString(value)
|
||||
? new globalThis.Date(`${value}T00:00:00.000Z`)
|
||||
: value;
|
||||
}
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
// Cast
|
||||
// ----------------------------------------------------------------------------------------------
|
||||
function Any(schema, references, value) {
|
||||
return value;
|
||||
}
|
||||
function Array(schema, references, value) {
|
||||
if (IsArray(value)) {
|
||||
return value.map((value) => Visit(schema.items, references, value));
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function BigInt(schema, references, value) {
|
||||
return TryConvertBigInt(value);
|
||||
}
|
||||
function Boolean(schema, references, value) {
|
||||
return TryConvertBoolean(value);
|
||||
}
|
||||
function Constructor(schema, references, value) {
|
||||
return clone_1.ValueClone.Clone(value);
|
||||
}
|
||||
function Date(schema, references, value) {
|
||||
return TryConvertDate(value);
|
||||
}
|
||||
function Function(schema, references, value) {
|
||||
return value;
|
||||
}
|
||||
function Integer(schema, references, value) {
|
||||
return TryConvertInteger(value);
|
||||
}
|
||||
function Intersect(schema, references, value) {
|
||||
return value;
|
||||
}
|
||||
function Literal(schema, references, value) {
|
||||
return TryConvertLiteral(schema, value);
|
||||
}
|
||||
function Never(schema, references, value) {
|
||||
return value;
|
||||
}
|
||||
function Null(schema, references, value) {
|
||||
return TryConvertNull(value);
|
||||
}
|
||||
function Number(schema, references, value) {
|
||||
return TryConvertNumber(value);
|
||||
}
|
||||
function Object(schema, references, value) {
|
||||
if (IsObject(value))
|
||||
return globalThis.Object.keys(schema.properties).reduce((acc, key) => {
|
||||
return value[key] !== undefined ? { ...acc, [key]: Visit(schema.properties[key], references, value[key]) } : { ...acc };
|
||||
}, value);
|
||||
return value;
|
||||
}
|
||||
function Promise(schema, references, value) {
|
||||
return value;
|
||||
}
|
||||
function Record(schema, references, value) {
|
||||
const propertyKey = globalThis.Object.getOwnPropertyNames(schema.patternProperties)[0];
|
||||
const property = schema.patternProperties[propertyKey];
|
||||
const result = {};
|
||||
for (const [propKey, propValue] of globalThis.Object.entries(value)) {
|
||||
result[propKey] = Visit(property, references, propValue);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function Ref(schema, references, value) {
|
||||
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
|
||||
if (index === -1)
|
||||
throw new ValueConvertDereferenceError(schema);
|
||||
const target = references[index];
|
||||
return Visit(target, references, value);
|
||||
}
|
||||
function String(schema, references, value) {
|
||||
return TryConvertString(value);
|
||||
}
|
||||
function Symbol(schema, references, value) {
|
||||
return value;
|
||||
}
|
||||
function TemplateLiteral(schema, references, value) {
|
||||
return value;
|
||||
}
|
||||
function This(schema, references, value) {
|
||||
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
|
||||
if (index === -1)
|
||||
throw new ValueConvertDereferenceError(schema);
|
||||
const target = references[index];
|
||||
return Visit(target, references, value);
|
||||
}
|
||||
function Tuple(schema, references, value) {
|
||||
if (IsArray(value) && schema.items !== undefined) {
|
||||
return value.map((value, index) => {
|
||||
return index < schema.items.length ? Visit(schema.items[index], references, value) : value;
|
||||
});
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function Undefined(schema, references, value) {
|
||||
return TryConvertUndefined(value);
|
||||
}
|
||||
function Union(schema, references, value) {
|
||||
for (const subschema of schema.anyOf) {
|
||||
const converted = Visit(subschema, references, value);
|
||||
if (check_1.ValueCheck.Check(subschema, references, converted)) {
|
||||
return converted;
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function Uint8Array(schema, references, value) {
|
||||
return value;
|
||||
}
|
||||
function Unknown(schema, references, value) {
|
||||
return value;
|
||||
}
|
||||
function Void(schema, references, value) {
|
||||
return value;
|
||||
}
|
||||
function UserDefined(schema, references, value) {
|
||||
return value;
|
||||
}
|
||||
function Visit(schema, references, value) {
|
||||
const references_ = IsString(schema.$id) ? [...references, schema] : references;
|
||||
const schema_ = schema;
|
||||
switch (schema[Types.Kind]) {
|
||||
case 'Any':
|
||||
return Any(schema_, references_, value);
|
||||
case 'Array':
|
||||
return Array(schema_, references_, value);
|
||||
case 'BigInt':
|
||||
return BigInt(schema_, references_, value);
|
||||
case 'Boolean':
|
||||
return Boolean(schema_, references_, value);
|
||||
case 'Constructor':
|
||||
return Constructor(schema_, references_, value);
|
||||
case 'Date':
|
||||
return Date(schema_, references_, value);
|
||||
case 'Function':
|
||||
return Function(schema_, references_, value);
|
||||
case 'Integer':
|
||||
return Integer(schema_, references_, value);
|
||||
case 'Intersect':
|
||||
return Intersect(schema_, references_, value);
|
||||
case 'Literal':
|
||||
return Literal(schema_, references_, value);
|
||||
case 'Never':
|
||||
return Never(schema_, references_, value);
|
||||
case 'Null':
|
||||
return Null(schema_, references_, value);
|
||||
case 'Number':
|
||||
return Number(schema_, references_, value);
|
||||
case 'Object':
|
||||
return Object(schema_, references_, value);
|
||||
case 'Promise':
|
||||
return Promise(schema_, references_, value);
|
||||
case 'Record':
|
||||
return Record(schema_, references_, value);
|
||||
case 'Ref':
|
||||
return Ref(schema_, references_, value);
|
||||
case 'String':
|
||||
return String(schema_, references_, value);
|
||||
case 'Symbol':
|
||||
return Symbol(schema_, references_, value);
|
||||
case 'TemplateLiteral':
|
||||
return TemplateLiteral(schema_, references_, value);
|
||||
case 'This':
|
||||
return This(schema_, references_, value);
|
||||
case 'Tuple':
|
||||
return Tuple(schema_, references_, value);
|
||||
case 'Undefined':
|
||||
return Undefined(schema_, references_, value);
|
||||
case 'Union':
|
||||
return Union(schema_, references_, value);
|
||||
case 'Uint8Array':
|
||||
return Uint8Array(schema_, references_, value);
|
||||
case 'Unknown':
|
||||
return Unknown(schema_, references_, value);
|
||||
case 'Void':
|
||||
return Void(schema_, references_, value);
|
||||
default:
|
||||
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
|
||||
throw new ValueConvertUnknownTypeError(schema_);
|
||||
return UserDefined(schema_, references_, value);
|
||||
}
|
||||
}
|
||||
ValueConvert.Visit = Visit;
|
||||
function Convert(schema, references, value) {
|
||||
return Visit(schema, references, clone_1.ValueClone.Clone(value));
|
||||
}
|
||||
ValueConvert.Convert = Convert;
|
||||
})(ValueConvert = exports.ValueConvert || (exports.ValueConvert = {}));
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
import * as Types from '../typebox';
|
||||
export declare class ValueCreateUnknownTypeError extends Error {
|
||||
readonly schema: Types.TSchema;
|
||||
constructor(schema: Types.TSchema);
|
||||
}
|
||||
export declare class ValueCreateNeverTypeError extends Error {
|
||||
readonly schema: Types.TSchema;
|
||||
constructor(schema: Types.TSchema);
|
||||
}
|
||||
export declare class ValueCreateIntersectTypeError extends Error {
|
||||
readonly schema: Types.TSchema;
|
||||
constructor(schema: Types.TSchema);
|
||||
}
|
||||
export declare class ValueCreateTempateLiteralTypeError extends Error {
|
||||
readonly schema: Types.TSchema;
|
||||
constructor(schema: Types.TSchema);
|
||||
}
|
||||
export declare class ValueCreateDereferenceError extends Error {
|
||||
readonly schema: Types.TRef | Types.TThis;
|
||||
constructor(schema: Types.TRef | Types.TThis);
|
||||
}
|
||||
export declare namespace ValueCreate {
|
||||
/** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */
|
||||
function Visit(schema: Types.TSchema, references: Types.TSchema[]): unknown;
|
||||
function Create<T extends Types.TSchema>(schema: T, references: Types.TSchema[]): Types.Static<T>;
|
||||
}
|
||||
|
|
@ -0,0 +1,480 @@
|
|||
"use strict";
|
||||
/*--------------------------------------------------------------------------
|
||||
|
||||
@sinclair/typebox/value
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.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.
|
||||
|
||||
---------------------------------------------------------------------------*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ValueCreate = exports.ValueCreateDereferenceError = exports.ValueCreateTempateLiteralTypeError = exports.ValueCreateIntersectTypeError = exports.ValueCreateNeverTypeError = exports.ValueCreateUnknownTypeError = void 0;
|
||||
const Types = require("../typebox");
|
||||
const check_1 = require("./check");
|
||||
// --------------------------------------------------------------------------
|
||||
// Errors
|
||||
// --------------------------------------------------------------------------
|
||||
class ValueCreateUnknownTypeError extends Error {
|
||||
constructor(schema) {
|
||||
super('ValueCreate: Unknown type');
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueCreateUnknownTypeError = ValueCreateUnknownTypeError;
|
||||
class ValueCreateNeverTypeError extends Error {
|
||||
constructor(schema) {
|
||||
super('ValueCreate: Never types cannot be created');
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueCreateNeverTypeError = ValueCreateNeverTypeError;
|
||||
class ValueCreateIntersectTypeError extends Error {
|
||||
constructor(schema) {
|
||||
super('ValueCreate: Intersect produced invalid value. Consider using a default value.');
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueCreateIntersectTypeError = ValueCreateIntersectTypeError;
|
||||
class ValueCreateTempateLiteralTypeError extends Error {
|
||||
constructor(schema) {
|
||||
super('ValueCreate: Can only create template literal values from patterns that produce finite sequences. Consider using a default value.');
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueCreateTempateLiteralTypeError = ValueCreateTempateLiteralTypeError;
|
||||
class ValueCreateDereferenceError extends Error {
|
||||
constructor(schema) {
|
||||
super(`ValueCreate: Unable to dereference schema with $id '${schema.$ref}'`);
|
||||
this.schema = schema;
|
||||
}
|
||||
}
|
||||
exports.ValueCreateDereferenceError = ValueCreateDereferenceError;
|
||||
// --------------------------------------------------------------------------
|
||||
// ValueCreate
|
||||
// --------------------------------------------------------------------------
|
||||
var ValueCreate;
|
||||
(function (ValueCreate) {
|
||||
// --------------------------------------------------------
|
||||
// Guards
|
||||
// --------------------------------------------------------
|
||||
function IsString(value) {
|
||||
return typeof value === 'string';
|
||||
}
|
||||
// --------------------------------------------------------
|
||||
// Types
|
||||
// --------------------------------------------------------
|
||||
function Any(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
function Array(schema, references) {
|
||||
if (schema.uniqueItems === true && schema.default === undefined) {
|
||||
throw new Error('ValueCreate.Array: Arrays with uniqueItems require a default value');
|
||||
}
|
||||
else if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else if (schema.minItems !== undefined) {
|
||||
return globalThis.Array.from({ length: schema.minItems }).map((item) => {
|
||||
return ValueCreate.Create(schema.items, references);
|
||||
});
|
||||
}
|
||||
else {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
function BigInt(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else {
|
||||
return globalThis.BigInt(0);
|
||||
}
|
||||
}
|
||||
function Boolean(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function Constructor(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else {
|
||||
const value = ValueCreate.Create(schema.returns, references);
|
||||
if (typeof value === 'object' && !globalThis.Array.isArray(value)) {
|
||||
return class {
|
||||
constructor() {
|
||||
for (const [key, val] of globalThis.Object.entries(value)) {
|
||||
const self = this;
|
||||
self[key] = val;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
else {
|
||||
return class {
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
function Date(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else if (schema.minimumTimestamp !== undefined) {
|
||||
return new globalThis.Date(schema.minimumTimestamp);
|
||||
}
|
||||
else {
|
||||
return new globalThis.Date(0);
|
||||
}
|
||||
}
|
||||
function Function(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else {
|
||||
return () => ValueCreate.Create(schema.returns, references);
|
||||
}
|
||||
}
|
||||
function Integer(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else if (schema.minimum !== undefined) {
|
||||
return schema.minimum;
|
||||
}
|
||||
else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
function Intersect(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else {
|
||||
// Note: The best we can do here is attempt to instance each sub type and apply through object assign. For non-object
|
||||
// sub types, we just escape the assignment and just return the value. In the latter case, this is typically going to
|
||||
// be a consequence of an illogical intersection.
|
||||
const value = schema.allOf.reduce((acc, schema) => {
|
||||
const next = Visit(schema, references);
|
||||
return typeof next === 'object' ? { ...acc, ...next } : next;
|
||||
}, {});
|
||||
if (!check_1.ValueCheck.Check(schema, references, value))
|
||||
throw new ValueCreateIntersectTypeError(schema);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
function Literal(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else {
|
||||
return schema.const;
|
||||
}
|
||||
}
|
||||
function Never(schema, references) {
|
||||
throw new ValueCreateNeverTypeError(schema);
|
||||
}
|
||||
function Not(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else {
|
||||
return Visit(schema.allOf[1], references);
|
||||
}
|
||||
}
|
||||
function Null(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
function Number(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else if (schema.minimum !== undefined) {
|
||||
return schema.minimum;
|
||||
}
|
||||
else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
function Object(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else {
|
||||
const required = new Set(schema.required);
|
||||
return (schema.default ||
|
||||
globalThis.Object.entries(schema.properties).reduce((acc, [key, schema]) => {
|
||||
return required.has(key) ? { ...acc, [key]: ValueCreate.Create(schema, references) } : { ...acc };
|
||||
}, {}));
|
||||
}
|
||||
}
|
||||
function Promise(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else {
|
||||
return globalThis.Promise.resolve(ValueCreate.Create(schema.item, references));
|
||||
}
|
||||
}
|
||||
function Record(schema, references) {
|
||||
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else if (!(keyPattern === Types.PatternStringExact || keyPattern === Types.PatternNumberExact)) {
|
||||
const propertyKeys = keyPattern.slice(1, keyPattern.length - 1).split('|');
|
||||
return propertyKeys.reduce((acc, key) => {
|
||||
return { ...acc, [key]: Create(valueSchema, references) };
|
||||
}, {});
|
||||
}
|
||||
else {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
function Ref(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else {
|
||||
const index = references.findIndex((foreign) => foreign.$id === schema.$id);
|
||||
if (index === -1)
|
||||
throw new ValueCreateDereferenceError(schema);
|
||||
const target = references[index];
|
||||
return Visit(target, references);
|
||||
}
|
||||
}
|
||||
function String(schema, references) {
|
||||
if (schema.pattern !== undefined) {
|
||||
if (!('default' in schema)) {
|
||||
throw new Error('ValueCreate.String: String types with patterns must specify a default value');
|
||||
}
|
||||
else {
|
||||
return schema.default;
|
||||
}
|
||||
}
|
||||
else if (schema.format !== undefined) {
|
||||
if (!('default' in schema)) {
|
||||
throw new Error('ValueCreate.String: String types with formats must specify a default value');
|
||||
}
|
||||
else {
|
||||
return schema.default;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else if (schema.minLength !== undefined) {
|
||||
return globalThis.Array.from({ length: schema.minLength })
|
||||
.map(() => '.')
|
||||
.join('');
|
||||
}
|
||||
else {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
}
|
||||
function Symbol(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else if ('value' in schema) {
|
||||
return globalThis.Symbol.for(schema.value);
|
||||
}
|
||||
else {
|
||||
return globalThis.Symbol();
|
||||
}
|
||||
}
|
||||
function TemplateLiteral(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
const expression = Types.TemplateLiteralParser.ParseExact(schema.pattern);
|
||||
if (!Types.TemplateLiteralFinite.Check(expression))
|
||||
throw new ValueCreateTempateLiteralTypeError(schema);
|
||||
const sequence = Types.TemplateLiteralGenerator.Generate(expression);
|
||||
return sequence.next().value;
|
||||
}
|
||||
function This(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else {
|
||||
const index = references.findIndex((foreign) => foreign.$id === schema.$id);
|
||||
if (index === -1)
|
||||
throw new ValueCreateDereferenceError(schema);
|
||||
const target = references[index];
|
||||
return Visit(target, references);
|
||||
}
|
||||
}
|
||||
function Tuple(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
if (schema.items === undefined) {
|
||||
return [];
|
||||
}
|
||||
else {
|
||||
return globalThis.Array.from({ length: schema.minItems }).map((_, index) => ValueCreate.Create(schema.items[index], references));
|
||||
}
|
||||
}
|
||||
function Undefined(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
function Union(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else if (schema.anyOf.length === 0) {
|
||||
throw new Error('ValueCreate.Union: Cannot create Union with zero variants');
|
||||
}
|
||||
else {
|
||||
return ValueCreate.Create(schema.anyOf[0], references);
|
||||
}
|
||||
}
|
||||
function Uint8Array(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else if (schema.minByteLength !== undefined) {
|
||||
return new globalThis.Uint8Array(schema.minByteLength);
|
||||
}
|
||||
else {
|
||||
return new globalThis.Uint8Array(0);
|
||||
}
|
||||
}
|
||||
function Unknown(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
function Void(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else {
|
||||
return void 0;
|
||||
}
|
||||
}
|
||||
function UserDefined(schema, references) {
|
||||
if ('default' in schema) {
|
||||
return schema.default;
|
||||
}
|
||||
else {
|
||||
throw new Error('ValueCreate.UserDefined: User defined types must specify a default value');
|
||||
}
|
||||
}
|
||||
/** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */
|
||||
function Visit(schema, references) {
|
||||
const references_ = IsString(schema.$id) ? [...references, schema] : references;
|
||||
const schema_ = schema;
|
||||
switch (schema_[Types.Kind]) {
|
||||
case 'Any':
|
||||
return Any(schema_, references_);
|
||||
case 'Array':
|
||||
return Array(schema_, references_);
|
||||
case 'BigInt':
|
||||
return BigInt(schema_, references_);
|
||||
case 'Boolean':
|
||||
return Boolean(schema_, references_);
|
||||
case 'Constructor':
|
||||
return Constructor(schema_, references_);
|
||||
case 'Date':
|
||||
return Date(schema_, references_);
|
||||
case 'Function':
|
||||
return Function(schema_, references_);
|
||||
case 'Integer':
|
||||
return Integer(schema_, references_);
|
||||
case 'Intersect':
|
||||
return Intersect(schema_, references_);
|
||||
case 'Literal':
|
||||
return Literal(schema_, references_);
|
||||
case 'Never':
|
||||
return Never(schema_, references_);
|
||||
case 'Not':
|
||||
return Not(schema_, references_);
|
||||
case 'Null':
|
||||
return Null(schema_, references_);
|
||||
case 'Number':
|
||||
return Number(schema_, references_);
|
||||
case 'Object':
|
||||
return Object(schema_, references_);
|
||||
case 'Promise':
|
||||
return Promise(schema_, references_);
|
||||
case 'Record':
|
||||
return Record(schema_, references_);
|
||||
case 'Ref':
|
||||
return Ref(schema_, references_);
|
||||
case 'String':
|
||||
return String(schema_, references_);
|
||||
case 'Symbol':
|
||||
return Symbol(schema_, references_);
|
||||
case 'TemplateLiteral':
|
||||
return TemplateLiteral(schema_, references_);
|
||||
case 'This':
|
||||
return This(schema_, references_);
|
||||
case 'Tuple':
|
||||
return Tuple(schema_, references_);
|
||||
case 'Undefined':
|
||||
return Undefined(schema_, references_);
|
||||
case 'Union':
|
||||
return Union(schema_, references_);
|
||||
case 'Uint8Array':
|
||||
return Uint8Array(schema_, references_);
|
||||
case 'Unknown':
|
||||
return Unknown(schema_, references_);
|
||||
case 'Void':
|
||||
return Void(schema_, references_);
|
||||
default:
|
||||
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
|
||||
throw new ValueCreateUnknownTypeError(schema_);
|
||||
return UserDefined(schema_, references_);
|
||||
}
|
||||
}
|
||||
ValueCreate.Visit = Visit;
|
||||
function Create(schema, references) {
|
||||
return Visit(schema, references);
|
||||
}
|
||||
ValueCreate.Create = Create;
|
||||
})(ValueCreate = exports.ValueCreate || (exports.ValueCreate = {}));
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue