fake-node 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- package/LICENSE +21 -0
- package/globals.ts +38 -0
- package/index.js +1 -0
- package/index.ts +80 -0
- package/modules/assert.ts +205 -0
- package/modules/buffer.ts +4 -0
- package/modules/fs.ts +8 -0
- package/modules/os.ts +81 -0
- package/modules/path.ts +56 -0
- package/modules/process.ts +78 -0
- package/modules/querystring.ts +33 -0
- package/modules/util.ts +116 -0
- package/package.json +14 -0
package/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
MIT License
|
2
|
+
|
3
|
+
Copyright (c) 2025 speedydelete
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
13
|
+
copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21
|
+
SOFTWARE.
|
package/globals.ts
ADDED
@@ -0,0 +1,38 @@
|
|
1
|
+
|
2
|
+
import {Buffer} from './modules/buffer';
|
3
|
+
import * as process from './modules/process';
|
4
|
+
|
5
|
+
// todo: properly implement eval
|
6
|
+
const ES_GLOBALS = {Infinity, NaN, undefined, eval, isFinite, isNaN, parseFloat, parseInt, decodeURI, decodeURIComponent, encodeURI, encodeURIComponent, escape, unescape, Object, Function, Boolean, Symbol, Error, AggregateError, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError, Number, BigInt, Math, Date, String, RegExp, Array, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, BigUint64Array, Float32Array, Float64Array, Map, Set, WeakMap, WeakSet, ArrayBuffer, SharedArrayBuffer, DataView, Atomics, JSON, WeakRef, FinalizationRegistry, Promise, Reflect, Proxy, Intl};
|
7
|
+
|
8
|
+
const WEB_ONLY_GLOBALS: string[] = ['webkitSpeechRecognitionEvent', 'webkitSpeechRecognitionError', 'webkitSpeechRecognition', 'webkitSpeechGrammarList', 'webkitSpeechGrammar', 'WebSocketStream', 'WebSocketError', 'ViewTransitionTypeSet', 'SpeechSynthesisVoice', 'SpeechSynthesisUtterance', 'SpeechSynthesisEvent', 'SpeechSynthesisErrorEvent', 'SpeechSynthesis', 'SnapEvent', 'SharedWorker', 'SharedStorageWorklet', 'SharedStorage', 'ViewTimeline', 'ScrollTimeline', 'RemotePlayback', 'RTCDataChannel', 'PushSubscriptionOptions', 'PushSubscription', 'PushManager', 'Permissions', 'PermissionStatus', 'PeriodicSyncManager', 'PerformanceScriptTiming', 'PerformanceLongAnimationFrameTiming', 'PageSwapEvent', 'PageRevealEvent', 'Notification', 'NavigationActivation', 'MediaSession', 'MediaMetadata', 'HTMLFencedFrameElement', 'FencedFrameConfig', 'Fence', 'DocumentPictureInPictureEvent', 'CropTarget', 'ChapterInformation', 'CaretPosition', 'CSSViewTransitionRule', 'CSSNestedDeclarations', 'CSSMarginRule', 'BluetoothUUID', 'BackgroundFetchRegistration', 'BackgroundFetchRecord', 'BackgroundFetchManager', 'Option', 'Image', 'Audio', 'webkitURL', 'webkitRTCPeerConnection', 'webkitMediaStream', 'WebKitMutationObserver', 'WebKitCSSMatrix', 'XSLTProcessor', 'XPathResult', 'XPathExpression', 'XPathEvaluator', 'XMLSerializer', 'XMLHttpRequestUpload', 'XMLHttpRequestEventTarget', 'XMLHttpRequest', 'XMLDocument', 'Worker', 'WindowControlsOverlayGeometryChangeEvent', 'WindowControlsOverlay', 'Window', 'WheelEvent', 'WebGLVertexArrayObject', 'WebGLUniformLocation', 'WebGLTransformFeedback', 'WebGLTexture', 'WebGLSync', 'WebGLShaderPrecisionFormat', 'WebGLShader', 'WebGLSampler', 'WebGLRenderingContext', 'WebGLRenderbuffer', 'WebGLQuery', 'WebGLProgram', 'WebGLObject', 'WebGLFramebuffer', 'WebGLContextEvent', 'WebGLBuffer', 'WebGLActiveInfo', 'WebGL2RenderingContext', 'WaveShaperNode', 'VisualViewport', 'VisibilityStateEntry', 'VirtualKeyboardGeometryChangeEvent', 'ViewTransition', 'VideoPlaybackQuality', 'VideoFrame', 'VideoColorSpace', 'ValidityState', 'VTTCue', 'UserActivation', 'URLPattern', 'UIEvent', 'TrustedTypePolicyFactory', 'TrustedTypePolicy', 'TrustedScriptURL', 'TrustedScript', 'TrustedHTML', 'TreeWalker', 'TransitionEvent', 'TransformStream', 'TrackEvent', 'TouchList', 'TouchEvent', 'Touch', 'ToggleEvent', 'TimeRanges', 'TextUpdateEvent', 'TextTrackList', 'TextTrackCueList', 'TextTrackCue', 'TextTrack', 'TextMetrics', 'TextFormatUpdateEvent', 'TextFormat', 'TextEvent', 'Text', 'TaskSignal', 'TaskPriorityChangeEvent', 'TaskController', 'TaskAttributionTiming', 'SyncManager', 'SubmitEvent', 'StyleSheetList', 'StyleSheet', 'StylePropertyMapReadOnly', 'StylePropertyMap', 'StorageEvent', 'StereoPannerNode', 'StaticRange', 'SourceBufferList', 'SourceBuffer', 'ShadowRoot', 'Selection', 'SecurityPolicyViolationEvent', 'ScriptProcessorNode', 'ScreenOrientation', 'Screen', 'Scheduling', 'Scheduler', 'SVGViewElement', 'SVGUseElement', 'SVGUnitTypes', 'SVGTransformList', 'SVGTransform', 'SVGTitleElement', 'SVGTextPositioningElement', 'SVGTextPathElement', 'SVGTextElement', 'SVGTextContentElement', 'SVGTSpanElement', 'SVGSymbolElement', 'SVGSwitchElement', 'SVGStyleElement', 'SVGStringList', 'SVGStopElement', 'SVGSetElement', 'SVGScriptElement', 'SVGSVGElement', 'SVGRectElement', 'SVGRect', 'SVGRadialGradientElement', 'SVGPreserveAspectRatio', 'SVGPolylineElement', 'SVGPolygonElement', 'SVGPointList', 'SVGPoint', 'SVGPatternElement', 'SVGPathElement', 'SVGNumberList', 'SVGNumber', 'SVGMetadataElement', 'SVGMatrix', 'SVGMaskElement', 'SVGMarkerElement', 'SVGMPathElement', 'SVGLinearGradientElement', 'SVGLineElement', 'SVGLengthList', 'SVGLength', 'SVGImageElement', 'SVGGraphicsElement', 'SVGGradientElement', 'SVGGeometryElement', 'SVGGElement', 'SVGForeignObjectElement', 'SVGFilterElement', 'SVGFETurbulenceElement', 'SVGFETileElement', 'SVGFESpotLightElement', 'SVGFESpecularLightingElement', 'SVGFEPointLightElement', 'SVGFEOffsetElement', 'SVGFEMorphologyElement', 'SVGFEMergeNodeElement', 'SVGFEMergeElement', 'SVGFEImageElement', 'SVGFEGaussianBlurElement', 'SVGFEFuncRElement', 'SVGFEFuncGElement', 'SVGFEFuncBElement', 'SVGFEFuncAElement', 'SVGFEFloodElement', 'SVGFEDropShadowElement', 'SVGFEDistantLightElement', 'SVGFEDisplacementMapElement', 'SVGFEDiffuseLightingElement', 'SVGFEConvolveMatrixElement', 'SVGFECompositeElement', 'SVGFEComponentTransferElement', 'SVGFEColorMatrixElement', 'SVGFEBlendElement', 'SVGEllipseElement', 'SVGElement', 'SVGDescElement', 'SVGDefsElement', 'SVGComponentTransferFunctionElement', 'SVGClipPathElement', 'SVGCircleElement', 'SVGAnimationElement', 'SVGAnimatedTransformList', 'SVGAnimatedString', 'SVGAnimatedRect', 'SVGAnimatedPreserveAspectRatio', 'SVGAnimatedNumberList', 'SVGAnimatedNumber', 'SVGAnimatedLengthList', 'SVGAnimatedLength', 'SVGAnimatedInteger', 'SVGAnimatedEnumeration', 'SVGAnimatedBoolean', 'SVGAnimatedAngle', 'SVGAnimateTransformElement', 'SVGAnimateMotionElement', 'SVGAnimateElement', 'SVGAngle', 'SVGAElement', 'ResizeObserverSize', 'ResizeObserverEntry', 'ResizeObserver', 'ReportingObserver', 'ReadableStreamDefaultReader', 'ReadableStreamDefaultController', 'ReadableStreamBYOBRequest', 'ReadableStreamBYOBReader', 'ReadableStream', 'Range', 'RadioNodeList', 'RTCTrackEvent', 'RTCStatsReport', 'RTCSessionDescription', 'RTCSctpTransport', 'RTCRtpTransceiver', 'RTCRtpSender', 'RTCRtpReceiver', 'RTCPeerConnectionIceEvent', 'RTCPeerConnectionIceErrorEvent', 'RTCPeerConnection', 'RTCIceTransport', 'RTCIceCandidate', 'RTCErrorEvent', 'RTCError', 'RTCEncodedVideoFrame', 'RTCEncodedAudioFrame', 'RTCDtlsTransport', 'RTCDataChannelEvent', 'RTCDTMFToneChangeEvent', 'RTCDTMFSender', 'RTCCertificate', 'PromiseRejectionEvent', 'ProgressEvent', 'Profiler', 'ProcessingInstruction', 'PopStateEvent', 'PointerEvent', 'PluginArray', 'Plugin', 'PictureInPictureWindow', 'PictureInPictureEvent', 'PeriodicWave', 'PerformanceTiming', 'PerformanceServerTiming', 'PerformancePaintTiming', 'PerformanceObserverEntryList', 'PerformanceNavigationTiming', 'PerformanceNavigation', 'PerformanceLongTaskTiming', 'PerformanceEventTiming', 'PerformanceElementTiming', 'Performance', 'Path2D', 'PannerNode', 'PageTransitionEvent', 'OverconstrainedError', 'OscillatorNode', 'OffscreenCanvasRenderingContext2D', 'OffscreenCanvas', 'OfflineAudioContext', 'OfflineAudioCompletionEvent', 'NodeList', 'NodeIterator', 'NodeFilter', 'Node', 'NetworkInformation', 'NavigatorUAData', 'NavigationTransition', 'NavigationHistoryEntry', 'NavigationDestination', 'NavigationCurrentEntryChangeEvent', 'Navigation', 'NavigateEvent', 'NamedNodeMap', 'MutationRecord', 'MutationObserver', 'MouseEvent', 'MimeTypeArray', 'MimeType', 'MediaStreamTrackVideoStats', 'MediaStreamTrackProcessor', 'MediaStreamTrackGenerator', 'MediaStreamTrackEvent', 'MediaStreamTrackAudioStats', 'MediaStreamTrack', 'MediaStreamEvent', 'MediaStreamAudioSourceNode', 'MediaStreamAudioDestinationNode', 'MediaStream', 'MediaSourceHandle', 'MediaSource', 'MediaRecorder', 'MediaQueryListEvent', 'MediaQueryList', 'MediaList', 'MediaError', 'MediaEncryptedEvent', 'MediaElementAudioSourceNode', 'MediaCapabilities', 'MathMLElement', 'Location', 'LayoutShiftAttribution', 'LayoutShift', 'LargestContentfulPaint', 'KeyframeEffect', 'KeyboardEvent', 'IntersectionObserverEntry', 'IntersectionObserver', 'InputEvent', 'InputDeviceInfo', 'InputDeviceCapabilities', 'Ink', 'ImageData', 'ImageCapture', 'ImageBitmapRenderingContext', 'ImageBitmap', 'IdleDeadline', 'IIRFilterNode', 'IDBVersionChangeEvent', 'IDBTransaction', 'IDBRequest', 'IDBOpenDBRequest', 'IDBObjectStore', 'IDBKeyRange', 'IDBIndex', 'IDBFactory', 'IDBDatabase', 'IDBCursorWithValue', 'IDBCursor', 'History', 'HighlightRegistry', 'Highlight', 'HashChangeEvent', 'HTMLVideoElement', 'HTMLUnknownElement', 'HTMLUListElement', 'HTMLTrackElement', 'HTMLTitleElement', 'HTMLTimeElement', 'HTMLTextAreaElement', 'HTMLTemplateElement', 'HTMLTableSectionElement', 'HTMLTableRowElement', 'HTMLTableElement', 'HTMLTableColElement', 'HTMLTableCellElement', 'HTMLTableCaptionElement', 'HTMLStyleElement', 'HTMLSpanElement', 'HTMLSourceElement', 'HTMLSlotElement', 'HTMLSelectElement', 'HTMLScriptElement', 'HTMLQuoteElement', 'HTMLProgressElement', 'HTMLPreElement', 'HTMLPictureElement', 'HTMLParamElement', 'HTMLParagraphElement', 'HTMLOutputElement', 'HTMLOptionsCollection', 'HTMLOptionElement', 'HTMLOptGroupElement', 'HTMLObjectElement', 'HTMLOListElement', 'HTMLModElement', 'HTMLMeterElement', 'HTMLMetaElement', 'HTMLMenuElement', 'HTMLMediaElement', 'HTMLMarqueeElement', 'HTMLMapElement', 'HTMLLinkElement', 'HTMLLegendElement', 'HTMLLabelElement', 'HTMLLIElement', 'HTMLInputElement', 'HTMLImageElement', 'HTMLIFrameElement', 'HTMLHtmlElement', 'HTMLHeadingElement', 'HTMLHeadElement', 'HTMLHRElement', 'HTMLFrameSetElement', 'HTMLFrameElement', 'HTMLFormElement', 'HTMLFormControlsCollection', 'HTMLFontElement', 'HTMLFieldSetElement', 'HTMLEmbedElement', 'HTMLElement', 'HTMLDocument', 'HTMLDivElement', 'HTMLDirectoryElement', 'HTMLDialogElement', 'HTMLDetailsElement', 'HTMLDataListElement', 'HTMLDataElement', 'HTMLDListElement', 'HTMLCollection', 'HTMLCanvasElement', 'HTMLButtonElement', 'HTMLBodyElement', 'HTMLBaseElement', 'HTMLBRElement', 'HTMLAudioElement', 'HTMLAreaElement', 'HTMLAnchorElement', 'HTMLAllCollection', 'GeolocationPositionError', 'GeolocationPosition', 'GeolocationCoordinates', 'Geolocation', 'GamepadHapticActuator', 'GamepadEvent', 'GamepadButton', 'Gamepad', 'GainNode', 'FormDataEvent', 'FontFaceSetLoadEvent', 'FontFace', 'FocusEvent', 'FileReader', 'FileList', 'File', 'FeaturePolicy', 'External', 'EventCounts', 'ErrorEvent', 'EncodedVideoChunk', 'EncodedAudioChunk', 'ElementInternals', 'Element', 'EditContext', 'DynamicsCompressorNode', 'DragEvent', 'DocumentType', 'DocumentTimeline', 'DocumentFragment', 'Document', 'DelegatedInkTrailPresenter', 'DelayNode', 'DataTransferItemList', 'DataTransferItem', 'DataTransfer', 'DOMTokenList', 'DOMStringMap', 'DOMStringList', 'DOMRectReadOnly', 'DOMRectList', 'DOMRect', 'DOMQuad', 'DOMPointReadOnly', 'DOMPoint', 'DOMParser', 'DOMMatrixReadOnly', 'DOMMatrix', 'DOMImplementation', 'DOMError', 'CustomStateSet', 'CustomElementRegistry', 'ConvolverNode', 'ContentVisibilityAutoStateChangeEvent', 'ConstantSourceNode', 'CompositionEvent', 'Comment', 'CloseWatcher', 'ClipboardEvent', 'CharacterData', 'CharacterBoundsUpdateEvent', 'ChannelSplitterNode', 'ChannelMergerNode', 'CanvasRenderingContext2D', 'CanvasPattern', 'CanvasGradient', 'CanvasCaptureMediaStreamTrack', 'CSSVariableReferenceValue', 'CSSUnparsedValue', 'CSSUnitValue', 'CSSTranslate', 'CSSTransition', 'CSSTransformValue', 'CSSTransformComponent', 'CSSSupportsRule', 'CSSStyleValue', 'CSSStyleSheet', 'CSSStyleRule', 'CSSStyleDeclaration', 'CSSStartingStyleRule', 'CSSSkewY', 'CSSSkewX', 'CSSSkew', 'CSSScopeRule', 'CSSScale', 'CSSRuleList', 'CSSRule', 'CSSRotate', 'CSSPropertyRule', 'CSSPositionValue', 'CSSPositionTryRule', 'CSSPositionTryDescriptors', 'CSSPerspective', 'CSSPageRule', 'CSSNumericValue', 'CSSNumericArray', 'CSSNamespaceRule', 'CSSMediaRule', 'CSSMatrixComponent', 'CSSMathValue', 'CSSMathSum', 'CSSMathProduct', 'CSSMathNegate', 'CSSMathMin', 'CSSMathMax', 'CSSMathInvert', 'CSSMathClamp', 'CSSLayerStatementRule', 'CSSLayerBlockRule', 'CSSKeywordValue', 'CSSKeyframesRule', 'CSSKeyframeRule', 'CSSImportRule', 'CSSImageValue', 'CSSGroupingRule', 'CSSFontPaletteValuesRule', 'CSSFontFaceRule', 'CSSCounterStyleRule', 'CSSContainerRule', 'CSSConditionRule', 'CSSAnimation', 'CSS', 'CDATASection', 'BrowserCaptureMediaStreamTrack', 'BroadcastChannel', 'BlobEvent', 'BiquadFilterNode', 'BeforeUnloadEvent', 'BeforeInstallPromptEvent', 'BaseAudioContext', 'BarProp', 'AudioWorkletNode', 'AudioSinkInfo', 'AudioScheduledSourceNode', 'AudioProcessingEvent', 'AudioParamMap', 'AudioParam', 'AudioNode', 'AudioListener', 'AudioDestinationNode', 'AudioData', 'AudioContext', 'AudioBufferSourceNode', 'AudioBuffer', 'Attr', 'AnimationTimeline', 'AnimationPlaybackEvent', 'AnimationEvent', 'AnimationEffect', 'Animation', 'AnalyserNode', 'AbstractRange', 'AbortSignal', 'window', 'self', 'document', 'name', 'location', 'customElements', 'history', 'navigation', 'locationbar', 'menubar', 'personalbar', 'scrollbars', 'statusbar', 'toolbar', 'status', 'closed', 'frames', 'length', 'top', 'opener', 'parent', 'frameElement', 'origin', 'external', 'screen', 'innerWidth', 'innerHeight', 'scrollX', 'pageXOffset', 'scrollY', 'pageYOffset', 'visualViewport', 'screenX', 'screenY', 'outerWidth', 'outerHeight', 'devicePixelRatio', 'event', 'clientInformation', 'offscreenBuffering', 'screenLeft', 'screenTop', 'styleMedia', 'onsearch', 'isSecureContext', 'trustedTypes', 'performance', 'onappinstalled', 'onbeforeinstallprompt', 'indexedDB', 'onbeforexrselect', 'onabort', 'onbeforeinput', 'onbeforematch', 'onbeforetoggle', 'onblur', 'oncancel', 'oncanplay', 'oncanplaythrough', 'onchange', 'onclick', 'onclose', 'oncontentvisibilityautostatechange', 'oncontextlost', 'oncontextmenu', 'oncontextrestored', 'oncuechange', 'ondblclick', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'ondurationchange', 'onemptied', 'onended', 'onerror', 'onfocus', 'onformdata', 'oninput', 'oninvalid', 'onkeydown', 'onkeypress', 'onkeyup', 'onload', 'onloadeddata', 'onloadedmetadata', 'onloadstart', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onpause', 'onplay', 'onplaying', 'onprogress', 'onratechange', 'onreset', 'onresize', 'onscroll', 'onsecuritypolicyviolation', 'onseeked', 'onseeking', 'onselect', 'onslotchange', 'onstalled', 'onsubmit', 'onsuspend', 'ontimeupdate', 'ontoggle', 'onvolumechange', 'onwaiting', 'onwebkitanimationend', 'onwebkitanimationiteration', 'onwebkitanimationstart', 'onwebkittransitionend', 'onwheel', 'onauxclick', 'ongotpointercapture', 'onlostpointercapture', 'onpointerdown', 'onpointermove', 'onpointerrawupdate', 'onpointerup', 'onpointercancel', 'onpointerover', 'onpointerout', 'onpointerenter', 'onpointerleave', 'onselectstart', 'onselectionchange', 'onanimationend', 'onanimationiteration', 'onanimationstart', 'ontransitionrun', 'ontransitionstart', 'ontransitionend', 'ontransitioncancel', 'onafterprint', 'onbeforeprint', 'onbeforeunload', 'onhashchange', 'onlanguagechange', 'onmessage', 'onmessageerror', 'onoffline', 'ononline', 'onpagehide', 'onpageshow', 'onpopstate', 'onrejectionhandled', 'onstorage', 'onunhandledrejection', 'onunload', 'crossOriginIsolated', 'scheduler', 'alert', 'blur', 'cancelAnimationFrame', 'cancelIdleCallback', 'captureEvents', 'close', 'confirm', 'createImageBitmap', 'find', 'focus', 'getComputedStyle', 'getSelection', 'matchMedia', 'moveBy', 'moveTo', 'open', 'postMessage', 'print', 'prompt', 'releaseEvents', 'reportError', 'requestAnimationFrame', 'requestIdleCallback', 'resizeBy', 'resizeTo', 'scroll', 'scrollBy', 'scrollTo', 'stop', 'webkitCancelAnimationFrame', 'webkitRequestAnimationFrame', 'originAgentCluster', 'onpageswap', 'onpagereveal', 'credentialless', 'fence', 'speechSynthesis', 'onscrollend', 'onscrollsnapchange', 'onscrollsnapchanging', 'webkitRequestFileSystem', 'webkitResolveLocalFileSystemURL', 'Iterator', 'chrome', 'caches', 'cookieStore', 'ondevicemotion', 'ondeviceorientation', 'ondeviceorientationabsolute', 'launchQueue', 'sharedStorage', 'documentPictureInPicture', 'AbsoluteOrientationSensor', 'Accelerometer', 'AudioDecoder', 'AudioEncoder', 'AudioWorklet', 'BatteryManager', 'Cache', 'CacheStorage', 'Clipboard', 'ClipboardItem', 'CookieChangeEvent', 'CookieStore', 'CookieStoreManager', 'Credential', 'CredentialsContainer', 'DeviceMotionEvent', 'DeviceMotionEventAcceleration', 'DeviceMotionEventRotationRate', 'DeviceOrientationEvent', 'FederatedCredential', 'GPU', 'GPUAdapter', 'GPUAdapterInfo', 'GPUBindGroup', 'GPUBindGroupLayout', 'GPUBuffer', 'GPUBufferUsage', 'GPUCanvasContext', 'GPUColorWrite', 'GPUCommandBuffer', 'GPUCommandEncoder', 'GPUCompilationInfo', 'GPUCompilationMessage', 'GPUComputePassEncoder', 'GPUComputePipeline', 'GPUDevice', 'GPUDeviceLostInfo', 'GPUError', 'GPUExternalTexture', 'GPUInternalError', 'GPUMapMode', 'GPUOutOfMemoryError', 'GPUPipelineError', 'GPUPipelineLayout', 'GPUQuerySet', 'GPUQueue', 'GPURenderBundle', 'GPURenderBundleEncoder', 'GPURenderPassEncoder', 'GPURenderPipeline', 'GPUSampler', 'GPUShaderModule', 'GPUShaderStage', 'GPUSupportedFeatures', 'GPUSupportedLimits', 'GPUTexture', 'GPUTextureUsage', 'GPUTextureView', 'GPUUncapturedErrorEvent', 'GPUValidationError', 'GravitySensor', 'Gyroscope', 'IdleDetector', 'ImageDecoder', 'ImageTrack', 'ImageTrackList', 'Keyboard', 'KeyboardLayoutMap', 'LinearAccelerationSensor', 'Lock', 'LockManager', 'MIDIAccess', 'MIDIConnectionEvent', 'MIDIInput', 'MIDIInputMap', 'MIDIMessageEvent', 'MIDIOutput', 'MIDIOutputMap', 'MIDIPort', 'MediaDeviceInfo', 'MediaDevices', 'MediaKeyMessageEvent', 'MediaKeySession', 'MediaKeyStatusMap', 'MediaKeySystemAccess', 'MediaKeys', 'NavigationPreloadManager', 'NavigatorManagedData', 'OrientationSensor', 'PasswordCredential', 'RelativeOrientationSensor', 'ScreenDetailed', 'ScreenDetails', 'Sensor', 'SensorErrorEvent', 'ServiceWorker', 'ServiceWorkerContainer', 'ServiceWorkerRegistration', 'StorageManager', 'VideoDecoder', 'VideoEncoder', 'VirtualKeyboard', 'WGSLLanguageFeatures', 'WebTransport', 'WebTransportBidirectionalStream', 'WebTransportDatagramDuplexStream', 'WebTransportError', 'Worklet', 'XRDOMOverlayState', 'XRLayer', 'XRWebGLBinding', 'AuthenticatorAssertionResponse', 'AuthenticatorAttestationResponse', 'AuthenticatorResponse', 'PublicKeyCredential', 'BarcodeDetector', 'Bluetooth', 'BluetoothCharacteristicProperties', 'BluetoothDevice', 'BluetoothRemoteGATTCharacteristic', 'BluetoothRemoteGATTDescriptor', 'BluetoothRemoteGATTServer', 'BluetoothRemoteGATTService', 'CaptureController', 'DocumentPictureInPicture', 'EyeDropper', 'FileSystemDirectoryHandle', 'FileSystemFileHandle', 'FileSystemHandle', 'FileSystemWritableFileStream', 'FontData', 'FragmentDirective', 'HID', 'HIDConnectionEvent', 'HIDDevice', 'HIDInputReportEvent', 'HandwritingStroke', 'IdentityCredential', 'IdentityProvider', 'IdentityCredentialError', 'LaunchParams', 'LaunchQueue', 'NavigatorLogin', 'NotRestoredReasonDetails', 'NotRestoredReasons', 'OTPCredential', 'PaymentAddress', 'PaymentRequest', 'PaymentRequestUpdateEvent', 'PaymentResponse', 'PaymentManager', 'PaymentMethodChangeEvent', 'Presentation', 'PresentationAvailability', 'PresentationConnection', 'PresentationConnectionAvailableEvent', 'PresentationConnectionCloseEvent', 'PresentationConnectionList', 'PresentationReceiver', 'PresentationRequest', 'PressureObserver', 'PressureRecord', 'ProtectedAudience', 'Serial', 'SerialPort', 'StorageBucket', 'StorageBucketManager', 'USB', 'USBAlternateInterface', 'USBConfiguration', 'USBConnectionEvent', 'USBDevice', 'USBEndpoint', 'USBInTransferResult', 'USBInterface', 'USBIsochronousInTransferPacket', 'USBIsochronousInTransferResult', 'USBIsochronousOutTransferPacket', 'USBIsochronousOutTransferResult', 'USBOutTransferResult', 'WakeLock', 'WakeLockSentinel', 'XRAnchor', 'XRAnchorSet', 'XRBoundedReferenceSpace', 'XRCPUDepthInformation', 'XRCamera', 'XRDepthInformation', 'XRFrame', 'XRHitTestResult', 'XRHitTestSource', 'XRInputSource', 'XRInputSourceArray', 'XRInputSourceEvent', 'XRInputSourcesChangeEvent', 'XRLightEstimate', 'XRLightProbe', 'XRPose', 'XRRay', 'XRReferenceSpace', 'XRReferenceSpaceEvent', 'XRRenderState', 'XRRigidTransform', 'XRSession', 'XRSessionEvent', 'XRSpace', 'XRSystem', 'XRTransientInputHitTestResult', 'XRTransientInputHitTestSource', 'XRView', 'XRViewerPose', 'XRViewport', 'XRWebGLDepthInformation', 'XRWebGLLayer', 'XRHand', 'XRJointPose', 'XRJointSpace', 'getDigitalGoodsService', 'getScreenDetails', 'queryLocalFonts', 'showDirectoryPicker', 'showOpenFilePicker', 'showSaveFilePicker', 'copy'];
|
9
|
+
|
10
|
+
const NODE_AND_WEB_GLOBALS = {AbortController, Blob, ByteLengthQueuingStrategy, atob, BroadcastChannel, btoa, clearInterval, clearTimeout, CloseEvent, CompressionStream, console, CountQueuingStrategy, Crypto, crypto, CryptoKey, CustomEvent, DecompressionStream, Event, EventSource, EventTarget, fetch, FormData, Headers, localStorage, MessageChannel, MessageEvent, MessagePort, Navigator, navigator, PerformanceEntry, PerformanceMark, PerformanceMeasure, PerformanceObserver, PerformanceObserverEntryList, performance, queueMicrotask, ReadableByteStreamController, Response, Request, sessionStorage, setInterval, setTimeout, Storage, structuredClone, SubtleCrypto, DOMException, TextDecoder, TextDecoderStream, TextEncoder, TextEncoderStream, TransformStreamDefaultController, URL, URLSearchParams, WebAssembly, WebSocket, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter};
|
11
|
+
|
12
|
+
let modules: Map<string, any> = new Map();
|
13
|
+
let builtinModules: Map<string, any> = new Map();
|
14
|
+
|
15
|
+
globalThis.__fakeNode_modules = modules;
|
16
|
+
globalThis.__fakeNode_builtinModules = builtinModules;
|
17
|
+
|
18
|
+
function require(name: string): any {
|
19
|
+
if (modules.has(name)) {
|
20
|
+
return modules.get(name);
|
21
|
+
} else if (builtinModules.has(name)) {
|
22
|
+
return builtinModules.get(name);
|
23
|
+
} else {
|
24
|
+
throw new Error(`cannot find module '${name}'`);
|
25
|
+
}
|
26
|
+
}
|
27
|
+
|
28
|
+
const NODE_ONLY_GLOBALS = {Buffer, require, process};
|
29
|
+
|
30
|
+
let globals = {};
|
31
|
+
Object.assign(globals, ES_GLOBALS);
|
32
|
+
for (const name of WEB_ONLY_GLOBALS) {
|
33
|
+
Object.defineProperty(globals, name, {get: () => {throw new ReferenceError(`${name} is not defined`)}});
|
34
|
+
}
|
35
|
+
Object.assign(globals, NODE_AND_WEB_GLOBALS);
|
36
|
+
Object.assign(globals, NODE_ONLY_GLOBALS);
|
37
|
+
|
38
|
+
export default globals;
|
package/index.js
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
throw new ReferenceError('module is not defined');
|
package/index.ts
ADDED
@@ -0,0 +1,80 @@
|
|
1
|
+
|
2
|
+
import globals from './globals';
|
3
|
+
|
4
|
+
import * as module_assert from './modules/assert';
|
5
|
+
import * as module_buffer from './modules/buffer';
|
6
|
+
import * as module_fs from './modules/fs';
|
7
|
+
import * as module_os from './modules/os';
|
8
|
+
import * as module_path from './modules/path';
|
9
|
+
import * as module_process from './modules/process';
|
10
|
+
import * as module_querystring from './modules/querystring';
|
11
|
+
import * as module_util from './modules/util';
|
12
|
+
|
13
|
+
function setup(path?: string, argv: string[] = []): object {
|
14
|
+
module_process._argv.argv = argv;
|
15
|
+
let scope: {[key: string]: any} = {};
|
16
|
+
Object.assign(scope, globals);
|
17
|
+
let readonly: {[key: string]: any} = {};
|
18
|
+
scope.global = scope;
|
19
|
+
scope.globalThis = scope;
|
20
|
+
globalThis.__fakeNode_oldWd = globalThis.__fakeNode_wd;
|
21
|
+
if (path !== undefined) {
|
22
|
+
const splitPath = path.split('/');
|
23
|
+
readonly.__dirname = splitPath.slice(0, -1).join('/');
|
24
|
+
readonly.__filename = splitPath[splitPath.length - 1];
|
25
|
+
scope.__fakeNode_wd = readonly.__dirname;
|
26
|
+
}
|
27
|
+
Object.defineProperties(scope, Object.fromEntries(Object.entries(readonly).map(([name, value]) => [name, {value: value, writable: false}])));
|
28
|
+
return scope;
|
29
|
+
}
|
30
|
+
|
31
|
+
globalThis.__fakeNode_setup = setup;
|
32
|
+
|
33
|
+
function cleanup(): void {
|
34
|
+
globalThis.__fakeNode_wd = globalThis.__fakeNode_oldWd;
|
35
|
+
}
|
36
|
+
|
37
|
+
globalThis.__fakeNode_cleanup = cleanup;
|
38
|
+
|
39
|
+
function run(code: string, argv: string[] = []): void {
|
40
|
+
code = `with(window.__fakeNode_setup(undefined,${JSON.stringify(argv)})){(function(){${code}})();window.__fakeNode_cleanup();}`;
|
41
|
+
let elt = document.createElement('script');
|
42
|
+
elt.textContent = code;
|
43
|
+
document.body.appendChild(elt);
|
44
|
+
}
|
45
|
+
|
46
|
+
function addModule(name: string, code: string): void {
|
47
|
+
code = `with(window.__fakeNode_setup()){window.__fakeNode_modules.set('${name}',(function(){${code};return module.exports;})();window.__fakeNode_cleanup();}`;
|
48
|
+
let elt = document.createElement('script');
|
49
|
+
elt.textContent = code;
|
50
|
+
document.body.appendChild(elt);
|
51
|
+
}
|
52
|
+
|
53
|
+
function addBuiltinModule(name: string, data: any): void {
|
54
|
+
globalThis.__fakeNode_builtinModules.set(name, data);
|
55
|
+
}
|
56
|
+
|
57
|
+
function deleteModule(name: string): void {
|
58
|
+
globalThis.__fakeNode_modules.delete(name);
|
59
|
+
}
|
60
|
+
|
61
|
+
function deleteBuiltinModule(name: string): void {
|
62
|
+
globalThis.__fakeNode_builtinModules.delete(name);
|
63
|
+
}
|
64
|
+
|
65
|
+
addBuiltinModule('assert', module_assert);
|
66
|
+
addBuiltinModule('buffer', module_buffer);
|
67
|
+
addBuiltinModule('fs', module_fs);
|
68
|
+
addBuiltinModule('os', module_os);
|
69
|
+
addBuiltinModule('path', module_path);
|
70
|
+
addBuiltinModule('process', module_process);
|
71
|
+
addBuiltinModule('querystring', module_querystring);
|
72
|
+
addBuiltinModule('util', module_util);
|
73
|
+
|
74
|
+
export {
|
75
|
+
run,
|
76
|
+
addModule,
|
77
|
+
addBuiltinModule,
|
78
|
+
deleteModule,
|
79
|
+
deleteBuiltinModule,
|
80
|
+
}
|
@@ -0,0 +1,205 @@
|
|
1
|
+
|
2
|
+
export class AssertionError extends Error {
|
3
|
+
|
4
|
+
message: string;
|
5
|
+
actual: any;
|
6
|
+
expected: any;
|
7
|
+
operator: string;
|
8
|
+
generatedMessage: boolean;
|
9
|
+
name: 'AssertionError' = 'AssertionError';
|
10
|
+
|
11
|
+
constructor({message, actual, expected, operator}: {message?: string | Error, actual?: any, expected?: any, operator: string}) {
|
12
|
+
super();
|
13
|
+
this.actual = actual;
|
14
|
+
this.expected = expected.
|
15
|
+
this.operator = operator;
|
16
|
+
if (message !== undefined) {
|
17
|
+
this.message = message instanceof Error ? message.message : message;
|
18
|
+
this.generatedMessage = false;
|
19
|
+
} else {
|
20
|
+
// todo: finish this
|
21
|
+
this.message = `expected ${expected} but got ${actual} using ${operator}`;
|
22
|
+
this.generatedMessage = true;
|
23
|
+
}
|
24
|
+
}
|
25
|
+
|
26
|
+
get [Symbol.toStringTag]() {
|
27
|
+
return 'AssertionError';
|
28
|
+
}
|
29
|
+
|
30
|
+
}
|
31
|
+
|
32
|
+
export function deepEqual(actual: any, expected: any, message?: string | Error): void {
|
33
|
+
if (typeof actual === 'object' && actual !== null) {
|
34
|
+
if (typeof expected === 'object' && expected !== null) {
|
35
|
+
// todo: finish this
|
36
|
+
let expectedKeys = Object.keys(expected);
|
37
|
+
for (const key of Object.keys(actual)) {
|
38
|
+
if (!expectedKeys.includes(key)) {
|
39
|
+
throw new AssertionError({message, actual, expected, operator: 'deepEqual'});
|
40
|
+
}
|
41
|
+
expectedKeys = expectedKeys.filter(x => x !== key);
|
42
|
+
}
|
43
|
+
if (expectedKeys.length > 0) {
|
44
|
+
throw new AssertionError({message, actual, expected, operator: 'deepEqual'});
|
45
|
+
}
|
46
|
+
} else {
|
47
|
+
throw new AssertionError({message, actual, expected, operator: 'deepEqual'});
|
48
|
+
}
|
49
|
+
} else {
|
50
|
+
if (actual != expected && !(Number.isNaN(actual) && Number.isNaN(expected))) {
|
51
|
+
throw new AssertionError({message, actual, expected, operator: 'deepEqual'});
|
52
|
+
}
|
53
|
+
}
|
54
|
+
}
|
55
|
+
|
56
|
+
export function deepStrictEqual(actual: any, expected: any, message?: string | Error): void {
|
57
|
+
if (typeof actual === 'object' && actual !== null) {
|
58
|
+
if (typeof expected === 'object' && expected !== null) {
|
59
|
+
// todo: finish this
|
60
|
+
let expectedKeys = Object.keys(expected);
|
61
|
+
for (const key of Object.keys(actual)) {
|
62
|
+
if (!expectedKeys.includes(key)) {
|
63
|
+
throw new AssertionError({message, actual, expected, operator: 'deepStrictEqual'});
|
64
|
+
}
|
65
|
+
expectedKeys = expectedKeys.filter(x => x !== key);
|
66
|
+
}
|
67
|
+
if (expectedKeys.length > 0) {
|
68
|
+
throw new AssertionError({message, actual, expected, operator: 'deepStrictEqual'});
|
69
|
+
}
|
70
|
+
} else {
|
71
|
+
throw new AssertionError({message, actual, expected, operator: 'deepStrictEqual'});
|
72
|
+
}
|
73
|
+
} else {
|
74
|
+
if (actual !== expected && !(Number.isNaN(actual) && Number.isNaN(expected))) {
|
75
|
+
throw new AssertionError({message, actual, expected, operator: 'deepStrictEqual'});
|
76
|
+
}
|
77
|
+
}
|
78
|
+
}
|
79
|
+
|
80
|
+
export function doesNotMatch(string: string, regexp: RegExp, message?: string | Error): void {
|
81
|
+
if (string.match(regexp)) {
|
82
|
+
throw new AssertionError({message, operator: 'doesNotMatch'});
|
83
|
+
}
|
84
|
+
}
|
85
|
+
|
86
|
+
export function equal(expected: any, actual: any, message?: string | Error): void {
|
87
|
+
if (actual != expected && !(Number.isNaN(actual) && Number.isNaN(expected))) {
|
88
|
+
throw new AssertionError({message, actual, expected, operator: 'equal'});
|
89
|
+
}
|
90
|
+
}
|
91
|
+
|
92
|
+
export function fail(message: string | Error = 'Failed'): void {
|
93
|
+
throw new AssertionError({message, operator: 'fail'});
|
94
|
+
}
|
95
|
+
|
96
|
+
export function ifError(value: any): void {
|
97
|
+
if (value !== undefined && value !== null) {
|
98
|
+
throw new AssertionError({operator: 'ifError'});
|
99
|
+
}
|
100
|
+
}
|
101
|
+
|
102
|
+
export function match(string: string, regexp: RegExp, message?: string | Error): void {
|
103
|
+
if (!string.match(regexp)) {
|
104
|
+
throw new AssertionError({message, operator: 'match'});
|
105
|
+
}
|
106
|
+
}
|
107
|
+
|
108
|
+
export function notDeepEqual(actual: any, expected: any, message?: string | Error): void {
|
109
|
+
try {
|
110
|
+
deepEqual(actual, expected);
|
111
|
+
} catch (error) {
|
112
|
+
if (error instanceof AssertionError) {
|
113
|
+
return;
|
114
|
+
} else {
|
115
|
+
throw error;
|
116
|
+
}
|
117
|
+
}
|
118
|
+
throw new AssertionError({message, actual, expected, operator: 'notDeepEqual'});
|
119
|
+
}
|
120
|
+
|
121
|
+
export function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void {
|
122
|
+
try {
|
123
|
+
deepStrictEqual(actual, expected);
|
124
|
+
} catch (error) {
|
125
|
+
if (error instanceof AssertionError) {
|
126
|
+
return;
|
127
|
+
} else {
|
128
|
+
throw error;
|
129
|
+
}
|
130
|
+
}
|
131
|
+
throw new AssertionError({message, actual, expected, operator: 'notDeepStrictEqual'});
|
132
|
+
}
|
133
|
+
|
134
|
+
export function notEqual(actual: any, expected: any, message?: string | Error): void {
|
135
|
+
try {
|
136
|
+
equal(actual, expected);
|
137
|
+
} catch (error) {
|
138
|
+
if (error instanceof AssertionError) {
|
139
|
+
return;
|
140
|
+
} else {
|
141
|
+
throw error;
|
142
|
+
}
|
143
|
+
}
|
144
|
+
throw new AssertionError({message, actual, expected, operator: 'notEqual'});
|
145
|
+
}
|
146
|
+
|
147
|
+
export function notStrictEqual(actual: any, expected: any, message?: string | Error): void {
|
148
|
+
try {
|
149
|
+
strictEqual(actual, expected);
|
150
|
+
} catch (error) {
|
151
|
+
if (error instanceof AssertionError) {
|
152
|
+
return;
|
153
|
+
} else {
|
154
|
+
throw error;
|
155
|
+
}
|
156
|
+
}
|
157
|
+
throw new AssertionError({message, actual, expected, operator: 'notStrictEqual'});
|
158
|
+
}
|
159
|
+
|
160
|
+
export function ok(value: any, message?: string | Error): void {
|
161
|
+
if (!value) {
|
162
|
+
throw new AssertionError({message, operator: 'ok'})
|
163
|
+
}
|
164
|
+
}
|
165
|
+
|
166
|
+
export function strictEqual(expected: any, actual: any, message?: string | Error): void {
|
167
|
+
if (actual !== expected && !(Number.isNaN(actual) && Number.isNaN(expected))) {
|
168
|
+
throw new AssertionError({message, actual, expected, operator: 'strictEqual'});
|
169
|
+
}
|
170
|
+
}
|
171
|
+
|
172
|
+
export function assert(value: any, message?: string | Error): void {
|
173
|
+
ok(value, message);
|
174
|
+
}
|
175
|
+
|
176
|
+
Object.assign(assert, {
|
177
|
+
deepEqual,
|
178
|
+
deepStrictEqual,
|
179
|
+
doesNotMatch,
|
180
|
+
equal,
|
181
|
+
fail,
|
182
|
+
ifError,
|
183
|
+
match,
|
184
|
+
notDeepEqual,
|
185
|
+
notDeepStrictEqual,
|
186
|
+
notEqual,
|
187
|
+
notStrictEqual,
|
188
|
+
ok,
|
189
|
+
strictEqual,
|
190
|
+
strict: {
|
191
|
+
deepEqual: deepStrictEqual,
|
192
|
+
deepStrictEqual,
|
193
|
+
doesNotMatch,
|
194
|
+
equal: strictEqual,
|
195
|
+
fail,
|
196
|
+
ifError,
|
197
|
+
match,
|
198
|
+
notDeepEqual: notDeepStrictEqual,
|
199
|
+
notDeepStrictEqual,
|
200
|
+
notEqual: notStrictEqual,
|
201
|
+
notStrictEqual,
|
202
|
+
ok,
|
203
|
+
strictEqual,
|
204
|
+
},
|
205
|
+
});
|
package/modules/fs.ts
ADDED
package/modules/os.ts
ADDED
@@ -0,0 +1,81 @@
|
|
1
|
+
|
2
|
+
export const EOL = '\r\n';
|
3
|
+
|
4
|
+
export function availableParallelism(): number {
|
5
|
+
return navigator.hardwareConcurrency;
|
6
|
+
}
|
7
|
+
|
8
|
+
export function arch(): string {
|
9
|
+
return 'web';
|
10
|
+
}
|
11
|
+
|
12
|
+
export const constants = {
|
13
|
+
|
14
|
+
};
|
15
|
+
|
16
|
+
export function cpus(): {model: string, speed: number, times: {user: number, nice: number, sys: number, idle: number, irq: number}}[] {
|
17
|
+
return [];
|
18
|
+
}
|
19
|
+
|
20
|
+
export const devNull = '/dev/null';
|
21
|
+
|
22
|
+
export function endianness(): string {
|
23
|
+
return 'LE';
|
24
|
+
}
|
25
|
+
|
26
|
+
export function freemem(): number {
|
27
|
+
// @ts-ignore
|
28
|
+
return navigator.deviceMemory * 2**30;
|
29
|
+
}
|
30
|
+
|
31
|
+
export function homedir(): string {
|
32
|
+
return '/home/root';
|
33
|
+
}
|
34
|
+
|
35
|
+
export function hostname(): string {
|
36
|
+
return 'fake-node';
|
37
|
+
}
|
38
|
+
|
39
|
+
export function loadavg(): [number, number, number] {
|
40
|
+
return [0, 0, 0];
|
41
|
+
}
|
42
|
+
|
43
|
+
export function machine(): string {
|
44
|
+
return 'fake';
|
45
|
+
}
|
46
|
+
|
47
|
+
export function platform(): string {
|
48
|
+
const data = navigator.userAgent.slice('Mozilla/5.0 ('.length, navigator.userAgent.indexOf(')'));
|
49
|
+
if (data.includes('Windows')) {
|
50
|
+
return 'win32';
|
51
|
+
} else if (data.includes('Linux')) {
|
52
|
+
return 'linux';
|
53
|
+
} else if (data.includes('Mac')) {
|
54
|
+
return 'darwin';
|
55
|
+
} else {
|
56
|
+
return 'unknown';
|
57
|
+
}
|
58
|
+
}
|
59
|
+
|
60
|
+
export function tmpdir(): string {
|
61
|
+
return '/tmp';
|
62
|
+
}
|
63
|
+
|
64
|
+
export function totalmem(): number {
|
65
|
+
// @ts-ignore
|
66
|
+
return navigator.deviceMemory * 2**30;
|
67
|
+
}
|
68
|
+
|
69
|
+
export function type(): string {
|
70
|
+
const data = navigator.userAgent.slice('Mozilla/5.0 ('.length, navigator.userAgent.indexOf(')'));
|
71
|
+
if (data.includes('Windows NT')) {
|
72
|
+
return 'Windows_NT';
|
73
|
+
} else if (data.includes('Linux')) {
|
74
|
+
return 'Linux';
|
75
|
+
} else if (data.includes('Mac')) {
|
76
|
+
return 'Darwin';
|
77
|
+
} else {
|
78
|
+
return 'unknown';
|
79
|
+
}
|
80
|
+
}
|
81
|
+
|
package/modules/path.ts
ADDED
@@ -0,0 +1,56 @@
|
|
1
|
+
|
2
|
+
export function basename(path: string, suffix?: string): string {
|
3
|
+
const parts = path.split('/');
|
4
|
+
let out = parts[parts.length - 1];
|
5
|
+
if (suffix !== undefined && out.endsWith(suffix)) {
|
6
|
+
out = out.slice(0, out.length - suffix.length);
|
7
|
+
}
|
8
|
+
return out;
|
9
|
+
}
|
10
|
+
|
11
|
+
export const delimiter = ':';
|
12
|
+
|
13
|
+
export function dirname(path: string): string {
|
14
|
+
const parts = path.split('/');
|
15
|
+
return parts.slice(0, parts.length - 1).join('/');
|
16
|
+
}
|
17
|
+
|
18
|
+
export function extname(path: string): string {
|
19
|
+
const parts = path.split('.');
|
20
|
+
return parts[parts.length - 1];
|
21
|
+
}
|
22
|
+
|
23
|
+
export function isAbsolute(path: string): boolean {
|
24
|
+
return path.startsWith('/');
|
25
|
+
}
|
26
|
+
|
27
|
+
export function join(...paths: string[]): string {
|
28
|
+
return normalize(paths.join('/'));
|
29
|
+
}
|
30
|
+
|
31
|
+
export function normalize(path: string): string {
|
32
|
+
let out: string[] = [];
|
33
|
+
const segments = path.split('/');
|
34
|
+
for (let i = 0; i < segments.length; i++) {
|
35
|
+
const segment = segments[i];
|
36
|
+
if ((segment === '.' && i !== 0) || segment === '') {
|
37
|
+
continue;
|
38
|
+
} else if (segment === '..') {
|
39
|
+
out.pop();
|
40
|
+
} else {
|
41
|
+
out.push(segment);
|
42
|
+
}
|
43
|
+
}
|
44
|
+
return out.join('');
|
45
|
+
}
|
46
|
+
|
47
|
+
export function resolve(...paths: string[]): string {
|
48
|
+
const path = join(...paths);
|
49
|
+
if (path.startsWith('/')) {
|
50
|
+
return path;
|
51
|
+
} else {
|
52
|
+
return globalThis.__fakeNode_wd + path;
|
53
|
+
}
|
54
|
+
}
|
55
|
+
|
56
|
+
export const sep = '/';
|
@@ -0,0 +1,78 @@
|
|
1
|
+
|
2
|
+
import {join} from './path';
|
3
|
+
import {platform as _platform} from './os';
|
4
|
+
|
5
|
+
export function abort(): void {
|
6
|
+
window.close();
|
7
|
+
}
|
8
|
+
|
9
|
+
export const allowedNodeEnvironmentFlags = new Set<never>();
|
10
|
+
|
11
|
+
export let _argv: {argv: string[]} = {argv: []};
|
12
|
+
export const argv = _argv.argv;
|
13
|
+
|
14
|
+
export const argv0 = '/usr/bin/local/node';
|
15
|
+
|
16
|
+
export const channel = undefined;
|
17
|
+
|
18
|
+
export function chdir(directory: string): void {
|
19
|
+
globalThis.__fakeNode_wd = join(globalThis.__fakeNode_wd, directory);
|
20
|
+
}
|
21
|
+
|
22
|
+
export const config = {};
|
23
|
+
|
24
|
+
export const connected = undefined;
|
25
|
+
|
26
|
+
export function constrainedMemory(): number {
|
27
|
+
return 0;
|
28
|
+
}
|
29
|
+
|
30
|
+
export function availableMemory(): number {
|
31
|
+
// @ts-ignore
|
32
|
+
return navigator.deviceMemory * 2**30;
|
33
|
+
}
|
34
|
+
|
35
|
+
export function cwd(): string {
|
36
|
+
return globalThis.__fakeNode_wd;
|
37
|
+
}
|
38
|
+
|
39
|
+
export const env = {
|
40
|
+
SHELL: '/usr/local/bin/bash',
|
41
|
+
USER: 'root',
|
42
|
+
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
|
43
|
+
PWD: '/home/root',
|
44
|
+
EDITOR: 'vim',
|
45
|
+
SHLVL: '1',
|
46
|
+
HOME: '/home/root',
|
47
|
+
LOGNAME: 'root',
|
48
|
+
_: '/usr/local/bin/node'
|
49
|
+
};
|
50
|
+
|
51
|
+
export const execPath = '/usr/bin/local/node';
|
52
|
+
|
53
|
+
export function exit(code: number = 0): void {
|
54
|
+
console.log('Exit code', code);
|
55
|
+
window.close();
|
56
|
+
}
|
57
|
+
|
58
|
+
export const exitCode = undefined;
|
59
|
+
|
60
|
+
export const features = {
|
61
|
+
cached_builtins: true,
|
62
|
+
debug: false,
|
63
|
+
inspector: false,
|
64
|
+
ipv6: true,
|
65
|
+
require_module: true,
|
66
|
+
tls: false,
|
67
|
+
tls_alpn: false,
|
68
|
+
tls_ocsp: false,
|
69
|
+
tls_sni: false,
|
70
|
+
typescript: false,
|
71
|
+
uv: false,
|
72
|
+
};
|
73
|
+
|
74
|
+
export function getBuiltinModule(id: string): any {
|
75
|
+
return globalThis.__fakeNode_builtinModules[id];
|
76
|
+
}
|
77
|
+
|
78
|
+
export const platform = _platform();
|
@@ -0,0 +1,33 @@
|
|
1
|
+
|
2
|
+
type Parsed = object;
|
3
|
+
|
4
|
+
export function decode(str: string) {
|
5
|
+
return parse(str);
|
6
|
+
}
|
7
|
+
|
8
|
+
export function encode(obj: Parsed): string {
|
9
|
+
return stringify(obj);
|
10
|
+
}
|
11
|
+
|
12
|
+
export function parse(str: string): Parsed {
|
13
|
+
let obj = Object.create(null);
|
14
|
+
const params = new URLSearchParams(str);
|
15
|
+
for (const key of params.keys()) {
|
16
|
+
obj[key] = params.getAll(key);
|
17
|
+
}
|
18
|
+
return obj;
|
19
|
+
}
|
20
|
+
|
21
|
+
export function stringify(obj: Parsed): string {
|
22
|
+
let params = new URLSearchParams();
|
23
|
+
for (const [key, value] of Object.entries(obj)) {
|
24
|
+
if (typeof value === 'string') {
|
25
|
+
params.append(key, value);
|
26
|
+
} else {
|
27
|
+
for (const item of Object.keys(value)) {
|
28
|
+
params.append(key, item);
|
29
|
+
}
|
30
|
+
}
|
31
|
+
}
|
32
|
+
return params.toString();
|
33
|
+
}
|
package/modules/util.ts
ADDED
@@ -0,0 +1,116 @@
|
|
1
|
+
|
2
|
+
export function callbackify(original: (...args: any[]) => Promise<any>): (...args: [...any[], (err: Error | null, value: any) => void]) => void {
|
3
|
+
return function(...args: [...any[], (err: Error | null, value: any) => void]): void {
|
4
|
+
const callback = args[args.length - 1];
|
5
|
+
original(...args.slice(0, -1)).then((value: any) => callback(null, value)).catch((reason) => callback(reason instanceof Error ?
|
6
|
+
reason : new Error(reason), null));
|
7
|
+
};
|
8
|
+
}
|
9
|
+
|
10
|
+
const PERCENT_REGEX = /(?<!%)(%[sdifjoOc%])/;
|
11
|
+
|
12
|
+
export function format(format: string, ...args: any[]): string {
|
13
|
+
const parts = format.split(PERCENT_REGEX);
|
14
|
+
let out = '';
|
15
|
+
let j = 0;
|
16
|
+
for (let i = 0; i < parts.length; i++) {
|
17
|
+
const part = parts[i];
|
18
|
+
if (i % 2 === 0) {
|
19
|
+
out += part;
|
20
|
+
} else if (part === '%%') {
|
21
|
+
out += '%';
|
22
|
+
} else {
|
23
|
+
const arg = args[j];
|
24
|
+
if (part === '%s') {
|
25
|
+
if (typeof arg === 'object') {
|
26
|
+
if (arg === null) {
|
27
|
+
out += String(part);
|
28
|
+
} else {
|
29
|
+
if (arg.toString === Object.prototype.toString) {
|
30
|
+
out += inspect(arg, {depth: 0, colors: false, compact: 3});
|
31
|
+
} else {
|
32
|
+
out += arg.toString();
|
33
|
+
}
|
34
|
+
}
|
35
|
+
} else if (typeof part === 'bigint') {
|
36
|
+
out += String(part) + 'n';
|
37
|
+
} else {
|
38
|
+
out += String(part);
|
39
|
+
}
|
40
|
+
} else if (part === '%d') {
|
41
|
+
if (typeof arg === 'bigint') {
|
42
|
+
out += String(arg) + 'n';
|
43
|
+
} else if (typeof arg === 'symbol') {
|
44
|
+
out += String(arg);
|
45
|
+
} else {
|
46
|
+
out += String(Number(arg));
|
47
|
+
}
|
48
|
+
} else if (part === '%i') {
|
49
|
+
if (typeof arg === 'symbol') {
|
50
|
+
out += String(arg);
|
51
|
+
} else {
|
52
|
+
out += String(parseInt(arg, 10));
|
53
|
+
}
|
54
|
+
} else if (part === '%f') {
|
55
|
+
if (typeof arg === 'symbol') {
|
56
|
+
out += String(arg);
|
57
|
+
} else {
|
58
|
+
out += String(parseFloat(arg));
|
59
|
+
}
|
60
|
+
} else if (part === '%j') {
|
61
|
+
out += JSON.stringify(part);
|
62
|
+
} else if (part === '%o') {
|
63
|
+
out += inspect(part, {showHidden: true, showProxy: true});
|
64
|
+
} else if (part === '%O') {
|
65
|
+
out += inspect(part);
|
66
|
+
}
|
67
|
+
j++;
|
68
|
+
}
|
69
|
+
}
|
70
|
+
return out;
|
71
|
+
}
|
72
|
+
|
73
|
+
interface InspectOptions {
|
74
|
+
showHidden?: boolean;
|
75
|
+
depth?: number;
|
76
|
+
colors?: boolean;
|
77
|
+
customInspect?: boolean;
|
78
|
+
showProxy?: boolean;
|
79
|
+
maxArrayLength?: number;
|
80
|
+
maxStringLength?: number;
|
81
|
+
breakLength?: number;
|
82
|
+
compact?: false | number;
|
83
|
+
sorted?: true | ((a: any, b: any) => number);
|
84
|
+
getters?: boolean | 'get';
|
85
|
+
numericSeperator?: boolean;
|
86
|
+
}
|
87
|
+
|
88
|
+
export function inspect(object: any, {showHidden = false, depth = 2, colors = false, customInspect = true, showProxy = false, maxArrayLength = 100, maxStringLength = 10000, breakLength = 80, compact = 3, sorted = true, getters = false, numericSeperator = false}: InspectOptions = {}): string {
|
89
|
+
if (typeof object !== 'object' || object === 'null') {
|
90
|
+
return String(object);
|
91
|
+
} else {
|
92
|
+
return '<util.inspect is not implemented yet>';
|
93
|
+
}
|
94
|
+
|
95
|
+
}
|
96
|
+
|
97
|
+
export function promisify(original: (...args: [...any[], (err: Error | null, value: any) => void]) => void): (...args: any[]) => Promise<any> {
|
98
|
+
return async (...args: any[]) => {
|
99
|
+
return new Promise((resolve: (value: any) => void, reject: (reason?: any) => void) => {
|
100
|
+
original(...args, (err: Error | null, value: any) => {
|
101
|
+
if (err) {
|
102
|
+
reject(err);
|
103
|
+
} else {
|
104
|
+
resolve(value);
|
105
|
+
}
|
106
|
+
});
|
107
|
+
|
108
|
+
});
|
109
|
+
};
|
110
|
+
}
|
111
|
+
|
112
|
+
const ANSI_CONTROL_REGEX = /\x1b\[[0-?]*[ -\/]*[@-~]/g;
|
113
|
+
|
114
|
+
export function stripVTControlCharacters(str: string) {
|
115
|
+
return str.replace(ANSI_CONTROL_REGEX, '');
|
116
|
+
}
|
package/package.json
ADDED
@@ -0,0 +1,14 @@
|
|
1
|
+
{
|
2
|
+
"name": "fake-node",
|
3
|
+
"version": "0.1.0",
|
4
|
+
"description": "A fake version of Node that works in the browser",
|
5
|
+
"license": "MIT",
|
6
|
+
"author": "speedydelete",
|
7
|
+
"type": "module",
|
8
|
+
"main": "index.js",
|
9
|
+
"homepage": "https://github.com/speedydelete/fake-node",
|
10
|
+
"repository": "github:speedydelete/fake-node",
|
11
|
+
"scripts": {
|
12
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
13
|
+
}
|
14
|
+
}
|