import process from "node:process";
import { primordials } from "ext:core/mod.js";
import _mod1 from "ext:deno_node/internal/errors.ts";
import Duplex from "node:_stream_duplex";
import { getHighWaterMark } from "ext:deno_node/internal/streams/state.js";
const {
ERR_METHOD_NOT_IMPLEMENTED,
} = _mod1.codes;
"use strict";
const {
ObjectSetPrototypeOf,
Symbol,
} = primordials;
ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype);
ObjectSetPrototypeOf(Transform, Duplex);
const kCallback = Symbol("kCallback");
function Transform(options) {
if (!(this instanceof Transform)) {
return new Transform(options);
}
const readableHighWaterMark = options
? getHighWaterMark(this, options, "readableHighWaterMark", true)
: null;
if (readableHighWaterMark === 0) {
options = {
...options,
highWaterMark: null,
readableHighWaterMark,
writableHighWaterMark: options.writableHighWaterMark || 0,
};
}
Duplex.call(this, options);
this._readableState.sync = false;
this[kCallback] = null;
if (options) {
if (typeof options.transform === "function") {
this._transform = options.transform;
}
if (typeof options.flush === "function") {
this._flush = options.flush;
}
}
this.on("prefinish", prefinish);
}
function final(cb) {
if (typeof this._flush === "function" && !this.destroyed) {
this._flush((er, data) => {
if (er) {
if (cb) {
cb(er);
} else {
this.destroy(er);
}
return;
}
if (data != null) {
this.push(data);
}
this.push(null);
if (cb) {
cb();
}
});
} else {
this.push(null);
if (cb) {
cb();
}
}
}
function prefinish() {
if (this._final !== final) {
final.call(this);
}
}
Transform.prototype._final = final;
Transform.prototype._transform = function (chunk, encoding, callback) {
throw new ERR_METHOD_NOT_IMPLEMENTED("_transform()");
};
Transform.prototype._write = function (chunk, encoding, callback) {
const rState = this._readableState;
const wState = this._writableState;
const length = rState.length;
this._transform(chunk, encoding, (err, val) => {
if (err) {
callback(err);
return;
}
if (val != null) {
this.push(val);
}
if (rState.ended) {
process.nextTick(callback);
} else if (
wState.ended || length === rState.length || rState.length < rState.highWaterMark
) {
callback();
} else {
this[kCallback] = callback;
}
});
};
Transform.prototype._read = function () {
if (this[kCallback]) {
const callback = this[kCallback];
this[kCallback] = null;
callback();
}
};
export default Transform;
export { Transform };