@adviser/cement 0.2.5 → 0.2.7
Sign up to get free protection for your applications and to get access to all the features.
- package/index.cjs +247 -15
- package/index.cjs.map +1 -1
- package/index.d.cts +137 -7
- package/index.d.ts +137 -7
- package/index.js +241 -14
- package/index.js.map +1 -1
- package/package.json +10 -7
- package/utils/index.cjs +3 -1
- package/utils/index.cjs.map +1 -1
- package/utils/index.js +3 -1
- package/utils/index.js.map +1 -1
package/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../src/logger.ts","../../src/logger_impl.ts","../../src/test/log_collector.ts","../../src/test/mock_logger.ts","../../src/result.ts","../../src/option.ts"],"sourcesContent":["import { Result } from \"./result\";\n\nexport enum Level {\n WARN = \"warn\",\n DEBUG = \"debug\",\n INFO = \"info\",\n ERROR = \"error\",\n}\n\nexport type Serialized = string | number | boolean;\nexport type FnSerialized = () => Serialized;\n\nexport class LogValue {\n constructor(readonly fn: FnSerialized) {}\n value(): Serialized {\n return this.fn();\n }\n toJSON(): Serialized {\n return this.value();\n }\n}\n\nexport type LogSerializable = Record<string, LogValue>;\n\nexport function removeSelfRef(): (key: unknown, val: unknown) => unknown {\n const cache = new Set();\n return function (key: unknown, value: unknown) {\n if (typeof value === \"object\" && value !== null) {\n // Duplicate reference found, discard key\n if (cache.has(value)) return \"...\";\n cache.add(value);\n }\n return value;\n };\n}\n\nexport function logValue(val: Serialized | FnSerialized | LogSerializable | undefined | null): LogValue {\n switch (typeof val) {\n case \"function\":\n return new LogValue(val);\n case \"string\":\n return new LogValue(() => val.toString());\n case \"number\":\n return new LogValue(() => val);\n case \"boolean\":\n return new LogValue(() => val);\n case \"object\":\n return new LogValue(() => JSON.parse(JSON.stringify(val, removeSelfRef())));\n default:\n if (!val) {\n return new LogValue(() => \"--Falsy--\");\n }\n throw new Error(`Invalid type:${typeof val}`);\n }\n}\n\nexport interface LoggerInterface<R> {\n Module(key: string): R;\n // if modules is empty, set for all Levels\n EnableLevel(level: Level, ...modules: string[]): R;\n DisableLevel(level: Level, ...modules: string[]): R;\n\n SetDebug(...modules: (string | string[])[]): R;\n\n Ref(key: string, action: { toString: () => string } | FnSerialized): R;\n Result<T>(key: string, res: Result<T>): R;\n // default key url\n Url(url: URL, key?: string): R;\n // len\n Len(value: object | { length: number } | string | undefined | null, key?: string): R;\n\n Str(key: string, value?: string): R;\n Error(): R;\n Warn(): R;\n Debug(): R;\n Log(): R;\n WithLevel(level: Level): R;\n\n Err(err: unknown): R; // could be Error, or something which coerces to string\n Info(): R;\n Timestamp(): R;\n Any(key: string, value: unknown): R;\n Dur(key: string, nsec: number): R;\n Uint64(key: string, value: number): R;\n Int(key: string, value: number): R;\n Bool(key: string, value: unknown): R;\n}\n\nexport function IsLogger(obj: unknown): obj is Logger {\n return (\n typeof obj === \"object\" &&\n [\n \"Module\",\n \"EnableLevel\",\n \"DisableLevel\",\n \"SetDebug\",\n \"Str\",\n \"Error\",\n \"Warn\",\n \"Debug\",\n \"Log\",\n \"WithLevel\",\n \"Err\",\n \"Info\",\n \"Timestamp\",\n \"Any\",\n \"Dur\",\n \"Uint64\",\n ]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map((fn) => typeof (obj as any)[fn] === \"function\")\n .reduce((a, b) => a && b, true)\n );\n}\n\nexport interface WithLogger extends LoggerInterface<WithLogger> {\n Logger(): Logger;\n}\n\nexport interface AsError {\n AsError(): Error;\n}\n\nexport interface Logger extends LoggerInterface<Logger> {\n With(): WithLogger;\n\n Msg(...args: string[]): AsError;\n Flush(): Promise<void>;\n}\n","// import { v4 } from \"uuid\";\nimport { AsError, FnSerialized, LogSerializable, Level, Logger, logValue, Serialized, WithLogger, removeSelfRef } from \"./logger\";\nimport { WebSysAbstraction } from \"./web/web_sys_abstraction\";\nimport { SysAbstraction } from \"./sys_abstraction\";\nimport { Result } from \"./result\";\n\nconst encoder = new TextEncoder();\n\n// function resolveLogValue(val: LogSerializable): Record<string, Serialized> {\n// const ret: Record<string, Serialized> = {};\n// Object.keys(val).forEach((key) => {\n// const v = val[key];\n// if (v instanceof LogValue) {\n// ret[key] = v.value();\n// }\n// });\n// return ret;\n// }\n\nexport interface LevelHandler {\n enableLevel(level: Level, ...modules: string[]): void;\n disableLevel(level: Level, ...modules: string[]): void;\n setDebug(...modules: (string | string[])[]): void;\n isEnabled(ilevel: unknown, module: unknown): boolean;\n}\n\nexport class LevelHandlerImpl implements LevelHandler {\n readonly _globalLevels = new Set<Level>([Level.INFO, Level.ERROR, Level.WARN]);\n readonly _modules = new Map<string, Set<Level>>();\n enableLevel(level: Level, ...modules: string[]): void {\n if (modules.length == 0) {\n this._globalLevels.add(level);\n return;\n }\n this.forModules(\n level,\n (p) => {\n this._modules.set(p, new Set([...this._globalLevels, level]));\n },\n ...modules,\n );\n }\n disableLevel(level: Level, ...modules: string[]): void {\n if (modules.length == 0) {\n this._globalLevels.delete(level);\n return;\n }\n this.forModules(\n level,\n (p) => {\n this._modules.delete(p);\n },\n ...modules,\n );\n }\n\n forModules(level: Level, fnAction: (p: string) => void, ...modules: (string | string[])[]): void {\n for (const m of modules.flat()) {\n if (typeof m !== \"string\") {\n continue;\n }\n const parts = m\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length);\n for (const p of parts) {\n fnAction(p);\n }\n }\n }\n setDebug(...modules: (string | string[])[]): void {\n this.forModules(\n Level.DEBUG,\n (p) => {\n this._modules.set(p, new Set([...this._globalLevels, Level.DEBUG]));\n },\n ...modules,\n );\n }\n isEnabled(ilevel: unknown, module: unknown): boolean {\n const level = ilevel as Level; // what if it's not a level?\n if (typeof module === \"string\") {\n const levels = this._modules.get(module);\n if (levels && levels.has(level)) {\n return true;\n }\n }\n const wlevel = this._modules.get(\"*\");\n if (wlevel && typeof level === \"string\") {\n if (wlevel.has(level)) {\n return true;\n }\n }\n if (typeof level !== \"string\") {\n // this is a plain log\n return true;\n }\n return this._globalLevels.has(level);\n }\n}\n\nconst levelSingleton = new LevelHandlerImpl();\n\n// globalThis[Symbol(\"levelSingleton\")] = new LevelHandlerImpl()\n\nexport class LogWriter {\n readonly _out: WritableStream<Uint8Array>;\n readonly _toFlush: (() => Promise<void>)[] = [];\n\n constructor(out: WritableStream<Uint8Array>) {\n this._out = out;\n }\n\n write(encoded: Uint8Array) {\n const my = async () => {\n // const val = Math.random();\n // console.log(\">>>My:\", val)\n try {\n const writer = this._out.getWriter();\n await writer.ready;\n await writer.write(encoded);\n await writer.releaseLock();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"Chunk error:\", err);\n }\n // console.log(\"<<<My:\", val)\n };\n this._toFlush.push(my);\n this._flush();\n }\n\n _flushIsRunning = false;\n _flushDoneFns = Array<() => void>();\n _flush(toFlush: (() => Promise<void>)[] | undefined = undefined, done?: () => void): void {\n if (done) {\n this._flushDoneFns.push(done);\n }\n\n if (this._toFlush.length == 0) {\n // console.log(\"Flush is stopped\", this._toFlush.length)\n this._flushIsRunning = false;\n this._flushDoneFns.forEach((fn) => fn());\n this._flushDoneFns = [];\n return;\n }\n\n if (!toFlush && this._toFlush.length == 1 && !this._flushIsRunning) {\n this._flushIsRunning = true;\n // console.log(\"Flush is started\", this._toFlush.length)\n } else if (!toFlush) {\n // console.log(\"flush queue check but is running\", this._toFlush.length)\n return;\n }\n\n // console.log(\">>>Msg:\", this._toFlush.length)\n const my = this._toFlush.shift();\n my?.().finally(() => {\n // console.log(\"<<<Msg:\", this._toFlush.length)\n this._flush(this._toFlush);\n });\n }\n}\n\nexport interface LoggerImplParams {\n readonly out?: WritableStream<Uint8Array>;\n readonly logWriter?: LogWriter;\n readonly sys?: SysAbstraction;\n readonly withAttributes?: LogSerializable;\n readonly levelHandler?: LevelHandler;\n}\nexport class LoggerImpl implements Logger {\n readonly _sys: SysAbstraction;\n readonly _attributes: LogSerializable = {};\n readonly _withAttributes: LogSerializable;\n readonly _logWriter: LogWriter;\n readonly _levelHandler: LevelHandler;\n // readonly _id: string = \"logger-\" + Math.random().toString(36)\n\n constructor(params?: LoggerImplParams) {\n if (!params) {\n params = {};\n }\n if (!params.sys) {\n this._sys = WebSysAbstraction();\n } else {\n this._sys = params.sys;\n }\n if (params.logWriter) {\n this._logWriter = params.logWriter;\n } else {\n if (!params.out) {\n this._logWriter = new LogWriter(this._sys.Stdout());\n } else {\n this._logWriter = new LogWriter(params.out);\n }\n }\n if (!params.withAttributes) {\n this._withAttributes = {};\n } else {\n this._withAttributes = { ...params.withAttributes };\n }\n this._attributes = { ...this._withAttributes };\n if (params.levelHandler) {\n this._levelHandler = params.levelHandler;\n } else {\n this._levelHandler = levelSingleton;\n }\n // console.log(\"LoggerImpl\", this._id, this._attributes, this._withAttributes)\n }\n\n EnableLevel(level: Level, ...modules: string[]): Logger {\n this._levelHandler.enableLevel(level, ...modules);\n return this;\n }\n DisableLevel(level: Level, ...modules: string[]): Logger {\n this._levelHandler.disableLevel(level, ...modules);\n return this;\n }\n\n Module(key: string): Logger {\n this._attributes[\"module\"] = logValue(key);\n this._withAttributes[\"module\"] = logValue(key);\n return this;\n }\n // if the string is \"*\" it will enable for all modules\n SetDebug(...modules: (string | string[])[]): Logger {\n this._levelHandler.setDebug(...modules);\n return this;\n }\n\n Timestamp(): Logger {\n // this is called with .call from _produceError where this\n // this is crafted to have _sys and _attributes\n // CAUTION so done use other ref from this\n this._attributes[\"ts\"] = logValue(this._sys.Time().Now().toISOString());\n return this;\n }\n Warn(): Logger {\n this._attributes[\"level\"] = logValue(Level.WARN);\n return this;\n }\n Log(): Logger {\n return this;\n }\n Debug(): Logger {\n this._attributes[\"level\"] = logValue(Level.DEBUG);\n return this;\n }\n Error(): Logger {\n this._attributes[\"level\"] = logValue(Level.ERROR);\n return this;\n }\n Info(): Logger {\n this._attributes[\"level\"] = logValue(Level.INFO);\n return this;\n }\n Err(err: unknown): Logger {\n if (err instanceof Error) {\n this._attributes[\"error\"] = logValue(err.message);\n } else {\n this._attributes[\"error\"] = logValue(\"\" + err);\n }\n return this;\n }\n WithLevel(l: Level): Logger {\n this._attributes[\"level\"] = logValue(l);\n return this;\n }\n\n Ref(key: string, action: { toString: () => string } | FnSerialized): Logger {\n if (typeof action === \"function\") {\n this._attributes[key] = logValue(action as FnSerialized);\n } else if (typeof action.toString === \"function\") {\n this._attributes[key] = logValue(() => action.toString());\n } else {\n this._attributes[key] = logValue(\"INVALID REF\");\n }\n return this;\n }\n Bool(key: string, value: unknown): Logger {\n this._attributes[key] = logValue(!!value);\n return this;\n }\n Result<T>(key: string, res: Result<T, Error>): Logger {\n if (res.isOk()) {\n this._attributes[key] = logValue(res.Ok() as Serialized);\n } else {\n this.Err(res.Err());\n }\n return this;\n }\n\n Len(value: unknown, key = \"len\"): Logger {\n if (Array.isArray(value)) {\n this._attributes[key] = logValue(() => value.length);\n } else if (typeof value === \"string\") {\n this._attributes[key] = logValue(() => value.length);\n } else if (typeof value === \"object\" && value !== null) {\n this._attributes[key] = logValue(() => Object.keys(value).length);\n } else {\n this.Int(key, -1);\n }\n return this;\n }\n\n Url(url: URL, key = \"url\"): Logger {\n this.Ref(key, () => url.toString());\n return this;\n }\n\n Str(key: string, value?: string): Logger {\n this._attributes[key] = logValue(value);\n return this;\n }\n\n Any(key: string, value?: string | number | boolean | LogSerializable): Logger {\n this._attributes[key] = logValue(value);\n return this;\n }\n Dur(key: string, nsec: number): Logger {\n this._attributes[key] = logValue(`${nsec}ms`);\n // new Intl.DurationFormat(\"en\", { style: \"narrow\" }).format(nsec);\n return this;\n }\n Uint64(key: string, value: number): Logger {\n this._attributes[key] = logValue(value);\n return this;\n }\n Int(key: string, value: number): Logger {\n return this.Uint64(key, value);\n }\n\n async Flush(): Promise<void> {\n return new Promise((resolve) => {\n this._logWriter._flush(undefined, resolve);\n });\n }\n\n With(): WithLogger {\n // console.log(\"WithLoggerBuilder.With\", this._id, this._attributes, this._withAttributes);\n return new WithLoggerBuilder(\n new LoggerImpl({\n logWriter: this._logWriter,\n sys: this._sys,\n levelHandler: this._levelHandler,\n withAttributes: {\n module: this._attributes[\"module\"],\n ...this._withAttributes,\n },\n }),\n );\n }\n\n _resetAttributes(fn: () => () => string): () => string {\n const ret = fn();\n Object.keys(this._attributes).forEach((key) => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._attributes[key];\n });\n Object.assign(this._attributes, this._withAttributes);\n return ret;\n }\n _produceError(attr: LogSerializable, ...args: string[]): string {\n attr[\"msg\"] = logValue(args.join(\" \"));\n const msg = attr[\"msg\"].value();\n if (typeof msg === \"string\" && !msg.trim().length) {\n delete attr[\"msg\"];\n }\n if (attr[\"ts\"]?.value() === \"ETERNITY\") {\n // hacky but it works\n this.Timestamp.call({\n _sys: this._sys,\n _attributes: attr,\n });\n }\n return JSON.stringify(attr, removeSelfRef());\n }\n\n Msg(...args: string[]): AsError {\n const fnError = this._resetAttributes(() => {\n const doWrite = this._levelHandler.isEnabled(this._attributes[\"level\"]?.value(), this._attributes[\"module\"]?.value());\n let fnRet = () => this._produceError({ ...this._attributes }, ...args);\n if (doWrite) {\n const str = fnRet();\n const encoded = encoder.encode(str + \"\\n\");\n this._logWriter.write(encoded);\n fnRet = () => str;\n }\n return fnRet;\n });\n return {\n AsError: () => new Error(fnError()),\n };\n }\n}\n\nclass WithLoggerBuilder implements WithLogger {\n readonly _li: LoggerImpl;\n constructor(li: LoggerImpl) {\n this._li = li;\n }\n\n Logger(): Logger {\n Object.assign(this._li._withAttributes, this._li._attributes);\n return this._li;\n }\n\n EnableLevel(level: Level, ...modules: string[]): WithLogger {\n this._li._levelHandler.enableLevel(level, ...modules);\n return this;\n }\n DisableLevel(level: Level, ...modules: string[]): WithLogger {\n this._li._levelHandler.enableLevel(level, ...modules);\n return this;\n }\n\n Module(key: string): WithLogger {\n this._li.Module(key);\n return this;\n }\n SetDebug(...modules: (string | string[])[]): WithLogger {\n this._li.SetDebug(...modules);\n return this;\n }\n\n Str(key: string, value?: string): WithLogger {\n this._li.Str(key, value);\n return this;\n }\n\n Len(value: unknown, key?: string): WithLogger {\n this._li.Len(value, key);\n return this;\n }\n\n Ref(key: string, action: Serialized | FnSerialized): WithLogger {\n this._li.Ref(key, action);\n return this;\n }\n Bool(key: string, value: unknown): WithLogger {\n this._li.Bool(key, value);\n return this;\n }\n Result<T>(key: string, res: Result<T, Error>): WithLogger {\n this._li.Result(key, res);\n return this;\n }\n Url(url: URL, key?: string): WithLogger {\n this._li.Url(url, key);\n return this;\n }\n Int(key: string, value: number): WithLogger {\n this._li.Int(key, value);\n return this;\n }\n\n Log(): WithLogger {\n this._li.Log();\n return this;\n }\n\n WithLevel(level: Level): WithLogger {\n this._li.WithLevel(level);\n return this;\n }\n\n Error(): WithLogger {\n this._li.Error();\n return this;\n }\n Warn(): WithLogger {\n this._li.Error();\n return this;\n }\n Debug(): WithLogger {\n this._li.Debug();\n return this;\n }\n Err(err: unknown): WithLogger {\n this._li.Err(err);\n return this;\n }\n Info(): WithLogger {\n this._li.Info();\n return this;\n }\n Timestamp(): WithLogger {\n this._li._attributes[\"ts\"] = logValue(\"ETERNITY\");\n return this;\n }\n Any(key: string, value: LogSerializable): WithLogger {\n this._li.Any(key, value);\n return this;\n }\n Dur(key: string, nsec: number): WithLogger {\n this._li.Dur(key, nsec);\n return this;\n }\n Uint64(key: string, value: number): WithLogger {\n this._li.Uint64(key, value);\n return this;\n }\n}\n","class LogWriter implements WritableStreamDefaultWriter<Uint8Array> {\n readonly _bufferArr: Uint8Array[] = [];\n\n _resolveClosed: (value?: PromiseLike<undefined>) => void;\n closed: Promise<undefined>;\n desiredSize: number | null = null;\n ready: Promise<undefined> = Promise.resolve(undefined);\n\n constructor() {\n this._resolveClosed = () => {\n // do nothing\n };\n this.closed = new Promise((resolve) => {\n this._resolveClosed = resolve;\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any\n abort(reason?: any): Promise<void> {\n throw new Error(\"Method not implemented.\");\n }\n close(): Promise<void> {\n this._resolveClosed();\n return Promise.resolve(undefined);\n }\n releaseLock(): void {\n // do nothing\n }\n write(chunk?: Uint8Array): Promise<void> {\n chunk && this._bufferArr.push(chunk);\n return Promise.resolve(undefined);\n }\n}\n\nexport class LogCollector implements WritableStream<Uint8Array> {\n readonly locked: boolean = false;\n _writer?: LogWriter;\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abort(reason?: Uint8Array): Promise<void> {\n throw new Error(\"Method not implemented.\");\n }\n\n async close(): Promise<void> {\n if (this._writer) {\n const ret = await this._writer.close();\n this._writer = undefined;\n return ret;\n }\n return Promise.resolve(undefined);\n }\n\n getWriter(): WritableStreamDefaultWriter<Uint8Array> {\n if (!this._writer) {\n this._writer = new LogWriter();\n }\n return this._writer;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Logs(): any[] {\n if (!this._writer) {\n return [];\n }\n const jsonNlStr = new TextDecoder().decode(\n new Uint8Array(\n (function* (res: Uint8Array[]) {\n for (const x of res) {\n yield* x;\n }\n })(this._writer._bufferArr),\n ),\n );\n const splitStr = jsonNlStr.split(\"\\n\");\n const filterStr = splitStr.filter((a) => a.length);\n const mapStr = filterStr.map((a) => JSON.parse(a));\n return mapStr;\n }\n}\n","import { Logger } from \"../logger\";\nimport { LevelHandlerImpl, LoggerImpl } from \"../logger_impl\";\nimport { SysAbstraction } from \"../sys_abstraction\";\nimport { LogCollector } from \"./log_collector\";\n\nexport interface MockLoggerReturn {\n readonly logger: Logger;\n readonly logCollector: LogCollector;\n}\n\nexport function MockLogger(params?: {\n readonly sys?: SysAbstraction;\n moduleName?: string | string[];\n readonly disableDebug?: boolean;\n}): MockLoggerReturn {\n const lc = new LogCollector();\n let modNames = [\"MockLogger\"];\n if (typeof params?.moduleName === \"string\") {\n modNames = [params?.moduleName];\n } else if (Array.isArray(params?.moduleName)) {\n modNames = [...params.moduleName, ...modNames];\n }\n const logger = new LoggerImpl({\n out: lc,\n sys: params?.sys,\n levelHandler: new LevelHandlerImpl(),\n })\n .With()\n .Module(modNames[0])\n .Logger();\n !params?.disableDebug && logger.SetDebug(...modNames);\n return {\n logCollector: lc,\n logger,\n };\n}\n","export abstract class Result<T, E = Error> {\n static Ok<T>(t: T): Result<T, Error> {\n return new ResultOK(t);\n }\n static Err<T extends Error = Error>(t: T | string): Result<never, T> {\n if (typeof t === \"string\") {\n return new ResultError(new Error(t) as T);\n }\n return new ResultError(t);\n }\n static Is<T>(t: unknown): t is Result<T> {\n if (!t) {\n return false;\n }\n if (t instanceof Result) {\n return true;\n }\n const rt = t as Result<T>;\n if ([typeof rt.is_ok, typeof rt.is_err, typeof rt.unwrap, typeof rt.unwrap_err].every((x) => x === \"function\")) {\n return true;\n }\n return false;\n }\n\n isOk(): boolean {\n return this.is_ok();\n }\n isErr(): boolean {\n return this.is_err();\n }\n\n Ok(): T {\n return this.unwrap();\n }\n Err(): E {\n return this.unwrap_err();\n }\n\n abstract is_ok(): boolean;\n abstract is_err(): boolean;\n abstract unwrap(): T;\n abstract unwrap_err(): E;\n}\n\nexport class ResultOK<T> extends Result<T, Error> {\n private _t: T;\n constructor(t: T) {\n super();\n this._t = t;\n }\n is_ok(): boolean {\n return true;\n }\n is_err(): boolean {\n return false;\n }\n unwrap_err(): Error {\n throw new Error(\"Result is Ok\");\n }\n unwrap(): T {\n return this._t;\n }\n}\n\nexport class ResultError<T extends Error> extends Result<never, T> {\n private _error: T;\n constructor(t: T) {\n super();\n this._error = t;\n }\n is_ok(): boolean {\n return false;\n }\n is_err(): boolean {\n return true;\n }\n unwrap(): never {\n throw new Error(`Result is Err: ${this._error}`);\n }\n unwrap_err(): T {\n return this._error;\n }\n}\n\nexport type WithoutResult<T> = T extends Result<infer U> ? U : T;\n\n/*\n\ntype FinalizedResult<T> = {\n result: T;\n scopeResult?: Result<void>;\n finally: () => Promise<void>;\n}\n\ntype exection2ResultParam<T> = {\n init: () => Promise<T>;\n inScope?: (t: T) => Promise<void>;\n cleanup: (t: T) => Promise<void>;\n\n}\n\nasync function expection2Result<T>({fn, inScope, cleanup}: exection2ResultParam<T>): Promise<Result<FinalizedResult<T>>> {\n try {\n const res = await fn();\n if (inScope) {\n try {\n await inScope?.(res)\n } catch (err) {\n return Result.Err(err as Error)\n }\n await cleanup(res)\n return Result.Ok({\n result: res,\n finally: async () => { }\n })\n }\n return Result.Ok({\n result: res ,\n finally: async () => {\n return cleanup(res)\n }\n })\n } catch (err) {\n return Result.Err(err as Error)\n }\n}\n*/\n\n// await expection2Result({\n// init: openDB,\n// inScope: (res) => {\n// res.query()\n// },\n// cleanup: async (y) => {\n// await y.close()\n// }\n// })\n// async function openDB() {\n// try {\n// const opendb = await openDB()\n// return Result.Ok({\n// openDB,\n// finally: async () => {\n// await opendb.close()\n// }})\n// } catch (err) {\n// return Result.Err(err)\n// }\n// }\n// }\n","export abstract class Option<T> {\n static Some<T>(t: T): Option<T> {\n return new Some(t);\n }\n\n static None<T>(): Option<T> {\n return new None();\n }\n\n static Is<T>(t: unknown): t is Option<T> {\n return t instanceof Option;\n }\n\n IsNone(): boolean {\n return this.is_none();\n }\n\n IsSome(): boolean {\n return this.is_some();\n }\n Unwrap(): T {\n return this.unwrap();\n }\n\n abstract is_none(): boolean;\n abstract is_some(): boolean;\n abstract unwrap(): T;\n}\n\nexport class Some<T> extends Option<T> {\n private _t: T;\n constructor(_t: T) {\n super();\n this._t = _t;\n }\n\n is_none(): boolean {\n return false;\n }\n is_some(): boolean {\n return true;\n }\n unwrap(): T {\n return this._t;\n }\n}\n\nexport class None<T> extends Option<T> {\n is_none(): boolean {\n return true;\n }\n is_some(): boolean {\n return false;\n }\n unwrap(): T {\n throw new Error(\"None.unwrap\");\n }\n}\n\nexport type WithoutOption<T> = T extends Option<infer U> ? U : T;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAEO,IAAK,QAAL,kBAAKA,WAAL;AACL,EAAAA,OAAA,UAAO;AACP,EAAAA,OAAA,WAAQ;AACR,EAAAA,OAAA,UAAO;AACP,EAAAA,OAAA,WAAQ;AAJE,SAAAA;AAAA,GAAA;AAUL,IAAM,WAAN,MAAe;AAAA,EACpB,YAAqB,IAAkB;AAA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KAAK,QAAQ;AAAA,EACtB;AAAA,EACA,SAAY;AACV,WAAO,KAAK,OAAO;AAAA,EACrB;AAKF;AAEO,IAAM,OAAN,cAAsB,OAAU;AAAA,EAErC,YAAY,IAAO;AACjB,UAAM;AACN,SAAK,KAAK;AAAA,EACZ;AAAA,EAEA,UAAmB;AACjB,WAAO;AAAA,EACT;AAAA,EACA,UAAmB;AACjB,WAAO;AAAA,EACT;AAAA,EACA,SAAY;AACV,WAAO,KAAK;AAAA,EACd;AACF;AAEO,IAAM,OAAN,cAAsB,OAAU;AAAA,EACrC,UAAmB;AACjB,WAAO;AAAA,EACT;AAAA,EACA,UAAmB;AACjB,WAAO;AAAA,EACT;AAAA,EACA,SAAY;AACV,UAAM,IAAI,MAAM,aAAa;AAAA,EAC/B;AACF;","names":["Level","LogWriter"]}
|
1
|
+
{"version":3,"sources":["../../src/logger.ts","../../src/logger_impl.ts","../../src/test/log_collector.ts","../../src/test/mock_logger.ts","../../src/result.ts","../../src/option.ts","../../src/runtime.ts","../../src/uri.ts","../../src/crypto.ts"],"sourcesContent":["import { Result } from \"./result\";\nimport { URI } from \"./uri\";\n\nexport enum Level {\n WARN = \"warn\",\n DEBUG = \"debug\",\n INFO = \"info\",\n ERROR = \"error\",\n}\n\nexport type Serialized = string | number | boolean;\nexport type FnSerialized = () => Serialized;\n\nexport class LogValue {\n constructor(readonly fn: FnSerialized) {}\n value(): Serialized {\n return this.fn();\n }\n toJSON(): Serialized {\n return this.value();\n }\n}\n\nexport type LogSerializable = Record<string, LogValue | Promise<LogValue>>;\n\nexport function removeSelfRef(): (key: unknown, val: unknown) => unknown {\n const cache = new Set();\n return function (key: unknown, value: unknown) {\n if (typeof value === \"object\" && value !== null) {\n // Duplicate reference found, discard key\n if (cache.has(value)) return \"...\";\n cache.add(value);\n }\n return value;\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function asyncLogValue(val: () => Promise<Serialized>): Promise<LogValue> {\n // return Promise.resolve(logValue(val));\n throw new Error(\"Not implemented\");\n}\n\nexport function logValue(val: Serialized | FnSerialized | LogSerializable | undefined | null): LogValue {\n switch (typeof val) {\n case \"function\":\n return new LogValue(val);\n case \"string\":\n return new LogValue(() => val.toString());\n case \"number\":\n return new LogValue(() => val);\n case \"boolean\":\n return new LogValue(() => val);\n case \"object\":\n return new LogValue(() => JSON.parse(JSON.stringify(val, removeSelfRef())));\n default:\n if (!val) {\n return new LogValue(() => \"--Falsy--\");\n }\n throw new Error(`Invalid type:${typeof val}`);\n }\n}\n\nexport interface Sized {\n size: number;\n}\nexport interface Lengthed {\n length: number;\n}\nexport type SizeOrLength = Sized | Lengthed;\n\nexport interface LoggerInterface<R> {\n Module(key: string): R;\n // if modules is empty, set for all Levels\n EnableLevel(level: Level, ...modules: string[]): R;\n DisableLevel(level: Level, ...modules: string[]): R;\n\n SetDebug(...modules: (string | string[])[]): R;\n\n Ref(key: string, action: { toString: () => string } | FnSerialized): R;\n Result<T>(key: string, res: Result<T>): R;\n // default key url\n Url(url: URL | URI | string, key?: string): R;\n // len\n Len(value: unknown, key?: string): R;\n\n Hash(value: unknown, key?: string): R;\n\n Str(key: string, value?: string): R;\n Error(): R;\n Warn(): R;\n Debug(): R;\n Log(): R;\n WithLevel(level: Level): R;\n\n Err(err: unknown): R; // could be Error, or something which coerces to string\n Info(): R;\n Timestamp(): R;\n Any(key: string, value: unknown): R;\n Dur(key: string, nsec: number): R;\n Uint64(key: string, value: number): R;\n Int(key: string, value: number): R;\n Bool(key: string, value: unknown): R;\n}\n\nexport function IsLogger(obj: unknown): obj is Logger {\n return (\n typeof obj === \"object\" &&\n [\n \"Module\",\n \"EnableLevel\",\n \"DisableLevel\",\n \"SetDebug\",\n \"Str\",\n \"Error\",\n \"Warn\",\n \"Debug\",\n \"Log\",\n \"WithLevel\",\n \"Err\",\n \"Info\",\n \"Timestamp\",\n \"Any\",\n \"Dur\",\n \"Uint64\",\n ]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map((fn) => typeof (obj as any)[fn] === \"function\")\n .reduce((a, b) => a && b, true)\n );\n}\n\nexport interface WithLogger extends LoggerInterface<WithLogger> {\n Logger(): Logger;\n}\n\nexport interface AsError {\n AsError(): Error;\n}\n\nexport interface Logger extends LoggerInterface<Logger> {\n With(): WithLogger;\n\n Msg(...args: string[]): AsError;\n Flush(): Promise<void>;\n}\n","// import { v4 } from \"uuid\";\nimport {\n AsError,\n FnSerialized,\n LogSerializable,\n Level,\n Logger,\n logValue,\n Serialized,\n WithLogger,\n removeSelfRef,\n Sized,\n Lengthed,\n LogValue,\n asyncLogValue,\n} from \"./logger\";\nimport { WebSysAbstraction } from \"./web/web_sys_abstraction\";\nimport { SysAbstraction } from \"./sys_abstraction\";\nimport { Result } from \"./result\";\nimport { URI } from \"./uri\";\n\nconst encoder = new TextEncoder();\n\n// function resolveLogValue(val: LogSerializable): Record<string, Serialized> {\n// const ret: Record<string, Serialized> = {};\n// Object.keys(val).forEach((key) => {\n// const v = val[key];\n// if (v instanceof LogValue) {\n// ret[key] = v.value();\n// }\n// });\n// return ret;\n// }\n\nexport interface LevelHandler {\n enableLevel(level: Level, ...modules: string[]): void;\n disableLevel(level: Level, ...modules: string[]): void;\n setDebug(...modules: (string | string[])[]): void;\n isEnabled(ilevel: unknown, module: unknown): boolean;\n}\n\nexport class LevelHandlerImpl implements LevelHandler {\n readonly _globalLevels = new Set<Level>([Level.INFO, Level.ERROR, Level.WARN]);\n readonly _modules = new Map<string, Set<Level>>();\n enableLevel(level: Level, ...modules: string[]): void {\n if (modules.length == 0) {\n this._globalLevels.add(level);\n return;\n }\n this.forModules(\n level,\n (p) => {\n this._modules.set(p, new Set([...this._globalLevels, level]));\n },\n ...modules,\n );\n }\n disableLevel(level: Level, ...modules: string[]): void {\n if (modules.length == 0) {\n this._globalLevels.delete(level);\n return;\n }\n this.forModules(\n level,\n (p) => {\n this._modules.delete(p);\n },\n ...modules,\n );\n }\n\n forModules(level: Level, fnAction: (p: string) => void, ...modules: (string | string[])[]): void {\n for (const m of modules.flat()) {\n if (typeof m !== \"string\") {\n continue;\n }\n const parts = m\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length);\n for (const p of parts) {\n fnAction(p);\n }\n }\n }\n setDebug(...modules: (string | string[])[]): void {\n this.forModules(\n Level.DEBUG,\n (p) => {\n this._modules.set(p, new Set([...this._globalLevels, Level.DEBUG]));\n },\n ...modules,\n );\n }\n isEnabled(ilevel: unknown, module: unknown): boolean {\n const level = ilevel as Level; // what if it's not a level?\n if (typeof module === \"string\") {\n const levels = this._modules.get(module);\n if (levels && levels.has(level)) {\n return true;\n }\n }\n const wlevel = this._modules.get(\"*\");\n if (wlevel && typeof level === \"string\") {\n if (wlevel.has(level)) {\n return true;\n }\n }\n if (typeof level !== \"string\") {\n // this is a plain log\n return true;\n }\n return this._globalLevels.has(level);\n }\n}\n\nconst levelSingleton = new LevelHandlerImpl();\n\n// globalThis[Symbol(\"levelSingleton\")] = new LevelHandlerImpl()\n\nexport class LogWriter {\n readonly _out: WritableStream<Uint8Array>;\n readonly _toFlush: (() => Promise<void>)[] = [];\n\n constructor(out: WritableStream<Uint8Array>) {\n this._out = out;\n }\n\n write(encoded: Uint8Array) {\n const my = async () => {\n // const val = Math.random();\n // console.log(\">>>My:\", val)\n try {\n const writer = this._out.getWriter();\n await writer.ready;\n await writer.write(encoded);\n await writer.releaseLock();\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"Chunk error:\", err);\n }\n // console.log(\"<<<My:\", val)\n };\n this._toFlush.push(my);\n this._flush();\n }\n\n _flushIsRunning = false;\n _flushDoneFns = Array<() => void>();\n _flush(toFlush: (() => Promise<void>)[] | undefined = undefined, done?: () => void): void {\n if (done) {\n this._flushDoneFns.push(done);\n }\n\n if (this._toFlush.length == 0) {\n // console.log(\"Flush is stopped\", this._toFlush.length)\n this._flushIsRunning = false;\n this._flushDoneFns.forEach((fn) => fn());\n this._flushDoneFns = [];\n return;\n }\n\n if (!toFlush && this._toFlush.length == 1 && !this._flushIsRunning) {\n this._flushIsRunning = true;\n // console.log(\"Flush is started\", this._toFlush.length)\n } else if (!toFlush) {\n // console.log(\"flush queue check but is running\", this._toFlush.length)\n return;\n }\n\n // console.log(\">>>Msg:\", this._toFlush.length)\n const my = this._toFlush.shift();\n my?.().finally(() => {\n // console.log(\"<<<Msg:\", this._toFlush.length)\n this._flush(this._toFlush);\n });\n }\n}\n\nfunction getLen(value: unknown): LogValue {\n if (Array.isArray(value)) {\n return logValue(() => value.length);\n } else if (typeof value === \"string\") {\n return logValue(() => value.length);\n } else if (typeof value === \"object\" && value !== null) {\n if (typeof (value as Sized).size === \"number\") {\n return logValue(() => (value as Sized).size);\n } else if (typeof (value as Lengthed).length === \"number\") {\n return logValue(() => (value as Lengthed).length);\n }\n return logValue(() => Object.keys(value).length);\n }\n return logValue(() => -1);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction hash(value: unknown): string {\n // const hasher = createHash(\"sha256\");\n // hasher.update(JSON.stringify(value, removeSelfRef()));\n // return hasher.digest(\"hex\");\n return \"not implemented\";\n}\n\nfunction toLogValue(lop: LogValue | Promise<LogValue>): LogValue | undefined {\n if (lop && typeof (lop as Promise<LogValue>).then === \"function\") {\n throw new Error(\"async logValue Not implemented\");\n }\n return lop as LogValue;\n}\n\nexport interface LoggerImplParams {\n readonly out?: WritableStream<Uint8Array>;\n readonly logWriter?: LogWriter;\n readonly sys?: SysAbstraction;\n readonly withAttributes?: LogSerializable;\n readonly levelHandler?: LevelHandler;\n}\nexport class LoggerImpl implements Logger {\n readonly _sys: SysAbstraction;\n readonly _attributes: LogSerializable = {};\n readonly _withAttributes: LogSerializable;\n readonly _logWriter: LogWriter;\n readonly _levelHandler: LevelHandler;\n // readonly _id: string = \"logger-\" + Math.random().toString(36)\n\n constructor(params?: LoggerImplParams) {\n if (!params) {\n params = {};\n }\n if (!params.sys) {\n this._sys = WebSysAbstraction();\n } else {\n this._sys = params.sys;\n }\n if (params.logWriter) {\n this._logWriter = params.logWriter;\n } else {\n if (!params.out) {\n this._logWriter = new LogWriter(this._sys.Stdout());\n } else {\n this._logWriter = new LogWriter(params.out);\n }\n }\n if (!params.withAttributes) {\n this._withAttributes = {};\n } else {\n this._withAttributes = { ...params.withAttributes };\n }\n this._attributes = { ...this._withAttributes };\n if (params.levelHandler) {\n this._levelHandler = params.levelHandler;\n } else {\n this._levelHandler = levelSingleton;\n }\n // console.log(\"LoggerImpl\", this._id, this._attributes, this._withAttributes)\n }\n\n EnableLevel(level: Level, ...modules: string[]): Logger {\n this._levelHandler.enableLevel(level, ...modules);\n return this;\n }\n DisableLevel(level: Level, ...modules: string[]): Logger {\n this._levelHandler.disableLevel(level, ...modules);\n return this;\n }\n\n Module(key: string): Logger {\n this._attributes[\"module\"] = logValue(key);\n this._withAttributes[\"module\"] = logValue(key);\n return this;\n }\n // if the string is \"*\" it will enable for all modules\n SetDebug(...modules: (string | string[])[]): Logger {\n this._levelHandler.setDebug(...modules);\n return this;\n }\n\n Timestamp(): Logger {\n // this is called with .call from _produceError where this\n // this is crafted to have _sys and _attributes\n // CAUTION so done use other ref from this\n this._attributes[\"ts\"] = logValue(this._sys.Time().Now().toISOString());\n return this;\n }\n Warn(): Logger {\n this._attributes[\"level\"] = logValue(Level.WARN);\n return this;\n }\n Log(): Logger {\n return this;\n }\n Debug(): Logger {\n this._attributes[\"level\"] = logValue(Level.DEBUG);\n return this;\n }\n Error(): Logger {\n this._attributes[\"level\"] = logValue(Level.ERROR);\n return this;\n }\n Info(): Logger {\n this._attributes[\"level\"] = logValue(Level.INFO);\n return this;\n }\n Err(err: unknown): Logger {\n if (err instanceof Error) {\n this._attributes[\"error\"] = logValue(err.message);\n } else {\n this._attributes[\"error\"] = logValue(\"\" + err);\n }\n return this;\n }\n WithLevel(l: Level): Logger {\n this._attributes[\"level\"] = logValue(l);\n return this;\n }\n\n Ref(key: string, action: { toString: () => string } | FnSerialized): Logger {\n if (typeof action === \"function\") {\n this._attributes[key] = logValue(action as FnSerialized);\n } else if (typeof action.toString === \"function\") {\n this._attributes[key] = logValue(() => action.toString());\n } else {\n this._attributes[key] = logValue(\"INVALID REF\");\n }\n return this;\n }\n Bool(key: string, value: unknown): Logger {\n this._attributes[key] = logValue(!!value);\n return this;\n }\n Result<T>(key: string, res: Result<T, Error>): Logger {\n if (res.isOk()) {\n this._attributes[key] = logValue(res.Ok() as Serialized);\n } else {\n this.Err(res.Err());\n }\n return this;\n }\n\n Len(value: unknown, key = \"len\"): Logger {\n this._attributes[key] = getLen(value);\n return this;\n }\n\n Hash(value: unknown, key = \"hash\"): Logger {\n this._attributes[key] = asyncLogValue(async () => `${getLen(value).value()}:${await hash(value)}`);\n return this;\n }\n\n Url(url: URL | URI | string, key = \"url\"): Logger {\n this.Ref(key, () => url.toString());\n return this;\n }\n\n Str(key: string, value?: string): Logger {\n this._attributes[key] = logValue(value);\n return this;\n }\n\n Any(key: string, value?: string | number | boolean | LogSerializable): Logger {\n this._attributes[key] = logValue(value);\n return this;\n }\n Dur(key: string, nsec: number): Logger {\n this._attributes[key] = logValue(`${nsec}ms`);\n // new Intl.DurationFormat(\"en\", { style: \"narrow\" }).format(nsec);\n return this;\n }\n Uint64(key: string, value: number): Logger {\n this._attributes[key] = logValue(value);\n return this;\n }\n Int(key: string, value: number): Logger {\n return this.Uint64(key, value);\n }\n\n async Flush(): Promise<void> {\n return new Promise((resolve) => {\n this._logWriter._flush(undefined, resolve);\n });\n }\n\n With(): WithLogger {\n // console.log(\"WithLoggerBuilder.With\", this._id, this._attributes, this._withAttributes);\n return new WithLoggerBuilder(\n new LoggerImpl({\n logWriter: this._logWriter,\n sys: this._sys,\n levelHandler: this._levelHandler,\n withAttributes: {\n module: this._attributes[\"module\"],\n ...this._withAttributes,\n },\n }),\n );\n }\n\n _resetAttributes(fn: () => () => string): () => string {\n const ret = fn();\n Object.keys(this._attributes).forEach((key) => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._attributes[key];\n });\n Object.assign(this._attributes, this._withAttributes);\n return ret;\n }\n _produceError(attr: LogSerializable, ...args: string[]): string {\n attr[\"msg\"] = logValue(args.join(\" \"));\n const msg = attr[\"msg\"].value();\n if (typeof msg === \"string\" && !msg.trim().length) {\n delete attr[\"msg\"];\n }\n if (toLogValue(attr[\"ts\"])?.value() === \"ETERNITY\") {\n // hacky but it works\n this.Timestamp.call({\n _sys: this._sys,\n _attributes: attr,\n });\n }\n return JSON.stringify(attr, removeSelfRef());\n }\n\n Msg(...args: string[]): AsError {\n const fnError = this._resetAttributes(() => {\n const doWrite = this._levelHandler.isEnabled(\n toLogValue(this._attributes[\"level\"])?.value(),\n toLogValue(this._attributes[\"module\"])?.value(),\n );\n let fnRet = () => this._produceError({ ...this._attributes }, ...args);\n if (doWrite) {\n const str = fnRet();\n const encoded = encoder.encode(str + \"\\n\");\n this._logWriter.write(encoded);\n fnRet = () => str;\n }\n return fnRet;\n });\n return {\n AsError: () => new Error(fnError()),\n };\n }\n}\n\nclass WithLoggerBuilder implements WithLogger {\n readonly _li: LoggerImpl;\n constructor(li: LoggerImpl) {\n this._li = li;\n }\n\n Logger(): Logger {\n Object.assign(this._li._withAttributes, this._li._attributes);\n return this._li;\n }\n\n EnableLevel(level: Level, ...modules: string[]): WithLogger {\n this._li._levelHandler.enableLevel(level, ...modules);\n return this;\n }\n DisableLevel(level: Level, ...modules: string[]): WithLogger {\n this._li._levelHandler.enableLevel(level, ...modules);\n return this;\n }\n\n Module(key: string): WithLogger {\n this._li.Module(key);\n return this;\n }\n SetDebug(...modules: (string | string[])[]): WithLogger {\n this._li.SetDebug(...modules);\n return this;\n }\n\n Str(key: string, value?: string): WithLogger {\n this._li.Str(key, value);\n return this;\n }\n\n Len(value: unknown, key?: string): WithLogger {\n this._li.Len(value, key);\n return this;\n }\n\n Hash(value: unknown, key?: string): WithLogger {\n this._li.Hash(value, key);\n return this;\n }\n\n Ref(key: string, action: Serialized | FnSerialized): WithLogger {\n this._li.Ref(key, action);\n return this;\n }\n Bool(key: string, value: unknown): WithLogger {\n this._li.Bool(key, value);\n return this;\n }\n Result<T>(key: string, res: Result<T, Error>): WithLogger {\n this._li.Result(key, res);\n return this;\n }\n Url(url: URL, key?: string): WithLogger {\n this._li.Url(url, key);\n return this;\n }\n Int(key: string, value: number): WithLogger {\n this._li.Int(key, value);\n return this;\n }\n\n Log(): WithLogger {\n this._li.Log();\n return this;\n }\n\n WithLevel(level: Level): WithLogger {\n this._li.WithLevel(level);\n return this;\n }\n\n Error(): WithLogger {\n this._li.Error();\n return this;\n }\n Warn(): WithLogger {\n this._li.Error();\n return this;\n }\n Debug(): WithLogger {\n this._li.Debug();\n return this;\n }\n Err(err: unknown): WithLogger {\n this._li.Err(err);\n return this;\n }\n Info(): WithLogger {\n this._li.Info();\n return this;\n }\n Timestamp(): WithLogger {\n this._li._attributes[\"ts\"] = logValue(\"ETERNITY\");\n return this;\n }\n Any(key: string, value: LogSerializable): WithLogger {\n this._li.Any(key, value);\n return this;\n }\n Dur(key: string, nsec: number): WithLogger {\n this._li.Dur(key, nsec);\n return this;\n }\n Uint64(key: string, value: number): WithLogger {\n this._li.Uint64(key, value);\n return this;\n }\n}\n","class LogWriter implements WritableStreamDefaultWriter<Uint8Array> {\n readonly _bufferArr: Uint8Array[] = [];\n\n _resolveClosed: (value?: PromiseLike<undefined>) => void;\n closed: Promise<undefined>;\n desiredSize: number | null = null;\n ready: Promise<undefined> = Promise.resolve(undefined);\n\n constructor() {\n this._resolveClosed = () => {\n // do nothing\n };\n this.closed = new Promise((resolve) => {\n this._resolveClosed = resolve;\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any\n abort(reason?: any): Promise<void> {\n throw new Error(\"Method not implemented.\");\n }\n close(): Promise<void> {\n this._resolveClosed();\n return Promise.resolve(undefined);\n }\n releaseLock(): void {\n // do nothing\n }\n write(chunk?: Uint8Array): Promise<void> {\n if (chunk) {\n this._bufferArr.push(chunk);\n }\n return Promise.resolve(undefined);\n }\n}\n\nexport class LogCollector implements WritableStream<Uint8Array> {\n readonly locked: boolean = false;\n _writer?: LogWriter;\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n abort(reason?: Uint8Array): Promise<void> {\n throw new Error(\"Method not implemented.\");\n }\n\n async close(): Promise<void> {\n if (this._writer) {\n const ret = await this._writer.close();\n this._writer = undefined;\n return ret;\n }\n return Promise.resolve(undefined);\n }\n\n getWriter(): WritableStreamDefaultWriter<Uint8Array> {\n if (!this._writer) {\n this._writer = new LogWriter();\n }\n return this._writer;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Logs(): any[] {\n if (!this._writer) {\n return [];\n }\n const jsonNlStr = new TextDecoder().decode(\n new Uint8Array(\n (function* (res: Uint8Array[]) {\n for (const x of res) {\n yield* x;\n }\n })(this._writer._bufferArr),\n ),\n );\n const splitStr = jsonNlStr.split(\"\\n\");\n const filterStr = splitStr.filter((a) => a.length);\n const mapStr = filterStr.map((a) => JSON.parse(a));\n return mapStr;\n }\n}\n","import { Logger } from \"../logger\";\nimport { LevelHandlerImpl, LoggerImpl } from \"../logger_impl\";\nimport { SysAbstraction } from \"../sys_abstraction\";\nimport { LogCollector } from \"./log_collector\";\n\nexport interface MockLoggerReturn {\n readonly logger: Logger;\n readonly logCollector: LogCollector;\n}\n\nexport function MockLogger(params?: {\n readonly sys?: SysAbstraction;\n moduleName?: string | string[];\n readonly disableDebug?: boolean;\n}): MockLoggerReturn {\n const lc = new LogCollector();\n let modNames = [\"MockLogger\"];\n if (typeof params?.moduleName === \"string\") {\n modNames = [params?.moduleName];\n } else if (Array.isArray(params?.moduleName)) {\n modNames = [...params.moduleName, ...modNames];\n }\n const logger = new LoggerImpl({\n out: lc,\n sys: params?.sys,\n levelHandler: new LevelHandlerImpl(),\n })\n .With()\n .Module(modNames[0])\n .Logger();\n if (!params?.disableDebug) {\n logger.SetDebug(...modNames);\n }\n return {\n logCollector: lc,\n logger,\n };\n}\n","export abstract class Result<T, E = Error> {\n static Ok<T>(t: T): Result<T, Error> {\n return new ResultOK(t);\n }\n static Err<T extends Error = Error>(t: T | string): Result<never, T> {\n if (typeof t === \"string\") {\n return new ResultError(new Error(t) as T);\n }\n return new ResultError(t);\n }\n static Is<T>(t: unknown): t is Result<T> {\n if (!t) {\n return false;\n }\n if (t instanceof Result) {\n return true;\n }\n const rt = t as Result<T>;\n if ([typeof rt.is_ok, typeof rt.is_err, typeof rt.unwrap, typeof rt.unwrap_err].every((x) => x === \"function\")) {\n return true;\n }\n return false;\n }\n\n isOk(): boolean {\n return this.is_ok();\n }\n isErr(): boolean {\n return this.is_err();\n }\n\n Ok(): T {\n return this.unwrap();\n }\n Err(): E {\n return this.unwrap_err();\n }\n\n abstract is_ok(): boolean;\n abstract is_err(): boolean;\n abstract unwrap(): T;\n abstract unwrap_err(): E;\n}\n\nexport class ResultOK<T> extends Result<T, Error> {\n private _t: T;\n constructor(t: T) {\n super();\n this._t = t;\n }\n is_ok(): boolean {\n return true;\n }\n is_err(): boolean {\n return false;\n }\n unwrap_err(): Error {\n throw new Error(\"Result is Ok\");\n }\n unwrap(): T {\n return this._t;\n }\n}\n\nexport class ResultError<T extends Error> extends Result<never, T> {\n private _error: T;\n constructor(t: T) {\n super();\n this._error = t;\n }\n is_ok(): boolean {\n return false;\n }\n is_err(): boolean {\n return true;\n }\n unwrap(): never {\n throw new Error(`Result is Err: ${this._error}`);\n }\n unwrap_err(): T {\n return this._error;\n }\n}\n\nexport type WithoutResult<T> = T extends Result<infer U> ? U : T;\n\n/*\n\ntype FinalizedResult<T> = {\n result: T;\n scopeResult?: Result<void>;\n finally: () => Promise<void>;\n}\n\ntype exection2ResultParam<T> = {\n init: () => Promise<T>;\n inScope?: (t: T) => Promise<void>;\n cleanup: (t: T) => Promise<void>;\n\n}\n\nasync function expection2Result<T>({fn, inScope, cleanup}: exection2ResultParam<T>): Promise<Result<FinalizedResult<T>>> {\n try {\n const res = await fn();\n if (inScope) {\n try {\n await inScope?.(res)\n } catch (err) {\n return Result.Err(err as Error)\n }\n await cleanup(res)\n return Result.Ok({\n result: res,\n finally: async () => { }\n })\n }\n return Result.Ok({\n result: res ,\n finally: async () => {\n return cleanup(res)\n }\n })\n } catch (err) {\n return Result.Err(err as Error)\n }\n}\n*/\n\n// await expection2Result({\n// init: openDB,\n// inScope: (res) => {\n// res.query()\n// },\n// cleanup: async (y) => {\n// await y.close()\n// }\n// })\n// async function openDB() {\n// try {\n// const opendb = await openDB()\n// return Result.Ok({\n// openDB,\n// finally: async () => {\n// await opendb.close()\n// }})\n// } catch (err) {\n// return Result.Err(err)\n// }\n// }\n// }\n","export abstract class Option<T> {\n static Some<T>(t: T): Option<T> {\n return new Some(t);\n }\n\n static None<T>(): Option<T> {\n return new None();\n }\n\n static Is<T>(t: unknown): t is Option<T> {\n return t instanceof Option;\n }\n\n IsNone(): boolean {\n return this.is_none();\n }\n\n IsSome(): boolean {\n return this.is_some();\n }\n Unwrap(): T {\n return this.unwrap();\n }\n\n abstract is_none(): boolean;\n abstract is_some(): boolean;\n abstract unwrap(): T;\n}\n\nexport class Some<T> extends Option<T> {\n private _t: T;\n constructor(_t: T) {\n super();\n this._t = _t;\n }\n\n is_none(): boolean {\n return false;\n }\n is_some(): boolean {\n return true;\n }\n unwrap(): T {\n return this._t;\n }\n}\n\nexport class None<T> extends Option<T> {\n is_none(): boolean {\n return true;\n }\n is_some(): boolean {\n return false;\n }\n unwrap(): T {\n throw new Error(\"None.unwrap\");\n }\n}\n\nexport type WithoutOption<T> = T extends Option<infer U> ? U : T;\n","export interface Runtime {\n isNodeIsh: boolean;\n isBrowser: boolean;\n isDeno: boolean;\n isReactNative: boolean;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction isSet(value: string, ref: any = globalThis): boolean {\n const [head, ...tail] = value.split(\".\");\n if ([\"object\", \"function\"].includes(typeof ref) && ref && [\"object\", \"function\"].includes(typeof ref[head]) && ref[head]) {\n if (tail.length <= 1) {\n return true;\n }\n return isSet(tail.join(\".\"), ref[head]);\n }\n return false;\n}\n\nexport function runtimeFn(): Runtime {\n const isNodeIsh = isSet(\"process.versions.node\");\n const isDeno = isSet(\"Deno\");\n return {\n isNodeIsh,\n isBrowser: !(isNodeIsh || isDeno),\n isDeno,\n isReactNative: false,\n };\n}\n","type NullOrUndef = null | undefined;\n\nfunction falsy2undef<T>(value: T | NullOrUndef): T | undefined {\n return value === undefined || value === null ? undefined : value;\n}\n\nfunction ensureURLWithDefaultProto(url: string | URL, defaultProtocol: string): URL {\n if (!url) {\n return new URL(`${defaultProtocol}//`);\n }\n if (typeof url === \"string\") {\n try {\n return new URL(url);\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n return new URL(`${defaultProtocol}//${url}`);\n }\n } else {\n return url;\n }\n}\n\nexport class BuildURI {\n private _url: URL;\n constructor(url: URL) {\n this._url = url;\n }\n\n hostname(h: string) {\n this._url.hostname = h;\n return this;\n }\n\n password(p: string) {\n this._url.password = p;\n return this;\n }\n\n port(p: string) {\n this._url.port = p;\n return this;\n }\n\n username(u: string) {\n this._url.username = u;\n return this;\n }\n\n search(s: string) {\n this._url.search = s;\n return this;\n }\n\n protocol(p: string) {\n this._url.protocol = p;\n return this;\n }\n\n pathname(p: string) {\n this._url.pathname = p;\n return this;\n }\n\n hash(h: string) {\n this._url.hash = h;\n return this;\n }\n\n host(h: string) {\n this._url.host = h;\n return this;\n }\n\n delParam(key: string) {\n this._url.searchParams.delete(key);\n return this;\n }\n\n setParam(key: string, str: string) {\n this._url.searchParams.set(key, str);\n return this;\n }\n\n toString(): string {\n return this._url.toString();\n }\n\n build(): URI {\n return URI.from(this._url);\n }\n}\n\nexport type CoerceURI = string | URL | URI | NullOrUndef;\n\n// non mutable URL Implementation\nexport class URI {\n // if no protocol is provided, default to file:\n static from(strURLUri: CoerceURI, defaultProtocol = \"file:\"): URI {\n switch (typeof falsy2undef(strURLUri)) {\n case \"undefined\":\n return new URI(new URL(`${defaultProtocol}//`));\n case \"string\":\n return new URI(ensureURLWithDefaultProto(strURLUri as string, defaultProtocol));\n case \"object\":\n if (strURLUri instanceof URI) {\n return new URI(new URL(strURLUri._url.toString()));\n } else if (strURLUri instanceof URL) {\n return new URI(new URL(strURLUri.toString()));\n }\n throw new Error(`unknown object type: ${strURLUri}`);\n default:\n throw new Error(`Invalid argument: ${typeof strURLUri}`);\n }\n }\n\n readonly _url: URL;\n private constructor(url: URL) {\n this._url = url;\n }\n\n build(): BuildURI {\n return new BuildURI(this.asURL());\n }\n\n get hostname(): string {\n return this._url.hostname;\n }\n\n get password(): string {\n return this._url.password;\n }\n\n get port(): string {\n return this._url.port;\n }\n\n get username(): string {\n return this._url.username;\n }\n\n get search(): string {\n return this._url.search;\n }\n\n get protocol(): string {\n return this._url.protocol;\n }\n\n get pathname(): string {\n return this._url\n .toString()\n .replace(/^.*:\\/\\//, \"\")\n .replace(/\\?.*$/, \"\");\n }\n\n get hash(): string {\n return this._url.hash;\n }\n\n get host(): string {\n return this._url.host;\n }\n\n hasParam(key: string): boolean {\n return this._url.searchParams.has(key);\n }\n getParam(key: string): string | undefined {\n return falsy2undef(this._url.searchParams.get(key));\n }\n\n clone(): URI {\n return new URI(this.asURL());\n }\n\n asURL(): URL {\n const url = new URL(this._url.toString());\n url.searchParams.sort();\n return url;\n }\n\n toString(): string {\n return this._url.toString();\n }\n}\n","export interface CTJsonWebKey {\n alg?: string;\n crv?: string;\n d?: string;\n dp?: string;\n dq?: string;\n e?: string;\n ext?: boolean;\n k?: string;\n key_ops?: string[];\n kty?: string;\n n?: string;\n oth?: RsaOtherPrimesInfo[];\n p?: string;\n q?: string;\n qi?: string;\n use?: string;\n x?: string;\n y?: string;\n}\n\nexport type CTKeyFormat = \"jwk\" | \"pkcs8\" | \"raw\" | \"spki\";\nexport type CTKeyUsage = \"decrypt\" | \"deriveBits\" | \"deriveKey\" | \"encrypt\" | \"sign\" | \"unwrapKey\" | \"verify\" | \"wrapKey\";\n\nexport interface CTAlgorithm {\n name: string;\n}\nexport type CTAlgorithmIdentifier = CTAlgorithm | string;\n\nexport interface CTRsaHashedImportParams extends CTAlgorithm {\n hash: CTAlgorithmIdentifier;\n}\n\nexport type CTNamedCurve = string;\nexport interface CTEcKeyImportParams extends CTAlgorithm {\n namedCurve: CTNamedCurve;\n}\n\nexport interface CTHmacImportParams extends CTAlgorithm {\n hash: CTAlgorithmIdentifier;\n length?: number;\n}\n\nexport interface CTAesKeyAlgorithm extends CTAlgorithm {\n length: number;\n}\n\nexport type CTKeyType = \"private\" | \"public\" | \"secret\";\n\nexport interface CTCryptoKey {\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) */\n readonly algorithm: CTAlgorithm;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) */\n readonly extractable: boolean;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) */\n readonly type: CTKeyType;\n /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) */\n readonly usages: CTKeyUsage[];\n}\n\ninterface CTArrayBufferTypes {\n ArrayBuffer: ArrayBuffer;\n}\ntype CTArrayBufferLike = CTArrayBufferTypes[keyof CTArrayBufferTypes];\n\nexport interface CTArrayBufferView {\n /**\n * The ArrayBuffer instance referenced by the array.\n */\n buffer: CTArrayBufferLike;\n\n /**\n * The length in bytes of the array.\n */\n byteLength: number;\n\n /**\n * The offset in bytes of the array.\n */\n byteOffset: number;\n}\n\nexport type CTBufferSource = CTArrayBufferView | ArrayBuffer;\n\nexport interface CryptoRuntime {\n importKey(\n format: CTKeyFormat,\n keyData: CTJsonWebKey | CTBufferSource,\n algorithm: CTAlgorithmIdentifier | CTRsaHashedImportParams | CTEcKeyImportParams | CTHmacImportParams | CTAesKeyAlgorithm,\n extractable: boolean,\n keyUsages: CTKeyUsage[],\n ): Promise<CTCryptoKey>;\n\n //(format: \"raw\", key: ArrayBuffer, algo: string, extractable: boolean, usages: string[]) => Promise<CryptoKey>;\n decrypt(algo: { name: string; iv: Uint8Array; tagLength: number }, key: CTCryptoKey, data: Uint8Array): Promise<ArrayBuffer>;\n encrypt(algo: { name: string; iv: Uint8Array; tagLength: number }, key: CTCryptoKey, data: Uint8Array): Promise<ArrayBuffer>;\n digestSHA256(data: Uint8Array): Promise<ArrayBuffer>;\n randomBytes(size: number): Uint8Array;\n}\n\nfunction randomBytes(size: number) {\n const bytes = new Uint8Array(size);\n if (size > 0) {\n crypto.getRandomValues(bytes);\n }\n return bytes;\n}\n\nfunction digestSHA256(data: Uint8Array): Promise<ArrayBuffer> {\n return Promise.resolve(crypto.subtle.digest(\"SHA-256\", data));\n}\n\nexport function toCryptoRuntime(cryptoOpts: Partial<CryptoRuntime> = {}): CryptoRuntime {\n const runtime = {\n importKey: cryptoOpts.importKey || crypto.subtle.importKey.bind(crypto.subtle),\n encrypt: cryptoOpts.encrypt || crypto.subtle.encrypt.bind(crypto.subtle),\n decrypt: cryptoOpts.decrypt || crypto.subtle.decrypt.bind(crypto.subtle),\n randomBytes: cryptoOpts.randomBytes || randomBytes,\n digestSHA256: cryptoOpts.digestSHA256 || digestSHA256,\n };\n // console.log(\"cryptoOpts\", cryptoOpts, opts)\n return runtime;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,IAAK,QAAL,kBAAKA,WAAL;AACL,EAAAA,OAAA,UAAO;AACP,EAAAA,OAAA,WAAQ;AACR,EAAAA,OAAA,UAAO;AACP,EAAAA,OAAA,WAAQ;AAJE,SAAAA;AAAA,GAAA;AAUL,IAAM,WAAN,MAAe;AAAA,EACpB,YAAqB,IAAkB;AAAlB;AAAA,EAAmB;AAAA,EACxC,QAAoB;AAClB,WAAO,KAAK,GAAG;AAAA,EACjB;AAAA,EACA,SAAqB;AACnB,WAAO,KAAK,MAAM;AAAA,EACpB;AACF;AAIO,SAAS,gBAAyD;AACvE,QAAM,QAAQ,oBAAI,IAAI;AACtB,SAAO,SAAU,KAAc,OAAgB;AAC7C,QA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;AAAA,EAC9B;AACA,SAAO;AACT;AAEA,SAAS,aAAa,MAAwC;AAC5D,SAAO,QAAQ,QAAQ,OAAO,OAAO,OAAO,WAAW,IAAI,CAAC;AAC9D;AAEO,SAAS,gBAAgB,aAAqC,CAAC,GAAkB;AACtF,QAAM,UAAU;AAAA,IACd,WAAW,WAAW,aAAa,OAAO,OAAO,UAAU,KAAK,OAAO,MAAM;AAAA,IAC7E,SAAS,WAAW,WAAW,OAAO,OAAO,QAAQ,KAAK,OAAO,MAAM;AAAA,IACvE,SAAS,WAAW,WAAW,OAAO,OAAO,QAAQ,KAAK,OAAO,MAAM;AAAA,IACvE,aAAa,WAAW,eAAe;AAAA,IACvC,cAAc,WAAW,gBAAgB;AAAA,EAC3C;AAEA,SAAO;AACT;","names":["Level","LogWriter"]}
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@adviser/cement",
|
3
|
-
"version": "0.2.
|
3
|
+
"version": "0.2.7",
|
4
4
|
"description": "better try/catch/finally handling",
|
5
5
|
"main": "index.js",
|
6
6
|
"type": "module",
|
@@ -34,16 +34,19 @@
|
|
34
34
|
},
|
35
35
|
"homepage": "https://github.com/mabels/cement#readme",
|
36
36
|
"devDependencies": {
|
37
|
-
"@types/node": "^
|
38
|
-
"@typescript-eslint/eslint-plugin": "^
|
39
|
-
"@typescript-eslint/parser": "^
|
40
|
-
"
|
37
|
+
"@types/node": "^22.0.0",
|
38
|
+
"@typescript-eslint/eslint-plugin": "^8.0.0",
|
39
|
+
"@typescript-eslint/parser": "^8.0.0",
|
40
|
+
"@vitest/browser": "^2.0.5",
|
41
|
+
"eslint": "^9.8.0",
|
41
42
|
"prettier": "^3.2.5",
|
42
43
|
"tsup": "^8.1.0",
|
43
44
|
"tsx": "^4.16.0",
|
44
45
|
"typescript": "^5.5.0",
|
45
|
-
"typescript-eslint": "^
|
46
|
-
"
|
46
|
+
"typescript-eslint": "^8.0.0",
|
47
|
+
"vite-tsconfig-paths": "^4.3.2",
|
48
|
+
"vitest": "^2.0.5",
|
49
|
+
"webdriverio": "^8.39.1"
|
47
50
|
},
|
48
51
|
"engines": {
|
49
52
|
"node": ">=16"
|
package/utils/index.cjs
CHANGED
@@ -42,7 +42,9 @@ function streamMap(s, sm) {
|
|
42
42
|
async pull(controller) {
|
43
43
|
const { done, value } = await state.reader.read();
|
44
44
|
if (done) {
|
45
|
-
|
45
|
+
if (state.streamMap.Close) {
|
46
|
+
state.streamMap.Close();
|
47
|
+
}
|
46
48
|
controller.close();
|
47
49
|
return;
|
48
50
|
}
|
package/utils/index.cjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/index.ts","../../../src/utils/stream_map.ts","../../../src/utils/rebuffer.ts","../../../src/utils/stream2string.ts","../../../src/utils/stream_test_helper.ts","../../../src/utils/string2stream.ts"],"sourcesContent":["export * from \"./rebuffer\";\nexport * from \"./stream_map\";\nexport * from \"./stream2string\";\nexport * from \"./stream_test_helper\";\nexport * from \"./string2stream\";\n","export interface StreamMap<T, U> {\n Map(s: T, idx: number): U | Promise<U>;\n readonly Close?: () => void;\n}\nexport function streamMap<T, U>(s: ReadableStream<T>, sm: StreamMap<T, U>): ReadableStream<U> {\n const state = { reader: s.getReader(), streamMap: sm, idx: 0 };\n return new ReadableStream<U>({\n async pull(controller) {\n const { done, value } = await state.reader.read();\n if (done) {\n state.streamMap.Close && state.streamMap.Close();\n controller.close();\n return;\n }\n const promiseOrU = state.streamMap.Map(value, state.idx++);\n let mapped: U;\n if (promiseOrU instanceof Promise || typeof (promiseOrU as { then: () => void }).then === \"function\") {\n mapped = await promiseOrU;\n } else {\n mapped = promiseOrU;\n }\n controller.enqueue(mapped);\n },\n });\n}\n\nexport async function devnull<T>(a: ReadableStream<T>): Promise<number> {\n const reader = a.getReader();\n let cnt = 0;\n while (true) {\n const { done } = await reader.read();\n if (done) {\n break;\n }\n cnt++;\n }\n return cnt;\n}\n\nexport function array2stream<T>(a: T[]): ReadableStream<T> {\n let i = 0;\n return new ReadableStream<T>({\n pull(controller) {\n if (i >= a.length) {\n controller.close();\n return;\n }\n controller.enqueue(a[i]);\n i++;\n },\n });\n}\n\nexport async function stream2array<T>(a: ReadableStream<T>): Promise<T[]> {\n const ret: T[] = [];\n const reader = a.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n ret.push(value);\n }\n return ret;\n}\n","import { array2stream, stream2array } from \"./stream_map\";\n\ninterface ReChunkResult {\n readonly rest: Uint8Array;\n readonly chunk: Uint8Array;\n}\n\nexport async function rebufferArray(a: Uint8Array[], chunkSize: number): Promise<Uint8Array[]> {\n return stream2array(rebuffer(array2stream(a), chunkSize));\n}\n\nfunction reChunk(cs: Uint8Array[], chunkSize: number): ReChunkResult {\n const len = cs.reduce((acc, v) => acc + v.length, 0);\n const last = cs[cs.length - 1];\n const lastOfs = len - last.length;\n // console.log(\"reChunk\", len, lastOfs, last.length, chunkSize, chunkSize - lastOfs)\n const rest = last.subarray(chunkSize - lastOfs);\n cs[cs.length - 1] = last.subarray(0, chunkSize - lastOfs);\n const chunk = new Uint8Array(chunkSize);\n let ofs = 0;\n for (const c of cs) {\n chunk.set(c, ofs);\n ofs += c.length;\n }\n return { rest, chunk };\n}\n\ninterface pumpState {\n readonly reader: ReadableStreamDefaultReader<Uint8Array>;\n tmp: Uint8Array[];\n tmpLen: number;\n readonly chunkSize: number;\n}\n\nfunction pump(ps: pumpState, controller: ReadableStreamDefaultController<Uint8Array>, next: () => void): void {\n ps.reader.read().then(({ done, value }) => {\n if (done) {\n if (ps.tmpLen > 0) {\n controller.enqueue(reChunk(ps.tmp, ps.tmpLen).chunk);\n }\n controller.close();\n next();\n return;\n }\n if (ps.tmpLen + value.length > ps.chunkSize) {\n ps.tmp.push(value);\n const res = reChunk(ps.tmp, ps.chunkSize);\n controller.enqueue(res.chunk);\n ps.tmp = [res.rest];\n ps.tmpLen = res.rest.length;\n next();\n return;\n } else if (value.length) {\n ps.tmp.push(value);\n ps.tmpLen += value.length;\n }\n pump(ps, controller, next);\n });\n}\n\nexport function rebuffer(a: ReadableStream<Uint8Array>, chunkSize: number): ReadableStream<Uint8Array> {\n const state: pumpState = {\n reader: a.getReader(),\n tmp: [],\n tmpLen: 0,\n chunkSize,\n };\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n return new Promise<void>((resolve) => {\n pump(state, controller, resolve);\n });\n },\n });\n}\n","export async function stream2string(stream?: ReadableStream<Uint8Array> | null, maxSize?: number): Promise<string> {\n if (!stream) {\n return Promise.resolve(\"\");\n }\n const reader = stream.getReader();\n let res = \"\";\n const decoder = new TextDecoder();\n let rSize = 0;\n while (typeof maxSize === \"undefined\" || rSize < maxSize) {\n try {\n const read = await reader.read();\n if (read.done) {\n break;\n }\n if (maxSize && rSize + read.value.length > maxSize) {\n read.value = read.value.slice(0, maxSize - rSize);\n }\n const block = decoder.decode(read.value, { stream: true });\n rSize += read.value.length;\n res += block;\n } catch (err) {\n return Promise.reject(err);\n }\n }\n return Promise.resolve(res);\n}\n\nexport async function stream2uint8array(stream?: ReadableStream<Uint8Array> | null): Promise<Uint8Array> {\n if (!stream) {\n return Promise.resolve(new Uint8Array());\n }\n const reader = stream.getReader();\n let res = new Uint8Array();\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n res = new Uint8Array([...res, ...value]);\n } catch (err) {\n return Promise.reject(err);\n }\n }\n return Promise.resolve(res);\n}\n","import { Mock } from \"vitest\";\n\ninterface mockValue {\n done: boolean;\n value: Uint8Array | undefined;\n fillCalls: number;\n reBufferCalls: number;\n}\nexport interface streamingTestState {\n readonly sendChunks: number;\n readonly sendChunkSize: number;\n fillCalls: number;\n CollectorFn: Mock<(mv: mockValue) => void>;\n}\n\nexport async function receiveFromStream(reb: ReadableStream<Uint8Array>, state: streamingTestState) {\n return new Promise<void>((resolve) => {\n let reBufferCalls = 0;\n const reader = reb.getReader();\n function pump() {\n reader.read().then(({ done, value }) => {\n state.CollectorFn({ done, value, fillCalls: state.fillCalls, reBufferCalls });\n reBufferCalls++;\n if (done) {\n resolve();\n return;\n }\n pump();\n });\n }\n pump();\n });\n}\n\nexport async function sendToStream(reb: WritableStream<Uint8Array>, state: streamingTestState) {\n return new Promise<void>((resolve) => {\n const writer = reb.getWriter();\n function pump(i: number) {\n if (i >= state.sendChunks) {\n writer.close();\n resolve();\n return;\n }\n writer.ready.then(() => {\n state.fillCalls++;\n writer.write(new Uint8Array(Array(state.sendChunkSize).fill(i)));\n pump(i + 1);\n });\n }\n pump(0);\n });\n}\n\n// it(\"does nothing\", () => {});\n","export function string2stream(str: string): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n return uint8array2stream(encoder.encode(str));\n}\n\nexport function uint8array2stream(str: Uint8Array): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(str);\n controller.close();\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIO,SAAS,UAAgB,GAAsB,IAAwC;AAC5F,QAAM,QAAQ,EAAE,QAAQ,EAAE,UAAU,GAAG,WAAW,IAAI,KAAK,EAAE;AAC7D,SAAO,IAAI,eAAkB;AAAA,IAC3B,MAAM,KAAK,YAAY;AACrB,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,MAAM,OAAO,KAAK;AAChD,UAAI,MAAM;AACR,cAAM,UAAU,SAAS,MAAM,UAAU,MAAM;AAC/C,mBAAW,MAAM;AACjB;AAAA,MACF;AACA,YAAM,aAAa,MAAM,UAAU,IAAI,OAAO,MAAM,KAAK;AACzD,UAAI;AACJ,UAAI,sBAAsB,WAAW,OAAQ,WAAoC,SAAS,YAAY;AACpG,iBAAS,MAAM;AAAA,MACjB,OAAO;AACL,iBAAS;AAAA,MACX;AAC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AACA,YAAI,MAAM;AACR,kBAAQ;AACR;AAAA,QACF;AACA,QAAAA,MAAK;AAAA,MACP,CAAC;AAAA,IACH;AACA,IAAAA,MAAK;AAAA,EACP,CAAC;AACH;AAEA,eAAsB,aAAa,KAAiC,OAA2B;AAC7F,SAAO,IAAI,QAAc,CAAC,YAAY;AACpC,UAAM,SAAS,IAAI,UAAU;AAC7B,aAASA,MAAK,GAAW;AACvB,UAAI,KAAK,MAAM,YAAY;AACzB,eAAO,MAAM;AACb,gBAAQ;AACR;AAAA,MACF;AACA,aAAO,MAAM,KAAK,MAAM;AACtB,cAAM;AACN,eAAO,MAAM,IAAI,WAAW,MAAM,MAAM,aAAa,EAAE,KAAK,CAAC,CAAC,CAAC;AAC/D,QAAAA,MAAK,IAAI,CAAC;AAAA,MACZ,CAAC;AAAA,IACH;AACA,IAAAA,MAAK,CAAC;AAAA,EACR,CAAC;AACH;;;ACnDO,SAAS,cAAc,KAAyC;AACrE,QAAM,UAAU,IAAI,YAAY;AAChC,SAAO,kBAAkB,QAAQ,OAAO,GAAG,CAAC;AAC9C;AAEO,SAAS,kBAAkB,KAA6C;AAC7E,SAAO,IAAI,eAA2B;AAAA,IACpC,MAAM,YAAY;AAChB,iBAAW,QAAQ,GAAG;AACtB,iBAAW,MAAM;AAAA,IACnB;AAAA,EACF,CAAC;AACH;","names":["pump"]}
|
1
|
+
{"version":3,"sources":["../../../src/utils/index.ts","../../../src/utils/stream_map.ts","../../../src/utils/rebuffer.ts","../../../src/utils/stream2string.ts","../../../src/utils/stream_test_helper.ts","../../../src/utils/string2stream.ts"],"sourcesContent":["export * from \"./rebuffer\";\nexport * from \"./stream_map\";\nexport * from \"./stream2string\";\nexport * from \"./stream_test_helper\";\nexport * from \"./string2stream\";\n","export interface StreamMap<T, U> {\n Map(s: T, idx: number): U | Promise<U>;\n readonly Close?: () => void;\n}\nexport function streamMap<T, U>(s: ReadableStream<T>, sm: StreamMap<T, U>): ReadableStream<U> {\n const state = { reader: s.getReader(), streamMap: sm, idx: 0 };\n return new ReadableStream<U>({\n async pull(controller) {\n const { done, value } = await state.reader.read();\n if (done) {\n if (state.streamMap.Close) {\n state.streamMap.Close();\n }\n controller.close();\n return;\n }\n const promiseOrU = state.streamMap.Map(value, state.idx++);\n let mapped: U;\n if (promiseOrU instanceof Promise || typeof (promiseOrU as { then: () => void }).then === \"function\") {\n mapped = await promiseOrU;\n } else {\n mapped = promiseOrU;\n }\n controller.enqueue(mapped);\n },\n });\n}\n\nexport async function devnull<T>(a: ReadableStream<T>): Promise<number> {\n const reader = a.getReader();\n let cnt = 0;\n while (true) {\n const { done } = await reader.read();\n if (done) {\n break;\n }\n cnt++;\n }\n return cnt;\n}\n\nexport function array2stream<T>(a: T[]): ReadableStream<T> {\n let i = 0;\n return new ReadableStream<T>({\n pull(controller) {\n if (i >= a.length) {\n controller.close();\n return;\n }\n controller.enqueue(a[i]);\n i++;\n },\n });\n}\n\nexport async function stream2array<T>(a: ReadableStream<T>): Promise<T[]> {\n const ret: T[] = [];\n const reader = a.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n ret.push(value);\n }\n return ret;\n}\n","import { array2stream, stream2array } from \"./stream_map\";\n\ninterface ReChunkResult {\n readonly rest: Uint8Array;\n readonly chunk: Uint8Array;\n}\n\nexport async function rebufferArray(a: Uint8Array[], chunkSize: number): Promise<Uint8Array[]> {\n return stream2array(rebuffer(array2stream(a), chunkSize));\n}\n\nfunction reChunk(cs: Uint8Array[], chunkSize: number): ReChunkResult {\n const len = cs.reduce((acc, v) => acc + v.length, 0);\n const last = cs[cs.length - 1];\n const lastOfs = len - last.length;\n // console.log(\"reChunk\", len, lastOfs, last.length, chunkSize, chunkSize - lastOfs)\n const rest = last.subarray(chunkSize - lastOfs);\n cs[cs.length - 1] = last.subarray(0, chunkSize - lastOfs);\n const chunk = new Uint8Array(chunkSize);\n let ofs = 0;\n for (const c of cs) {\n chunk.set(c, ofs);\n ofs += c.length;\n }\n return { rest, chunk };\n}\n\ninterface pumpState {\n readonly reader: ReadableStreamDefaultReader<Uint8Array>;\n tmp: Uint8Array[];\n tmpLen: number;\n readonly chunkSize: number;\n}\n\nfunction pump(ps: pumpState, controller: ReadableStreamDefaultController<Uint8Array>, next: () => void): void {\n ps.reader.read().then(({ done, value }) => {\n if (done) {\n if (ps.tmpLen > 0) {\n controller.enqueue(reChunk(ps.tmp, ps.tmpLen).chunk);\n }\n controller.close();\n next();\n return;\n }\n if (ps.tmpLen + value.length > ps.chunkSize) {\n ps.tmp.push(value);\n const res = reChunk(ps.tmp, ps.chunkSize);\n controller.enqueue(res.chunk);\n ps.tmp = [res.rest];\n ps.tmpLen = res.rest.length;\n next();\n return;\n } else if (value.length) {\n ps.tmp.push(value);\n ps.tmpLen += value.length;\n }\n pump(ps, controller, next);\n });\n}\n\nexport function rebuffer(a: ReadableStream<Uint8Array>, chunkSize: number): ReadableStream<Uint8Array> {\n const state: pumpState = {\n reader: a.getReader(),\n tmp: [],\n tmpLen: 0,\n chunkSize,\n };\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n return new Promise<void>((resolve) => {\n pump(state, controller, resolve);\n });\n },\n });\n}\n","export async function stream2string(stream?: ReadableStream<Uint8Array> | null, maxSize?: number): Promise<string> {\n if (!stream) {\n return Promise.resolve(\"\");\n }\n const reader = stream.getReader();\n let res = \"\";\n const decoder = new TextDecoder();\n let rSize = 0;\n while (typeof maxSize === \"undefined\" || rSize < maxSize) {\n try {\n const read = await reader.read();\n if (read.done) {\n break;\n }\n if (maxSize && rSize + read.value.length > maxSize) {\n read.value = read.value.slice(0, maxSize - rSize);\n }\n const block = decoder.decode(read.value, { stream: true });\n rSize += read.value.length;\n res += block;\n } catch (err) {\n return Promise.reject(err);\n }\n }\n return Promise.resolve(res);\n}\n\nexport async function stream2uint8array(stream?: ReadableStream<Uint8Array> | null): Promise<Uint8Array> {\n if (!stream) {\n return Promise.resolve(new Uint8Array());\n }\n const reader = stream.getReader();\n let res = new Uint8Array();\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n res = new Uint8Array([...res, ...value]);\n } catch (err) {\n return Promise.reject(err);\n }\n }\n return Promise.resolve(res);\n}\n","import { Mock } from \"vitest\";\n\ninterface mockValue {\n done: boolean;\n value: Uint8Array | undefined;\n fillCalls: number;\n reBufferCalls: number;\n}\nexport interface streamingTestState {\n readonly sendChunks: number;\n readonly sendChunkSize: number;\n fillCalls: number;\n CollectorFn: Mock<(mv: mockValue) => void>;\n}\n\nexport async function receiveFromStream(reb: ReadableStream<Uint8Array>, state: streamingTestState) {\n return new Promise<void>((resolve) => {\n let reBufferCalls = 0;\n const reader = reb.getReader();\n function pump() {\n reader.read().then(({ done, value }) => {\n state.CollectorFn({ done, value, fillCalls: state.fillCalls, reBufferCalls });\n reBufferCalls++;\n if (done) {\n resolve();\n return;\n }\n pump();\n });\n }\n pump();\n });\n}\n\nexport async function sendToStream(reb: WritableStream<Uint8Array>, state: streamingTestState) {\n return new Promise<void>((resolve) => {\n const writer = reb.getWriter();\n function pump(i: number) {\n if (i >= state.sendChunks) {\n writer.close();\n resolve();\n return;\n }\n writer.ready.then(() => {\n state.fillCalls++;\n writer.write(new Uint8Array(Array(state.sendChunkSize).fill(i)));\n pump(i + 1);\n });\n }\n pump(0);\n });\n}\n\n// it(\"does nothing\", () => {});\n","export function string2stream(str: string): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n return uint8array2stream(encoder.encode(str));\n}\n\nexport function uint8array2stream(str: Uint8Array): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(str);\n controller.close();\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIO,SAAS,UAAgB,GAAsB,IAAwC;AAC5F,QAAM,QAAQ,E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W,QAAQ,GAAG;AACtB,iBAAW,MAAM;AAAA,IACnB;AAAA,EACF,CAAC;AACH;","names":["pump"]}
|
package/utils/index.js
CHANGED
@@ -7,7 +7,9 @@ function streamMap(s, sm) {
|
|
7
7
|
async pull(controller) {
|
8
8
|
const { done, value } = await state.reader.read();
|
9
9
|
if (done) {
|
10
|
-
|
10
|
+
if (state.streamMap.Close) {
|
11
|
+
state.streamMap.Close();
|
12
|
+
}
|
11
13
|
controller.close();
|
12
14
|
return;
|
13
15
|
}
|
package/utils/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/stream_map.ts","../../../src/utils/rebuffer.ts","../../../src/utils/stream2string.ts","../../../src/utils/stream_test_helper.ts","../../../src/utils/string2stream.ts"],"sourcesContent":["export interface StreamMap<T, U> {\n Map(s: T, idx: number): U | Promise<U>;\n readonly Close?: () => void;\n}\nexport function streamMap<T, U>(s: ReadableStream<T>, sm: StreamMap<T, U>): ReadableStream<U> {\n const state = { reader: s.getReader(), streamMap: sm, idx: 0 };\n return new ReadableStream<U>({\n async pull(controller) {\n const { done, value } = await state.reader.read();\n if (done) {\n state.streamMap.Close && state.streamMap.Close();\n controller.close();\n return;\n }\n const promiseOrU = state.streamMap.Map(value, state.idx++);\n let mapped: U;\n if (promiseOrU instanceof Promise || typeof (promiseOrU as { then: () => void }).then === \"function\") {\n mapped = await promiseOrU;\n } else {\n mapped = promiseOrU;\n }\n controller.enqueue(mapped);\n },\n });\n}\n\nexport async function devnull<T>(a: ReadableStream<T>): Promise<number> {\n const reader = a.getReader();\n let cnt = 0;\n while (true) {\n const { done } = await reader.read();\n if (done) {\n break;\n }\n cnt++;\n }\n return cnt;\n}\n\nexport function array2stream<T>(a: T[]): ReadableStream<T> {\n let i = 0;\n return new ReadableStream<T>({\n pull(controller) {\n if (i >= a.length) {\n controller.close();\n return;\n }\n controller.enqueue(a[i]);\n i++;\n },\n });\n}\n\nexport async function stream2array<T>(a: ReadableStream<T>): Promise<T[]> {\n const ret: T[] = [];\n const reader = a.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n ret.push(value);\n }\n return ret;\n}\n","import { array2stream, stream2array } from \"./stream_map\";\n\ninterface ReChunkResult {\n readonly rest: Uint8Array;\n readonly chunk: Uint8Array;\n}\n\nexport async function rebufferArray(a: Uint8Array[], chunkSize: number): Promise<Uint8Array[]> {\n return stream2array(rebuffer(array2stream(a), chunkSize));\n}\n\nfunction reChunk(cs: Uint8Array[], chunkSize: number): ReChunkResult {\n const len = cs.reduce((acc, v) => acc + v.length, 0);\n const last = cs[cs.length - 1];\n const lastOfs = len - last.length;\n // console.log(\"reChunk\", len, lastOfs, last.length, chunkSize, chunkSize - lastOfs)\n const rest = last.subarray(chunkSize - lastOfs);\n cs[cs.length - 1] = last.subarray(0, chunkSize - lastOfs);\n const chunk = new Uint8Array(chunkSize);\n let ofs = 0;\n for (const c of cs) {\n chunk.set(c, ofs);\n ofs += c.length;\n }\n return { rest, chunk };\n}\n\ninterface pumpState {\n readonly reader: ReadableStreamDefaultReader<Uint8Array>;\n tmp: Uint8Array[];\n tmpLen: number;\n readonly chunkSize: number;\n}\n\nfunction pump(ps: pumpState, controller: ReadableStreamDefaultController<Uint8Array>, next: () => void): void {\n ps.reader.read().then(({ done, value }) => {\n if (done) {\n if (ps.tmpLen > 0) {\n controller.enqueue(reChunk(ps.tmp, ps.tmpLen).chunk);\n }\n controller.close();\n next();\n return;\n }\n if (ps.tmpLen + value.length > ps.chunkSize) {\n ps.tmp.push(value);\n const res = reChunk(ps.tmp, ps.chunkSize);\n controller.enqueue(res.chunk);\n ps.tmp = [res.rest];\n ps.tmpLen = res.rest.length;\n next();\n return;\n } else if (value.length) {\n ps.tmp.push(value);\n ps.tmpLen += value.length;\n }\n pump(ps, controller, next);\n });\n}\n\nexport function rebuffer(a: ReadableStream<Uint8Array>, chunkSize: number): ReadableStream<Uint8Array> {\n const state: pumpState = {\n reader: a.getReader(),\n tmp: [],\n tmpLen: 0,\n chunkSize,\n };\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n return new Promise<void>((resolve) => {\n pump(state, controller, resolve);\n });\n },\n });\n}\n","export async function stream2string(stream?: ReadableStream<Uint8Array> | null, maxSize?: number): Promise<string> {\n if (!stream) {\n return Promise.resolve(\"\");\n }\n const reader = stream.getReader();\n let res = \"\";\n const decoder = new TextDecoder();\n let rSize = 0;\n while (typeof maxSize === \"undefined\" || rSize < maxSize) {\n try {\n const read = await reader.read();\n if (read.done) {\n break;\n }\n if (maxSize && rSize + read.value.length > maxSize) {\n read.value = read.value.slice(0, maxSize - rSize);\n }\n const block = decoder.decode(read.value, { stream: true });\n rSize += read.value.length;\n res += block;\n } catch (err) {\n return Promise.reject(err);\n }\n }\n return Promise.resolve(res);\n}\n\nexport async function stream2uint8array(stream?: ReadableStream<Uint8Array> | null): Promise<Uint8Array> {\n if (!stream) {\n return Promise.resolve(new Uint8Array());\n }\n const reader = stream.getReader();\n let res = new Uint8Array();\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n res = new Uint8Array([...res, ...value]);\n } catch (err) {\n return Promise.reject(err);\n }\n }\n return Promise.resolve(res);\n}\n","import { Mock } from \"vitest\";\n\ninterface mockValue {\n done: boolean;\n value: Uint8Array | undefined;\n fillCalls: number;\n reBufferCalls: number;\n}\nexport interface streamingTestState {\n readonly sendChunks: number;\n readonly sendChunkSize: number;\n fillCalls: number;\n CollectorFn: Mock<(mv: mockValue) => void>;\n}\n\nexport async function receiveFromStream(reb: ReadableStream<Uint8Array>, state: streamingTestState) {\n return new Promise<void>((resolve) => {\n let reBufferCalls = 0;\n const reader = reb.getReader();\n function pump() {\n reader.read().then(({ done, value }) => {\n state.CollectorFn({ done, value, fillCalls: state.fillCalls, reBufferCalls });\n reBufferCalls++;\n if (done) {\n resolve();\n return;\n }\n pump();\n });\n }\n pump();\n });\n}\n\nexport async function sendToStream(reb: WritableStream<Uint8Array>, state: streamingTestState) {\n return new Promise<void>((resolve) => {\n const writer = reb.getWriter();\n function pump(i: number) {\n if (i >= state.sendChunks) {\n writer.close();\n resolve();\n return;\n }\n writer.ready.then(() => {\n state.fillCalls++;\n writer.write(new Uint8Array(Array(state.sendChunkSize).fill(i)));\n pump(i + 1);\n });\n }\n pump(0);\n });\n}\n\n// it(\"does nothing\", () => {});\n","export function string2stream(str: string): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n return uint8array2stream(encoder.encode(str));\n}\n\nexport function uint8array2stream(str: Uint8Array): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(str);\n controller.close();\n },\n });\n}\n"],"mappings":";;;AAIO,SAAS,UAAgB,GAAsB,IAAwC;AAC5F,QAAM,QAAQ,EAAE,QAAQ,EAAE,UAAU,GAAG,WAAW,IAAI,KAAK,EAAE;AAC7D,SAAO,IAAI,eAAkB;AAAA,IAC3B,MAAM,KAAK,YAAY;AACrB,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,MAAM,OAAO,KAAK;AAChD,UAAI,MAAM;AACR,cAAM,UAAU,SAAS,MAAM,UAAU,MAAM;AAC/C,mBAAW,MAAM;AACjB;AAAA,MACF;AACA,YAAM,aAAa,MAAM,UAAU,IAAI,OAAO,MAAM,KAAK;AACzD,UAAI;AACJ,UAAI,sBAAsB,WAAW,OAAQ,WAAoC,SAAS,YAAY;AACpG,iBAAS,MAAM;AAAA,MACjB,OAAO;AACL,iBAAS;AAAA,MACX;AACA,iBAAW,QAAQ,MAAM;AAAA,IAC3B;AAAA,EACF,CAAC;AACH;AAEA,eAAsB,QAAW,GAAuC;AACtE,QAAM,SAAS,EAAE,UAAU;AAC3B,MAAI,MAAM;AACV,SAAO,MAAM;AACX,UAAM,EAAE,KAAK,IAAI,MAAM,OAAO,KAAK;AACnC,QAAI,MAAM;AACR;AAAA,IACF;AACA;AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,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,MAAM,YAAY;AACzB,eAAO,MAAM;AACb,gBAAQ;AACR;AAAA,MACF;AACA,aAAO,MAAM,KAAK,MAAM;AACtB,cAAM;AACN,eAAO,MAAM,IAAI,WAAW,MAAM,MAAM,aAAa,EAAE,KAAK,CAAC,CAAC,CAAC;AAC/D,QAAAA,MAAK,IAAI,CAAC;AAAA,MACZ,CAAC;AAAA,IACH;AACA,IAAAA,MAAK,CAAC;AAAA,EACR,CAAC;AACH;;;ACnDO,SAAS,cAAc,KAAyC;AACrE,QAAM,UAAU,IAAI,YAAY;AAChC,SAAO,kBAAkB,QAAQ,OAAO,GAAG,CAAC;AAC9C;AAEO,SAAS,kBAAkB,KAA6C;AAC7E,SAAO,IAAI,eAA2B;AAAA,IACpC,MAAM,YAAY;AAChB,iBAAW,QAAQ,GAAG;AACtB,iBAAW,MAAM;AAAA,IACnB;AAAA,EACF,CAAC;AACH;","names":["pump"]}
|
1
|
+
{"version":3,"sources":["../../../src/utils/stream_map.ts","../../../src/utils/rebuffer.ts","../../../src/utils/stream2string.ts","../../../src/utils/stream_test_helper.ts","../../../src/utils/string2stream.ts"],"sourcesContent":["export interface StreamMap<T, U> {\n Map(s: T, idx: number): U | Promise<U>;\n readonly Close?: () => void;\n}\nexport function streamMap<T, U>(s: ReadableStream<T>, sm: StreamMap<T, U>): ReadableStream<U> {\n const state = { reader: s.getReader(), streamMap: sm, idx: 0 };\n return new ReadableStream<U>({\n async pull(controller) {\n const { done, value } = await state.reader.read();\n if (done) {\n if (state.streamMap.Close) {\n state.streamMap.Close();\n }\n controller.close();\n return;\n }\n const promiseOrU = state.streamMap.Map(value, state.idx++);\n let mapped: U;\n if (promiseOrU instanceof Promise || typeof (promiseOrU as { then: () => void }).then === \"function\") {\n mapped = await promiseOrU;\n } else {\n mapped = promiseOrU;\n }\n controller.enqueue(mapped);\n },\n });\n}\n\nexport async function devnull<T>(a: ReadableStream<T>): Promise<number> {\n const reader = a.getReader();\n let cnt = 0;\n while (true) {\n const { done } = await reader.read();\n if (done) {\n break;\n }\n cnt++;\n }\n return cnt;\n}\n\nexport function array2stream<T>(a: T[]): ReadableStream<T> {\n let i = 0;\n return new ReadableStream<T>({\n pull(controller) {\n if (i >= a.length) {\n controller.close();\n return;\n }\n controller.enqueue(a[i]);\n i++;\n },\n });\n}\n\nexport async function stream2array<T>(a: ReadableStream<T>): Promise<T[]> {\n const ret: T[] = [];\n const reader = a.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n ret.push(value);\n }\n return ret;\n}\n","import { array2stream, stream2array } from \"./stream_map\";\n\ninterface ReChunkResult {\n readonly rest: Uint8Array;\n readonly chunk: Uint8Array;\n}\n\nexport async function rebufferArray(a: Uint8Array[], chunkSize: number): Promise<Uint8Array[]> {\n return stream2array(rebuffer(array2stream(a), chunkSize));\n}\n\nfunction reChunk(cs: Uint8Array[], chunkSize: number): ReChunkResult {\n const len = cs.reduce((acc, v) => acc + v.length, 0);\n const last = cs[cs.length - 1];\n const lastOfs = len - last.length;\n // console.log(\"reChunk\", len, lastOfs, last.length, chunkSize, chunkSize - lastOfs)\n const rest = last.subarray(chunkSize - lastOfs);\n cs[cs.length - 1] = last.subarray(0, chunkSize - lastOfs);\n const chunk = new Uint8Array(chunkSize);\n let ofs = 0;\n for (const c of cs) {\n chunk.set(c, ofs);\n ofs += c.length;\n }\n return { rest, chunk };\n}\n\ninterface pumpState {\n readonly reader: ReadableStreamDefaultReader<Uint8Array>;\n tmp: Uint8Array[];\n tmpLen: number;\n readonly chunkSize: number;\n}\n\nfunction pump(ps: pumpState, controller: ReadableStreamDefaultController<Uint8Array>, next: () => void): void {\n ps.reader.read().then(({ done, value }) => {\n if (done) {\n if (ps.tmpLen > 0) {\n controller.enqueue(reChunk(ps.tmp, ps.tmpLen).chunk);\n }\n controller.close();\n next();\n return;\n }\n if (ps.tmpLen + value.length > ps.chunkSize) {\n ps.tmp.push(value);\n const res = reChunk(ps.tmp, ps.chunkSize);\n controller.enqueue(res.chunk);\n ps.tmp = [res.rest];\n ps.tmpLen = res.rest.length;\n next();\n return;\n } else if (value.length) {\n ps.tmp.push(value);\n ps.tmpLen += value.length;\n }\n pump(ps, controller, next);\n });\n}\n\nexport function rebuffer(a: ReadableStream<Uint8Array>, chunkSize: number): ReadableStream<Uint8Array> {\n const state: pumpState = {\n reader: a.getReader(),\n tmp: [],\n tmpLen: 0,\n chunkSize,\n };\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n return new Promise<void>((resolve) => {\n pump(state, controller, resolve);\n });\n },\n });\n}\n","export async function stream2string(stream?: ReadableStream<Uint8Array> | null, maxSize?: number): Promise<string> {\n if (!stream) {\n return Promise.resolve(\"\");\n }\n const reader = stream.getReader();\n let res = \"\";\n const decoder = new TextDecoder();\n let rSize = 0;\n while (typeof maxSize === \"undefined\" || rSize < maxSize) {\n try {\n const read = await reader.read();\n if (read.done) {\n break;\n }\n if (maxSize && rSize + read.value.length > maxSize) {\n read.value = read.value.slice(0, maxSize - rSize);\n }\n const block = decoder.decode(read.value, { stream: true });\n rSize += read.value.length;\n res += block;\n } catch (err) {\n return Promise.reject(err);\n }\n }\n return Promise.resolve(res);\n}\n\nexport async function stream2uint8array(stream?: ReadableStream<Uint8Array> | null): Promise<Uint8Array> {\n if (!stream) {\n return Promise.resolve(new Uint8Array());\n }\n const reader = stream.getReader();\n let res = new Uint8Array();\n // eslint-disable-next-line no-constant-condition\n while (1) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n res = new Uint8Array([...res, ...value]);\n } catch (err) {\n return Promise.reject(err);\n }\n }\n return Promise.resolve(res);\n}\n","import { Mock } from \"vitest\";\n\ninterface mockValue {\n done: boolean;\n value: Uint8Array | undefined;\n fillCalls: number;\n reBufferCalls: number;\n}\nexport interface streamingTestState {\n readonly sendChunks: number;\n readonly sendChunkSize: number;\n fillCalls: number;\n CollectorFn: Mock<(mv: mockValue) => void>;\n}\n\nexport async function receiveFromStream(reb: ReadableStream<Uint8Array>, state: streamingTestState) {\n return new Promise<void>((resolve) => {\n let reBufferCalls = 0;\n const reader = reb.getReader();\n function pump() {\n reader.read().then(({ done, value }) => {\n state.CollectorFn({ done, value, fillCalls: state.fillCalls, reBufferCalls });\n reBufferCalls++;\n if (done) {\n resolve();\n return;\n }\n pump();\n });\n }\n pump();\n });\n}\n\nexport async function sendToStream(reb: WritableStream<Uint8Array>, state: streamingTestState) {\n return new Promise<void>((resolve) => {\n const writer = reb.getWriter();\n function pump(i: number) {\n if (i >= state.sendChunks) {\n writer.close();\n resolve();\n return;\n }\n writer.ready.then(() => {\n state.fillCalls++;\n writer.write(new Uint8Array(Array(state.sendChunkSize).fill(i)));\n pump(i + 1);\n });\n }\n pump(0);\n });\n}\n\n// it(\"does nothing\", () => {});\n","export function string2stream(str: string): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n return uint8array2stream(encoder.encode(str));\n}\n\nexport function uint8array2stream(str: Uint8Array): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(str);\n controller.close();\n },\n });\n}\n"],"mappings":";;;AAIO,SAAS,UAAgB,GAAsB,IAAwC;AAC5F,QAAM,QAAQ,EAAE,QAAQ,EAAE,UAAU,GAAG,WAAW,IAAI,KAAK,EAAE;AAC7D,SAAO,IAAI,eAAkB;AAAA,IAC3B,MAAM,KAAK,YAAY;AACrB,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,MAAM,OAAO,KAAK;AAChD,UAAI,MAAM;AACR,YAAI,MAAM,UAAU,OAAO;AACzB,gBAAM,UAAU,MAAM;AAAA,QACxB;AACA,mBAAW,MAAM;AACjB;AAAA,MACF;AACA,YAAM,aAAa,MAAM,UAAU,IAAI,OAAO,MAAM,KAAK;AACzD,UAAI;AACJ,UAAI,sBAAsB,WAAW,OAAQ,WAAoC,SAAS,YAAY;AACpG,iBAAS,MAAM;AAAA,MACjB,OAAO;AACL,iBAAS;AAAA,MACX;AACA,iBAAW,QAAQ,MAAM;AAAA,IAC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