file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
ssce_messages_not_processed/launch/run_until_fail.launch.py
Python
# Copyright 2023 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import launch.actions import launch.event_handlers from launch import LaunchDescription import launch_ros.actions def generate_launch_description(): receiver_action = launch_ros.actions.Node( package='ssce_messages_not_processed', executable='receiver', output='screen') return LaunchDescription([ receiver_action, launch.actions.RegisterEventHandler( launch.event_handlers.OnProcessExit( target_action=receiver_action, on_exit=[ launch.actions.LogInfo(msg=["Receiver process exited, stopping the test..."]), launch.actions.EmitEvent(event=launch.events.Shutdown()), ], ), ), launch_ros.actions.Node( package='ssce_messages_not_processed', executable='sender.py', output='screen', respawn=True, respawn_delay=3.0, ), ])
wjwwood/ssce_messages_not_processed
0
Python
wjwwood
William Woodall
ssce_messages_not_processed/scripts/sender.py
Python
#!/usr/bin/env python3 # Copyright 2023 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from threading import Thread from time import sleep import rclpy from rclpy.node import Node from rclpy.duration import Duration from std_msgs.msg import Header class BurstSender(Node): def __init__(self): super().__init__('burst_sender') self.publisher_ = self.create_publisher(Header, 'data', 10) timer_period = 0.5 # seconds self.i = 1 self.number_of_expected_subscriptions = 1 def wait_for_subscriptions(self): matched_subscriptions = self.publisher_.get_subscription_count() while matched_subscriptions < self.number_of_expected_subscriptions: print( f'Waiting on subscriptions... ' f'{matched_subscriptions}/{self.number_of_expected_subscriptions}') sleep(0.1) matched_subscriptions = self.publisher_.get_subscription_count() def timer_callback(self): msg = Header() msg.frame_id = 'Hello World: %d' % self.i msg.stamp = self.get_clock().now().to_msg() self.publisher_.publish(msg) self.get_logger().info(f'Publishing: {msg}') self.i += 1 def main(args=None): rclpy.init(args=args) minimal_publisher = BurstSender() spin_thread = Thread(target=rclpy.spin, args=(minimal_publisher,)) spin_thread.start() minimal_publisher.wait_for_subscriptions() for x in range(8): minimal_publisher.timer_callback() timeout = 10 if not minimal_publisher.publisher_.wait_for_all_acked(timeout=Duration(seconds=timeout)): raise RuntimeError(f"messages were not sent after {timeout} seconds") rclpy.shutdown() spin_thread.join() if __name__ == '__main__': try: main() except KeyboardInterrupt: pass
wjwwood/ssce_messages_not_processed
0
Python
wjwwood
William Woodall
ssce_messages_not_processed/src/receiver.cpp
C++
// Copyright 2023 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <rclcpp/rclcpp.hpp> #include <std_msgs/msg/header.hpp> int main(int argc, char const *argv[]) { rclcpp::init(argc, argv); auto node = std::make_shared<rclcpp::Node>("receiver"); double time_between_publishes = node->declare_parameter("time_between_publishes", 3.0); auto callback = [node, &time_between_publishes]( const std_msgs::msg::Header & msg, const rclcpp::MessageInfo & message_info ) { auto now = rclcpp::Clock().now(); auto time_received = rclcpp::Time(message_info.get_rmw_message_info().received_timestamp); auto time_sent = rclcpp::Time(msg.stamp, RCL_SYSTEM_TIME); auto transit_time = time_received - time_sent; auto time_waited_for_processing = now - time_received; RCLCPP_INFO_STREAM( node->get_logger(), "Received '" << msg.frame_id << "' msg" << " at '" << std::fixed << time_received.seconds() << "'s" << " - sent at '" << time_sent.seconds() << "'s" << " = transit time of '" << transit_time.seconds() << "'s" ", and processed at '" << now.seconds() << "', wait time: " << time_waited_for_processing.seconds()); if (msg.frame_id == "Hello World: 7") { //std::this_thread::sleep_for(std::chrono::seconds(5)); } if (time_waited_for_processing.seconds() > (time_between_publishes * 0.75)) { RCLCPP_ERROR(node->get_logger(), "Took too long to process message."); rclcpp::shutdown(); } }; rclcpp::SubscriptionOptions so; //so.event_callbacks.matched_callback = [node](const rclcpp::MatchedInfo & matched_info) { // RCLCPP_INFO_STREAM( // node->get_logger(), // "Matched publisher event, " << // "total_count: '" << matched_info.total_count << "', " << // "total_count_change: '" << matched_info.total_count_change << "', " << // "current_count: '" << matched_info.current_count << "', " << // "current_count_change: '" << matched_info.current_count_change << "'"); //}; auto subscription = node->create_subscription<std_msgs::msg::Header>("data", 10, callback, so); rclcpp::spin(node); return 0; }
wjwwood/ssce_messages_not_processed
0
Python
wjwwood
William Woodall
examples/countdown_plugin.py
Python
import imgviz import numpy as np from imshow.plugins import base class Plugin(base.Plugin): @staticmethod def add_arguments(parser): # define additional command line options parser.add_argument( "--number", type=int, default=10, help="number to count down from" ) number: int def __init__(self, args): self.number = args.number def get_items(self): # convert command line options into items to visualize. # each item represent the chunk that is visualized on a single window. yield from range(self.number, -1, -1) def get_image(self, item): # convert item into numpy array image = np.full((480, 640, 3), 220, dtype=np.uint8) font_size = image.shape[0] // 2 height, width = imgviz.draw.text_size(text=f"{item}", size=font_size) image = imgviz.draw.text( src=image, text=f"{item}", yx=(image.shape[0] // 2 - height // 2, image.shape[1] // 2 - width // 2), color=(0, 0, 0), size=font_size, ) return image def get_title(self, item): # convert item into str return str(item)
wkentaro/imshow
13
Imshow - Flexible and Customizable Image Display with Python
Python
wkentaro
Kentaro Wada
mujin
imshow/__init__.py
Python
import importlib.metadata from imshow._imshow import imshow # noqa: F401 __version__ = importlib.metadata.version("imshow")
wkentaro/imshow
13
Imshow - Flexible and Customizable Image Display with Python
Python
wkentaro
Kentaro Wada
mujin
imshow/__main__.py
Python
import argparse import importlib.machinery import os import sys import imshow import imshow.plugins from imshow import _args def main(): parser = argparse.ArgumentParser(add_help=False) parser.add_argument( "--help", "-h", action="store_true", help="show this help message and exit", ) parser.add_argument( "--version", "-V", action="version", version=f"imshow {imshow.__version__}", ) official_plugins = [ plugin for plugin in dir(imshow.plugins) if not plugin.startswith("_") ] parser.add_argument( "--plugin", "-p", default="base", help=f"plugin module or file path. official plugins: " f"{official_plugins}. (default: %(default)r)", ) args, _ = parser.parse_known_args() if os.path.exists(args.plugin): plugin_module = importlib.machinery.SourceFileLoader( "plugin", args.plugin ).load_module() else: try: plugin_module = importlib.import_module(f"imshow.plugins.{args.plugin}") except ModuleNotFoundError: try: plugin_module = importlib.import_module(args.plugin) except ModuleNotFoundError: print(f"Error: plugin {args.plugin!r} is not found.", file=sys.stderr) sys.exit(1) plugin_module.Plugin.add_arguments(parser=parser) args = _args.expand_args(sys.argv[1:]) if os.name == "nt" else sys.argv[1:] args = parser.parse_args(args=args) if args.help: parser.print_help() return plugin = plugin_module.Plugin(args=args) imshow.imshow( items=plugin.get_items(), keymap=plugin.get_keymap(), get_image_from_item=plugin.get_image, get_title_from_item=plugin.get_title, ) if __name__ == "__main__": main()
wkentaro/imshow
13
Imshow - Flexible and Customizable Image Display with Python
Python
wkentaro
Kentaro Wada
mujin
imshow/_args.py
Python
import glob import os from collections.abc import Iterable # https://github.com/pallets/click/blob/cab9483a30379f9b8e3ddb72d5a4e88f88d517b6/src/click/utils.py#L578 # noqa: E501 def expand_args( args: Iterable[str], *, user: bool = True, env: bool = True, glob_recursive: bool = True, ) -> list[str]: out = [] for arg in args: if user: arg = os.path.expanduser(arg) if env: arg = os.path.expandvars(arg) matches = glob.glob(arg, recursive=glob_recursive) if not matches: out.append(arg) else: out.extend(matches) return out
wkentaro/imshow
13
Imshow - Flexible and Customizable Image Display with Python
Python
wkentaro
Kentaro Wada
mujin
imshow/_generators.py
Python
import types from typing import Any class CachedGenerator: def __init__(self, generator: types.GeneratorType) -> None: self._exhausted: bool = False self._generator = generator self._yielded: list = [] @property def exhausted(self) -> bool: return self._exhausted def __iter__(self): return self def __next__(self): try: item = next(self._generator) except StopIteration: self._exhausted = True raise StopIteration self._yielded.append(item) return item def __getitem__(self, index: int) -> Any: return self._yielded[index] def __len__(self) -> int: if self._exhausted: return len(self._yielded) else: raise TypeError("len() of a not fully exhausted generator is not allowed")
wkentaro/imshow
13
Imshow - Flexible and Customizable Image Display with Python
Python
wkentaro
Kentaro Wada
mujin
imshow/_imshow.py
Python
import sys import types from collections.abc import Callable from typing import Any import numpy as np import pyglet from imshow import _generators from imshow import _pyglet def imshow( items: Any, *, keymap: dict | None = None, get_image_from_item: Callable | None = None, get_title_from_item: Callable | None = None, ) -> None: if not isinstance(items, (list, types.GeneratorType)): items = [items] if keymap is None: keymap = {} if get_image_from_item is None: def get_image_from_item(item): return item if get_title_from_item is None: def get_title_from_item(item): return str(item) items = _generators.CachedGenerator(iter(items)) try: item = next(items) except StopIteration: print("No items to show.", file=sys.stderr) return image: np.ndarray = get_image_from_item(item) aspect_ratio: float = image.shape[1] / image.shape[0] # width / height window = _pyglet.initialize_window( aspect_ratio=aspect_ratio, caption=get_title_from_item(item) ) sprite: pyglet.sprite.Sprite = pyglet.sprite.Sprite( img=_pyglet.convert_to_imagedata(image) ) _pyglet.centerize_sprite_in_window(sprite, window) @window.event def on_draw(): pyglet.gl.glClearColor(0.5, 0.5, 0.5, 1.0) window.clear() sprite.draw() state = types.SimpleNamespace(items=items, index=0) def show_help(state): usage() def close_window(state): window.close() def print_item_and_index() -> None: total_size_str: str try: total_size_str = str(len(items)) except TypeError: total_size_str = "n" print( f"[{state.index + 1}/{total_size_str}] " f"{get_title_from_item(items[state.index])}", file=sys.stderr, ) def update(item): window.set_caption(get_title_from_item(item)) sprite.image = _pyglet.convert_to_imagedata(get_image_from_item(item)) _pyglet.centerize_sprite_in_window(sprite, window) print_item_and_index() def next_image(state): try: try: item = state.items[state.index + 1] except IndexError: item = next(state.items) state.index += 1 update(item) except StopIteration: pass def previous_image(state): try: if state.index > 0: item = state.items[state.index - 1] else: raise IndexError state.index -= 1 update(item) except IndexError: pass def usage(): print("Usage: ", file=sys.stderr) for (symbol, modifiers), action in keymap.items(): symbol_string = pyglet.window.key.symbol_string(symbol).lower() modifiers_string = pyglet.window.key.modifiers_string(modifiers) if modifiers_string: key = f"{modifiers_string.lstrip('MOD_')}+{symbol_string}" else: key = symbol_string print( f" {key}: {' '.join(action.__name__.split('_'))}", file=sys.stderr, ) DEFAULT_KEYMAP = { (pyglet.window.key.H, 0): show_help, (pyglet.window.key.Q, 0): close_window, (pyglet.window.key.N, 0): next_image, (pyglet.window.key.P, 0): previous_image, } for key, action in DEFAULT_KEYMAP.items(): if key not in keymap: keymap[key] = action usage() @window.event() def on_key_press(symbol, modifiers): if (symbol, modifiers) in keymap: if keymap[(symbol, modifiers)](state=state): update(state.items[state.index]) print_item_and_index() pyglet.app.run()
wkentaro/imshow
13
Imshow - Flexible and Customizable Image Display with Python
Python
wkentaro
Kentaro Wada
mujin
imshow/_paths.py
Python
import os.path import PIL.Image def get_image_filepaths(files_or_dirs, recursive=False, filter_by_ext=True): supported_image_extensions = { ext for ext, fmt in PIL.Image.registered_extensions().items() if fmt in PIL.Image.OPEN } for file_or_dir in files_or_dirs: if os.path.isdir(file_or_dir) and not recursive: continue if os.path.isdir(file_or_dir): yield from get_image_filepaths( files_or_dirs=( os.path.join(file_or_dir, basename) for basename in sorted(os.listdir(file_or_dir)) ), recursive=recursive, filter_by_ext=filter_by_ext, ) continue if not filter_by_ext: yield file_or_dir if os.path.splitext(file_or_dir)[1].lower() in supported_image_extensions: yield file_or_dir
wkentaro/imshow
13
Imshow - Flexible and Customizable Image Display with Python
Python
wkentaro
Kentaro Wada
mujin
imshow/_pyglet.py
Python
import numpy as np import PIL.Image import pyglet def initialize_window( aspect_ratio: float, caption: str | None = None ) -> pyglet.window.Window: display: pyglet.canvas.Display = pyglet.canvas.Display() screen: pyglet.canvas.Screen = display.get_default_screen() max_window_width: int = int(round(screen.width * 0.75)) max_window_height: int = int(round(screen.height * 0.75)) window_width: int window_height: int # try to fit the image into the screen if aspect_ratio > 1: # width > height window_width = max_window_width window_height = int(round(window_width / aspect_ratio)) else: window_height = max_window_height window_width = int(round(window_height * aspect_ratio)) # if still too large, shrink it if window_width > max_window_width: window_width = max_window_width window_height = int(round(window_width / aspect_ratio)) if window_height > max_window_height: window_height = max_window_height window_width = int(round(window_height * aspect_ratio)) window: pyglet.window.Window = pyglet.window.Window( width=window_width, height=window_height, caption=caption, ) return window def centerize_sprite_in_window( sprite: pyglet.sprite.Sprite, window: pyglet.window.Window ) -> None: scale_x = 0.95 * window.width / sprite.image.width scale_y = 0.95 * window.height / sprite.image.height scale = min(scale_x, scale_y) width = sprite.image.width * scale height = sprite.image.height * scale x = (window.width - width) / 2.0 y = (window.height - height) / 2.0 sprite.update(x=x, y=y, scale=scale) def convert_to_imagedata(image: np.ndarray) -> pyglet.image.ImageData: image_pil: PIL.Image.Image = PIL.Image.fromarray(image) image_pil = image_pil.convert("RGB") image_pyglet: pyglet.image.ImageData = pyglet.image.ImageData( width=image_pil.width, height=image_pil.height, data=image_pil.tobytes(), pitch=-image_pil.width * len(image_pil.mode), format=image_pil.mode, ) return image_pyglet
wkentaro/imshow
13
Imshow - Flexible and Customizable Image Display with Python
Python
wkentaro
Kentaro Wada
mujin
imshow/plugins/__init__.py
Python
# flake8: noqa: F401 from imshow.plugins import base from imshow.plugins import mark from imshow.plugins import tile
wkentaro/imshow
13
Imshow - Flexible and Customizable Image Display with Python
Python
wkentaro
Kentaro Wada
mujin
imshow/plugins/base.py
Python
import imgviz import numpy as np from imshow import _paths class Plugin: @staticmethod def add_arguments(parser): parser.add_argument( "files_or_dirs", nargs="*", help="files or dirs that contain images", ) parser.add_argument( "--recursive", "-r", action="store_true", help="recursively search files in dirs", ) parser.add_argument( "--rotate", type=int, default=0, choices=[0, 90, 180, 270], help="rotate images by 90, 180, or 270 degrees", ) files_or_dirs: list[str] recursive: bool rotate: int def __init__(self, args): self.files_or_dirs = args.files_or_dirs self.recursive = args.recursive self.rotate = args.rotate def get_items(self): yield from _paths.get_image_filepaths( files_or_dirs=self.files_or_dirs, recursive=self.recursive ) def get_image(self, item): image = imgviz.io.imread(item) if self.rotate > 0: image = np.rot90(image, k=self.rotate // 90) return image def get_keymap(self): return {} def get_title(self, item): return str(item)
wkentaro/imshow
13
Imshow - Flexible and Customizable Image Display with Python
Python
wkentaro
Kentaro Wada
mujin
imshow/plugins/mark.py
Python
import argparse import os import sys import numpy as np import pyglet from imshow.plugins import base class Plugin(base.Plugin): @staticmethod def add_arguments(parser: argparse.ArgumentParser): base.Plugin.add_arguments(parser=parser) parser.add_argument( "--mark-file", default="mark.txt", help="file path to save marked items (default: %(default)r)", ) mark_file: str marked_items: list[str] def __init__(self, args): super().__init__(args=args) self.mark_file = args.mark_file self.marked_items = self._read_mark_file(self.mark_file) def _read_mark_file(self, mark_file): if not os.path.exists(mark_file): return [] with open(mark_file) as f: return [line.strip() for line in f] def get_image(self, item): image = super().get_image(item) if item in self.marked_items: image = np.pad( image, ((5, 5), (5, 5), (0, 0)), mode="constant", ) image[:5] = (0, 255, 0) image[-5:] = (0, 255, 0) image[:, :5] = (0, 255, 0) image[:, -5:] = (0, 255, 0) else: image = np.pad( image, ((5, 5), (5, 5), (0, 0)), mode="constant", constant_values=127, ) return image def get_keymap(self): return { (pyglet.window.key.M, 0): self._mark_item, (pyglet.window.key.M, pyglet.window.key.MOD_SHIFT): self._unmark_item, } def _unmark_item(self, state) -> bool: item = state.items[state.index] if item not in self.marked_items: print(f"not marked: {item!r} in {self.mark_file!r}", file=sys.stderr) return False self.marked_items.remove(item) with open(self.mark_file, "w") as f: for marked_item in self.marked_items: f.write(f"{marked_item}\n") return True def _mark_item(self, state) -> bool: with open(self.mark_file, "a+") as f: item = state.items[state.index] if item in self.marked_items: print( f"already marked: {item!r} in {self.mark_file!r}", file=sys.stderr ) return False else: f.write(f"{item}\n") self.marked_items.append(item) print(f"marked: {item!r} in {self.mark_file!r}", file=sys.stderr) return True
wkentaro/imshow
13
Imshow - Flexible and Customizable Image Display with Python
Python
wkentaro
Kentaro Wada
mujin
imshow/plugins/tile.py
Python
import itertools import os import imgviz import numpy as np from imshow.plugins import base try: from itertools import batched # type: ignore[attr-defined] except ImportError: def batched(iterable, n): # type: ignore[no-redef] if n < 1: raise ValueError("n must be >= 1") return itertools.zip_longest(*[iter(iterable)] * n) class Plugin(base.Plugin): @staticmethod def add_arguments(parser): base.Plugin.add_arguments(parser) parser.add_argument( "--row", type=int, help="Number of images in row (default: %(default)s)", default=1, ) parser.add_argument( "--col", type=int, help="Number of images in column (default: %(default)s)", default=1, ) parser.add_argument( "--padding-color", nargs=3, help="Padding color (default: %(default)s)", default=[0, 0, 0], ) parser.add_argument( "--border-width", type=int, help="Border width (default: %(default)s)", default=10, ) parser.add_argument( "--border-color", nargs=3, help="border color (default: %(default)s)", default=[127, 127, 127], ) row: int col: int padding_color: list[int] border_width: int border_color: list[int] def __init__(self, args): super().__init__(args=args) self.row = args.row self.col = args.col self.padding_color = args.padding_color self.border_width = args.border_width self.border_color = args.border_color def get_items(self): yield from batched(super().get_items(), self.row * self.col) def get_image(self, item): images = [ ( np.zeros((1, 1, 3), dtype=np.uint8) if filepath is None else imgviz.asrgb(super(Plugin, self).get_image(item=filepath)) ) for filepath in item ] return imgviz.tile( imgs=images, shape=(self.row, self.col), cval=self.padding_color, border=self.border_color, border_width=self.border_width, ) def get_title(self, item): root_path = os.path.dirname(item[0]) title = [item[0]] for filepath in item[1:]: if filepath is None: continue title.append(os.path.relpath(filepath, root_path)) return ", ".join(title)
wkentaro/imshow
13
Imshow - Flexible and Customizable Image Display with Python
Python
wkentaro
Kentaro Wada
mujin
jqk/__main__.py
Python
import argparse import json import os import sys import pkg_resources import rich.console import rich.pretty import rich.text class Key: def __init__(self, jqkey): self._jqkey = jqkey def __repr__(self): return f"\033[1;34m{self._jqkey}\033[0m" class StrData: def __init__(self, value): self._value = value def __repr__(self): return f'\033[0;32m"{self._value}"\033[0m' def format_data(data, parent=""): if isinstance(data, str): return StrData(data) elif isinstance(data, list): if parent == "": parent = "." return [ format_data(data[i], parent=f"{parent}[{i}]") for i in range(len(data)) ] elif isinstance(data, dict): return { Key(f"{parent}.{k}"): format_data(data[k], parent=f"{parent}.{k}") for k in data.keys() } else: return data def print_data_keys(console, data): if isinstance(data, dict): for key, value in data.items(): print_data(console=console, data=key) print_data_keys(console=console, data=value) elif isinstance(data, list): for value in data: print_data_keys(console=console, data=value) else: pass def print_data(console, data): console.print( rich.pretty.Pretty( data, indent_guides=False, expand_all=True, indent_size=2, ) ) __version__ = pkg_resources.get_distribution("jqkey").version class _ShowVersionAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): print( "jqk {ver} at {pos}".format( ver=__version__, pos=os.path.dirname(os.path.dirname(__file__)) ) ) parser.exit() def main(): parser = argparse.ArgumentParser( prog="jqk", formatter_class=argparse.ArgumentDefaultsHelpFormatter, usage="""jqk [-h] [--color-output] jqk - Query key finder for jq [version %s] Example: $ echo '{"japan": [{"name": "tokyo", "population": "14M"}, {"name": "osaka", "population": "2.7M"}]}' > data.json $ cat data.json | jqk { .japan: [ { .japan[0].name: "tokyo", .japan[0].population: "14M" }, { .japan[1].name: "osaka", .japan[1].population: "2.7M" } ] } $ cat data.json | jq .japan | jqk [ { .[0].name: "tokyo", .[0].population: "14M" }, { .[1].name: "osaka", .[1].population: "2.7M" } ] $ cat data.json | jq .japan[1].population -r 2.7M """ # NOQA % __version__, ) parser.add_argument( "--version", "-V", action=_ShowVersionAction, help="display version", nargs=0, ) parser.add_argument( "--color-output", "-C", action="store_true", help="force color output even with pipe", ) parser.add_argument( "--list", "-l", action="store_true", help="list all keys", ) parser.add_argument( "file", nargs="?", help="JSON file to parse", ) args = parser.parse_args() if args.color_output: force_terminal = True else: force_terminal = None if args.file is None: if sys.stdin.isatty(): parser.print_help() sys.exit(0) else: string = sys.stdin.read() else: with open(args.file) as f: string = f.read() try: data = json.loads(string) except json.decoder.JSONDecodeError as e: print(f"parse error: {e}", file=sys.stderr) sys.exit(1) formatted = format_data(data) console = rich.console.Console( force_terminal=force_terminal, theme=rich.theme.Theme({"repr.brace": "bold"}, inherit=False), ) try: if args.list: print_data_keys(console=console, data=formatted) else: print_data(console=console, data=formatted) except BrokenPipeError: devnull = os.open(os.devnull, os.O_WRONLY) os.dup2(devnull, sys.stdout.fileno()) sys.exit(1) if __name__ == "__main__": main()
wkentaro/jqk-python
3
Render a JSON with jq patterns. Faster version in Rust -> https://github.com/wkentaro/jqk
Python
wkentaro
Kentaro Wada
mujin
export_onnx.py
Python
#!/usr/bin/env python3 import pathlib import typing import imgviz import numpy as np import onnxruntime import PIL.Image import torch from loguru import logger from numpy.typing import NDArray from osam._models.yoloworld.clip import tokenize from torchvision.transforms import v2 from infer_torch import get_replace_freqs_cis from sam3.model.sam3_image import Sam3Image # type: ignore[unresolved-import] from sam3.model.sam3_image_processor import ( # type: ignore[unresolved-import] Sam3Processor, ) from sam3.model_builder import build_sam3_image_model # type: ignore[unresolved-import] class _ImageEncoder(torch.nn.Module): def __init__(self, processor: Sam3Processor) -> None: super().__init__() self._processor: Sam3Processor = processor self._transform = v2.Compose( [ # NOTE: Resize in .transform has difference between pytorch and onnx # v2.ToDtype(torch.uint8, scale=True), # v2.Resize(size=(resolution := 1008, resolution)), v2.ToDtype(torch.float32, scale=True), v2.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]), ] ) def forward(self, image: torch.Tensor) -> tuple[torch.Tensor, ...]: image = self._transform(image).unsqueeze(0) backbone_out = self._processor.model.backbone._forward_image_no_act_ckpt(image) del backbone_out["vision_features"] del backbone_out["sam2_backbone_out"] assert len(backbone_out["vision_pos_enc"]) == 3 assert len(backbone_out["backbone_fpn"]) == 3 return *backbone_out["vision_pos_enc"], *backbone_out["backbone_fpn"] def _export_image_encoder( processor: Sam3Processor, image: PIL.Image.Image ) -> tuple[list[NDArray], list[NDArray]]: image = image.resize((1008, 1008), resample=PIL.Image.BILINEAR) onnx_file: pathlib.Path = pathlib.Path("models/sam3_image_encoder.onnx") if onnx_file.exists(): logger.debug("onnx model already exists, skip export: {!r}", str(onnx_file)) else: encoder: _ImageEncoder = _ImageEncoder(processor=processor) input_image: torch.Tensor = v2.functional.to_image(image).to("cuda") # with torch.no_grad(): # output = image_backbone(input_image) logger.debug("exporting onnx model: {!r}", str(onnx_file)) torch.onnx.export( encoder, args=(input_image,), f=onnx_file, input_names=["image"], output_names=[ "vision_pos_enc_0", "vision_pos_enc_1", "vision_pos_enc_2", "backbone_fpn_0", "backbone_fpn_1", "backbone_fpn_2", ], opset_version=21, verify=True, ) logger.debug("exported onnx model: {!r}", str(onnx_file)) session: onnxruntime.InferenceSession = onnxruntime.InferenceSession(onnx_file) output = session.run(None, {"image": np.asarray(image).transpose(2, 0, 1)}) assert all(isinstance(o, np.ndarray) for o in output) output = typing.cast(list[NDArray], output) logger.debug("finished onnx runtime inference") vision_pos_enc: list[NDArray] = output[:3] backbone_fpn: list[NDArray] = output[3:] return vision_pos_enc, backbone_fpn class _LanguageEncoder(torch.nn.Module): def __init__(self, processor: Sam3Processor) -> None: super().__init__() self._processor: Sam3Processor = processor def forward( self, tokens: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: model: Sam3Image = self._processor.model # VETextEncoder.forward text_attention_mask = (tokens != 0).bool() # inputs_embeds = model.backbone.language_backbone.encoder.token_embedding(tokens) _, text_memory = model.backbone.language_backbone.encoder(tokens) # assert text_memory.shape[1] == inputs_embeds.shape[1] text_attention_mask = text_attention_mask.ne(1) text_memory = text_memory.transpose(0, 1) text_memory_resized = model.backbone.language_backbone.resizer(text_memory) return text_attention_mask, text_memory_resized, inputs_embeds.transpose(0, 1) def _export_language_encoder(processor: Sam3Processor) -> list[NDArray]: tokens = tokenize(texts=["person"], context_length=32) onnx_file: pathlib.Path = pathlib.Path("models/sam3_language_encoder.onnx") if onnx_file.exists(): logger.debug("onnx model already exists, skip export: {!r}", str(onnx_file)) else: encoder: _LanguageEncoder = _LanguageEncoder(processor=processor) tokens_input: torch.Tensor = torch.from_numpy(tokens).to("cuda") # with torch.no_grad(): # output = encoder(tokens=tokens_input) logger.debug("exporting onnx model: {!r}", str(onnx_file)) torch.onnx.export( encoder, args=(tokens_input,), f=onnx_file, input_names=["tokens"], output_names=["text_attention_mask", "text_memory", "text_embeds"], opset_version=21, verify=True, ) logger.debug("exported onnx model: {!r}", str(onnx_file)) session: onnxruntime.InferenceSession = onnxruntime.InferenceSession(onnx_file) output = session.run(None, {"tokens": tokens}) assert all(isinstance(o, np.ndarray) for o in output) output = typing.cast(list[NDArray], output) logger.debug("finished onnx runtime inference") return output class _Decoder(torch.nn.Module): def __init__(self) -> None: super().__init__() self._model: Sam3Image = build_sam3_image_model() self._processor: Sam3Processor = Sam3Processor(self._model) def forward( self, original_height: torch.Tensor, original_width: torch.Tensor, vision_pos_enc_0: torch.Tensor, vision_pos_enc_1: torch.Tensor, vision_pos_enc_2: torch.Tensor, backbone_fpn_0: torch.Tensor, backbone_fpn_1: torch.Tensor, backbone_fpn_2: torch.Tensor, language_mask: torch.Tensor, language_features: torch.Tensor, language_embeds: torch.Tensor, box_coords: torch.Tensor, box_labels: torch.Tensor, box_masks: torch.Tensor, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: geometric_prompt = self._processor.model._get_dummy_prompt() geometric_prompt.box_embeddings = box_coords geometric_prompt.box_labels = box_labels geometric_prompt.box_mask = box_masks state = { "original_height": original_height, "original_width": original_width, "backbone_out": { "vision_pos_enc": [ vision_pos_enc_0, vision_pos_enc_1, vision_pos_enc_2, ], "backbone_fpn": [ backbone_fpn_0, backbone_fpn_1, backbone_fpn_2, ], "language_mask": language_mask, "language_features": language_features, "language_embeds": language_embeds, }, "geometric_prompt": geometric_prompt, } result = self._processor._forward_grounding(state) return result["boxes"], result["scores"], result["masks"] def _export_decoder( original_height: int, original_width: int, vision_pos_enc_0: NDArray, vision_pos_enc_1: NDArray, vision_pos_enc_2: NDArray, backbone_fpn_0: NDArray, backbone_fpn_1: NDArray, backbone_fpn_2: NDArray, language_mask: NDArray, language_features: NDArray, language_embeds: NDArray, box_coords: NDArray, box_labels: NDArray, box_masks: NDArray, ) -> list[NDArray]: onnx_file: pathlib.Path = pathlib.Path("models/sam3_decoder.onnx") if onnx_file.exists(): logger.debug("onnx model already exists, skip export: {!r}", str(onnx_file)) else: logger.debug("exporting onnx model: {!r}", str(onnx_file)) decoder: _Decoder = _Decoder() # XXX: this inference is needed to make export work with if-condition with # torch.compiler.is_dynamo_compiling # with torch.no_grad(): # output = decoder( # original_height=torch.tensor(original_height)[None].to("cuda"), # original_width=torch.tensor(original_width)[None].to("cuda"), # vision_pos_enc_0=torch.tensor(vision_pos_enc_0).to("cuda"), # vision_pos_enc_1=torch.tensor(vision_pos_enc_1).to("cuda"), # vision_pos_enc_2=torch.tensor(vision_pos_enc_2).to("cuda"), # backbone_fpn_0=torch.tensor(backbone_fpn_0).to("cuda"), # backbone_fpn_1=torch.tensor(backbone_fpn_1).to("cuda"), # backbone_fpn_2=torch.tensor(backbone_fpn_2).to("cuda"), # language_mask=torch.tensor(language_mask).to("cuda"), # language_features=torch.tensor(language_features).to("cuda"), # language_embeds=torch.tensor(language_embeds).to("cuda"), # box_coords=torch.tensor(box_coords).to("cuda"), # box_labels=torch.tensor(box_labels).to("cuda"), # ) torch.onnx.export( decoder, args=( torch.tensor(original_height).to("cuda"), torch.tensor(original_width).to("cuda"), torch.tensor(vision_pos_enc_0).to("cuda"), torch.tensor(vision_pos_enc_1).to("cuda"), torch.tensor(vision_pos_enc_2).to("cuda"), torch.tensor(backbone_fpn_0).to("cuda"), torch.tensor(backbone_fpn_1).to("cuda"), torch.tensor(backbone_fpn_2).to("cuda"), torch.tensor(language_mask).to("cuda"), torch.tensor(language_features).to("cuda"), torch.tensor(language_embeds).to("cuda"), torch.tensor(box_coords).to("cuda"), torch.tensor(box_labels).to("cuda"), torch.tensor(box_masks).to("cuda"), ), f=onnx_file, input_names=[ "original_height", "original_width", "vision_pos_enc_0", "vision_pos_enc_1", "vision_pos_enc_2", "backbone_fpn_0", "backbone_fpn_1", "backbone_fpn_2", "language_mask", "language_features", "language_embeds", "box_coords", "box_labels", "box_masks", ], output_names=["boxes", "scores", "masks"], opset_version=21, dynamo=False, verify=True, ) logger.debug("exported onnx model: {!r}", str(onnx_file)) session = onnxruntime.InferenceSession(onnx_file) output = session.run( None, { "original_height": np.array(original_height), "original_width": np.array(original_width), # "vision_pos_enc_0": vision_pos_enc_0, # "vision_pos_enc_1": vision_pos_enc_1, "vision_pos_enc_2": vision_pos_enc_2, "backbone_fpn_0": backbone_fpn_0, "backbone_fpn_1": backbone_fpn_1, "backbone_fpn_2": backbone_fpn_2, "language_mask": language_mask, "language_features": language_features, # "language_embeds": language_embeds, "box_coords": box_coords, "box_labels": box_labels, "box_masks": box_masks, }, ) assert all(isinstance(o, np.ndarray) for o in output) output = typing.cast(list[NDArray], output) logger.debug("decoder onnx runtime inference done") return output def main(): model: Sam3Image = build_sam3_image_model() get_replace_freqs_cis(model) processor: Sam3Processor = Sam3Processor(model) image: PIL.Image.Image = PIL.Image.open("images/bus.jpg") # image: PIL.Image.Image = PIL.Image.open("2011_000006.jpg") # image_encoder {{ # state = processor.set_image(image) vision_pos_enc, backbone_fpn = _export_image_encoder(processor, image) # }} # language_encoder {{ # result = processor.set_text_prompt(prompt="person", state=state) language_mask, language_features, language_embeds = _export_language_encoder( processor=processor ) # }} # decoder {{ # result = processor._forward_grounding(state) # boxes, scores, masks = result["boxes"], result["scores"], result["masks"] box_coords = np.array([[[0.1620, 0.4010, 0.0640, 0.0180]]], dtype=np.float32) box_labels = np.array([[1]], dtype=np.int64) box_masks = np.array([[True]], dtype=np.bool_) boxes, scores, masks = _export_decoder( original_height=image.height, original_width=image.width, vision_pos_enc_0=vision_pos_enc[0], vision_pos_enc_1=vision_pos_enc[1], vision_pos_enc_2=vision_pos_enc[2], backbone_fpn_0=backbone_fpn[0], backbone_fpn_1=backbone_fpn[1], backbone_fpn_2=backbone_fpn[2], language_mask=language_mask, language_features=language_features, language_embeds=language_embeds, box_coords=box_coords, box_labels=box_labels, box_masks=box_masks, ) # }} viz = imgviz.instances2rgb( image=np.asarray(image), masks=masks[:, 0, :, :], bboxes=boxes[:, [1, 0, 3, 2]], labels=np.arange(len(boxes)) + 1, captions=[f"{s:.2f}" for s in scores], ) imgviz.io.pil_imshow(viz) if __name__ == "__main__": main()
wkentaro/sam3-onnx
49
ONNX export and inference for SAM3.
Python
wkentaro
Kentaro Wada
mujin
infer_onnx.py
Python
#!/usr/bin/env python3 import argparse import pathlib import sys import typing import cv2 import imgviz import numpy as np import onnxruntime import PIL.Image from loguru import logger from numpy.typing import NDArray from osam._models.yoloworld.clip import tokenize def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument( "--image", type=pathlib.Path, help="Path to the input image.", required=True, ) prompt_group = parser.add_mutually_exclusive_group(required=True) prompt_group.add_argument( "--text-prompt", type=str, help="Text prompt for segmentation.", ) prompt_group.add_argument( "--box-prompt", type=str, nargs="?", const="0,0,0,0", help="Box prompt for segmentation in format: cx cy w h (normalized).", ) args = parser.parse_args() logger.debug("input: {}", args.__dict__) if args.box_prompt: args.box_prompt = [float(x) for x in args.box_prompt.split(",")] if len(args.box_prompt) != 4: logger.error("box_prompt must have 4 values: cx, cy, w, h") sys.exit(1) if args.box_prompt == [0, 0, 0, 0]: image: NDArray[np.uint8] = imgviz.asrgb(imgviz.io.imread(args.image)) logger.info("please select box prompt in the image window") x, y, w, h = cv2.selectROI( "Select box prompt and press ENTER or SPACE", image[:, :, ::-1], fromCenter=False, showCrosshair=True, ) cv2.destroyAllWindows() if [x, y, w, h] == [0, 0, 0, 0]: logger.warning("no box prompt selected, exiting") sys.exit(1) args.box_prompt = [ (x + w / 2) / image.shape[1], (y + h / 2) / image.shape[0], w / image.shape[1], h / image.shape[0], ] logger.debug("box_prompt: {!r}", ",".join(f"{x:.3f}" for x in args.box_prompt)) return args def main(): args = parse_args() sess_image = onnxruntime.InferenceSession("models/sam3_image_encoder.onnx") sess_language = onnxruntime.InferenceSession("models/sam3_language_encoder.onnx") sess_decode = onnxruntime.InferenceSession("models/sam3_decoder.onnx") image: PIL.Image.Image = PIL.Image.open(args.image).convert("RGB") logger.debug("original image size: {}", image.size) logger.debug("running image encoder...") output = sess_image.run( None, {"image": np.asarray(image.resize((1008, 1008))).transpose(2, 0, 1)} ) assert len(output) == 6 assert all(isinstance(o, np.ndarray) for o in output) output = typing.cast(list[NDArray], output) vision_pos_enc: list[NDArray] = output[:3] backbone_fpn: list[NDArray] = output[3:] logger.debug("finished running image encoder") logger.debug("running language encoder...") text_prompt: str = args.text_prompt if args.text_prompt else "visual" output = sess_language.run( None, {"tokens": tokenize(texts=[text_prompt], context_length=32)} ) assert len(output) == 3 assert all(isinstance(o, np.ndarray) for o in output) output = typing.cast(list[NDArray], output) language_mask: NDArray = output[0] language_features: NDArray = output[1] # language_embeds: NDArray = output[2] logger.debug("finished running language encoder") logger.debug("running decoder...") box_coords: NDArray[np.float32] = np.array( args.box_prompt if args.box_prompt else [0, 0, 0, 0], dtype=np.float32 ).reshape(1, 1, 4) box_labels: NDArray[np.int64] = np.array([[1]], dtype=np.int64) box_masks: NDArray[np.bool_] = np.array( [False] if args.box_prompt else [True], dtype=np.bool_ ).reshape(1, 1) output = sess_decode.run( None, { "original_height": np.array(image.height, dtype=np.int64), "original_width": np.array(image.width, dtype=np.int64), "backbone_fpn_0": backbone_fpn[0], "backbone_fpn_1": backbone_fpn[1], "backbone_fpn_2": backbone_fpn[2], # "vision_pos_enc_0": vision_pos_enc[0], # "vision_pos_enc_1": vision_pos_enc[1], "vision_pos_enc_2": vision_pos_enc[2], "language_mask": language_mask, "language_features": language_features, # "language_embeds": language_embeds, "box_coords": box_coords, "box_labels": box_labels, "box_masks": box_masks, }, ) assert len(output) == 3 assert all(isinstance(o, np.ndarray) for o in output) output = typing.cast(list[NDArray], output) boxes: NDArray = output[0] scores: NDArray = output[1] masks: NDArray = output[2] logger.debug("finished running decoder") logger.debug( "output: {}", {"masks": masks.shape, "boxes": boxes.shape, "scores": scores.shape}, ) viz = imgviz.instances2rgb( image=np.asarray(image), masks=masks[:, 0, :, :], bboxes=boxes[:, [1, 0, 3, 2]], labels=np.arange(len(masks)) + 1, captions=[f"{text_prompt}: {s:.0%}" for s in scores], font_size=max(1, min(image.size) // 40), ) imgviz.io.pil_imshow(viz) if __name__ == "__main__": main()
wkentaro/sam3-onnx
49
ONNX export and inference for SAM3.
Python
wkentaro
Kentaro Wada
mujin
infer_torch.py
Python
#!/usr/bin/env python3 import sys import imgviz import numpy as np import PIL.Image import torch from loguru import logger from infer_onnx import parse_args def get_replace_freqs_cis(module): if hasattr(module, "freqs_cis"): freqs_cos = module.freqs_cis.real.float() freqs_sin = module.freqs_cis.imag.float() # Replace the buffer module.register_buffer("freqs_cos", freqs_cos) module.register_buffer("freqs_sin", freqs_sin) del module.freqs_cis # Remove complex version for child in module.children(): get_replace_freqs_cis(child) def main() -> None: args = parse_args() # XXX: those imports has to be after cv2.selectROI to avoid segfault from sam3.model.sam3_image import Sam3Image # type: ignore[unresolved-import] from sam3.model.sam3_image_processor import ( # type: ignore[unresolved-import] Sam3Processor, ) from sam3.model_builder import ( # type: ignore[unresolved-import] build_sam3_image_model, ) model: Sam3Image = build_sam3_image_model() if 0: with torch.no_grad(): get_replace_freqs_cis(model) processor: Sam3Processor = Sam3Processor(model) image: PIL.Image.Image = PIL.Image.open(args.image).convert("RGB") state = processor.set_image(image) if args.text_prompt: output = processor.set_text_prompt(prompt=args.text_prompt, state=state) elif args.box_prompt: output = processor.add_geometric_prompt( box=args.box_prompt, label=True, state=state, ) else: logger.error("either text_prompt or box_prompt must be provided") sys.exit(1) masks, boxes, scores = output["masks"], output["boxes"], output["scores"] logger.debug( "output: {}", {"masks": masks.shape, "boxes": boxes.shape, "scores": scores.shape}, ) text_prompt: str = args.text_prompt if args.text_prompt else "visual" viz = imgviz.instances2rgb( image=np.asarray(image), masks=masks.cpu().numpy()[:, 0, :, :], bboxes=boxes.cpu().numpy()[:, [1, 0, 3, 2]], labels=np.arange(len(masks)) + 1, captions=[f"{text_prompt}: {s:.0%}" for s in scores], ) imgviz.io.pil_imshow(viz) if __name__ == "__main__": main()
wkentaro/sam3-onnx
49
ONNX export and inference for SAM3.
Python
wkentaro
Kentaro Wada
mujin
.yarn/plugins/plugin-remove-postinstall.cjs
JavaScript
module.exports = { name: 'plugin-remove-postinstall', factory: () => ({ hooks: { beforeWorkspacePacking(workspace, rawManifest) { delete rawManifest.scripts.postinstall; }, }, }), };
wojtekmaj/is-valid-ein
2
Check if a number is a valid Employer Identification Number (EIN)
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
src/index.spec.ts
TypeScript
import { describe, expect, it } from 'vitest'; import isValidEIN from './index.js'; describe('isValidEIN', () => { it('returns false for no input', () => { // @ts-expect-error-next-line const result = isValidEIN(); expect(result).toBe(false); }); it('returns false for non-numeric input', () => { const result = isValidEIN('elephants'); expect(result).toBe(false); }); it('returns false for partially numeric input', () => { const result = isValidEIN('12-34567fox'); expect(result).toBe(false); }); it('returns false for partially numeric input', () => { const result = isValidEIN('12-34567FOX'); expect(result).toBe(false); }); it('returns false for invalid input with invalid length', () => { const result = isValidEIN('123'); expect(result).toBe(false); }); it('returns false for invalid input with valid length', () => { const result = isValidEIN('00-0000000'); expect(result).toBe(false); }); it('returns true for valid numeric input', () => { const result = isValidEIN(123456789); expect(result).toBe(true); }); it('returns true for valid input', () => { const result = isValidEIN('12-3456789'); expect(result).toBe(true); }); it('returns true for valid input with spaces', () => { const result = isValidEIN('12 3456789'); expect(result).toBe(true); }); it('returns true for valid input with dashes', () => { const result = isValidEIN('12-3456789'); expect(result).toBe(true); }); });
wojtekmaj/is-valid-ein
2
Check if a number is a valid Employer Identification Number (EIN)
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
src/index.ts
TypeScript
export default function isValidEIN(rawEin: string | number): boolean { if (!rawEin) { return false; } const rawString = rawEin.toString(); // reject any letters if (/[a-z]/i.test(rawString)) { return false; } // strip non-digit characters const ein = rawString.replace(/\D/g, ''); // EIN must be 9 digits if (ein.length !== 9) { return false; } // disallow all zeros and invalid prefix if (ein === '000000000' || ein.startsWith('00')) { return false; } return true; }
wojtekmaj/is-valid-ein
2
Check if a number is a valid Employer Identification Number (EIN)
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
vitest.config.ts
TypeScript
import { defineConfig } from 'vitest/config'; import type { ViteUserConfig } from 'vitest/config'; const config: ViteUserConfig = defineConfig({ test: { watch: false, }, }); export default config;
wojtekmaj/is-valid-ein
2
Check if a number is a valid Employer Identification Number (EIN)
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
.yarn/plugins/@yarnpkg/plugin-nolyfill.cjs
JavaScript
/* eslint-disable */ //prettier-ignore module.exports = { name: "@yarnpkg/plugin-nolyfill", factory: function (require) { "use strict";var plugin=(()=>{var p=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var n=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var l=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(r,e)=>(typeof require<"u"?require:r)[e]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+t+'" is not supported')});var c=(t,r)=>{for(var e in r)p(t,e,{get:r[e],enumerable:!0})},g=(t,r,e,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let a of n(r))!y.call(t,a)&&a!==e&&p(t,a,{get:()=>r[a],enumerable:!(s=i(r,a))||s.enumerable});return t};var f=t=>g(p({},"__esModule",{value:!0}),t);var m={};c(m,{default:()=>h});var o=l("@yarnpkg/core"),d=["abab","array-buffer-byte-length","array-includes","array.from","array.of","array.prototype.at","array.prototype.every","array.prototype.find","array.prototype.findlast","array.prototype.findlastindex","array.prototype.flat","array.prototype.flatmap","array.prototype.flatmap","array.prototype.foreach","array.prototype.reduce","array.prototype.toreversed","array.prototype.tosorted","arraybuffer.prototype.slice","assert","asynciterator.prototype","available-typed-arrays","deep-equal","deep-equal-json","define-properties","es-aggregate-error","es-iterator-helpers","es-set-tostringtag","es6-object-assign","function-bind","function.prototype.name","get-symbol-description","globalthis","gopd","harmony-reflect","has","has-property-descriptors","has-proto","has-symbols","has-tostringtag","hasown","internal-slot","is-arguments","is-array-buffer","is-core-module","is-date-object","is-generator-function","is-nan","is-regex","is-shared-array-buffer","is-string","is-symbol","is-typed-array","is-weakref","isarray","iterator.prototype","json-stable-stringify","jsonify","object-is","object-keys","object.assign","object.entries","object.fromentries","object.getownpropertydescriptors","object.groupby","object.hasown","object.values","promise.allsettled","promise.any","reflect.getprototypeof","reflect.ownkeys","regexp.prototype.flags","safe-array-concat","safe-regex-test","set-function-length","side-channel","string.prototype.at","string.prototype.codepointat","string.prototype.includes","string.prototype.matchall","string.prototype.padend","string.prototype.padstart","string.prototype.repeat","string.prototype.replaceall","string.prototype.split","string.prototype.startswith","string.prototype.trim","string.prototype.trimend","string.prototype.trimleft","string.prototype.trimright","string.prototype.trimstart","typed-array-buffer","typed-array-byte-length","typed-array-byte-offset","typed-array-length","typedarray","unbox-primitive","util.promisify","which-boxed-primitive","which-typed-array"],u=new Map(d.map(t=>[o.structUtils.makeIdent(null,t).identHash,o.structUtils.makeIdent("nolyfill",t)])),b={hooks:{reduceDependency:async t=>{let r=u.get(t.identHash);if(r){let e=o.structUtils.makeDescriptor(r,"latest"),s=o.structUtils.makeRange({protocol:"npm:",source:null,selector:o.structUtils.stringifyDescriptor(e),params:null});return o.structUtils.makeDescriptor(t,s)}return t}}},h=b;return f(m);})(); return plugin; } };
wojtekmaj/react-docx
1
Render DOCX documents with React
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
.github/template-cleanup.sh
Shell
#!/bin/bash IFS='/' read -ra REPOARR <<< "$GITHUB_REPOSITORY" echo "Repository: ${REPOARR[0]}" echo "Repository: ${REPOARR[1]}" rm README.md mv .github/template-cleanup/README.md README.md rm .github/workflows/cleanup.yml rm .github/template-cleanup.sh sed -i -e "s~%REPOSITORY%~$GITHUB_REPOSITORY~g" README.md sed -i -e "s~%NAME%~${REPOARR[1]}~g" README.md
wojtekmaj/react-native-crash-on-missing-prettier
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/.eslintrc.js
JavaScript
module.exports = { root: true, extends: '@react-native', };
wojtekmaj/react-native-crash-on-missing-prettier
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/.prettierrc.js
JavaScript
module.exports = { arrowParens: 'avoid', singleQuote: true, trailingComma: 'all', };
wojtekmaj/react-native-crash-on-missing-prettier
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/App.tsx
TypeScript (TSX)
/** * Sample React Native App * https://github.com/facebook/react-native * * @format */ import { NewAppScreen } from '@react-native/new-app-screen'; import { StatusBar, StyleSheet, useColorScheme, View } from 'react-native'; import { SafeAreaProvider, useSafeAreaInsets, } from 'react-native-safe-area-context'; function App() { const isDarkMode = useColorScheme() === 'dark'; return ( <SafeAreaProvider> <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} /> <AppContent /> </SafeAreaProvider> ); } function AppContent() { const safeAreaInsets = useSafeAreaInsets(); return ( <View style={styles.container}> <NewAppScreen templateFileName="App.tsx" safeAreaInsets={safeAreaInsets} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, }, }); export default App;
wojtekmaj/react-native-crash-on-missing-prettier
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/__tests__/App.test.tsx
TypeScript (TSX)
/** * @format */ import React from 'react'; import ReactTestRenderer from 'react-test-renderer'; import App from '../App'; test('renders correctly', async () => { await ReactTestRenderer.act(() => { ReactTestRenderer.create(<App />); }); });
wojtekmaj/react-native-crash-on-missing-prettier
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/android/app/build.gradle
Gradle
apply plugin: "com.android.application" apply plugin: "org.jetbrains.kotlin.android" apply plugin: "com.facebook.react" /** * This is the configuration block to customize your React Native Android app. * By default you don't need to apply any configuration, just uncomment the lines you need. */ react { /* Folders */ // The root of your project, i.e. where "package.json" lives. Default is '../..' // root = file("../../") // The folder where the react-native NPM package is. Default is ../../node_modules/react-native // reactNativeDir = file("../../node_modules/react-native") // The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen // codegenDir = file("../../node_modules/@react-native/codegen") // The cli.js file which is the React Native CLI entrypoint. Default is ../../node_modules/react-native/cli.js // cliFile = file("../../node_modules/react-native/cli.js") /* Variants */ // The list of variants to that are debuggable. For those we're going to // skip the bundling of the JS bundle and the assets. By default is just 'debug'. // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. // debuggableVariants = ["liteDebug", "prodDebug"] /* Bundling */ // A list containing the node command and its flags. Default is just 'node'. // nodeExecutableAndArgs = ["node"] // // The command to run when bundling. By default is 'bundle' // bundleCommand = "ram-bundle" // // The path to the CLI configuration file. Default is empty. // bundleConfig = file(../rn-cli.config.js) // // The name of the generated asset file containing your JS bundle // bundleAssetName = "MyApplication.android.bundle" // // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' // entryFile = file("../js/MyApplication.android.js") // // A list of extra flags to pass to the 'bundle' commands. // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle // extraPackagerArgs = [] /* Hermes Commands */ // The hermes compiler command to run. By default it is 'hermesc' // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" // // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" // hermesFlags = ["-O", "-output-source-map"] /* Autolinking */ autolinkLibrariesWithApp() } /** * Set this to true to Run Proguard on Release builds to minify the Java bytecode. */ def enableProguardInReleaseBuilds = false /** * The preferred build flavor of JavaScriptCore (JSC) * * For example, to use the international variant, you can use: * `def jscFlavor = io.github.react-native-community:jsc-android-intl:2026004.+` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that * give correct results when using with locales other than en-US. Note that * this variant is about 6MiB larger per architecture than default. */ def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+' android { ndkVersion rootProject.ext.ndkVersion buildToolsVersion rootProject.ext.buildToolsVersion compileSdk rootProject.ext.compileSdkVersion namespace "com.reproducerapp" defaultConfig { applicationId "com.reproducerapp" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" } signingConfigs { debug { storeFile file('debug.keystore') storePassword 'android' keyAlias 'androiddebugkey' keyPassword 'android' } } buildTypes { debug { signingConfig signingConfigs.debug } release { // Caution! In production, you need to generate your own keystore file. // see https://reactnative.dev/docs/signed-apk-android. signingConfig signingConfigs.debug minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } } dependencies { // The version of react-native is set by the React Native Gradle Plugin implementation("com.facebook.react:react-android") if (hermesEnabled.toBoolean()) { implementation("com.facebook.react:hermes-android") } else { implementation jscFlavor } }
wojtekmaj/react-native-crash-on-missing-prettier
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/android/app/src/main/java/com/reproducerapp/MainActivity.kt
Kotlin
package com.reproducerapp import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled import com.facebook.react.defaults.DefaultReactActivityDelegate class MainActivity : ReactActivity() { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ override fun getMainComponentName(): String = "ReproducerApp" /** * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] */ override fun createReactActivityDelegate(): ReactActivityDelegate = DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) }
wojtekmaj/react-native-crash-on-missing-prettier
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/android/app/src/main/java/com/reproducerapp/MainApplication.kt
Kotlin
package com.reproducerapp import android.app.Application import com.facebook.react.PackageList import com.facebook.react.ReactApplication import com.facebook.react.ReactHost import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost class MainApplication : Application(), ReactApplication { override val reactHost: ReactHost by lazy { getDefaultReactHost( context = applicationContext, packageList = PackageList(this).packages.apply { // Packages that cannot be autolinked yet can be added manually here, for example: // add(MyReactNativePackage()) }, ) } override fun onCreate() { super.onCreate() loadReactNative(this) } }
wojtekmaj/react-native-crash-on-missing-prettier
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/android/build.gradle
Gradle
buildscript { ext { buildToolsVersion = "36.0.0" minSdkVersion = 24 compileSdkVersion = 36 targetSdkVersion = 36 ndkVersion = "27.1.12297006" kotlinVersion = "2.1.20" } repositories { google() mavenCentral() } dependencies { classpath("com.android.tools.build:gradle") classpath("com.facebook.react:react-native-gradle-plugin") classpath("org.jetbrains.kotlin:kotlin-gradle-plugin") } } apply plugin: "com.facebook.react.rootproject"
wojtekmaj/react-native-crash-on-missing-prettier
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/android/settings.gradle
Gradle
pluginManagement { includeBuild("../node_modules/@react-native/gradle-plugin") } plugins { id("com.facebook.react.settings") } extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() } rootProject.name = 'ReproducerApp' include ':app' includeBuild('../node_modules/@react-native/gradle-plugin')
wojtekmaj/react-native-crash-on-missing-prettier
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/babel.config.js
JavaScript
module.exports = { presets: ['module:@react-native/babel-preset'], };
wojtekmaj/react-native-crash-on-missing-prettier
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/index.js
JavaScript
/** * @format */ import { AppRegistry } from 'react-native'; import App from './App'; import { name as appName } from './app.json'; AppRegistry.registerComponent(appName, () => App);
wojtekmaj/react-native-crash-on-missing-prettier
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/ios/ReproducerApp/AppDelegate.swift
Swift
import UIKit import React import React_RCTAppDelegate import ReactAppDependencyProvider @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var reactNativeDelegate: ReactNativeDelegate? var reactNativeFactory: RCTReactNativeFactory? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { let delegate = ReactNativeDelegate() let factory = RCTReactNativeFactory(delegate: delegate) delegate.dependencyProvider = RCTAppDependencyProvider() reactNativeDelegate = delegate reactNativeFactory = factory window = UIWindow(frame: UIScreen.main.bounds) factory.startReactNative( withModuleName: "ReproducerApp", in: window, launchOptions: launchOptions ) return true } } class ReactNativeDelegate: RCTDefaultReactNativeFactoryDelegate { override func sourceURL(for bridge: RCTBridge) -> URL? { self.bundleURL() } override func bundleURL() -> URL? { #if DEBUG RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index") #else Bundle.main.url(forResource: "main", withExtension: "jsbundle") #endif } }
wojtekmaj/react-native-crash-on-missing-prettier
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/jest.config.js
JavaScript
module.exports = { preset: 'react-native', };
wojtekmaj/react-native-crash-on-missing-prettier
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/metro.config.js
JavaScript
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config'); /** * Metro configuration * https://reactnative.dev/docs/metro * * @type {import('@react-native/metro-config').MetroConfig} */ const config = {}; module.exports = mergeConfig(getDefaultConfig(__dirname), config);
wojtekmaj/react-native-crash-on-missing-prettier
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/.eslintrc.js
JavaScript
module.exports = { root: true, extends: '@react-native', };
wojtekmaj/react-native-missing-dom-node-apis-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/.prettierrc.js
JavaScript
module.exports = { arrowParens: 'avoid', singleQuote: true, trailingComma: 'all', };
wojtekmaj/react-native-missing-dom-node-apis-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/App.tsx
TypeScript (TSX)
/** * Sample React Native App * https://github.com/facebook/react-native * * @format */ import { NewAppScreen } from '@react-native/new-app-screen'; import { StatusBar, StyleSheet, useColorScheme, View } from 'react-native'; import { SafeAreaProvider, useSafeAreaInsets, } from 'react-native-safe-area-context'; function App() { const isDarkMode = useColorScheme() === 'dark'; return ( <SafeAreaProvider> <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} /> <AppContent /> </SafeAreaProvider> ); } function AppContent() { const safeAreaInsets = useSafeAreaInsets(); return ( <View style={styles.container} ref={ref => { if (!ref) return; // Old APIs are fine ref.measure(() => {}); // New APIs trigger TypeScript error ref.getBoundingClientRect() }} > <NewAppScreen templateFileName="App.tsx" safeAreaInsets={safeAreaInsets} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, }, }); export default App;
wojtekmaj/react-native-missing-dom-node-apis-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/__tests__/App.test.tsx
TypeScript (TSX)
/** * @format */ import React from 'react'; import ReactTestRenderer from 'react-test-renderer'; import App from '../App'; test('renders correctly', async () => { await ReactTestRenderer.act(() => { ReactTestRenderer.create(<App />); }); });
wojtekmaj/react-native-missing-dom-node-apis-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/android/app/build.gradle
Gradle
apply plugin: "com.android.application" apply plugin: "org.jetbrains.kotlin.android" apply plugin: "com.facebook.react" /** * This is the configuration block to customize your React Native Android app. * By default you don't need to apply any configuration, just uncomment the lines you need. */ react { /* Folders */ // The root of your project, i.e. where "package.json" lives. Default is '../..' // root = file("../../") // The folder where the react-native NPM package is. Default is ../../node_modules/react-native // reactNativeDir = file("../../node_modules/react-native") // The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen // codegenDir = file("../../node_modules/@react-native/codegen") // The cli.js file which is the React Native CLI entrypoint. Default is ../../node_modules/react-native/cli.js // cliFile = file("../../node_modules/react-native/cli.js") /* Variants */ // The list of variants to that are debuggable. For those we're going to // skip the bundling of the JS bundle and the assets. By default is just 'debug'. // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. // debuggableVariants = ["liteDebug", "prodDebug"] /* Bundling */ // A list containing the node command and its flags. Default is just 'node'. // nodeExecutableAndArgs = ["node"] // // The command to run when bundling. By default is 'bundle' // bundleCommand = "ram-bundle" // // The path to the CLI configuration file. Default is empty. // bundleConfig = file(../rn-cli.config.js) // // The name of the generated asset file containing your JS bundle // bundleAssetName = "MyApplication.android.bundle" // // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' // entryFile = file("../js/MyApplication.android.js") // // A list of extra flags to pass to the 'bundle' commands. // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle // extraPackagerArgs = [] /* Hermes Commands */ // The hermes compiler command to run. By default it is 'hermesc' // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" // // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" // hermesFlags = ["-O", "-output-source-map"] /* Autolinking */ autolinkLibrariesWithApp() } /** * Set this to true to Run Proguard on Release builds to minify the Java bytecode. */ def enableProguardInReleaseBuilds = false /** * The preferred build flavor of JavaScriptCore (JSC) * * For example, to use the international variant, you can use: * `def jscFlavor = io.github.react-native-community:jsc-android-intl:2026004.+` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that * give correct results when using with locales other than en-US. Note that * this variant is about 6MiB larger per architecture than default. */ def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+' android { ndkVersion rootProject.ext.ndkVersion buildToolsVersion rootProject.ext.buildToolsVersion compileSdk rootProject.ext.compileSdkVersion namespace "com.reproducerapp" defaultConfig { applicationId "com.reproducerapp" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" } signingConfigs { debug { storeFile file('debug.keystore') storePassword 'android' keyAlias 'androiddebugkey' keyPassword 'android' } } buildTypes { debug { signingConfig signingConfigs.debug } release { // Caution! In production, you need to generate your own keystore file. // see https://reactnative.dev/docs/signed-apk-android. signingConfig signingConfigs.debug minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } } dependencies { // The version of react-native is set by the React Native Gradle Plugin implementation("com.facebook.react:react-android") if (hermesEnabled.toBoolean()) { implementation("com.facebook.react:hermes-android") } else { implementation jscFlavor } }
wojtekmaj/react-native-missing-dom-node-apis-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/android/app/src/main/java/com/reproducerapp/MainActivity.kt
Kotlin
package com.reproducerapp import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled import com.facebook.react.defaults.DefaultReactActivityDelegate class MainActivity : ReactActivity() { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ override fun getMainComponentName(): String = "ReproducerApp" /** * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] */ override fun createReactActivityDelegate(): ReactActivityDelegate = DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) }
wojtekmaj/react-native-missing-dom-node-apis-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/android/app/src/main/java/com/reproducerapp/MainApplication.kt
Kotlin
package com.reproducerapp import android.app.Application import com.facebook.react.PackageList import com.facebook.react.ReactApplication import com.facebook.react.ReactHost import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost class MainApplication : Application(), ReactApplication { override val reactHost: ReactHost by lazy { getDefaultReactHost( context = applicationContext, packageList = PackageList(this).packages.apply { // Packages that cannot be autolinked yet can be added manually here, for example: // add(MyReactNativePackage()) }, ) } override fun onCreate() { super.onCreate() loadReactNative(this) } }
wojtekmaj/react-native-missing-dom-node-apis-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/android/build.gradle
Gradle
buildscript { ext { buildToolsVersion = "36.0.0" minSdkVersion = 24 compileSdkVersion = 36 targetSdkVersion = 36 ndkVersion = "27.1.12297006" kotlinVersion = "2.1.20" } repositories { google() mavenCentral() } dependencies { classpath("com.android.tools.build:gradle") classpath("com.facebook.react:react-native-gradle-plugin") classpath("org.jetbrains.kotlin:kotlin-gradle-plugin") } } apply plugin: "com.facebook.react.rootproject"
wojtekmaj/react-native-missing-dom-node-apis-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/android/settings.gradle
Gradle
pluginManagement { includeBuild("../node_modules/@react-native/gradle-plugin") } plugins { id("com.facebook.react.settings") } extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() } rootProject.name = 'ReproducerApp' include ':app' includeBuild('../node_modules/@react-native/gradle-plugin')
wojtekmaj/react-native-missing-dom-node-apis-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/babel.config.js
JavaScript
module.exports = { presets: ['module:@react-native/babel-preset'], };
wojtekmaj/react-native-missing-dom-node-apis-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/index.js
JavaScript
/** * @format */ import { AppRegistry } from 'react-native'; import App from './App'; import { name as appName } from './app.json'; AppRegistry.registerComponent(appName, () => App);
wojtekmaj/react-native-missing-dom-node-apis-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/ios/ReproducerApp/AppDelegate.swift
Swift
import UIKit import React import React_RCTAppDelegate import ReactAppDependencyProvider @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var reactNativeDelegate: ReactNativeDelegate? var reactNativeFactory: RCTReactNativeFactory? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { let delegate = ReactNativeDelegate() let factory = RCTReactNativeFactory(delegate: delegate) delegate.dependencyProvider = RCTAppDependencyProvider() reactNativeDelegate = delegate reactNativeFactory = factory window = UIWindow(frame: UIScreen.main.bounds) factory.startReactNative( withModuleName: "ReproducerApp", in: window, launchOptions: launchOptions ) return true } } class ReactNativeDelegate: RCTDefaultReactNativeFactoryDelegate { override func sourceURL(for bridge: RCTBridge) -> URL? { self.bundleURL() } override func bundleURL() -> URL? { #if DEBUG RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index") #else Bundle.main.url(forResource: "main", withExtension: "jsbundle") #endif } }
wojtekmaj/react-native-missing-dom-node-apis-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/jest.config.js
JavaScript
module.exports = { preset: 'react-native', };
wojtekmaj/react-native-missing-dom-node-apis-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/metro.config.js
JavaScript
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config'); /** * Metro configuration * https://reactnative.dev/docs/metro * * @type {import('@react-native/metro-config').MetroConfig} */ const config = {}; module.exports = mergeConfig(getDefaultConfig(__dirname), config);
wojtekmaj/react-native-missing-dom-node-apis-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/.eslintrc.js
JavaScript
module.exports = { root: true, extends: '@react-native', };
wojtekmaj/react-native-missing-strict-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/.prettierrc.js
JavaScript
module.exports = { arrowParens: 'avoid', singleQuote: true, trailingComma: 'all', };
wojtekmaj/react-native-missing-strict-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/App.tsx
TypeScript (TSX)
/** * Sample React Native App * https://github.com/facebook/react-native * * @format */ import { NewAppScreen } from '@react-native/new-app-screen'; import { useEffect, useRef } from 'react'; import { StatusBar, StyleSheet, useColorScheme, View } from 'react-native'; import { SafeAreaProvider, useSafeAreaInsets, } from 'react-native-safe-area-context'; function App() { const isDarkMode = useColorScheme() === 'dark'; return ( <SafeAreaProvider> <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} /> <AppContent /> </SafeAreaProvider> ); } function AppContent() { const safeAreaInsets = useSafeAreaInsets(); const viewRef = useRef<View>(null); useEffect(() => { if (viewRef.current) { viewRef.current.measure(() => {}); } }, []); return ( <View style={styles.container}> <NewAppScreen templateFileName="App.tsx" safeAreaInsets={safeAreaInsets} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, }, }); export default App;
wojtekmaj/react-native-missing-strict-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/__tests__/App.test.tsx
TypeScript (TSX)
/** * @format */ import React from 'react'; import ReactTestRenderer from 'react-test-renderer'; import App from '../App'; test('renders correctly', async () => { await ReactTestRenderer.act(() => { ReactTestRenderer.create(<App />); }); });
wojtekmaj/react-native-missing-strict-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/android/app/build.gradle
Gradle
apply plugin: "com.android.application" apply plugin: "org.jetbrains.kotlin.android" apply plugin: "com.facebook.react" /** * This is the configuration block to customize your React Native Android app. * By default you don't need to apply any configuration, just uncomment the lines you need. */ react { /* Folders */ // The root of your project, i.e. where "package.json" lives. Default is '../..' // root = file("../../") // The folder where the react-native NPM package is. Default is ../../node_modules/react-native // reactNativeDir = file("../../node_modules/react-native") // The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen // codegenDir = file("../../node_modules/@react-native/codegen") // The cli.js file which is the React Native CLI entrypoint. Default is ../../node_modules/react-native/cli.js // cliFile = file("../../node_modules/react-native/cli.js") /* Variants */ // The list of variants to that are debuggable. For those we're going to // skip the bundling of the JS bundle and the assets. By default is just 'debug'. // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. // debuggableVariants = ["liteDebug", "prodDebug"] /* Bundling */ // A list containing the node command and its flags. Default is just 'node'. // nodeExecutableAndArgs = ["node"] // // The command to run when bundling. By default is 'bundle' // bundleCommand = "ram-bundle" // // The path to the CLI configuration file. Default is empty. // bundleConfig = file(../rn-cli.config.js) // // The name of the generated asset file containing your JS bundle // bundleAssetName = "MyApplication.android.bundle" // // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' // entryFile = file("../js/MyApplication.android.js") // // A list of extra flags to pass to the 'bundle' commands. // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle // extraPackagerArgs = [] /* Hermes Commands */ // The hermes compiler command to run. By default it is 'hermesc' // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" // // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" // hermesFlags = ["-O", "-output-source-map"] /* Autolinking */ autolinkLibrariesWithApp() } /** * Set this to true to Run Proguard on Release builds to minify the Java bytecode. */ def enableProguardInReleaseBuilds = false /** * The preferred build flavor of JavaScriptCore (JSC) * * For example, to use the international variant, you can use: * `def jscFlavor = io.github.react-native-community:jsc-android-intl:2026004.+` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that * give correct results when using with locales other than en-US. Note that * this variant is about 6MiB larger per architecture than default. */ def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+' android { ndkVersion rootProject.ext.ndkVersion buildToolsVersion rootProject.ext.buildToolsVersion compileSdk rootProject.ext.compileSdkVersion namespace "com.reproducerapp" defaultConfig { applicationId "com.reproducerapp" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" } signingConfigs { debug { storeFile file('debug.keystore') storePassword 'android' keyAlias 'androiddebugkey' keyPassword 'android' } } buildTypes { debug { signingConfig signingConfigs.debug } release { // Caution! In production, you need to generate your own keystore file. // see https://reactnative.dev/docs/signed-apk-android. signingConfig signingConfigs.debug minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } } dependencies { // The version of react-native is set by the React Native Gradle Plugin implementation("com.facebook.react:react-android") if (hermesEnabled.toBoolean()) { implementation("com.facebook.react:hermes-android") } else { implementation jscFlavor } }
wojtekmaj/react-native-missing-strict-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/android/app/src/main/java/com/reproducerapp/MainActivity.kt
Kotlin
package com.reproducerapp import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled import com.facebook.react.defaults.DefaultReactActivityDelegate class MainActivity : ReactActivity() { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ override fun getMainComponentName(): String = "ReproducerApp" /** * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] */ override fun createReactActivityDelegate(): ReactActivityDelegate = DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) }
wojtekmaj/react-native-missing-strict-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/android/app/src/main/java/com/reproducerapp/MainApplication.kt
Kotlin
package com.reproducerapp import android.app.Application import com.facebook.react.PackageList import com.facebook.react.ReactApplication import com.facebook.react.ReactHost import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost class MainApplication : Application(), ReactApplication { override val reactHost: ReactHost by lazy { getDefaultReactHost( context = applicationContext, packageList = PackageList(this).packages.apply { // Packages that cannot be autolinked yet can be added manually here, for example: // add(MyReactNativePackage()) }, ) } override fun onCreate() { super.onCreate() loadReactNative(this) } }
wojtekmaj/react-native-missing-strict-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/android/build.gradle
Gradle
buildscript { ext { buildToolsVersion = "36.0.0" minSdkVersion = 24 compileSdkVersion = 36 targetSdkVersion = 36 ndkVersion = "27.1.12297006" kotlinVersion = "2.1.20" } repositories { google() mavenCentral() } dependencies { classpath("com.android.tools.build:gradle") classpath("com.facebook.react:react-native-gradle-plugin") classpath("org.jetbrains.kotlin:kotlin-gradle-plugin") } } apply plugin: "com.facebook.react.rootproject"
wojtekmaj/react-native-missing-strict-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/android/settings.gradle
Gradle
pluginManagement { includeBuild("../node_modules/@react-native/gradle-plugin") } plugins { id("com.facebook.react.settings") } extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() } rootProject.name = 'ReproducerApp' include ':app' includeBuild('../node_modules/@react-native/gradle-plugin')
wojtekmaj/react-native-missing-strict-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/babel.config.js
JavaScript
module.exports = { presets: ['module:@react-native/babel-preset'], };
wojtekmaj/react-native-missing-strict-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/index.js
JavaScript
/** * @format */ import { AppRegistry } from 'react-native'; import App from './App'; import { name as appName } from './app.json'; AppRegistry.registerComponent(appName, () => App);
wojtekmaj/react-native-missing-strict-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/ios/ReproducerApp/AppDelegate.swift
Swift
import UIKit import React import React_RCTAppDelegate import ReactAppDependencyProvider @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var reactNativeDelegate: ReactNativeDelegate? var reactNativeFactory: RCTReactNativeFactory? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { let delegate = ReactNativeDelegate() let factory = RCTReactNativeFactory(delegate: delegate) delegate.dependencyProvider = RCTAppDependencyProvider() reactNativeDelegate = delegate reactNativeFactory = factory window = UIWindow(frame: UIScreen.main.bounds) factory.startReactNative( withModuleName: "ReproducerApp", in: window, launchOptions: launchOptions ) return true } } class ReactNativeDelegate: RCTDefaultReactNativeFactoryDelegate { override func sourceURL(for bridge: RCTBridge) -> URL? { self.bundleURL() } override func bundleURL() -> URL? { #if DEBUG RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index") #else Bundle.main.url(forResource: "main", withExtension: "jsbundle") #endif } }
wojtekmaj/react-native-missing-strict-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/jest.config.js
JavaScript
module.exports = { preset: 'react-native', };
wojtekmaj/react-native-missing-strict-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
ReproducerApp/metro.config.js
JavaScript
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config'); /** * Metro configuration * https://reactnative.dev/docs/metro * * @type {import('@react-native/metro-config').MetroConfig} */ const config = {}; module.exports = mergeConfig(getDefaultConfig(__dirname), config);
wojtekmaj/react-native-missing-strict-types
0
Kotlin
wojtekmaj
Wojciech Maj
Rewardo, Codete
sample/Sample.css
CSS
html, body { height: 100%; } body { margin: 0; font-family: 'Segoe UI', Tahoma, sans-serif; } .Sample input, .Sample output, .Sample button { font: inherit; } .Sample header { background-color: #323639; box-shadow: 0 0 8px rgba(0, 0, 0, 0.5); padding: 20px; color: white; } .Sample header h1 { font-size: inherit; margin: 0; } .Sample__container { display: flex; flex-direction: row; flex-wrap: wrap; align-items: flex-start; margin: 10px 0; padding: 10px; } .Sample__container > * > * { margin: 10px; } .Sample__container__content { display: flex; max-width: 100%; flex-basis: 420px; flex-direction: column; flex-grow: 100; align-items: stretch; padding-top: 1em; }
wojtekmaj/react-recaptcha-v3
21
Integrate Google reCAPTCHA v3 with your React app
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
sample/Sample.tsx
TypeScript (TSX)
import { useId, useState } from 'react'; import { ReCaptchaProvider, ReCaptcha } from '@wojtekmaj/react-recaptcha-v3'; import './Sample.css'; export default function Sample() { const [token, setToken] = useState(''); const inputId = useId(); return ( <div className="Sample"> <header> <h1>@wojtekmaj/react-recaptcha-v3 sample page</h1> </header> <div className="Sample__container"> <main className="Sample__container__content"> <ReCaptchaProvider reCaptchaKey="YOUR_SITE_KEY"> <form> <ReCaptcha onVerify={setToken} /> <input type="hidden" name="g-recaptcha-response" value={token} /> <div> <label htmlFor={inputId}>Input</label> <input id={inputId} type="text" /> </div> <button type="submit">Submit</button> </form> </ReCaptchaProvider> </main> </div> </div> ); }
wojtekmaj/react-recaptcha-v3
21
Integrate Google reCAPTCHA v3 with your React app
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
sample/index.html
HTML
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@wojtekmaj/react-recaptcha-v3 sample page</title> </head> <body> <div id="root"></div> <script type="module" src="./index.tsx"></script> </body> </html>
wojtekmaj/react-recaptcha-v3
21
Integrate Google reCAPTCHA v3 with your React app
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
sample/index.tsx
TypeScript (TSX)
import { createRoot } from 'react-dom/client'; import Sample from './Sample.js'; const root = document.getElementById('root'); if (!root) { throw new Error('Could not find root element'); } createRoot(root).render(<Sample />);
wojtekmaj/react-recaptcha-v3
21
Integrate Google reCAPTCHA v3 with your React app
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
sample/vite.config.ts
TypeScript
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ base: './', plugins: [react()], });
wojtekmaj/react-recaptcha-v3
21
Integrate Google reCAPTCHA v3 with your React app
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
test/RecaptchaOptions.tsx
TypeScript (TSX)
import { useId } from 'react'; type OptionsProps = { useRecaptchaNet: boolean; setUseRecaptchaNet: (value: boolean) => void; useRecaptchaEnterprise: boolean; setUseRecaptchaEnterprise: (value: boolean) => void; reCaptchaKey: string; setRecaptchaKey: (value: string) => void; }; export default function RecaptchaOptions({ useRecaptchaNet, setUseRecaptchaNet, useRecaptchaEnterprise, setUseRecaptchaEnterprise, reCaptchaKey, setRecaptchaKey, }: OptionsProps) { const useRecaptchaNetId = useId(); const useRecaptchaEnterpriseId = useId(); const reCaptchaKeyId = useId(); function onUseRecaptchaNetChange(event: React.ChangeEvent<HTMLInputElement>) { setUseRecaptchaNet(event.target.checked); } function onUseRecaptchaEnterpriseChange(event: React.ChangeEvent<HTMLInputElement>) { setUseRecaptchaEnterprise(event.target.checked); } function onRecaptchaKeyChange(event: React.ChangeEvent<HTMLInputElement>) { setRecaptchaKey(event.target.value); } return ( <fieldset> <legend>reCAPTCHA options</legend> <div> <input type="checkbox" checked={useRecaptchaNet} id={useRecaptchaNetId} onChange={onUseRecaptchaNetChange} /> <label htmlFor={useRecaptchaNetId}>Use recaptcha.net</label> </div> <div> <input type="checkbox" checked={useRecaptchaEnterprise} id={useRecaptchaEnterpriseId} onChange={onUseRecaptchaEnterpriseChange} /> <label htmlFor={useRecaptchaEnterpriseId}>Use reCAPTCHA Enterprise</label> </div> <div> <label htmlFor={reCaptchaKeyId}>Recaptcha key</label> <input type="text" id={reCaptchaKeyId} value={reCaptchaKey} onChange={onRecaptchaKeyChange} /> </div> </fieldset> ); }
wojtekmaj/react-recaptcha-v3
21
Integrate Google reCAPTCHA v3 with your React app
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
test/Test.css
CSS
body { margin: 0; font-family: 'Segoe UI', Tahoma, sans-serif; } .Test header { background-color: #323639; box-shadow: 0 0 8px rgba(0, 0, 0, 0.5); padding: 20px; color: white; } .Test header h1 { font-size: inherit; margin: 0; } .Test__container { display: flex; flex-direction: row; flex-wrap: wrap; align-items: flex-start; margin: 10px 0; padding: 10px; } .Test__container > * > * { margin: 10px; } .Test__container__options { display: flex; flex-basis: 400px; flex-grow: 1; flex-wrap: wrap; margin: 0; } .Test__container__options input, .Test__container__options button { font: inherit; } .Test__container__options fieldset { border: 1px solid black; flex-grow: 1; position: relative; top: -10px; } .Test__container__options fieldset legend { font-weight: 600; } .Test__container__options fieldset legend + * { margin-top: 0 !important; } .Test__container__options fieldset label { font-weight: 600; display: block; } .Test__container__options fieldset label:not(:first-of-type) { margin-top: 1em; } .Test__container__options fieldset input[type='checkbox'] + label, .Test__container__options fieldset input[type='radio'] + label { font-weight: normal; display: inline-block; margin: 0; } .Test__container__options fieldset form:not(:first-child), .Test__container__options fieldset div:not(:first-child) { margin-top: 1em; } .Test__container__options fieldset form:not(:last-child), .Test__container__options fieldset div:not(:last-child) { margin-bottom: 1em; } .Test__container__content { display: flex; max-width: 100%; flex-basis: 420px; flex-direction: column; flex-grow: 100; align-items: stretch; } .Test__container__content__token { display: block; max-width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
wojtekmaj/react-recaptcha-v3
21
Integrate Google reCAPTCHA v3 with your React app
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
test/Test.tsx
TypeScript (TSX)
import { useId, useState } from 'react'; import { ReCaptchaProvider, ReCaptcha } from '@wojtekmaj/react-recaptcha-v3'; import RecaptchaOptions from './RecaptchaOptions.js'; import VisibilityOptions from './VisibilityOptions.js'; import './Test.css'; function onLoadCallback() { console.log('reCAPTCHA loaded'); } const onLoadCallbackName = 'onLoadCallback'; // @ts-ignore window[onLoadCallbackName] = onLoadCallback; const scriptProps = { onLoadCallbackName }; export default function Test() { const [useRecaptchaNet, setUseRecaptchaNet] = useState(false); const [useRecaptchaEnterprise, setUseRecaptchaEnterprise] = useState(true); const [reCaptchaKey, setRecaptchaKey] = useState(''); const [showInstance1, setShowInstance1Internal] = useState(false); const [showInstance2, setShowInstance2Internal] = useState(false); const [showInstance3, setShowInstance3Internal] = useState(false); const [showInstance4, setShowInstance4Internal] = useState(false); const containerId2 = useId(); const containerId3 = useId(); const [token, setToken] = useState(''); const [token2, setToken2] = useState(''); const [token3, setToken3] = useState(''); const [token4, setToken4] = useState(''); function setShowInstance1(value: boolean) { setShowInstance1Internal(value); if (!value) { setToken(''); } } function setShowInstance2(value: boolean) { setShowInstance2Internal(value); if (!value) { setToken2(''); } } function setShowInstance3(value: boolean) { setShowInstance3Internal(value); if (!value) { setToken3(''); } } function setShowInstance4(value: boolean) { setShowInstance4Internal(value); if (!value) { setToken4(''); } } return ( <div className="Test"> <header> <h1>@wojtekmaj/react-recaptcha-v3 test page</h1> </header> <div className="Test__container"> <aside className="Test__container__options"> <RecaptchaOptions useRecaptchaNet={useRecaptchaNet} setUseRecaptchaNet={setUseRecaptchaNet} useRecaptchaEnterprise={useRecaptchaEnterprise} setUseRecaptchaEnterprise={setUseRecaptchaEnterprise} reCaptchaKey={reCaptchaKey} setRecaptchaKey={setRecaptchaKey} /> <VisibilityOptions setShowInstance1={setShowInstance1} setShowInstance2={setShowInstance2} setShowInstance3={setShowInstance3} setShowInstance4={setShowInstance4} showInstance1={showInstance1} showInstance2={showInstance2} showInstance3={showInstance3} showInstance4={showInstance4} /> </aside> <main className="Test__container__content"> {showInstance1 ? ( <> <h2>Instance 1</h2> <ReCaptchaProvider reCaptchaKey={reCaptchaKey} scriptProps={scriptProps}> <form> <div> <output className="Test__container__content__token">{token}</output> <ReCaptcha onVerify={setToken} /> </div> </form> </ReCaptchaProvider> </> ) : null} {showInstance2 ? ( <> <h2>Instance 2</h2> <ReCaptchaProvider container={{ element: containerId2, parameters: { badge: 'inline', }, }} reCaptchaKey={reCaptchaKey} > <form> <div> <div id={containerId2} /> <ReCaptcha onVerify={setToken2} /> <output className="Test__container__content__token">{token2}</output> </div> </form> </ReCaptchaProvider> </> ) : null} {showInstance3 ? ( <> <h2>Instance 3</h2> <ReCaptchaProvider container={{ element: containerId3, parameters: { badge: 'inline', hidden: true, }, }} reCaptchaKey={reCaptchaKey} > <form> <div> <div id={containerId3} /> <ReCaptcha onVerify={setToken3} /> <output className="Test__container__content__token">{token3}</output> </div> </form> </ReCaptchaProvider> </> ) : null} {showInstance4 ? ( <> <h2>Instance 4</h2> <ReCaptchaProvider reCaptchaKey={reCaptchaKey} useEnterprise useRecaptchaNet> <form> <div> <ReCaptcha onVerify={setToken4} /> <output className="Test__container__content__token">{token4}</output> </div> </form> </ReCaptchaProvider> </> ) : null} </main> </div> </div> ); }
wojtekmaj/react-recaptcha-v3
21
Integrate Google reCAPTCHA v3 with your React app
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
test/VisibilityOptions.tsx
TypeScript (TSX)
import { useId } from 'react'; type VisibilityOptionsProps = { showInstance1: boolean; setShowInstance1: (value: boolean) => void; showInstance2: boolean; setShowInstance2: (value: boolean) => void; showInstance3: boolean; setShowInstance3: (value: boolean) => void; showInstance4: boolean; setShowInstance4: (value: boolean) => void; }; export default function VisibilityOptions({ showInstance1, setShowInstance1, showInstance2, setShowInstance2, showInstance3, setShowInstance3, showInstance4, setShowInstance4, }: VisibilityOptionsProps) { const showInstance1Id = useId(); const showInstance2Id = useId(); const showInstance3Id = useId(); const showInstance4Id = useId(); function onShowInstance1Change(event: React.ChangeEvent<HTMLInputElement>) { setShowInstance1(event.target.checked); } function onShowInstance2Change(event: React.ChangeEvent<HTMLInputElement>) { setShowInstance2(event.target.checked); } function onShowInstance3Change(event: React.ChangeEvent<HTMLInputElement>) { setShowInstance3(event.target.checked); } function onShowInstance4Change(event: React.ChangeEvent<HTMLInputElement>) { setShowInstance4(event.target.checked); } return ( <fieldset> <legend>Visibility options</legend> <div> <input id={showInstance1Id} type="checkbox" checked={showInstance1} onChange={onShowInstance1Change} /> <label htmlFor={showInstance1Id}>Show instance 1</label> <small>(default badge)</small> </div> <div> <input id={showInstance2Id} type="checkbox" checked={showInstance2} onChange={onShowInstance2Change} /> <label htmlFor={showInstance2Id}>Show instance 2</label> <small>(inline badge)</small> </div> <div> <input id={showInstance3Id} type="checkbox" checked={showInstance3} onChange={onShowInstance3Change} /> <label htmlFor={showInstance3Id}>Show instance 3</label>{' '} <small>(inline badge, too; hidden badge; use to test multiple instances)</small> </div> <div> <input id={showInstance4Id} type="checkbox" checked={showInstance4} onChange={onShowInstance4Change} /> <label htmlFor={showInstance4Id}>Show instance 4</label>{' '} <small>(different settings; should crash unless 1 and 2 are hidden)</small> </div> </fieldset> ); }
wojtekmaj/react-recaptcha-v3
21
Integrate Google reCAPTCHA v3 with your React app
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
test/index.html
HTML
<!doctype html> <html lang="en-US"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@wojtekmaj/react-recaptcha-v3 test page</title> </head> <body> <div id="root"></div> <script type="module" src="./index.tsx"></script> </body> </html>
wojtekmaj/react-recaptcha-v3
21
Integrate Google reCAPTCHA v3 with your React app
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
test/index.tsx
TypeScript (TSX)
import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import Test from './Test.js'; const root = document.getElementById('root'); if (!root) { throw new Error('Could not find root element'); } createRoot(root).render( <StrictMode> <Test />, </StrictMode>, );
wojtekmaj/react-recaptcha-v3
21
Integrate Google reCAPTCHA v3 with your React app
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
test/vite.config.ts
TypeScript
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ base: './', plugins: [react()], });
wojtekmaj/react-recaptcha-v3
21
Integrate Google reCAPTCHA v3 with your React app
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
.yarn/plugins/plugin-remove-postinstall.cjs
JavaScript
module.exports = { name: 'plugin-remove-postinstall', factory: () => ({ hooks: { beforeWorkspacePacking(workspace, rawManifest) { delete rawManifest.scripts.postinstall; }, }, }), };
wojtekmaj/vite-plugin-react-fallback-throttle
36
Vite plugin for configuring FALLBACK_THROTTLE_MS in React 19
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
src/index.spec.ts
TypeScript
import { describe, expect, it } from 'vitest'; import reactFallbackThrottlePlugin from './index.js'; function runPlugin( src: string, id: string, options?: Parameters<typeof reactFallbackThrottlePlugin>[0], ): string | undefined { const plugin = reactFallbackThrottlePlugin(options); return plugin.transform.handler(src, id)?.code; } describe('reactFallbackThrottlePlugin()', () => { describe('development builds', () => { it('should replace FALLBACK_THROTTLE_MS value with 0 by default', () => { const input = 'FALLBACK_THROTTLE_MS = 300,'; const expectedOutput = 'FALLBACK_THROTTLE_MS = 0,'; const result = runPlugin(input, 'react-dom-client.development.js'); expect(result).toEqual(expectedOutput); }); it('should replace FALLBACK_THROTTLE_MS value with a given value', () => { const input = 'FALLBACK_THROTTLE_MS = 300,'; const expectedOutput = 'FALLBACK_THROTTLE_MS = 500,'; const result = runPlugin(input, 'react-dom-client.development.js', 500); expect(result).toEqual(expectedOutput); }); }); describe('production builds', () => { it('should replace values corresponding with FALLBACK_THROTTLE_MS with 0 by default', () => { const input = `((exitStatus = globalMostRecentFallbackTime + 300 - now()) // … 300 > now() - globalMostRecentFallbackTime) `; const expectedOutput = `((exitStatus = globalMostRecentFallbackTime + 0 - now()) // … 0 > now() - globalMostRecentFallbackTime) `; const result = runPlugin(input, 'react-dom-client.production.js'); expect(result).toEqual(expectedOutput); }); it('should replace values corresponding with FALLBACK_THROTTLE_MS with a given value', () => { const input = `((exitStatus = globalMostRecentFallbackTime + 300 - now()) 300 > now() - globalMostRecentFallbackTime) `; const expectedOutput = `((exitStatus = globalMostRecentFallbackTime + 500 - now()) 500 > now() - globalMostRecentFallbackTime) `; const result = runPlugin(input, 'react-dom-client.production.js', 500); expect(result).toEqual(expectedOutput); }); }); });
wojtekmaj/vite-plugin-react-fallback-throttle
36
Vite plugin for configuring FALLBACK_THROTTLE_MS in React 19
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
src/index.ts
TypeScript
import type { PluginOption } from 'vite'; export default function viteReactFallbackThrottlePlugin(throttleMs = 0): { name: string; transform: { filter: { id: { include: string[] } }; handler: (src: string, id: string) => { code: string; map: null }; }; } { return { name: 'vite-plugin-react-fallback-throttle', transform: { filter: { id: { include: [ '**/react-dom-client.development.js', '**/react-dom-profiling.development.js', '**/react-dom-client.production.js', '**/react-dom*.js{?*,}', '**/vitest-browser-react.js{?*,}', ], }, }, handler(src) { const srcWithReplacedFallbackThrottle = src // development .replace('FALLBACK_THROTTLE_MS = 300,', `FALLBACK_THROTTLE_MS = ${throttleMs},`) // production .replace( '((exitStatus = globalMostRecentFallbackTime + 300 - now())', `((exitStatus = globalMostRecentFallbackTime + ${throttleMs} - now())`, ) .replace( '300 > now() - globalMostRecentFallbackTime)', `${throttleMs} > now() - globalMostRecentFallbackTime)`, ); const result = { code: srcWithReplacedFallbackThrottle, map: null, }; return result; }, }, } satisfies PluginOption; }
wojtekmaj/vite-plugin-react-fallback-throttle
36
Vite plugin for configuring FALLBACK_THROTTLE_MS in React 19
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
vitest.config.ts
TypeScript
import { defineConfig } from 'vitest/config'; import type { ViteUserConfig } from 'vitest/config'; const config: ViteUserConfig = defineConfig({ test: { watch: false, }, }); export default config;
wojtekmaj/vite-plugin-react-fallback-throttle
36
Vite plugin for configuring FALLBACK_THROTTLE_MS in React 19
TypeScript
wojtekmaj
Wojciech Maj
Rewardo, Codete
2048.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>2048 | 4 Games Challenge</title> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=Space+Mono:wght@400;700&display=swap" rel="stylesheet"> <style> * { margin: 0; padding: 0; box-sizing: border-box; } :root { --neon-yellow: #ffbe0b; --neon-orange: #fb5607; --dark-bg: #0a0a0f; --card-bg: #12121a; } body { font-family: 'Space Mono', monospace; background: var(--dark-bg); color: #fff; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 20px; overflow: hidden; } .bg-grid { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-image: linear-gradient(rgba(255, 190, 11, 0.03) 1px, transparent 1px), linear-gradient(90deg, rgba(255, 190, 11, 0.03) 1px, transparent 1px); background-size: 30px 30px; pointer-events: none; z-index: 0; } .container { position: relative; z-index: 1; text-align: center; } .back-link { position: fixed; top: 20px; left: 20px; color: var(--neon-yellow); text-decoration: none; font-family: 'Press Start 2P', cursive; font-size: 0.7rem; opacity: 0.7; transition: opacity 0.2s; } .back-link:hover { opacity: 1; } h1 { font-family: 'Press Start 2P', cursive; font-size: clamp(1.5rem, 4vw, 2.5rem); color: var(--neon-yellow); text-shadow: 0 0 20px var(--neon-yellow), 0 0 40px var(--neon-yellow); margin-bottom: 20px; } .score-board { display: flex; justify-content: center; gap: 30px; margin-bottom: 20px; font-family: 'Press Start 2P', cursive; font-size: 0.7rem; } .score-item { padding: 15px 25px; background: var(--card-bg); border: 1px solid rgba(255, 190, 11, 0.3); border-radius: 8px; min-width: 120px; } .score-item .label { font-size: 0.5rem; color: rgba(255,255,255,0.5); margin-bottom: 8px; } .score-item .value { font-size: 1rem; color: var(--neon-yellow); } .game-container { background: var(--card-bg); border: 3px solid var(--neon-yellow); border-radius: 12px; padding: 15px; box-shadow: 0 0 30px rgba(255, 190, 11, 0.3), inset 0 0 30px rgba(255, 190, 11, 0.05); } .grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; background: rgba(0, 0, 0, 0.3); padding: 10px; border-radius: 8px; } .cell { width: 80px; height: 80px; background: rgba(255, 255, 255, 0.05); border-radius: 8px; display: flex; align-items: center; justify-content: center; font-family: 'Press Start 2P', cursive; font-size: 1rem; font-weight: bold; transition: all 0.15s ease; } .cell[data-value="2"] { background: #1a1a2e; color: #eee; } .cell[data-value="4"] { background: #16213e; color: #eee; } .cell[data-value="8"] { background: #fb5607; color: #fff; box-shadow: 0 0 15px #fb5607; } .cell[data-value="16"] { background: #ff006e; color: #fff; box-shadow: 0 0 15px #ff006e; } .cell[data-value="32"] { background: #e63946; color: #fff; box-shadow: 0 0 20px #e63946; } .cell[data-value="64"] { background: #d00000; color: #fff; box-shadow: 0 0 20px #d00000; } .cell[data-value="128"] { background: #ffbe0b; color: #000; box-shadow: 0 0 25px #ffbe0b; font-size: 0.8rem; } .cell[data-value="256"] { background: #f9c74f; color: #000; box-shadow: 0 0 25px #f9c74f; font-size: 0.8rem; } .cell[data-value="512"] { background: #90be6d; color: #000; box-shadow: 0 0 25px #90be6d; font-size: 0.8rem; } .cell[data-value="1024"] { background: #43aa8b; color: #fff; box-shadow: 0 0 30px #43aa8b; font-size: 0.6rem; } .cell[data-value="2048"] { background: #39ff14; color: #000; box-shadow: 0 0 40px #39ff14; font-size: 0.6rem; animation: pulse 0.5s infinite; } @keyframes pulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.05); } } @keyframes pop { 0% { transform: scale(0); } 50% { transform: scale(1.2); } 100% { transform: scale(1); } } .cell.new { animation: pop 0.2s ease; } .cell.merged { animation: pop 0.15s ease; } .controls { margin-top: 20px; color: rgba(255, 255, 255, 0.5); font-size: 0.85rem; } .controls kbd { background: var(--card-bg); padding: 5px 10px; border-radius: 4px; border: 1px solid rgba(255, 255, 255, 0.2); margin: 0 3px; } .new-game-btn { margin-top: 20px; font-family: 'Press Start 2P', cursive; font-size: 0.6rem; padding: 12px 20px; background: transparent; border: 2px solid var(--neon-yellow); color: var(--neon-yellow); cursor: pointer; transition: all 0.2s; border-radius: 4px; } .new-game-btn:hover { background: var(--neon-yellow); color: var(--dark-bg); } .overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(10, 10, 15, 0.9); display: none; align-items: center; justify-content: center; z-index: 100; } .overlay-content { background: var(--card-bg); padding: 40px; border-radius: 16px; border: 2px solid var(--neon-yellow); box-shadow: 0 0 50px rgba(255, 190, 11, 0.4); text-align: center; } .overlay h2 { font-family: 'Press Start 2P', cursive; color: var(--neon-yellow); margin-bottom: 20px; font-size: 1.2rem; } .overlay p { margin-bottom: 20px; color: rgba(255,255,255,0.7); } .btn { font-family: 'Press Start 2P', cursive; font-size: 0.7rem; padding: 15px 30px; background: transparent; border: 2px solid var(--neon-yellow); color: var(--neon-yellow); cursor: pointer; transition: all 0.2s; margin: 5px; } .btn:hover { background: var(--neon-yellow); color: var(--dark-bg); box-shadow: 0 0 20px var(--neon-yellow); } @media (max-width: 400px) { .cell { width: 65px; height: 65px; font-size: 0.7rem; } .cell[data-value="128"], .cell[data-value="256"], .cell[data-value="512"] { font-size: 0.6rem; } .cell[data-value="1024"], .cell[data-value="2048"] { font-size: 0.5rem; } } </style> </head> <body> <div class="bg-grid"></div> <a href="index.html" class="back-link">← BACK</a> <div class="container"> <h1>🔢 2048</h1> <div class="score-board"> <div class="score-item"> <div class="label">SCORE</div> <div class="value" id="score">0</div> </div> <div class="score-item"> <div class="label">BEST</div> <div class="value" id="best">0</div> </div> </div> <div class="game-container"> <div class="grid" id="grid"></div> </div> <div class="controls"> Use <kbd>↑</kbd> <kbd>↓</kbd> <kbd>←</kbd> <kbd>→</kbd> or swipe to play </div> <button class="new-game-btn" onclick="newGame()">NEW GAME</button> </div> <div class="overlay" id="overlay"> <div class="overlay-content"> <h2 id="overlayTitle">GAME OVER</h2> <p>Score: <span id="finalScore">0</span></p> <button class="btn" onclick="newGame()">TRY AGAIN</button> <button class="btn" onclick="keepPlaying()" id="keepPlayingBtn" style="display: none;">KEEP GOING</button> </div> </div> <script> const gridElement = document.getElementById('grid'); let grid = []; let score = 0; let best = localStorage.getItem('2048best') || 0; let won = false; let gameOver = false; document.getElementById('best').textContent = best; function createGrid() { gridElement.innerHTML = ''; grid = Array(4).fill(null).map(() => Array(4).fill(0)); for (let i = 0; i < 16; i++) { const cell = document.createElement('div'); cell.className = 'cell'; cell.dataset.row = Math.floor(i / 4); cell.dataset.col = i % 4; gridElement.appendChild(cell); } } function updateDisplay() { const cells = gridElement.querySelectorAll('.cell'); cells.forEach(cell => { const row = parseInt(cell.dataset.row); const col = parseInt(cell.dataset.col); const value = grid[row][col]; cell.textContent = value || ''; cell.dataset.value = value || ''; }); document.getElementById('score').textContent = score; if (score > best) { best = score; localStorage.setItem('2048best', best); document.getElementById('best').textContent = best; } } function addRandomTile() { const emptyCells = []; for (let r = 0; r < 4; r++) { for (let c = 0; c < 4; c++) { if (grid[r][c] === 0) { emptyCells.push({r, c}); } } } if (emptyCells.length === 0) return false; const {r, c} = emptyCells[Math.floor(Math.random() * emptyCells.length)]; grid[r][c] = Math.random() < 0.9 ? 2 : 4; // Animate new tile setTimeout(() => { const cell = gridElement.querySelector(`[data-row="${r}"][data-col="${c}"]`); if (cell) cell.classList.add('new'); setTimeout(() => cell?.classList.remove('new'), 200); }, 50); return true; } function slide(row) { // Filter out zeros let arr = row.filter(val => val !== 0); let merged = []; // Merge adjacent equal values for (let i = 0; i < arr.length; i++) { if (arr[i] === arr[i + 1]) { arr[i] *= 2; score += arr[i]; merged.push(i); arr.splice(i + 1, 1); } } // Pad with zeros while (arr.length < 4) arr.push(0); return { row: arr, merged }; } function move(direction) { if (gameOver) return; let moved = false; const oldGrid = JSON.stringify(grid); if (direction === 'left') { for (let r = 0; r < 4; r++) { const result = slide(grid[r]); grid[r] = result.row; } } else if (direction === 'right') { for (let r = 0; r < 4; r++) { const result = slide(grid[r].reverse()); grid[r] = result.row.reverse(); } } else if (direction === 'up') { for (let c = 0; c < 4; c++) { let column = [grid[0][c], grid[1][c], grid[2][c], grid[3][c]]; const result = slide(column); for (let r = 0; r < 4; r++) { grid[r][c] = result.row[r]; } } } else if (direction === 'down') { for (let c = 0; c < 4; c++) { let column = [grid[3][c], grid[2][c], grid[1][c], grid[0][c]]; const result = slide(column); for (let r = 0; r < 4; r++) { grid[3 - r][c] = result.row[r]; } } } moved = oldGrid !== JSON.stringify(grid); if (moved) { updateDisplay(); setTimeout(() => { addRandomTile(); updateDisplay(); checkGameState(); }, 100); } } function checkGameState() { // Check for 2048 for (let r = 0; r < 4; r++) { for (let c = 0; c < 4; c++) { if (grid[r][c] === 2048 && !won) { won = true; document.getElementById('overlayTitle').textContent = 'YOU WIN!'; document.getElementById('finalScore').textContent = score; document.getElementById('keepPlayingBtn').style.display = 'inline-block'; document.getElementById('overlay').style.display = 'flex'; return; } } } // Check for game over if (isGameOver()) { gameOver = true; document.getElementById('overlayTitle').textContent = 'GAME OVER'; document.getElementById('finalScore').textContent = score; document.getElementById('keepPlayingBtn').style.display = 'none'; document.getElementById('overlay').style.display = 'flex'; } } function isGameOver() { // Check for empty cells for (let r = 0; r < 4; r++) { for (let c = 0; c < 4; c++) { if (grid[r][c] === 0) return false; } } // Check for possible merges for (let r = 0; r < 4; r++) { for (let c = 0; c < 4; c++) { const val = grid[r][c]; if (c < 3 && grid[r][c + 1] === val) return false; if (r < 3 && grid[r + 1][c] === val) return false; } } return true; } function newGame() { score = 0; won = false; gameOver = false; document.getElementById('overlay').style.display = 'none'; createGrid(); addRandomTile(); addRandomTile(); updateDisplay(); } function keepPlaying() { document.getElementById('overlay').style.display = 'none'; } // Keyboard controls document.addEventListener('keydown', (e) => { switch(e.key) { case 'ArrowUp': e.preventDefault(); move('up'); break; case 'ArrowDown': e.preventDefault(); move('down'); break; case 'ArrowLeft': e.preventDefault(); move('left'); break; case 'ArrowRight': e.preventDefault(); move('right'); break; } }); // Touch/swipe controls let touchStartX, touchStartY; document.addEventListener('touchstart', (e) => { touchStartX = e.touches[0].clientX; touchStartY = e.touches[0].clientY; }); document.addEventListener('touchend', (e) => { if (!touchStartX || !touchStartY) return; const touchEndX = e.changedTouches[0].clientX; const touchEndY = e.changedTouches[0].clientY; const diffX = touchEndX - touchStartX; const diffY = touchEndY - touchStartY; const minSwipe = 50; if (Math.abs(diffX) > Math.abs(diffY)) { if (Math.abs(diffX) > minSwipe) { move(diffX > 0 ? 'right' : 'left'); } } else { if (Math.abs(diffY) > minSwipe) { move(diffY > 0 ? 'down' : 'up'); } } touchStartX = null; touchStartY = null; }); // Prevent scrolling on touch document.addEventListener('touchmove', (e) => { e.preventDefault(); }, { passive: false }); // Initialize newGame(); </script> </body> </html>
wonderwhy-er/4-games-challenge
0
4 classic games built from a single chat session with Desktop Commander. Snake, Pong, Breakout, and 2048.
HTML
wonderwhy-er
Eduard Ruzga
breakout.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Breakout | 4 Games Challenge</title> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=Space+Mono:wght@400;700&display=swap" rel="stylesheet"> <style> * { margin: 0; padding: 0; box-sizing: border-box; } :root { --neon-pink: #ff006e; --neon-cyan: #00f5ff; --neon-yellow: #ffbe0b; --neon-green: #39ff14; --dark-bg: #0a0a0f; --card-bg: #12121a; } body { font-family: 'Space Mono', monospace; background: var(--dark-bg); color: #fff; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 20px; } .bg-grid { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-image: linear-gradient(rgba(255, 0, 110, 0.03) 1px, transparent 1px), linear-gradient(90deg, rgba(255, 0, 110, 0.03) 1px, transparent 1px); background-size: 30px 30px; pointer-events: none; z-index: 0; } .container { position: relative; z-index: 1; text-align: center; } .back-link { position: fixed; top: 20px; left: 20px; color: var(--neon-pink); text-decoration: none; font-family: 'Press Start 2P', cursive; font-size: 0.7rem; opacity: 0.7; transition: opacity 0.2s; } .back-link:hover { opacity: 1; } h1 { font-family: 'Press Start 2P', cursive; font-size: clamp(1.5rem, 4vw, 2.5rem); color: var(--neon-pink); text-shadow: 0 0 20px var(--neon-pink), 0 0 40px var(--neon-pink); margin-bottom: 20px; } .score-board { display: flex; justify-content: center; gap: 40px; margin-bottom: 20px; font-family: 'Press Start 2P', cursive; font-size: 0.8rem; } .score-item { padding: 10px 20px; background: var(--card-bg); border: 1px solid rgba(255, 0, 110, 0.3); border-radius: 8px; } .score-item span { color: var(--neon-pink); } #gameCanvas { border: 3px solid var(--neon-pink); border-radius: 8px; box-shadow: 0 0 30px rgba(255, 0, 110, 0.3), inset 0 0 30px rgba(255, 0, 110, 0.05); background: #0d0d12; } .controls { margin-top: 20px; color: rgba(255, 255, 255, 0.5); font-size: 0.85rem; } .controls kbd { background: var(--card-bg); padding: 5px 10px; border-radius: 4px; border: 1px solid rgba(255, 255, 255, 0.2); margin: 0 3px; } .lives { color: var(--neon-pink); font-size: 1.2rem; letter-spacing: 5px; } .overlay { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: rgba(10, 10, 15, 0.95); padding: 40px; border-radius: 16px; border: 2px solid var(--neon-pink); box-shadow: 0 0 50px rgba(255, 0, 110, 0.4); display: none; z-index: 100; } .overlay h2 { font-family: 'Press Start 2P', cursive; color: var(--neon-pink); margin-bottom: 20px; } .overlay p { margin-bottom: 20px; color: rgba(255,255,255,0.7); } .btn { font-family: 'Press Start 2P', cursive; font-size: 0.7rem; padding: 15px 30px; background: transparent; border: 2px solid var(--neon-pink); color: var(--neon-pink); cursor: pointer; transition: all 0.2s; } .btn:hover { background: var(--neon-pink); color: var(--dark-bg); box-shadow: 0 0 20px var(--neon-pink); } @media (max-width: 600px) { #gameCanvas { width: 100%; height: auto; } } </style> </head> <body> <div class="bg-grid"></div> <a href="index.html" class="back-link">← BACK</a> <div class="container"> <h1>🧱 BREAKOUT</h1> <div class="score-board"> <div class="score-item">SCORE: <span id="score">0</span></div> <div class="score-item">LEVEL: <span id="level">1</span></div> <div class="score-item">LIVES: <span class="lives" id="lives">❤❤❤</span></div> </div> <canvas id="gameCanvas" width="600" height="500"></canvas> <div class="controls"> Use <kbd>←</kbd> <kbd>→</kbd> or <kbd>A</kbd> <kbd>D</kbd> to move • <kbd>SPACE</kbd> to launch </div> <div class="overlay" id="gameOver"> <h2 id="overlayTitle">GAME OVER</h2> <p>Final Score: <span id="finalScore">0</span></p> <button class="btn" onclick="resetGame()">PLAY AGAIN</button> </div> </div> <script> const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); // Game settings const paddleWidth = 100; const paddleHeight = 15; const ballRadius = 8; const brickRowCount = 6; const brickColumnCount = 10; const brickWidth = 54; const brickHeight = 20; const brickPadding = 4; const brickOffsetTop = 50; const brickOffsetLeft = 15; // Colors for brick rows const rowColors = ['#ff006e', '#ff4d94', '#ff006e', '#ffbe0b', '#39ff14', '#00f5ff']; const rowPoints = [60, 50, 40, 30, 20, 10]; // Game state let paddleX = (canvas.width - paddleWidth) / 2; let ballX = canvas.width / 2; let ballY = canvas.height - 50; let ballDX = 4; let ballDY = -4; let score = 0; let lives = 3; let level = 1; let gameRunning = false; let ballLaunched = false; let bricks = []; const keys = {}; function createBricks() { bricks = []; for (let c = 0; c < brickColumnCount; c++) { bricks[c] = []; for (let r = 0; r < brickRowCount; r++) { bricks[c][r] = { x: 0, y: 0, status: 1, color: rowColors[r], points: rowPoints[r] }; } } } function drawBricks() { for (let c = 0; c < brickColumnCount; c++) { for (let r = 0; r < brickRowCount; r++) { if (bricks[c][r].status === 1) { const brickX = c * (brickWidth + brickPadding) + brickOffsetLeft; const brickY = r * (brickHeight + brickPadding) + brickOffsetTop; bricks[c][r].x = brickX; bricks[c][r].y = brickY; // Glow effect ctx.shadowColor = bricks[c][r].color; ctx.shadowBlur = 10; // Gradient brick const gradient = ctx.createLinearGradient(brickX, brickY, brickX, brickY + brickHeight); gradient.addColorStop(0, bricks[c][r].color); gradient.addColorStop(1, shadeColor(bricks[c][r].color, -30)); ctx.fillStyle = gradient; ctx.beginPath(); ctx.roundRect(brickX, brickY, brickWidth, brickHeight, 4); ctx.fill(); ctx.shadowBlur = 0; } } } } function shadeColor(color, percent) { const num = parseInt(color.replace('#', ''), 16); const amt = Math.round(2.55 * percent); const R = Math.max(0, Math.min(255, (num >> 16) + amt)); const G = Math.max(0, Math.min(255, ((num >> 8) & 0x00FF) + amt)); const B = Math.max(0, Math.min(255, (num & 0x0000FF) + amt)); return '#' + (0x1000000 + R * 0x10000 + G * 0x100 + B).toString(16).slice(1); } function drawPaddle() { ctx.shadowColor = '#00f5ff'; ctx.shadowBlur = 20; const gradient = ctx.createLinearGradient(paddleX, canvas.height - paddleHeight - 10, paddleX + paddleWidth, canvas.height - 10); gradient.addColorStop(0, '#00f5ff'); gradient.addColorStop(0.5, '#fff'); gradient.addColorStop(1, '#00f5ff'); ctx.fillStyle = gradient; ctx.beginPath(); ctx.roundRect(paddleX, canvas.height - paddleHeight - 10, paddleWidth, paddleHeight, 8); ctx.fill(); ctx.shadowBlur = 0; } function drawBall() { ctx.shadowColor = '#fff'; ctx.shadowBlur = 20; ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(ballX, ballY, ballRadius, 0, Math.PI * 2); ctx.fill(); // Trail effect ctx.shadowBlur = 0; ctx.fillStyle = 'rgba(255, 255, 255, 0.3)'; ctx.beginPath(); ctx.arc(ballX - ballDX * 2, ballY - ballDY * 2, ballRadius * 0.7, 0, Math.PI * 2); ctx.fill(); } function collisionDetection() { for (let c = 0; c < brickColumnCount; c++) { for (let r = 0; r < brickRowCount; r++) { const b = bricks[c][r]; if (b.status === 1) { if (ballX > b.x && ballX < b.x + brickWidth && ballY > b.y && ballY < b.y + brickHeight) { ballDY = -ballDY; b.status = 0; score += b.points * level; document.getElementById('score').textContent = score; // Check if all bricks destroyed if (checkAllBricksDestroyed()) { nextLevel(); } } } } } } function checkAllBricksDestroyed() { for (let c = 0; c < brickColumnCount; c++) { for (let r = 0; r < brickRowCount; r++) { if (bricks[c][r].status === 1) return false; } } return true; } function nextLevel() { level++; document.getElementById('level').textContent = level; createBricks(); resetBall(); ballLaunched = false; // Increase speed slightly ballDX *= 1.1; ballDY *= 1.1; } function resetBall() { ballX = paddleX + paddleWidth / 2; ballY = canvas.height - 50; ballDX = 4 * (Math.random() > 0.5 ? 1 : -1); ballDY = -4; } function updateLivesDisplay() { let hearts = ''; for (let i = 0; i < lives; i++) hearts += '❤'; document.getElementById('lives').textContent = hearts || '💔'; } function update() { if (!gameRunning) return; // Move paddle if (keys['ArrowLeft'] || keys['a'] || keys['A']) { paddleX = Math.max(0, paddleX - 8); } if (keys['ArrowRight'] || keys['d'] || keys['D']) { paddleX = Math.min(canvas.width - paddleWidth, paddleX + 8); } // Ball follows paddle before launch if (!ballLaunched) { ballX = paddleX + paddleWidth / 2; return; } // Move ball ballX += ballDX; ballY += ballDY; // Wall collision if (ballX + ballRadius > canvas.width || ballX - ballRadius < 0) { ballDX = -ballDX; } if (ballY - ballRadius < 0) { ballDY = -ballDY; } // Paddle collision if (ballY + ballRadius > canvas.height - paddleHeight - 10 && ballX > paddleX && ballX < paddleX + paddleWidth) { // Angle based on where ball hits paddle const hitPos = (ballX - paddleX) / paddleWidth; const angle = (hitPos - 0.5) * Math.PI * 0.6; const speed = Math.sqrt(ballDX * ballDX + ballDY * ballDY); ballDX = Math.sin(angle) * speed; ballDY = -Math.cos(angle) * speed; } // Ball lost if (ballY + ballRadius > canvas.height) { lives--; updateLivesDisplay(); if (lives <= 0) { gameOver(false); } else { resetBall(); ballLaunched = false; } } collisionDetection(); } function draw() { ctx.fillStyle = '#0d0d12'; ctx.fillRect(0, 0, canvas.width, canvas.height); drawBricks(); drawPaddle(); drawBall(); // Start message if (!ballLaunched) { ctx.fillStyle = 'rgba(255, 0, 110, 0.8)'; ctx.font = '14px "Press Start 2P"'; ctx.textAlign = 'center'; ctx.fillText('PRESS SPACE TO LAUNCH', canvas.width / 2, canvas.height - 100); } } function gameLoop() { update(); draw(); requestAnimationFrame(gameLoop); } function gameOver(won) { gameRunning = false; document.getElementById('overlayTitle').textContent = won ? 'YOU WIN!' : 'GAME OVER'; document.getElementById('finalScore').textContent = score; document.getElementById('gameOver').style.display = 'block'; } function resetGame() { score = 0; lives = 3; level = 1; ballDX = 4; ballDY = -4; document.getElementById('score').textContent = 0; document.getElementById('level').textContent = 1; updateLivesDisplay(); document.getElementById('gameOver').style.display = 'none'; paddleX = (canvas.width - paddleWidth) / 2; createBricks(); resetBall(); ballLaunched = false; gameRunning = true; } document.addEventListener('keydown', (e) => { keys[e.key] = true; if (e.code === 'Space' && gameRunning && !ballLaunched) { ballLaunched = true; } }); document.addEventListener('keyup', (e) => { keys[e.key] = false; }); // Mouse/touch control canvas.addEventListener('mousemove', (e) => { const rect = canvas.getBoundingClientRect(); const x = e.clientX - rect.left; paddleX = Math.max(0, Math.min(canvas.width - paddleWidth, x - paddleWidth / 2)); }); canvas.addEventListener('touchmove', (e) => { e.preventDefault(); const rect = canvas.getBoundingClientRect(); const x = e.touches[0].clientX - rect.left; paddleX = Math.max(0, Math.min(canvas.width - paddleWidth, x - paddleWidth / 2)); }, { passive: false }); canvas.addEventListener('click', () => { if (gameRunning && !ballLaunched) ballLaunched = true; }); // Polyfill for roundRect if (!ctx.roundRect) { ctx.roundRect = function(x, y, w, h, r) { if (w < 2 * r) r = w / 2; if (h < 2 * r) r = h / 2; this.moveTo(x + r, y); this.arcTo(x + w, y, x + w, y + h, r); this.arcTo(x + w, y + h, x, y + h, r); this.arcTo(x, y + h, x, y, r); this.arcTo(x, y, x + w, y, r); this.closePath(); }; } createBricks(); resetBall(); gameRunning = true; gameLoop(); </script> </body> </html>
wonderwhy-er/4-games-challenge
0
4 classic games built from a single chat session with Desktop Commander. Snake, Pong, Breakout, and 2048.
HTML
wonderwhy-er
Eduard Ruzga
index.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>4 Games Challenge | AI Built 4 Games While I Cooked Pancakes</title> <!-- Basic SEO --> <meta name="description" content="Someone said AI hype is overblown. Challenge accepted. 4 classic games (Snake, Pong, Breakout, 2048) built from a single AI chat session while cooking pancakes. Play them now."> <meta name="keywords" content="AI games, Claude AI, Desktop Commander, Snake game, Pong game, Breakout game, 2048 game, AI coding, vibe coding, AI productivity, Jevons Paradox"> <meta name="author" content="Eduards Ruzga"> <meta name="robots" content="index, follow"> <link rel="canonical" href="https://wonderwhy-er.github.io/4-games-challenge/"> <!-- Open Graph / Social Media --> <meta property="og:type" content="website"> <meta property="og:url" content="https://wonderwhy-er.github.io/4-games-challenge/"> <meta property="og:title" content="AI Made 4 Games While I Cooked Pancakes 🥞🎮"> <meta property="og:description" content="Someone said 'AI hype 🤡'. Challenge accepted. 4 classic games built from ONE chat session. Snake, Pong, Breakout, 2048. Play now."> <meta property="og:image" content="https://wonderwhy-er.github.io/4-games-challenge/og-image.png"> <meta property="og:image:width" content="1200"> <meta property="og:image:height" content="627"> <meta property="og:site_name" content="4 Games Challenge"> <!-- Twitter --> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:url" content="https://wonderwhy-er.github.io/4-games-challenge/"> <meta name="twitter:title" content="AI Made 4 Games While I Cooked Pancakes 🥞🎮"> <meta name="twitter:description" content="Someone said 'AI hype 🤡'. Challenge accepted. 4 games, ONE chat session. Play now."> <meta name="twitter:image" content="https://wonderwhy-er.github.io/4-games-challenge/og-image.png"> <meta name="twitter:creator" content="@paboronin"> <!-- Structured Data for rich snippets --> <script type="application/ld+json"> { "@context": "https://schema.org", "@type": "WebApplication", "name": "4 Games Challenge", "description": "4 classic games built from a single AI chat session", "url": "https://wonderwhy-er.github.io/4-games-challenge/", "applicationCategory": "Game", "operatingSystem": "Any", "offers": { "@type": "Offer", "price": "0", "priceCurrency": "USD" }, "author": { "@type": "Person", "name": "Eduards Ruzga", "url": "https://desktopcommander.app" } } </script> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=Space+Mono:wght@400;700&display=swap" rel="stylesheet"> <style> * { margin: 0; padding: 0; box-sizing: border-box; } :root { --neon-pink: #ff006e; --neon-cyan: #00f5ff; --neon-yellow: #ffbe0b; --neon-green: #39ff14; --dark-bg: #0a0a0f; --card-bg: #12121a; } body { font-family: 'Space Mono', monospace; background: var(--dark-bg); color: #fff; min-height: 100vh; overflow-x: hidden; } /* Animated background grid */ .bg-grid { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-image: linear-gradient(rgba(0, 245, 255, 0.03) 1px, transparent 1px), linear-gradient(90deg, rgba(0, 245, 255, 0.03) 1px, transparent 1px); background-size: 50px 50px; animation: gridMove 20s linear infinite; pointer-events: none; z-index: 0; } @keyframes gridMove { 0% { transform: perspective(500px) rotateX(60deg) translateY(0); } 100% { transform: perspective(500px) rotateX(60deg) translateY(50px); } } .container { position: relative; z-index: 1; max-width: 1200px; margin: 0 auto; padding: 40px 20px; } /* Header */ header { text-align: center; margin-bottom: 60px; } .glitch-title { font-family: 'Press Start 2P', cursive; font-size: clamp(1.5rem, 5vw, 3rem); color: var(--neon-cyan); text-shadow: 0 0 10px var(--neon-cyan), 0 0 20px var(--neon-cyan), 0 0 40px var(--neon-cyan), 3px 3px 0 var(--neon-pink); animation: flicker 3s infinite; margin-bottom: 20px; } @keyframes flicker { 0%, 100% { opacity: 1; } 92% { opacity: 1; } 93% { opacity: 0.8; } 94% { opacity: 1; } 95% { opacity: 0.9; } } .subtitle { font-size: 1.1rem; color: rgba(255, 255, 255, 0.6); max-width: 600px; margin: 0 auto; line-height: 1.8; } .highlight { color: var(--neon-yellow); font-weight: 700; } /* Story section */ .story { background: linear-gradient(135deg, var(--card-bg) 0%, rgba(255, 0, 110, 0.05) 100%); border: 1px solid rgba(255, 0, 110, 0.2); border-radius: 12px; padding: 30px; margin-bottom: 60px; position: relative; overflow: hidden; } .story::before { content: '"'; position: absolute; top: -20px; left: 20px; font-size: 120px; color: var(--neon-pink); opacity: 0.1; font-family: Georgia, serif; } .story h2 { font-family: 'Press Start 2P', cursive; font-size: 0.9rem; color: var(--neon-pink); margin-bottom: 20px; display: flex; align-items: center; gap: 10px; } .story h2::before { content: '>'; animation: blink 1s infinite; } @keyframes blink { 0%, 50% { opacity: 1; } 51%, 100% { opacity: 0; } } .story p { color: rgba(255, 255, 255, 0.8); line-height: 1.9; margin-bottom: 15px; } .story .quote { border-left: 3px solid var(--neon-cyan); padding-left: 20px; margin: 20px 0; font-style: italic; color: var(--neon-cyan); } /* Games grid */ .games-section h2 { font-family: 'Press Start 2P', cursive; font-size: 1rem; color: var(--neon-green); text-align: center; margin-bottom: 40px; text-shadow: 0 0 20px var(--neon-green); } .games-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 30px; } .game-card { background: var(--card-bg); border: 2px solid transparent; border-radius: 16px; padding: 30px; text-decoration: none; color: #fff; position: relative; overflow: hidden; transition: all 0.3s ease; cursor: pointer; } .game-card::before { content: ''; position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: linear-gradient(135deg, var(--card-color) 0%, transparent 60%); opacity: 0.1; transition: opacity 0.3s ease; } .game-card:hover { transform: translateY(-5px) scale(1.02); border-color: var(--card-color); box-shadow: 0 20px 40px rgba(0, 0, 0, 0.4), 0 0 30px var(--card-color), inset 0 0 30px rgba(255, 255, 255, 0.02); } .game-card:hover::before { opacity: 0.2; } .game-card.snake { --card-color: var(--neon-green); } .game-card.pong { --card-color: var(--neon-cyan); } .game-card.breakout { --card-color: var(--neon-pink); } .game-card.game-2048 { --card-color: var(--neon-yellow); } .game-icon { font-size: 3rem; margin-bottom: 20px; display: block; } .game-card h3 { font-family: 'Press Start 2P', cursive; font-size: 1rem; color: var(--card-color); margin-bottom: 15px; text-shadow: 0 0 10px var(--card-color); } .game-card p { font-size: 0.9rem; color: rgba(255, 255, 255, 0.6); line-height: 1.6; } .play-btn { display: inline-flex; align-items: center; gap: 8px; margin-top: 20px; padding: 10px 20px; background: transparent; border: 1px solid var(--card-color); color: var(--card-color); font-family: 'Space Mono', monospace; font-size: 0.85rem; border-radius: 4px; transition: all 0.2s ease; } .game-card:hover .play-btn { background: var(--card-color); color: var(--dark-bg); } /* Footer */ footer { text-align: center; margin-top: 80px; padding: 40px 20px; border-top: 1px solid rgba(255, 255, 255, 0.1); } .dc-badge { display: inline-flex; align-items: center; gap: 12px; padding: 15px 25px; background: linear-gradient(135deg, rgba(0, 245, 255, 0.1) 0%, rgba(255, 0, 110, 0.1) 100%); border: 1px solid rgba(0, 245, 255, 0.3); border-radius: 8px; text-decoration: none; color: #fff; transition: all 0.3s ease; } .dc-badge:hover { border-color: var(--neon-cyan); box-shadow: 0 0 30px rgba(0, 245, 255, 0.2); transform: translateY(-2px); } .dc-badge svg { width: 24px; height: 24px; fill: var(--neon-cyan); } .dc-badge span { font-size: 0.9rem; } .footer-note { margin-top: 20px; font-size: 0.8rem; color: rgba(255, 255, 255, 0.4); } /* Scanline effect */ .scanlines { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: repeating-linear-gradient( 0deg, rgba(0, 0, 0, 0.1) 0px, rgba(0, 0, 0, 0.1) 1px, transparent 1px, transparent 2px ); pointer-events: none; z-index: 1000; opacity: 0.3; } </style> </head> <body> <div class="bg-grid"></div> <div class="scanlines"></div> <div class="container"> <header> <h1 class="glitch-title">4 GAMES CHALLENGE</h1> <p class="subtitle"> Built from a <span class="highlight">single chat session</span> using <a href="https://desktopcommander.app" target="_blank" class="highlight" style="text-decoration: underline;">Desktop Commander</a> to prove a point about AI-augmented productivity. </p> </header> <section class="story"> <h2>THE BACKSTORY</h2> <p> It started with a <a href="https://www.linkedin.com/feed/update/urn:li:activity:7415705445396615168?commentUrn=urn%3Ali%3Acomment%3A%28activity%3A7415705445396615168%2C7415756885745631232%29&dashCommentUrn=urn%3Ali%3Afsd_comment%3A%287415756885745631232%2Curn%3Ali%3Aactivity%3A7415705445396615168%29" target="_blank" style="color: var(--neon-pink); text-decoration: underline;">LinkedIn post</a> about how AI tools are changing the way we work. Not replacing jobs, but making it so frictionless to work that we end up working <em>more</em>. </p> <p class="quote"> "I'm building from my iPad while 'watching TV.' Since I'm so much more productive, I'm just like, all right, I'm going to get it done... and the next thing I know, 16 hours later." </p> <p> Someone replied with skepticism: <strong>"When you walk you can build 4 games and deploy to the stores. AI hype 🤡"</strong> </p> <p> Fair point! Building 4 AAA games while walking is impossible. But small games? Challenge accepted. Here are 4 classic games, built and deployed to GitHub Pages from a single chat conversation. </p> </section> <section class="games-section"> <h2>SELECT YOUR GAME</h2> <div class="games-grid"> <a href="snake.html" class="game-card snake"> <span class="game-icon">🐍</span> <h3>SNAKE</h3> <p>The classic Nokia game. Eat food, grow longer, don't hit yourself or the walls.</p> <span class="play-btn">PLAY → </span> </a> <a href="pong.html" class="game-card pong"> <span class="game-icon">🏓</span> <h3>PONG</h3> <p>The grandfather of video games. Simple paddle action against AI or a friend.</p> <span class="play-btn">PLAY →</span> </a> <a href="breakout.html" class="game-card breakout"> <span class="game-icon">🧱</span> <h3>BREAKOUT</h3> <p>Smash bricks with a bouncing ball. Satisfying destruction, one block at a time.</p> <span class="play-btn">PLAY →</span> </a> <a href="2048.html" class="game-card game-2048"> <span class="game-icon">🔢</span> <h3>2048</h3> <p>Slide and merge tiles to reach 2048. Simple rules, addictive gameplay.</p> <span class="play-btn">PLAY →</span> </a> </div> </section> <footer> <a href="https://desktopcommander.app" target="_blank" class="dc-badge"> <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"> <path d="M4 4h16v12H4V4zm0 14h16v2H4v-2zm2-12v8h12V6H6z"/> </svg> <span>Built with <strong>Desktop Commander</strong></span> </a> <p class="footer-note"> Proving that AI doesn't replace work — it just makes starting easier. </p> </footer> </div> </body> </html>
wonderwhy-er/4-games-challenge
0
4 classic games built from a single chat session with Desktop Commander. Snake, Pong, Breakout, and 2048.
HTML
wonderwhy-er
Eduard Ruzga
pong.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Pong | 4 Games Challenge</title> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=Space+Mono:wght@400;700&display=swap" rel="stylesheet"> <style> * { margin: 0; padding: 0; box-sizing: border-box; } :root { --neon-cyan: #00f5ff; --dark-bg: #0a0a0f; --card-bg: #12121a; } body { font-family: 'Space Mono', monospace; background: var(--dark-bg); color: #fff; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 20px; } .bg-grid { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-image: linear-gradient(rgba(0, 245, 255, 0.03) 1px, transparent 1px), linear-gradient(90deg, rgba(0, 245, 255, 0.03) 1px, transparent 1px); background-size: 30px 30px; pointer-events: none; z-index: 0; } .container { position: relative; z-index: 1; text-align: center; } .back-link { position: fixed; top: 20px; left: 20px; color: var(--neon-cyan); text-decoration: none; font-family: 'Press Start 2P', cursive; font-size: 0.7rem; opacity: 0.7; transition: opacity 0.2s; } .back-link:hover { opacity: 1; } h1 { font-family: 'Press Start 2P', cursive; font-size: clamp(1.5rem, 4vw, 2.5rem); color: var(--neon-cyan); text-shadow: 0 0 20px var(--neon-cyan), 0 0 40px var(--neon-cyan); margin-bottom: 20px; } .score-board { display: flex; justify-content: center; gap: 60px; margin-bottom: 20px; font-family: 'Press Start 2P', cursive; } .score-item { padding: 15px 30px; background: var(--card-bg); border: 1px solid rgba(0, 245, 255, 0.3); border-radius: 8px; } .score-item .label { font-size: 0.6rem; color: rgba(255,255,255,0.5); margin-bottom: 5px; } .score-item .value { font-size: 1.5rem; color: var(--neon-cyan); } #gameCanvas { border: 3px solid var(--neon-cyan); border-radius: 8px; box-shadow: 0 0 30px rgba(0, 245, 255, 0.3), inset 0 0 30px rgba(0, 245, 255, 0.05); background: #0d0d12; } .controls { margin-top: 20px; color: rgba(255, 255, 255, 0.5); font-size: 0.85rem; } .controls kbd { background: var(--card-bg); padding: 5px 10px; border-radius: 4px; border: 1px solid rgba(255, 255, 255, 0.2); margin: 0 3px; } .mode-select { margin-bottom: 20px; display: flex; justify-content: center; gap: 20px; } .mode-btn { font-family: 'Press Start 2P', cursive; font-size: 0.6rem; padding: 12px 20px; background: transparent; border: 2px solid var(--neon-cyan); color: var(--neon-cyan); cursor: pointer; transition: all 0.2s; border-radius: 4px; } .mode-btn:hover, .mode-btn.active { background: var(--neon-cyan); color: var(--dark-bg); } .game-over { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: rgba(10, 10, 15, 0.95); padding: 40px; border-radius: 16px; border: 2px solid var(--neon-cyan); box-shadow: 0 0 50px rgba(0, 245, 255, 0.4); display: none; z-index: 100; } .game-over h2 { font-family: 'Press Start 2P', cursive; color: var(--neon-cyan); margin-bottom: 20px; font-size: 1.2rem; } .game-over p { margin-bottom: 20px; color: rgba(255,255,255,0.7); } .btn { font-family: 'Press Start 2P', cursive; font-size: 0.7rem; padding: 15px 30px; background: transparent; border: 2px solid var(--neon-cyan); color: var(--neon-cyan); cursor: pointer; transition: all 0.2s; } .btn:hover { background: var(--neon-cyan); color: var(--dark-bg); box-shadow: 0 0 20px var(--neon-cyan); } /* Mobile touch areas */ .touch-zones { display: none; position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); gap: 20px; } .touch-zone { width: 80px; height: 80px; background: rgba(0, 245, 255, 0.1); border: 2px solid var(--neon-cyan); border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 2rem; color: var(--neon-cyan); } @media (max-width: 600px) { .touch-zones { display: flex; } .controls { display: none; } } </style> </head> <body> <div class="bg-grid"></div> <a href="index.html" class="back-link">← BACK</a> <div class="container"> <h1>🏓 PONG</h1> <div class="mode-select"> <button class="mode-btn active" onclick="setMode('ai')">VS AI</button> <button class="mode-btn" onclick="setMode('2p')">2 PLAYERS</button> </div> <div class="score-board"> <div class="score-item"> <div class="label">PLAYER 1</div> <div class="value" id="score1">0</div> </div> <div class="score-item"> <div class="label" id="player2Label">AI</div> <div class="value" id="score2">0</div> </div> </div> <canvas id="gameCanvas" width="600" height="400"></canvas> <div class="controls" id="controlsText"> Player 1: <kbd>W</kbd> <kbd>S</kbd> • Press <kbd>SPACE</kbd> to start </div> <div class="touch-zones"> <div class="touch-zone" id="touchUp">↑</div> <div class="touch-zone" id="touchDown">↓</div> </div> <div class="game-over" id="gameOver"> <h2 id="winnerText">PLAYER 1 WINS!</h2> <p>Final Score: <span id="finalScore">5 - 3</span></p> <button class="btn" onclick="resetGame()">PLAY AGAIN</button> </div> </div> <script> const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const WINNING_SCORE = 5; let gameMode = 'ai'; let gameRunning = false; let score1 = 0, score2 = 0; const paddleHeight = 80; const paddleWidth = 12; const ballSize = 12; let paddle1Y = canvas.height / 2 - paddleHeight / 2; let paddle2Y = canvas.height / 2 - paddleHeight / 2; let ballX = canvas.width / 2; let ballY = canvas.height / 2; let ballSpeedX = 5; let ballSpeedY = 3; const keys = {}; function setMode(mode) { gameMode = mode; document.querySelectorAll('.mode-btn').forEach(btn => btn.classList.remove('active')); event.target.classList.add('active'); const label = document.getElementById('player2Label'); const controls = document.getElementById('controlsText'); if (mode === '2p') { label.textContent = 'PLAYER 2'; controls.innerHTML = 'P1: <kbd>W</kbd> <kbd>S</kbd> • P2: <kbd>↑</kbd> <kbd>↓</kbd> • <kbd>SPACE</kbd> to start'; } else { label.textContent = 'AI'; controls.innerHTML = 'Player 1: <kbd>W</kbd> <kbd>S</kbd> • Press <kbd>SPACE</kbd> to start'; } resetGame(); } function drawRect(x, y, w, h, color, glow = false) { if (glow) { ctx.shadowColor = color; ctx.shadowBlur = 20; } ctx.fillStyle = color; ctx.fillRect(x, y, w, h); ctx.shadowBlur = 0; } function drawBall(x, y, size, color) { ctx.shadowColor = color; ctx.shadowBlur = 20; ctx.fillStyle = color; ctx.beginPath(); ctx.arc(x, y, size / 2, 0, Math.PI * 2); ctx.fill(); ctx.shadowBlur = 0; } function drawNet() { ctx.setLineDash([10, 10]); ctx.strokeStyle = 'rgba(0, 245, 255, 0.2)'; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(canvas.width / 2, 0); ctx.lineTo(canvas.width / 2, canvas.height); ctx.stroke(); ctx.setLineDash([]); } function update() { if (!gameRunning) return; // Move paddles if (keys['w'] || keys['W']) paddle1Y -= 8; if (keys['s'] || keys['S']) paddle1Y += 8; if (gameMode === '2p') { if (keys['ArrowUp']) paddle2Y -= 8; if (keys['ArrowDown']) paddle2Y += 8; } else { // AI const aiSpeed = 4; const aiTarget = ballY - paddleHeight / 2; if (paddle2Y < aiTarget - 10) paddle2Y += aiSpeed; if (paddle2Y > aiTarget + 10) paddle2Y -= aiSpeed; } // Clamp paddles paddle1Y = Math.max(0, Math.min(canvas.height - paddleHeight, paddle1Y)); paddle2Y = Math.max(0, Math.min(canvas.height - paddleHeight, paddle2Y)); // Move ball ballX += ballSpeedX; ballY += ballSpeedY; // Ball collision with top/bottom if (ballY - ballSize/2 <= 0 || ballY + ballSize/2 >= canvas.height) { ballSpeedY = -ballSpeedY; } // Ball collision with paddles // Left paddle if (ballX - ballSize/2 <= paddleWidth + 10 && ballY >= paddle1Y && ballY <= paddle1Y + paddleHeight) { ballSpeedX = Math.abs(ballSpeedX) * 1.05; const hitPos = (ballY - paddle1Y) / paddleHeight; ballSpeedY = (hitPos - 0.5) * 10; } // Right paddle if (ballX + ballSize/2 >= canvas.width - paddleWidth - 10 && ballY >= paddle2Y && ballY <= paddle2Y + paddleHeight) { ballSpeedX = -Math.abs(ballSpeedX) * 1.05; const hitPos = (ballY - paddle2Y) / paddleHeight; ballSpeedY = (hitPos - 0.5) * 10; } // Scoring if (ballX < 0) { score2++; document.getElementById('score2').textContent = score2; resetBall(); checkWin(); } if (ballX > canvas.width) { score1++; document.getElementById('score1').textContent = score1; resetBall(); checkWin(); } } function resetBall() { ballX = canvas.width / 2; ballY = canvas.height / 2; ballSpeedX = (Math.random() > 0.5 ? 1 : -1) * 5; ballSpeedY = (Math.random() - 0.5) * 6; } function checkWin() { if (score1 >= WINNING_SCORE || score2 >= WINNING_SCORE) { gameRunning = false; const winner = score1 >= WINNING_SCORE ? 'PLAYER 1' : (gameMode === 'ai' ? 'AI' : 'PLAYER 2'); document.getElementById('winnerText').textContent = winner + ' WINS!'; document.getElementById('finalScore').textContent = score1 + ' - ' + score2; document.getElementById('gameOver').style.display = 'block'; } } function draw() { // Clear ctx.fillStyle = '#0d0d12'; ctx.fillRect(0, 0, canvas.width, canvas.height); drawNet(); // Paddles drawRect(10, paddle1Y, paddleWidth, paddleHeight, '#00f5ff', true); drawRect(canvas.width - paddleWidth - 10, paddle2Y, paddleWidth, paddleHeight, '#ff006e', true); // Ball drawBall(ballX, ballY, ballSize, '#fff'); // Start message if (!gameRunning && score1 === 0 && score2 === 0) { ctx.fillStyle = 'rgba(0, 245, 255, 0.8)'; ctx.font = '16px "Press Start 2P"'; ctx.textAlign = 'center'; ctx.fillText('PRESS SPACE TO START', canvas.width / 2, canvas.height / 2); } } function gameLoop() { update(); draw(); requestAnimationFrame(gameLoop); } function resetGame() { score1 = 0; score2 = 0; document.getElementById('score1').textContent = 0; document.getElementById('score2').textContent = 0; document.getElementById('gameOver').style.display = 'none'; paddle1Y = canvas.height / 2 - paddleHeight / 2; paddle2Y = canvas.height / 2 - paddleHeight / 2; resetBall(); gameRunning = false; } document.addEventListener('keydown', (e) => { keys[e.key] = true; if (e.code === 'Space' && !gameRunning && score1 < WINNING_SCORE && score2 < WINNING_SCORE) { gameRunning = true; } }); document.addEventListener('keyup', (e) => { keys[e.key] = false; }); // Touch controls document.getElementById('touchUp').addEventListener('touchstart', () => keys['w'] = true); document.getElementById('touchUp').addEventListener('touchend', () => keys['w'] = false); document.getElementById('touchDown').addEventListener('touchstart', () => keys['s'] = true); document.getElementById('touchDown').addEventListener('touchend', () => keys['s'] = false); // Prevent scrolling on touch document.addEventListener('touchmove', (e) => e.preventDefault(), { passive: false }); gameLoop(); </script> </body> </html>
wonderwhy-er/4-games-challenge
0
4 classic games built from a single chat session with Desktop Commander. Snake, Pong, Breakout, and 2048.
HTML
wonderwhy-er
Eduard Ruzga
snake.html
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Snake | 4 Games Challenge</title> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&family=Space+Mono:wght@400;700&display=swap" rel="stylesheet"> <style> * { margin: 0; padding: 0; box-sizing: border-box; } :root { --neon-green: #39ff14; --dark-bg: #0a0a0f; --card-bg: #12121a; } body { font-family: 'Space Mono', monospace; background: var(--dark-bg); color: #fff; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 20px; } .bg-grid { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-image: linear-gradient(rgba(57, 255, 20, 0.03) 1px, transparent 1px), linear-gradient(90deg, rgba(57, 255, 20, 0.03) 1px, transparent 1px); background-size: 30px 30px; pointer-events: none; z-index: 0; } .container { position: relative; z-index: 1; text-align: center; } .back-link { position: fixed; top: 20px; left: 20px; color: var(--neon-green); text-decoration: none; font-family: 'Press Start 2P', cursive; font-size: 0.7rem; opacity: 0.7; transition: opacity 0.2s; } .back-link:hover { opacity: 1; } h1 { font-family: 'Press Start 2P', cursive; font-size: clamp(1.5rem, 4vw, 2.5rem); color: var(--neon-green); text-shadow: 0 0 20px var(--neon-green), 0 0 40px var(--neon-green); margin-bottom: 20px; } .score-board { display: flex; justify-content: center; gap: 40px; margin-bottom: 20px; font-family: 'Press Start 2P', cursive; font-size: 0.8rem; } .score-item { padding: 10px 20px; background: var(--card-bg); border: 1px solid rgba(57, 255, 20, 0.3); border-radius: 8px; } .score-item span { color: var(--neon-green); } #gameCanvas { border: 3px solid var(--neon-green); border-radius: 8px; box-shadow: 0 0 30px rgba(57, 255, 20, 0.3), inset 0 0 30px rgba(57, 255, 20, 0.05); background: #0d0d12; } .controls { margin-top: 20px; color: rgba(255, 255, 255, 0.5); font-size: 0.85rem; } .controls kbd { background: var(--card-bg); padding: 5px 10px; border-radius: 4px; border: 1px solid rgba(255, 255, 255, 0.2); margin: 0 3px; } .game-over { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: rgba(10, 10, 15, 0.95); padding: 40px; border-radius: 16px; border: 2px solid var(--neon-green); box-shadow: 0 0 50px rgba(57, 255, 20, 0.4); display: none; z-index: 100; } .game-over h2 { font-family: 'Press Start 2P', cursive; color: var(--neon-green); margin-bottom: 20px; } .game-over p { margin-bottom: 20px; color: rgba(255,255,255,0.7); } .btn { font-family: 'Press Start 2P', cursive; font-size: 0.7rem; padding: 15px 30px; background: transparent; border: 2px solid var(--neon-green); color: var(--neon-green); cursor: pointer; transition: all 0.2s; } .btn:hover { background: var(--neon-green); color: var(--dark-bg); box-shadow: 0 0 20px var(--neon-green); } /* Mobile controls */ .mobile-controls { display: none; margin-top: 20px; gap: 10px; } .mobile-btn { width: 60px; height: 60px; font-size: 1.5rem; background: var(--card-bg); border: 2px solid var(--neon-green); border-radius: 8px; color: var(--neon-green); cursor: pointer; transition: all 0.1s; } .mobile-btn:active { background: var(--neon-green); color: var(--dark-bg); } .mobile-row { display: flex; justify-content: center; gap: 10px; } @media (max-width: 600px) { .mobile-controls { display: block; } .controls { display: none; } } </style> </head> <body> <div class="bg-grid"></div> <a href="index.html" class="back-link">← BACK</a> <div class="container"> <h1>🐍 SNAKE</h1> <div class="score-board"> <div class="score-item">SCORE: <span id="score">0</span></div> <div class="score-item">HIGH: <span id="highScore">0</span></div> </div> <canvas id="gameCanvas" width="400" height="400"></canvas> <div class="controls"> Use <kbd>↑</kbd> <kbd>↓</kbd> <kbd>←</kbd> <kbd>→</kbd> or <kbd>W</kbd> <kbd>A</kbd> <kbd>S</kbd> <kbd>D</kbd> to move • <kbd>SPACE</kbd> to pause </div> <div class="mobile-controls"> <div class="mobile-row"> <button class="mobile-btn" data-dir="up">↑</button> </div> <div class="mobile-row"> <button class="mobile-btn" data-dir="left">←</button> <button class="mobile-btn" data-dir="down">↓</button> <button class="mobile-btn" data-dir="right">→</button> </div> </div> <div class="game-over" id="gameOver"> <h2>GAME OVER</h2> <p>Your score: <span id="finalScore">0</span></p> <button class="btn" onclick="resetGame()">PLAY AGAIN</button> </div> </div> <script> const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const gridSize = 20; const tileCount = canvas.width / gridSize; let snake = [{x: 10, y: 10}]; let food = {x: 15, y: 15}; let dx = 0, dy = 0; let score = 0; let highScore = localStorage.getItem('snakeHighScore') || 0; let gameLoop; let isPaused = false; let gameSpeed = 100; let isGameOver = false; document.getElementById('highScore').textContent = highScore; function drawGame() { if (isPaused || isGameOver) return; // Clear canvas ctx.fillStyle = '#0d0d12'; ctx.fillRect(0, 0, canvas.width, canvas.height); // Draw grid (subtle) ctx.strokeStyle = 'rgba(57, 255, 20, 0.05)'; for (let i = 0; i <= tileCount; i++) { ctx.beginPath(); ctx.moveTo(i * gridSize, 0); ctx.lineTo(i * gridSize, canvas.height); ctx.stroke(); ctx.beginPath(); ctx.moveTo(0, i * gridSize); ctx.lineTo(canvas.width, i * gridSize); ctx.stroke(); } // Move snake const head = {x: snake[0].x + dx, y: snake[0].y + dy}; snake.unshift(head); // Check food collision if (head.x === food.x && head.y === food.y) { score += 10; document.getElementById('score').textContent = score; placeFood(); // Speed up slightly if (gameSpeed > 50) { gameSpeed -= 2; clearInterval(gameLoop); gameLoop = setInterval(drawGame, gameSpeed); } } else { snake.pop(); } // Check wall collision if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) { endGame(); return; } // Check self collision for (let i = 1; i < snake.length; i++) { if (head.x === snake[i].x && head.y === snake[i].y) { endGame(); return; } } // Draw food with glow ctx.shadowColor = '#ff006e'; ctx.shadowBlur = 15; ctx.fillStyle = '#ff006e'; ctx.beginPath(); ctx.arc(food.x * gridSize + gridSize/2, food.y * gridSize + gridSize/2, gridSize/2 - 2, 0, Math.PI * 2); ctx.fill(); ctx.shadowBlur = 0; // Draw snake snake.forEach((segment, index) => { const alpha = 1 - (index / snake.length) * 0.5; ctx.shadowColor = '#39ff14'; ctx.shadowBlur = index === 0 ? 20 : 10; ctx.fillStyle = `rgba(57, 255, 20, ${alpha})`; ctx.fillRect( segment.x * gridSize + 1, segment.y * gridSize + 1, gridSize - 2, gridSize - 2 ); }); ctx.shadowBlur = 0; } function placeFood() { food = { x: Math.floor(Math.random() * tileCount), y: Math.floor(Math.random() * tileCount) }; // Make sure food doesn't spawn on snake for (let segment of snake) { if (segment.x === food.x && segment.y === food.y) { placeFood(); break; } } } function endGame() { isGameOver = true; clearInterval(gameLoop); if (score > highScore) { highScore = score; localStorage.setItem('snakeHighScore', highScore); document.getElementById('highScore').textContent = highScore; } document.getElementById('finalScore').textContent = score; document.getElementById('gameOver').style.display = 'block'; } function resetGame() { snake = [{x: 10, y: 10}]; dx = 0; dy = 0; score = 0; gameSpeed = 100; isGameOver = false; isPaused = false; document.getElementById('score').textContent = 0; document.getElementById('gameOver').style.display = 'none'; placeFood(); gameLoop = setInterval(drawGame, gameSpeed); } function changeDirection(newDx, newDy) { // Prevent 180-degree turns if ((newDx === 1 && dx === -1) || (newDx === -1 && dx === 1)) return; if ((newDy === 1 && dy === -1) || (newDy === -1 && dy === 1)) return; dx = newDx; dy = newDy; } document.addEventListener('keydown', (e) => { if (e.code === 'Space') { isPaused = !isPaused; return; } switch(e.key) { case 'ArrowUp': case 'w': case 'W': changeDirection(0, -1); break; case 'ArrowDown': case 's': case 'S': changeDirection(0, 1); break; case 'ArrowLeft': case 'a': case 'A': changeDirection(-1, 0); break; case 'ArrowRight': case 'd': case 'D': changeDirection(1, 0); break; } }); // Mobile controls document.querySelectorAll('.mobile-btn').forEach(btn => { btn.addEventListener('click', () => { const dir = btn.dataset.dir; switch(dir) { case 'up': changeDirection(0, -1); break; case 'down': changeDirection(0, 1); break; case 'left': changeDirection(-1, 0); break; case 'right': changeDirection(1, 0); break; } }); }); // Touch swipe support let touchStartX, touchStartY; canvas.addEventListener('touchstart', (e) => { touchStartX = e.touches[0].clientX; touchStartY = e.touches[0].clientY; }); canvas.addEventListener('touchend', (e) => { const touchEndX = e.changedTouches[0].clientX; const touchEndY = e.changedTouches[0].clientY; const diffX = touchEndX - touchStartX; const diffY = touchEndY - touchStartY; if (Math.abs(diffX) > Math.abs(diffY)) { changeDirection(diffX > 0 ? 1 : -1, 0); } else { changeDirection(0, diffY > 0 ? 1 : -1); } }); // Start game placeFood(); gameLoop = setInterval(drawGame, gameSpeed); </script> </body> </html>
wonderwhy-er/4-games-challenge
0
4 classic games built from a single chat session with Desktop Commander. Snake, Pong, Breakout, and 2048.
HTML
wonderwhy-er
Eduard Ruzga
install-docker.ps1
PowerShell
#!/usr/bin/env powershell param( [string]$Option = "", [switch]$Help, [switch]$Status, [switch]$Reset, [switch]$VerboseOutput ) # Script-level variables for folder and Docker args $script:Folders = @() $script:DockerArgs = @() # Colors and output functions function Write-Success { param($Message) Write-Host "[SUCCESS] $Message" -ForegroundColor Green } function Write-Error { param($Message) Write-Host "[ERROR] $Message" -ForegroundColor Red } function Write-Warning { param($Message) Write-Host "[WARNING] $Message" -ForegroundColor Yellow } function Write-Info { param($Message) Write-Host "[INFO] $Message" -ForegroundColor Blue } function Write-Header { Write-Host "" Write-Host "================================================================" -ForegroundColor Blue Write-Host " CLAUDE " -ForegroundColor Blue Write-Host " SERVER COMMANDER " -ForegroundColor Blue Write-Host " Docker Installer " -ForegroundColor Blue Write-Host "================================================================" -ForegroundColor Blue Write-Host "" Write-Info "Experiment with AI in secure sandbox environment that won't mess up your main computer" Write-Host "" } function Test-Docker { while ($true) { try { $null = Get-Command docker -ErrorAction Stop } catch { Write-Error "Docker is not installed or not found" Write-Host "" Write-Error "Please install Docker first:" Write-Error "Download Docker Desktop: https://www.docker.com/products/docker-desktop/" Write-Host "" $null = Read-Host "Press Enter when Docker Desktop is installed or Ctrl+C to exit" continue } Write-Info "Checking Docker installation and daemon status..." try { $null = docker info 2>$null if ($LASTEXITCODE -eq 0) { Write-Success "Docker is installed and running" break } else { throw "Docker daemon not running" } } catch { Write-Error "Docker is installed but not running" Write-Host "" Write-Error "Please start Docker Desktop and try again" Write-Info "Make sure Docker Desktop is fully started (check system tray)" Write-Host "" $null = Read-Host "Press Enter when Docker Desktop is running or Ctrl+C to exit" continue } } } function Get-DockerImage { Write-Info "Pulling latest Docker image (this may take a moment)..." try { docker pull mcp/desktop-commander:latest if ($LASTEXITCODE -eq 0) { Write-Success "Docker image ready: mcp/desktop-commander:latest" } else { Write-Error "Failed to pull Docker image" Write-Info "Check your internet connection and Docker Hub access" exit 1 } } catch { Write-Error "Failed to get Docker image" Write-Info "This could be a network issue or Docker Hub being unavailable" exit 1 } }function Ask-ForFolders { Write-Host "" Write-Host "Folder Access Setup" -ForegroundColor Blue Write-Info "By default, Desktop Commander will have access to your user folder:" Write-Info "Folder: $env:USERPROFILE" Write-Host "" $response = Read-Host "Press Enter to accept user folder access or 'y' to customize" $script:Folders = @() if ($response -match "^[Yy]$") { Write-Host "" Write-Info "Custom folder selection:" $homeResponse = Read-Host "Mount your complete home directory ($env:USERPROFILE)? [Y/n]" switch ($homeResponse.ToLower()) { { $_ -in @("n", "no") } { Write-Info "Skipping home directory" } default { $script:Folders += $env:USERPROFILE Write-Success "Added home directory access" } } Write-Host "" Write-Info "Add extra folders outside home directory (optional):" while ($true) { $customDir = Read-Host "Enter folder path (or Enter to finish)" if ([string]::IsNullOrEmpty($customDir)) { break } $customDir = [System.Environment]::ExpandEnvironmentVariables($customDir) $customDir = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($customDir) if (Test-Path $customDir -PathType Container) { $script:Folders += $customDir Write-Success "Added: $customDir" } else { $addAnyway = Read-Host "Folder doesn't exist. Add anyway? [y/N]" if ($addAnyway -match "^[Yy]$") { $script:Folders += $customDir Write-Info "Added: $customDir (will create if needed)" } } } if ($script:Folders.Count -eq 0) { Write-Host "" Write-Warning "WARNING: No folders selected - Desktop Commander will have NO file access" Write-Host "" Write-Info "This means:" Write-Host " - Desktop Commander cannot read or write any files on your computer" Write-Host " - It cannot help with coding projects, file management, or document editing" Write-Host " - It will only work for system commands and package installation" Write-Host " - This makes Desktop Commander much less useful than intended" Write-Host "" Write-Info "You probably want to share at least some folder to work with files" Write-Info "Most users share their home directory: $env:USERPROFILE" Write-Host "" $confirm = Read-Host "Continue with NO file access? [y/N]" if ($confirm -notmatch "^[Yy]$") { Write-Info "Restarting folder selection..." Ask-ForFolders return } Write-Warning "Proceeding with no file access - Desktop Commander will be limited" } } else { $script:Folders += $env:USERPROFILE Write-Success "Using default access to your user folder" } } function Initialize-Volumes { Write-Info "Setting up persistent development environment" Write-Host "" Write-Info "Creating essential volumes for development persistence:" Write-Info "- dc-system: All system packages, binaries, libraries" Write-Info "- dc-home: User configs, dotfiles, SSH keys, git config" Write-Info "- dc-workspace: Development files and projects" Write-Info "- dc-packages: Package databases, caches, logs" Write-Host "" $volumes = @("dc-system", "dc-home", "dc-workspace", "dc-packages") $volumesCreated = 0 foreach ($volume in $volumes) { try { $null = docker volume inspect $volume 2>$null if ($LASTEXITCODE -ne 0) { docker volume create $volume | Out-Null if ($LASTEXITCODE -eq 0) { Write-Success "Created volume: $volume" $volumesCreated++ } else { Write-Warning "Failed to create volume: $volume" } } else { Write-Info "Volume already exists: $volume" } } catch { Write-Warning "Could not manage volume: $volume" } } if ($volumesCreated -gt 0) { Write-Host "" Write-Success "Created $volumesCreated new volume(s)" } Write-Success "Persistent environment ready - your tools will survive restarts!" } function Build-DockerArgs { Write-Info "Building Docker configuration..." $script:DockerArgs = @("run", "-i", "--rm") $essentialVolumes = @( "dc-system:/usr", "dc-home:/root", "dc-workspace:/workspace", "dc-packages:/var" ) foreach ($volume in $essentialVolumes) { $script:DockerArgs += "-v" $script:DockerArgs += $volume } foreach ($folder in $script:Folders) { # Get the full path structure after drive letter for absolute mounting if ($folder -match '^([A-Za-z]):(.+)$') { $absolutePath = $matches[2].TrimStart('\').Replace('\', '/') $script:DockerArgs += "-v" $script:DockerArgs += "${folder}:/home/$absolutePath" } else { # Fallback for non-standard paths - use basename $folderName = Split-Path $folder -Leaf $script:DockerArgs += "-v" $script:DockerArgs += "${folder}:/home/${folderName}" } } $script:DockerArgs += "mcp/desktop-commander:latest" if ($VerboseOutput) { Write-Info "Docker configuration ready" Write-Info "Essential volumes: 4 volumes" Write-Info "Mounted folders: $($script:Folders.Count) folders" Write-Info "Container mode: Auto-remove after each use (--rm)" } }function Find-ClaudeProcess { Write-Info "Looking for Claude Desktop processes..." # Try different process name patterns for Claude $processNames = @("Claude", "claude", "Claude Desktop", "claude-desktop", "ClaudeDesktop") $foundProcesses = @() foreach ($processName in $processNames) { if ($VerboseOutput) { Write-Info "Checking for process pattern: $processName" } try { $processes = Get-Process -Name $processName -ErrorAction SilentlyContinue if ($processes) { foreach ($proc in $processes) { $procPath = try { $proc.Path } catch { "Unknown" } $procWindowTitle = try { $proc.MainWindowTitle } catch { "N/A" } $foundProcesses += @{ Name = $proc.ProcessName Id = $proc.Id Path = $procPath WindowTitle = $procWindowTitle } if ($VerboseOutput) { Write-Info "Found: $($proc.ProcessName) (PID: $($proc.Id))" } } } } catch { if ($VerboseOutput) { Write-Info "No processes found for pattern: $processName" } } } # Also try WMI for more comprehensive search if ($VerboseOutput) { Write-Info "Searching with WMI for Claude-related processes..." } try { $wmiProcesses = Get-WmiObject Win32_Process | Where-Object { $_.Name -like "*claude*" -or $_.CommandLine -like "*claude*" -or $_.ExecutablePath -like "*claude*" } foreach ($proc in $wmiProcesses) { $foundProcesses += @{ Name = $proc.Name Id = $proc.ProcessId Path = $proc.ExecutablePath CommandLine = $proc.CommandLine } if ($VerboseOutput) { Write-Info "WMI Found: $($proc.Name) (PID: $($proc.ProcessId))" } } } catch { if ($VerboseOutput) { Write-Info "WMI search failed or no additional processes found" } } return $foundProcesses } function Stop-ClaudeProcess { Write-Info "Attempting to stop Claude Desktop..." $processes = Find-ClaudeProcess if ($processes.Count -eq 0) { Write-Info "No Claude Desktop processes found running" return $true } Write-Info "Found $($processes.Count) Claude-related process(es)" foreach ($proc in $processes) { Write-Info " - $($proc.Name) (PID: $($proc.Id))" if ($proc.Path -and $proc.Path -ne "Unknown" -and $VerboseOutput) { Write-Info " Path: $($proc.Path)" } } $stoppedCount = 0 # Method 1: Graceful shutdown using Stop-Process Write-Info "Attempting graceful shutdown..." foreach ($proc in $processes) { try { Stop-Process -Id $proc.Id -ErrorAction Stop Write-Success "Gracefully stopped: $($proc.Name) (PID: $($proc.Id))" $stoppedCount++ } catch { Write-Warning "Could not gracefully stop: $($proc.Name) (PID: $($proc.Id)) - $($_.Exception.Message)" } } # Wait a moment for graceful shutdown Start-Sleep -Seconds 2 # Method 2: Force kill remaining processes $remainingProcesses = Find-ClaudeProcess if ($remainingProcesses.Count -gt 0) { Write-Info "Force stopping remaining processes..." foreach ($proc in $remainingProcesses) { try { Stop-Process -Id $proc.Id -Force -ErrorAction Stop Write-Success "Force stopped: $($proc.Name) (PID: $($proc.Id))" $stoppedCount++ } catch { Write-Error "Could not force stop: $($proc.Name) (PID: $($proc.Id)) - $($_.Exception.Message)" } } } # Final verification Start-Sleep -Seconds 1 $finalProcesses = Find-ClaudeProcess if ($finalProcesses.Count -eq 0) { Write-Success "All Claude processes stopped successfully" return $true } else { Write-Warning "Some Claude processes may still be running" return $false } } function Find-ClaudeExecutable { if ($VerboseOutput) { Write-Info "Searching for Claude Desktop executable..." } # Common installation paths for Claude Desktop $claudePaths = @( "$env:LOCALAPPDATA\Programs\Claude\Claude.exe", "$env:PROGRAMFILES\Claude\Claude.exe", "$env:PROGRAMFILES(x86)\Claude\Claude.exe", "$env:APPDATA\Claude\Claude.exe", "$env:USERPROFILE\AppData\Local\Programs\Claude\Claude.exe" ) if ($VerboseOutput) { Write-Info "Checking standard installation paths..." } foreach ($path in $claudePaths) { if ($VerboseOutput) { Write-Info "Checking: $path" } if (Test-Path $path) { if ($VerboseOutput) { Write-Info "Found Claude executable: $path" } return $path } } # Check registry for installation location if ($VerboseOutput) { Write-Info "Searching Windows registry for Claude installation..." } try { $uninstallKeys = @( "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*", "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*", "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" ) foreach ($keyPath in $uninstallKeys) { try { $entries = Get-ItemProperty $keyPath -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like "*Claude*" } foreach ($entry in $entries) { if ($entry.InstallLocation) { $possibleExe = Join-Path $entry.InstallLocation "Claude.exe" if ($VerboseOutput) { Write-Info "Registry found: $($entry.DisplayName) at $possibleExe" } if (Test-Path $possibleExe) { if ($VerboseOutput) { Write-Info "Found Claude executable via registry: $possibleExe" } return $possibleExe } } if ($entry.UninstallString) { $uninstallDir = Split-Path $entry.UninstallString -Parent $possibleExe = Join-Path $uninstallDir "Claude.exe" if ($VerboseOutput) { Write-Info "Trying uninstall directory: $possibleExe" } if (Test-Path $possibleExe) { if ($VerboseOutput) { Write-Info "Found Claude executable via uninstall path: $possibleExe" } return $possibleExe } } } } catch { if ($VerboseOutput) { Write-Info "Could not check registry key: $keyPath" } } } } catch { if ($VerboseOutput) { Write-Info "Registry search failed" } } # Last resort: search common program directories if ($VerboseOutput) { Write-Info "Performing broader search in program directories..." } $searchDirs = @( "$env:LOCALAPPDATA\Programs", "$env:PROGRAMFILES", "$env:PROGRAMFILES(x86)" ) foreach ($dir in $searchDirs) { if (Test-Path $dir) { if ($VerboseOutput) { Write-Info "Searching in: $dir" } try { $found = Get-ChildItem -Path $dir -Recurse -Name "Claude.exe" -ErrorAction SilentlyContinue | Select-Object -First 1 if ($found) { $fullPath = Join-Path $dir $found if ($VerboseOutput) { Write-Info "Found Claude executable via search: $fullPath" } return $fullPath } } catch { if ($VerboseOutput) { Write-Info "Could not search in: $dir" } } } } return $null } function Start-ClaudeProcess { Write-Info "Attempting to start Claude Desktop..." $claudePath = Find-ClaudeExecutable if (-not $claudePath) { Write-Warning "Could not find Claude Desktop executable" Write-Info "Claude may not be installed or may be in a non-standard location" Write-Info "You can start Claude Desktop manually after installation completes" return $false } Write-Success "Found Claude executable: $claudePath" try { Write-Info "Starting Claude Desktop..." if ($VerboseOutput) { Write-Info "Executing: Start-Process -FilePath '$claudePath' -PassThru" } $process = Start-Process -FilePath $claudePath -PassThru -ErrorAction Stop if ($process) { Write-Success "Process started with PID: $($process.Id)" # Wait for the process to initialize Write-Info "Waiting 5 seconds for Claude to initialize..." Start-Sleep -Seconds 5 # Check if the process is still running try { $runningProcess = Get-Process -Id $process.Id -ErrorAction Stop Write-Success "Claude Desktop is running and stable (PID: $($runningProcess.Id))" Write-Success "Process name: $($runningProcess.ProcessName)" if ($runningProcess.MainWindowTitle -and $VerboseOutput) { Write-Info "Window title: $($runningProcess.MainWindowTitle)" } return $true } catch { Write-Warning "Process started but exited quickly (PID: $($process.Id))" Write-Info "This might indicate a configuration issue" return $false } } else { Write-Error "Failed to start process - Start-Process returned null" return $false } } catch { Write-Error "Exception starting Claude Desktop: $($_.Exception.Message)" if ($VerboseOutput) { Write-Info "Full exception: $($_.Exception)" } return $false } } function Restart-Claude { Write-Info "Attempting to restart Claude Desktop..." # Step 1: Stop Claude $stopSuccess = Stop-ClaudeProcess if (-not $stopSuccess) { Write-Warning "Failed to stop Claude completely, but continuing with startup attempt" } # Step 2: Start Claude $startSuccess = Start-ClaudeProcess # Step 3: Final verification Write-Info "Verifying Claude restart..." Start-Sleep -Seconds 2 $finalProcesses = Find-ClaudeProcess if ($startSuccess -and $finalProcesses.Count -gt 0) { Write-Success "Claude Desktop restart: SUCCESSFUL" Write-Info "Claude Desktop is now running with updated configuration" return $true } else { Write-Warning "Claude Desktop restart: PARTIAL or FAILED" Write-Info "You may need to start Claude Desktop manually" Write-Info "The configuration has been updated and will work when Claude starts" return $false } } function Update-ClaudeConfig { Write-Info "Updating Claude Desktop configuration..." $configPath = "$env:APPDATA\Claude\claude_desktop_config.json" Write-Info "Config location: $configPath" # No backup needed - direct config update $configDir = Split-Path $configPath -Parent if (!(Test-Path $configDir)) { New-Item -ItemType Directory -Path $configDir -Force | Out-Null Write-Info "Created config directory" } # Read existing config or create new $config = @{} if (Test-Path $configPath) { try { # Read as JSON object first, then convert to hashtable if needed $jsonContent = Get-Content $configPath -Raw | ConvertFrom-Json # Convert PSCustomObject to hashtable for easier manipulation $config = @{} foreach ($property in $jsonContent.PSObject.Properties) { if ($property.Name -eq "mcpServers" -and $property.Value) { # Preserve existing MCP servers $config.mcpServers = @{} foreach ($serverProperty in $property.Value.PSObject.Properties) { $serverConfig = @{ command = $serverProperty.Value.command } if ($serverProperty.Value.args) { $serverConfig.args = @($serverProperty.Value.args) } if ($serverProperty.Value.env) { $serverConfig.env = @{} foreach ($envProperty in $serverProperty.Value.env.PSObject.Properties) { $serverConfig.env[$envProperty.Name] = $envProperty.Value } } $config.mcpServers[$serverProperty.Name] = $serverConfig } Write-Info "Preserved $($config.mcpServers.Count) existing MCP server(s)" } else { $config[$property.Name] = $property.Value } } } catch { Write-Warning "Could not parse existing config, creating new one" Write-Warning "Error: $($_.Exception.Message)" $config = @{} } } else { Write-Info "Creating new Claude configuration" } # Ensure mcpServers section exists if (!$config.mcpServers) { $config.mcpServers = @{} Write-Info "Created new mcpServers section" } # Check if our server already exists if ($config.mcpServers.ContainsKey("desktop-commander")) { Write-Info "Updating existing Desktop Commander configuration" } else { Write-Info "Adding new Desktop Commander configuration" } # Convert PowerShell array to proper format for JSON $argsArray = @() foreach ($arg in $script:DockerArgs) { $argsArray += $arg } # Add/update our server configuration (this preserves all other servers) $config.mcpServers["desktop-commander"] = @{ command = "docker" args = $argsArray } # Save configuration try { $jsonConfig = $config | ConvertTo-Json -Depth 10 [System.IO.File]::WriteAllText($configPath, $jsonConfig, [System.Text.UTF8Encoding]::new($false)) Write-Success "Claude configuration updated successfully" Write-Info "Server 'desktop-commander' added to MCP servers" Write-Info "Total MCP servers configured: $($config.mcpServers.Count)" # List all configured servers if ($config.mcpServers.Count -gt 1) { Write-Host "" Write-Info "All configured MCP servers:" foreach ($serverName in $config.mcpServers.Keys) { if ($serverName -eq "desktop-commander") { Write-Info " * $serverName (Desktop Commander) - UPDATED" } else { Write-Info " * $serverName (preserved)" } } } # Show what folders are mounted for our server if ($script:Folders.Count -gt 0) { Write-Host "" Write-Info "Folders accessible to Desktop Commander:" foreach ($folder in $script:Folders) { $folderName = Split-Path $folder -Leaf Write-Info " Folder: $folder" Write-Info " -> /home/$folderName (home-style path)" # Show Windows-style path too $windowsPath = $folder.Replace('\', '/') if ($windowsPath -match '^([A-Za-z]):(.*)') { $windowsStylePath = "/$($matches[1].ToLower())$($matches[2])" Write-Info " -> $windowsStylePath (windows-style path)" } } } else { Write-Warning "No folders mounted - limited file access" } } catch { Write-Error "Failed to save Claude configuration" Write-Error "Error: $($_.Exception.Message)" if (Test-Path "$configPath.backup-*") { Write-Info "You can restore from backup if needed" } exit 1 } } function Show-Status { Write-Header Write-Info "Checking installation status..." Write-Host "" try { $null = docker info 2>$null if ($LASTEXITCODE -eq 0) { Write-Success "Docker daemon: Running" } else { Write-Warning "Docker daemon: Not running" } } catch { Write-Warning "Docker: Not available" } try { $null = docker image inspect desktop-commander:latest 2>$null if ($LASTEXITCODE -eq 0) { Write-Success "Docker image: Available" } else { Write-Warning "Docker image: Missing" } } catch { Write-Warning "Docker image: Cannot check" } $volumes = @("dc-system", "dc-home", "dc-workspace", "dc-packages") $volumesFound = 0 Write-Host "" Write-Info "Persistent Volumes Status:" foreach ($volume in $volumes) { try { $null = docker volume inspect $volume 2>$null if ($LASTEXITCODE -eq 0) { $volumesFound++ Write-Success " OK: $volume" } else { Write-Warning " MISSING: $volume" } } catch { Write-Warning " UNKNOWN: $volume (cannot check)" } } $configPath = "$env:APPDATA\Claude\claude_desktop_config.json" if (Test-Path $configPath) { try { $config = Get-Content $configPath | ConvertFrom-Json if ($config.mcpServers."desktop-commander") { Write-Success "Claude config: Desktop Commander configured" } else { Write-Warning "Claude config: Missing Desktop Commander server" } } catch { Write-Warning "Claude config: Cannot parse" } } else { Write-Warning "Claude config: File not found" } Write-Host "" Write-Host "Status Summary:" -ForegroundColor Yellow Write-Host " Essential volumes: $volumesFound/4 found" Write-Host " Container mode: Auto-remove (fresh containers)" Write-Host " Persistence: Data stored in volumes" Write-Host "" if ($volumesFound -eq 4) { Write-Success "Ready to use with Claude!" Write-Info "Each command creates a fresh container that uses your persistent volumes." } elseif ($volumesFound -gt 0) { Write-Warning "Some volumes missing - may need to reinstall" Write-Info "Run reset and reinstall to fix this" } else { Write-Error "No volumes found - please run full installation" Write-Info "Run: .\install-docker-clean.ps1" } }function Reset-Installation { Write-Header Write-Warning "This will remove ALL persistent container data!" Write-Info "This includes:" Write-Info " - All installed packages and software" Write-Info " - All user configurations and settings" Write-Info " - All development projects in /workspace" Write-Info " - All package caches and databases" Write-Host "" Write-Info "Your mounted folders will NOT be affected." Write-Host "" $confirm = Read-Host "Are you sure you want to reset everything? [y/N]" if ($confirm -match "^[yY]") { Write-Info "Cleaning up containers and volumes..." try { $containers = docker ps -q --filter "ancestor=mcp/desktop-commander:latest" 2>$null if ($containers -and $LASTEXITCODE -eq 0) { docker stop $containers 2>$null | Out-Null docker rm $containers 2>$null | Out-Null Write-Info "Stopped running containers" } } catch { # Ignore errors here } Write-Info "Removing persistent volumes..." $volumes = @("dc-system", "dc-home", "dc-workspace", "dc-packages") $removedCount = 0 foreach ($volume in $volumes) { try { docker volume rm $volume 2>$null | Out-Null if ($LASTEXITCODE -eq 0) { Write-Success "Removed volume: $volume" $removedCount++ } else { Write-Warning "Volume $volume is still in use or doesn't exist" } } catch { Write-Warning "Error removing volume: $volume" } } Write-Host "" Write-Success "Persistent data reset complete!" if ($removedCount -gt 0) { Write-Success "Successfully removed $removedCount volume(s)" } Write-Host "" Write-Info "To reinstall after reset:" Write-Info "Run: .\install-docker-clean.ps1" } else { Write-Info "Reset cancelled" } } function Show-Help { Write-Host "Desktop Commander Docker Installation (Enhanced)" -ForegroundColor Blue Write-Host "" Write-Host "Usage:" Write-Host " .\install-docker-clean.ps1 - Interactive installation with folder selection" Write-Host " .\install-docker-clean.ps1 -Status - Check installation status" Write-Host " .\install-docker-clean.ps1 -Reset - Reset all data" Write-Host " .\install-docker-clean.ps1 -VerboseOutput - Show detailed output" Write-Host " .\install-docker-clean.ps1 -Help - Show this help" Write-Host "" Write-Host "Features:" Write-Host " - Interactive folder selection (like Mac version)" Write-Host " - Custom folder mounting outside home directory" Write-Host " - Persistent development environment" Write-Host " - Enhanced configuration options" Write-Host "" Write-Host "Troubleshooting:" Write-Host "If you broke the Docker container or need a fresh start:" Write-Host " .\install-docker-clean.ps1 -Reset" Write-Host " .\install-docker-clean.ps1" Write-Host "" Write-Host "This will completely reset your persistent environment and reinstall everything fresh." } function Start-Installation { Write-Header if ($Help) { Show-Help return } if ($Status) { Show-Status return } if ($Reset) { Reset-Installation return } Test-Docker Get-DockerImage Ask-ForFolders Initialize-Volumes Build-DockerArgs Update-ClaudeConfig Restart-Claude Write-Host "" Write-Success "Installation successfully completed! Thank you for using Desktop Commander!" Write-Host "" Write-Info "How it works:" Write-Info "- Desktop Commander runs in isolated containers" Write-Info "- Your development tools and configs persist between uses" Write-Info "- Each command creates a fresh, clean container" if ($script:Folders.Count -gt 0) { Write-Host "" Write-Info "Your accessible folders (dual mount paths):" foreach ($folder in $script:Folders) { $folderName = Split-Path $folder -Leaf Write-Info " Folder: $folder" Write-Info " -> /home/$folderName (home-style)" # Show Windows-style path too $windowsPath = $folder.Replace('\', '/') if ($windowsPath -match '^([A-Za-z]):(.*)') { $windowsStylePath = "/$($matches[1].ToLower())$($matches[2])" Write-Info " -> $windowsStylePath (windows-style)" } } Write-Host "" Write-Info "Path Translation Examples:" Write-Info " Windows: C:\Users\wonde\projects\file.txt" Write-Info " Docker: /c/users/wonde/projects/file.txt (windows-style)" Write-Info " Docker: /home/wonde/projects/file.txt (home-style)" } Write-Host "" Write-Info "To refresh/reset your persistent environment:" Write-Info "- Run: .\install-docker-clean.ps1 -Reset" Write-Info "- This removes all installed packages and resets everything" Write-Host "" Write-Info "If you broke the Docker container or need a fresh start:" Write-Info "- Run: .\install-docker-clean.ps1 -Reset" Write-Info "- Then: .\install-docker-clean.ps1" Write-Info "- This will reset everything and reinstall from scratch" Write-Host "" Write-Info "Claude Desktop has been automatically restarted (if possible)" Write-Success "Desktop Commander is available as 'desktop-commander' in Claude" Write-Host "" Write-Info "Next steps: Install anything you want - it will persist!" Write-Info "- Global packages: npm install -g typescript" Write-Info "- User configs: git config, SSH keys, .bashrc" Write-Host "" Write-Info "Need help or have feedback? Happy to jump on a quick call:" Write-Info " https://calendar.app.google/SHMNZN5MJznJWC5A7" Write-Host "" Write-Info "Join our community: https://discord.com/invite/kQ27sNnZr7" } # Run installation Start-Installation
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
install-docker.sh
Shell
#!/bin/bash # Desktop Commander Docker Installation Script set -e # Colors for output RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BLUE='\033[0;34m' NC='\033[0m' # No Color # Docker image - can be changed to latest DOCKER_IMAGE="mcp/desktop-commander:latest" CONTAINER_NAME="desktop-commander" # Global flag for verbose output VERBOSE=false print_header() { echo echo -e "${BLUE}██████╗ ███████╗███████╗██╗ ██╗████████╗ ██████╗ ██████╗ ██████╗ ██████╗ ███╗ ███╗███╗ ███╗ █████╗ ███╗ ██╗██████╗ ███████╗██████╗${NC}" echo -e "${BLUE}██╔══██╗██╔════╝██╔════╝██║ ██╔╝╚══██╔══╝██╔═══██╗██╔══██╗ ██╔════╝██╔═══██╗████╗ ████║████╗ ████║██╔══██╗████╗ ██║██╔══██╗██╔════╝██╔══██╗${NC}" echo -e "${BLUE}██║ ██║█████╗ ███████╗█████╔╝ ██║ ██║ ██║██████╔╝ ██║ ██║ ██║██╔████╔██║██╔████╔██║███████║██╔██╗ ██║██║ ██║█████╗ ██████╔╝${NC}" echo -e "${BLUE}██║ ██║██╔══╝ ╚════██║██╔═██╗ ██║ ██║ ██║██╔═══╝ ██║ ██║ ██║██║╚██╔╝██║██║╚██╔╝██║██╔══██║██║╚██╗██║██║ ██║██╔══╝ ██╔══██╗${NC}" echo -e "${BLUE}██████╔╝███████╗███████║██║ ██╗ ██║ ╚██████╔╝██║ ╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ╚═╝ ██║██║ ██║██║ ╚████║██████╔╝███████╗██║ ██║${NC}" echo -e "${BLUE}╚═════╝ ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═╝${NC}" echo echo -e "${BLUE}🐳 Docker Installation${NC}" echo print_info "Experiment with AI in secure sandbox environment that won't mess up your main computer" echo } print_success() { echo -e "${GREEN}✅ $1${NC}" } print_error() { echo -e "${RED}❌ Error: $1${NC}" >&2 } print_warning() { echo -e "${YELLOW}⚠️ Warning: $1${NC}" } print_info() { echo -e "${BLUE}ℹ️ $1${NC}" } print_verbose() { if [ "$VERBOSE" = true ]; then echo -e "${BLUE}ℹ️ $1${NC}" fi } # Detect OS detect_os() { case "$OSTYPE" in darwin*) OS="macos" ;; linux*) OS="linux" ;; *) print_error "Unsupported OS: $OSTYPE" ; exit 1 ;; esac } # Get Claude config path based on OS get_claude_config_path() { case "$OS" in "macos") CLAUDE_CONFIG="$HOME/Library/Application Support/Claude/claude_desktop_config.json" ;; "linux") CLAUDE_CONFIG="$HOME/.config/claude/claude_desktop_config.json" ;; esac } # Check if Docker is available check_docker() { while true; do if ! command -v docker >/dev/null 2>&1; then print_error "Docker is not installed or not found" echo print_error "Please install Docker first:" case "$OS" in "macos") print_error "• Download Docker Desktop: https://www.docker.com/products/docker-desktop/" ;; "linux") print_error "• Install Docker Engine: https://docs.docker.com/engine/install/" ;; esac echo echo -n "Press Enter when Docker Desktop is running or Ctrl+C to exit: " read -r continue fi if ! docker info >/dev/null 2>&1; then print_error "Docker is installed but not running" echo print_error "Please start Docker Desktop and try again" echo echo -n "Press Enter when Docker Desktop is running or Ctrl+C to exit: " read -r continue fi # If we get here, Docker is working break done print_success "Docker is available and running" } # Pull the Docker image pull_docker_image() { print_info "Pulling latest Docker image (this may take a moment)..." if docker pull "$DOCKER_IMAGE"; then print_success "Docker image ready: $DOCKER_IMAGE" else print_error "Failed to pull Docker image" print_info "Check your internet connection and Docker Hub access" exit 1 fi } # Ask user which folders to mount ask_for_folders() { echo echo -e "${BLUE}📁 Folder Access Setup${NC}" print_info "By default, Desktop Commander will have access to your user folder:" print_info "📂 $HOME" echo echo -n "Press Enter to accept user folder access or 'y' to customize: " read -r response FOLDERS=() if [[ $response =~ ^[Yy]$ ]]; then # Custom folder selection echo print_info "Custom folder selection:" echo -n "Mount your complete home directory ($HOME)? [Y/n]: " read -r home_response case "$home_response" in [nN]|[nN][oO]) print_info "Skipping home directory" ;; *) FOLDERS+=("$HOME") print_success "Added home directory access" ;; esac # Ask for additional folders echo print_info "Add extra folders outside home directory (optional):" while true; do echo -n "Enter folder path (or Enter to finish): " read -r custom_dir if [ -z "$custom_dir" ]; then break fi custom_dir="${custom_dir/#\~/$HOME}" if [ -d "$custom_dir" ]; then FOLDERS+=("$custom_dir") print_success "Added: $custom_dir" else echo -n "Folder doesn't exist. Add anyway? [y/N]: " read -r add_anyway if [[ $add_anyway =~ ^[Yy]$ ]]; then FOLDERS+=("$custom_dir") print_info "Added: $custom_dir (will create if needed)" fi fi done if [ ${#FOLDERS[@]} -eq 0 ]; then echo print_warning "⚠️ No folders selected - Desktop Commander will have NO file access" echo print_info "This means:" echo " • Desktop Commander cannot read or write any files on your computer" echo " • It cannot help with coding projects, file management, or document editing" echo " • It will only work for system commands and package installation" echo " • This makes Desktop Commander much less useful than intended" echo print_info "You probably want to share at least some folder to work with files" print_info "Most users share their home directory: $HOME" echo echo -n "Continue with NO file access? [y/N]: " read -r confirm if [[ ! $confirm =~ ^[Yy]$ ]]; then print_info "Restarting folder selection..." ask_for_folders return fi print_warning "Proceeding with no file access - Desktop Commander will be limited" fi else # Default: use home directory FOLDERS+=("$HOME") print_success "Using default access to your user folder" fi } # Setup essential volumes for maximum persistence setup_persistent_volumes() { print_verbose "🔧 Setting up persistent development environment" # Essential volumes that cover everything a developer needs ESSENTIAL_VOLUMES=( "dc-system:/usr" # All system packages, binaries, libraries "dc-home:/root" # User configs, dotfiles, SSH keys, git config "dc-workspace:/workspace" # Development files and projects "dc-packages:/var" # Package databases, caches, logs ) for volume in "${ESSENTIAL_VOLUMES[@]}"; do volume_name=$(echo "$volume" | cut -d':' -f1) if ! docker volume inspect "$volume_name" >/dev/null 2>&1; then docker volume create "$volume_name" >/dev/null 2>&1 fi done print_verbose "Persistent environment ready - your tools will survive restarts" } # Build Docker run arguments build_docker_args() { print_verbose "Building Docker configuration..." # Start with base arguments (use --rm so containers auto-remove after each use) DOCKER_ARGS=("run" "-i" "--rm") # Add essential persistent volumes for volume in "${ESSENTIAL_VOLUMES[@]}"; do DOCKER_ARGS+=("-v" "$volume") done # Add user folder mounts with absolute path structure for folder in "${FOLDERS[@]}"; do # Remove leading /Users/username or /home/username and keep absolute structure if [[ "$folder" =~ ^/Users/[^/]+(/.+)$ ]]; then # Mac: /Users/john/projects/data → /home/projects/data absolute_path="${BASH_REMATCH[1]}" DOCKER_ARGS+=("-v" "$folder:/home$absolute_path") elif [[ "$folder" =~ ^/home/[^/]+(/.+)$ ]]; then # Linux: /home/john/projects/data → /home/projects/data absolute_path="${BASH_REMATCH[1]}" DOCKER_ARGS+=("-v" "$folder:/home$absolute_path") else # Fallback for other paths - use basename folder_name=$(basename "$folder") DOCKER_ARGS+=("-v" "$folder:/home/$folder_name") fi done # Add the image DOCKER_ARGS+=("$DOCKER_IMAGE") print_verbose "Docker configuration ready" print_verbose "Essential volumes: ${#ESSENTIAL_VOLUMES[@]} volumes" print_verbose "Mounted folders: ${#FOLDERS[@]} folders" print_verbose "Container mode: Auto-remove after each use (--rm)" } # Update Claude desktop config update_claude_config() { print_verbose "Updating Claude Desktop configuration..." # Create config directory if it doesn't exist CONFIG_DIR=$(dirname "$CLAUDE_CONFIG") if [[ ! -d "$CONFIG_DIR" ]]; then mkdir -p "$CONFIG_DIR" print_verbose "Created config directory: $CONFIG_DIR" fi # Create config if it doesn't exist if [[ ! -f "$CLAUDE_CONFIG" ]]; then echo '{"mcpServers": {}}' > "$CLAUDE_CONFIG" print_verbose "Created new Claude config file" fi # Convert DOCKER_ARGS array to JSON format ARGS_JSON="[" for i in "${!DOCKER_ARGS[@]}"; do if [[ $i -gt 0 ]]; then ARGS_JSON+=", " fi ARGS_JSON+="\"${DOCKER_ARGS[$i]}\"" done ARGS_JSON+="]" # Use Python to update JSON (preserves existing MCP servers) python3 -c " import json import sys config_path = '$CLAUDE_CONFIG' docker_args = $ARGS_JSON try: with open(config_path, 'r') as f: config = json.load(f) except: config = {'mcpServers': {}} if 'mcpServers' not in config: config['mcpServers'] = {} # Configure to use docker run with essential volumes config['mcpServers']['desktop-commander'] = { 'command': 'docker', 'args': docker_args } with open(config_path, 'w') as f: json.dump(config, f, indent=2) print('Successfully updated Claude config') " || { print_error "Failed to update Claude config with Python" exit 1 } print_verbose "Updated Claude config: $CLAUDE_CONFIG" print_verbose "Desktop Commander will be available as 'desktop-commander' in Claude" } # Test the persistent setup test_persistence() { print_verbose "Testing persistent container setup..." print_verbose "Testing essential volumes with a temporary container..." # Test that essential paths are available for persistence if docker "${DOCKER_ARGS[@]}" /bin/bash -c " echo 'Testing persistence paths...' mkdir -p /workspace/test echo 'test-data' > /workspace/test/file.txt && echo 'Workspace persistence: OK' touch /root/.test_config && echo 'Home persistence: OK' echo 'Container test completed successfully' " >/dev/null 2>&1; then print_verbose "Essential persistence test passed" print_verbose "Volumes are working correctly" else print_verbose "Some persistence tests had issues (might still work)" fi } # Show container management commands show_management_info() { echo print_success "🎉 Installation successfully completed! Thank you for using Desktop Commander!" echo print_info "How it works:" echo "• Desktop Commander runs in isolated containers" echo "• Your development tools and configs persist between uses" echo "• Each command creates a fresh, clean container" echo print_info "🤔 Need help or have feedback? Happy to jump on a quick call:" echo " https://calendar.app.google/SHMNZN5MJznJWC5A7" echo print_info "💬 Join our community: https://discord.com/invite/kQ27sNnZr7" echo print_info "💡 If you broke the Docker container or need a fresh start:" echo "• Run: $0 --reset && $0" echo "• This will reset everything and reinstall from scratch" } # Reset all persistent data reset_persistence() { echo print_warning "This will remove ALL persistent container data!" echo "This includes:" echo " • All installed packages and software" echo " • All user configurations and settings" echo " • All development projects in /workspace" echo " • All package caches and databases" echo print_info "Your mounted folders will NOT be affected." echo read -p "Are you sure you want to reset everything? [y/N]: " -r case "$REPLY" in [yY]|[yY][eE][sS]) print_info "Cleaning up containers and volumes..." # Stop and remove any containers that might be using our volumes print_verbose "Stopping any running Desktop Commander containers..." docker ps -q --filter "ancestor=$DOCKER_IMAGE" | xargs -r docker stop >/dev/null 2>&1 || true docker ps -a -q --filter "ancestor=$DOCKER_IMAGE" | xargs -r docker rm >/dev/null 2>&1 || true # Also try by container name if it exists docker stop "$CONTAINER_NAME" >/dev/null 2>&1 || true docker rm "$CONTAINER_NAME" >/dev/null 2>&1 || true print_info "Removing persistent volumes..." local volumes=("dc-system" "dc-home" "dc-workspace" "dc-packages") local failed_volumes=() for volume in "${volumes[@]}"; do if docker volume rm "$volume" >/dev/null 2>&1; then print_success "✅ Removed volume: $volume" else failed_volumes+=("$volume") print_warning "⚠️ Volume $volume is still in use or doesn't exist" fi done # If some volumes failed, try harder cleanup if [ ${#failed_volumes[@]} -gt 0 ]; then print_info "Attempting force cleanup of remaining volumes..." # Remove ALL containers that might be holding references (more aggressive) docker container prune -f >/dev/null 2>&1 || true for volume in "${failed_volumes[@]}"; do if docker volume rm "$volume" >/dev/null 2>&1; then print_success "✅ Force removed volume: $volume" else print_error "❌ Could not remove volume: $volume" print_info "Manual cleanup needed: docker volume rm $volume" fi done fi print_success "🎉 Persistent data reset complete!" echo print_info "Run the installer again to create a fresh environment" ;; *) print_info "Reset cancelled" ;; esac } # Show status of current setup show_status() { echo print_header # Check essential volumes local volumes=("dc-system" "dc-home" "dc-workspace" "dc-packages") local volumes_found=0 echo "Essential volumes status:" for volume in "${volumes[@]}"; do if docker volume inspect "$volume" >/dev/null 2>&1; then local mountpoint mountpoint=$(docker volume inspect "$volume" --format '{{.Mountpoint}}' 2>/dev/null || echo "unknown") local size size=$(sudo du -sh "$mountpoint" 2>/dev/null | cut -f1 || echo "unknown") echo " ✅ $volume ($size)" ((volumes_found++)) else echo " ❌ $volume (missing)" fi done echo echo "Status Summary:" echo " Essential volumes: $volumes_found/4 found" echo " Container mode: Auto-remove (--rm)" echo " Persistence: Data stored in volumes" echo if [ "$volumes_found" -eq 4 ]; then echo "✅ Ready to use with Claude!" echo "Each command creates a fresh container that uses your persistent volumes." elif [ "$volumes_found" -gt 0 ]; then echo "⚠️ Some volumes missing - may need to reinstall" else echo "🚀 Run the installer to create your persistent volumes" fi } # Try to restart Claude automatically restart_claude() { print_info "Attempting to restart Claude..." case "$OS" in macos) # Kill Claude if running if pgrep -f "Claude" > /dev/null; then killall "Claude" 2>/dev/null || true sleep 2 print_info "Stopped Claude" fi # Try to start Claude if command -v open &> /dev/null; then if open -a "Claude" 2>/dev/null; then print_success "Claude restarted successfully" else print_warning "Could not auto-start Claude. Please start it manually." fi else print_warning "Could not auto-restart Claude. Please start it manually." fi ;; linux) # Kill Claude if running if pgrep -f "claude" > /dev/null; then pkill -f "claude" 2>/dev/null || true sleep 2 print_info "Stopped Claude" fi # Try to start Claude if command -v claude &> /dev/null; then if claude &>/dev/null & disown; then print_success "Claude restarted successfully" else print_warning "Could not auto-start Claude. Please start it manually." fi else print_warning "Could not auto-restart Claude. Please start it manually." fi ;; esac } # Help message show_help() { print_header echo "Usage: $0 [OPTION]" echo echo "Options:" echo " (no args) Interactive installation" echo " --verbose Show detailed technical output" echo " --reset Remove all persistent data" echo " --status Show current status" echo " --help Show this help" echo echo "Creates a persistent development container using 4 essential volumes:" echo " • dc-system: System packages and binaries (/usr)" echo " • dc-home: User configurations (/root)" echo " • dc-workspace: Development projects (/workspace)" echo " • dc-packages: Package databases and caches (/var)" echo echo "This covers 99% of development persistence needs with simple management." echo } # Main execution logic case "${1:-}" in --reset) print_header reset_persistence exit 0 ;; --status) show_status exit 0 ;; --help) show_help exit 0 ;; --verbose) VERBOSE=true # Continue to main installation flow ;; ""|--install) # Main installation flow ;; *) print_error "Unknown option: $1" echo "Use --help for usage information" exit 1 ;; esac # Main installation flow print_header detect_os print_success "Detected OS: $OS" get_claude_config_path print_info "Claude config path: $CLAUDE_CONFIG" check_docker pull_docker_image ask_for_folders setup_persistent_volumes build_docker_args update_claude_config test_persistence restart_claude echo print_success "✅ Claude has been restarted (if possible)" print_info "Desktop Commander is available as 'desktop-commander' in Claude" echo print_info "Next steps: Install anything you want - it will persist!" echo "• Global packages: npm install -g typescript" echo "• User configs: git config, SSH keys, .bashrc" show_management_info
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
install.sh
Shell
#!/bin/bash # Exit on error set -e # Function to print error print_error() { echo "❌ Error: $1" >&2 } # Function to print success print_success() { echo "✅ $1" } # Check if Node.js is installed if command -v node &> /dev/null; then NODE_VERSION=$(node -v | cut -d 'v' -f 2) NODE_MAJOR_VERSION=$(echo "$NODE_VERSION" | cut -d '.' -f 1) if [ "$NODE_MAJOR_VERSION" -lt 18 ]; then print_error "Detected Node.js v$NODE_VERSION, but v18+ is required. Please upgrade Node.js." exit 1 else echo "Node.js v$NODE_VERSION detected. Continuing..." fi else echo "Node.js not found. Installing Node.js v22.14.0..." mkdir -p /tmp/nodejs-install curl -fsSL -o /tmp/nodejs-install/node-v22.14.0.pkg https://nodejs.org/dist/v22.14.0/node-v22.14.0.pkg sudo installer -pkg /tmp/nodejs-install/node-v22.14.0.pkg -target / if command -v node &> /dev/null; then rm -rf /tmp/nodejs-install print_success "Node.js v22.14.0 installed successfully." else print_error "Node.js installation failed. Visit https://nodejs.org to install manually." exit 1 fi fi # Run the setup echo "Running setup command..." if npx @wonderwhy-er/desktop-commander@latest setup; then print_success "Setup completed successfully!" else print_error "Setup failed. Check the console output above for more information." exit 1 fi exit 0
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
scripts/analyze-fuzzy-logs.js
JavaScript
#!/usr/bin/env node import { fuzzySearchLogger } from '../dist/utils/fuzzySearchLogger.js'; // Simple argument parsing const args = process.argv.slice(2); let failureThreshold = 0.7; let limit = 100; // Parse arguments for (let i = 0; i < args.length; i++) { if (args[i] === '--threshold' || args[i] === '-t') { failureThreshold = parseFloat(args[i + 1]) || 0.7; } if (args[i] === '--limit' || args[i] === '-l') { limit = parseInt(args[i + 1], 10) || 100; } if (args[i].startsWith('--threshold=')) { failureThreshold = parseFloat(args[i].split('=')[1]) || 0.7; } if (args[i].startsWith('--limit=')) { limit = parseInt(args[i].split('=')[1], 10) || 100; } } if (args.includes('--help') || args.includes('-h')) { console.log(`Analyze fuzzy search logs for patterns and issues Usage: node analyze-fuzzy-logs.js [options] Options: -t, --threshold <number> Failure threshold (0-1) (default: 0.7) -l, --limit <number> Maximum number of logs to analyze (default: 100) -h, --help Show this help message`); process.exit(0); } async function analyzeLogs() { try { const logs = await fuzzySearchLogger.getRecentLogs(limit); const logPath = await fuzzySearchLogger.getLogPath(); if (logs.length === 0) { console.log(`No fuzzy search logs found. Log file location: ${logPath}`); return; } console.log('\n=== Fuzzy Search Analysis ===\n'); // Parse logs and gather statistics let totalEntries = 0; let exactMatches = 0; let fuzzyMatches = 0; let failures = 0; let belowThresholdCount = 0; const executionTimes = []; const similarities = []; const fileExtensions = new Map(); const commonCharacterCodes = new Map(); const failureReasons = []; for (const log of logs) { const parts = log.split('\t'); if (parts.length >= 16) { totalEntries++; const [ timestamp, searchText, foundText, similarity, executionTime, exactMatchCount, expectedReplacements, fuzzyThreshold, belowThreshold, diff, searchLength, foundLength, fileExtension, characterCodes, uniqueCharacterCount, diffLength ] = parts; const simValue = parseFloat(similarity); const execTime = parseFloat(executionTime); const exactCount = parseInt(exactMatchCount); const belowThresh = belowThreshold === 'true'; if (exactCount > 0) { exactMatches++; } else if (simValue >= failureThreshold) { fuzzyMatches++; } else { failures++; // Store failure case for analysis failureReasons.push({ similarity: simValue, diff: diff.replace(/\\n/g, '\n').replace(/\\t/g, '\t'), fileExtension, characterCodes }); } if (belowThresh) { belowThresholdCount++; } executionTimes.push(execTime); similarities.push(simValue); // Track file extensions fileExtensions.set(fileExtension, (fileExtensions.get(fileExtension) || 0) + 1); // Track character codes that appear in diffs if (characterCodes && characterCodes !== '') { const codes = characterCodes.split(','); for (const code of codes) { const key = code.split(':')[0]; commonCharacterCodes.set(key, (commonCharacterCodes.get(key) || 0) + 1); } } } } // Calculate statistics const avgExecutionTime = executionTimes.reduce((a, b) => a + b, 0) / executionTimes.length; const avgSimilarity = similarities.reduce((a, b) => a + b, 0) / similarities.length; const maxExecutionTime = Math.max(...executionTimes); const minExecutionTime = Math.min(...executionTimes); // Sort by frequency const sortedExtensions = Array.from(fileExtensions.entries()).sort((a, b) => b[1] - a[1]); const sortedCharCodes = Array.from(commonCharacterCodes.entries()).sort((a, b) => b[1] - a[1]); // Display results console.log(`Total Entries: ${totalEntries}`); console.log(`Exact Matches: ${exactMatches} (${((exactMatches / totalEntries) * 100).toFixed(2)}%)`); console.log(`Fuzzy Matches: ${fuzzyMatches} (${((fuzzyMatches / totalEntries) * 100).toFixed(2)}%)`); console.log(`Failures: ${failures} (${((failures / totalEntries) * 100).toFixed(2)}%)`); console.log(`Below Threshold: ${belowThresholdCount} (${((belowThresholdCount / totalEntries) * 100).toFixed(2)}%)`); console.log('\n--- Performance Metrics ---'); console.log(`Average Execution Time: ${avgExecutionTime.toFixed(2)}ms`); console.log(`Min Execution Time: ${minExecutionTime.toFixed(2)}ms`); console.log(`Max Execution Time: ${maxExecutionTime.toFixed(2)}ms`); console.log(`Average Similarity: ${(avgSimilarity * 100).toFixed(2)}%`); console.log('\n--- File Extensions (Top 5) ---'); sortedExtensions.slice(0, 5).forEach(([ext, count]) => { console.log(`${ext || 'none'}: ${count} times`); }); console.log('\n--- Common Character Codes in Diffs (Top 10) ---'); sortedCharCodes.slice(0, 10).forEach(([code, count]) => { const charCode = parseInt(code); const char = String.fromCharCode(charCode); const display = charCode < 32 || charCode > 126 ? `\\x${charCode.toString(16).padStart(2, '0')}` : char; console.log(`${code} [${display}]: ${count} times`); }); // Analyze failure patterns if (failures > 0) { console.log('\n--- Failure Analysis ---'); console.log(`Total failures: ${failures}`); // Group failures by similarity ranges const similarityRanges = { '0-20%': 0, '21-40%': 0, '41-60%': 0, '61-80%': 0, '81-99%': 0 }; failureReasons.forEach(failure => { const sim = failure.similarity * 100; if (sim <= 20) similarityRanges['0-20%']++; else if (sim <= 40) similarityRanges['21-40%']++; else if (sim <= 60) similarityRanges['41-60%']++; else if (sim <= 80) similarityRanges['61-80%']++; else similarityRanges['81-99%']++; }); console.log('\nFailures by similarity range:'); Object.entries(similarityRanges).forEach(([range, count]) => { if (count > 0) { console.log(` ${range}: ${count} failures`); } }); // Show most common failure reasons const failuresByExtension = new Map(); failureReasons.forEach(failure => { const key = failure.fileExtension || 'none'; failuresByExtension.set(key, (failuresByExtension.get(key) || 0) + 1); }); console.log('\nFailures by file extension:'); Array.from(failuresByExtension.entries()) .sort((a, b) => b[1] - a[1]) .slice(0, 5) .forEach(([ext, count]) => { console.log(` ${ext}: ${count} failures`); }); } // Recommendations console.log('\n--- Recommendations ---'); if (failures > totalEntries * 0.1) { console.log(`⚠️ High failure rate (${((failures / totalEntries) * 100).toFixed(1)}%). Consider: - Reviewing search text formatting (whitespace, line endings) - Checking for encoding issues - Using smaller, more specific search patterns`); } if (avgExecutionTime > 100) { console.log(`⚠️ Slow execution times (avg: ${avgExecutionTime.toFixed(2)}ms). Consider: - Reducing search text length - Breaking large edits into smaller chunks`); } if (sortedCharCodes.length > 0) { const topCharCode = sortedCharCodes[0]; const charCode = parseInt(topCharCode[0]); if (charCode === 13 || charCode === 10) { console.log(`💡 Most common character differences involve line endings (CR/LF). Consider normalizing line endings in your search text.`); } else if (charCode === 32 || charCode === 9) { console.log(`💡 Most common character differences involve whitespace. Consider trimming whitespace or being more specific about spacing.`); } } console.log(`\nLog file location: ${logPath}`); console.log(`Analysis completed for ${totalEntries} entries.`); } catch (error) { console.error('Failed to analyze fuzzy search logs:', error.message); process.exit(1); } } analyzeLogs();
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
scripts/build-mcpb.cjs
JavaScript
#!/usr/bin/env node /** * Build script for creating Desktop Commander MCPB bundle * * This script: * 1. Builds the TypeScript project * 2. Creates a bundle directory structure * 3. Generates a proper MCPB manifest.json * 4. Copies the built server and dependencies * 5. Uses mcpb CLI to create the final .mcpb bundle */ const fs = require('fs'); const path = require('path'); const { execSync } = require('child_process'); const PROJECT_ROOT = path.resolve(__dirname, '..'); const BUNDLE_DIR = path.join(PROJECT_ROOT, 'mcpb-bundle'); const MANIFEST_PATH = path.join(BUNDLE_DIR, 'manifest.json'); console.log('🏗️ Building Desktop Commander MCPB Bundle...'); // Step 0: Download all ripgrep binaries for cross-platform support console.log('🌍 Downloading ripgrep binaries for all platforms...'); try { execSync('node scripts/download-all-ripgrep.cjs', { cwd: PROJECT_ROOT, stdio: 'inherit' }); console.log('✅ Ripgrep binaries downloaded'); } catch (error) { console.error('❌ Failed to download ripgrep binaries:', error.message); process.exit(1); } // Step 1: Build the TypeScript project console.log('📦 Building TypeScript project...'); try { execSync('npm run build', { cwd: PROJECT_ROOT, stdio: 'inherit' }); console.log('✅ TypeScript build completed'); } catch (error) { console.error('❌ TypeScript build failed:', error.message); process.exit(1); } // Step 2: Clean and create bundle directory if (fs.existsSync(BUNDLE_DIR)) { fs.rmSync(BUNDLE_DIR, { recursive: true }); }fs.mkdirSync(BUNDLE_DIR, { recursive: true }); // Step 3: Read package.json for version and metadata const packageJson = JSON.parse(fs.readFileSync(path.join(PROJECT_ROOT, 'package.json'), 'utf8')); // Step 4: Load and process manifest template console.log('📝 Processing manifest template...'); const manifestTemplatePath = path.join(PROJECT_ROOT, 'manifest.template.json'); console.log(`📄 Using manifest: manifest.template.json`); let manifestTemplate; try { manifestTemplate = fs.readFileSync(manifestTemplatePath, 'utf8'); } catch (error) { console.error('❌ Failed to read manifest template:', manifestTemplatePath); process.exit(1); } // Replace template variables const manifestContent = manifestTemplate.replace('{{VERSION}}', packageJson.version); // Parse and validate the resulting manifest let manifest; try { manifest = JSON.parse(manifestContent); } catch (error) { console.error('❌ Invalid JSON in manifest template:', error.message); process.exit(1); } // Write manifest fs.writeFileSync(MANIFEST_PATH, JSON.stringify(manifest, null, 2)); console.log('✅ Created manifest.json'); // Step 5: Copy necessary files const filesToCopy = [ 'dist', 'package.json', 'README.md', 'LICENSE', 'PRIVACY.md', 'icon.png' ]; filesToCopy.forEach(file => { const srcPath = path.join(PROJECT_ROOT, file); const destPath = path.join(BUNDLE_DIR, file); if (fs.existsSync(srcPath)) { if (fs.statSync(srcPath).isDirectory()) { // Copy directory recursively fs.cpSync(srcPath, destPath, { recursive: true }); } else { // Copy file fs.copyFileSync(srcPath, destPath); } console.log(`✅ Copied ${file}`); } else { console.log(`⚠️ Skipped ${file} (not found)`); } }); // Step 6: Create package.json in bundle with production dependencies from main package.json // This ensures MCPB bundle always has the same dependencies as the npm package const bundlePackageJson = { name: manifest.name, version: manifest.version, description: manifest.description, type: "module", // Required for ESM - without this, Node.js defaults to CommonJS and shows warnings main: "dist/index.js", author: manifest.author, license: manifest.license, repository: manifest.repository, dependencies: packageJson.dependencies // Use dependencies directly from package.json }; fs.writeFileSync( path.join(BUNDLE_DIR, 'package.json'), JSON.stringify(bundlePackageJson, null, 2) ); // Step 6b: Install dependencies in bundle directory console.log('📦 Installing production dependencies in bundle...'); try { execSync('npm install --omit=dev --production', { cwd: BUNDLE_DIR, stdio: 'inherit' }); console.log('✅ Dependencies installed'); } catch (error) { console.error('❌ Failed to install dependencies:', error.message); process.exit(1); } // Step 6c: Copy platform-specific ripgrep binaries and wrapper console.log('🔧 Setting up cross-platform ripgrep support...'); try { const ripgrepBinSrc = path.join(PROJECT_ROOT, 'node_modules/@vscode/ripgrep/bin'); const ripgrepBinDest = path.join(BUNDLE_DIR, 'node_modules/@vscode/ripgrep/bin'); const ripgrepWrapperSrc = path.join(PROJECT_ROOT, 'scripts/ripgrep-wrapper.js'); const ripgrepIndexDest = path.join(BUNDLE_DIR, 'node_modules/@vscode/ripgrep/lib/index.js'); // Ensure bin directory exists if (!fs.existsSync(ripgrepBinDest)) { fs.mkdirSync(ripgrepBinDest, { recursive: true }); } // Copy all platform-specific ripgrep binaries const binaries = fs.readdirSync(ripgrepBinSrc).filter(f => f.startsWith('rg-')); binaries.forEach(binary => { const src = path.join(ripgrepBinSrc, binary); const dest = path.join(ripgrepBinDest, binary); fs.copyFileSync(src, dest); // Set executable permissions (for development/testing) // Note: Zip archives don't preserve permissions reliably, so ripgrep-wrapper.js // also sets permissions at runtime to ensure compatibility after extraction if (!binary.endsWith('.exe')) { fs.chmodSync(dest, 0o755); } }); console.log(`✅ Copied ${binaries.length} ripgrep binaries`); // Replace index.js with our wrapper fs.copyFileSync(ripgrepWrapperSrc, ripgrepIndexDest); console.log('✅ Installed ripgrep runtime wrapper'); } catch (error) { console.error('❌ Failed to setup ripgrep:', error.message); process.exit(1); } // Step 7: Validate manifest console.log('🔍 Validating manifest...'); try { execSync(`npx @anthropic-ai/mcpb validate "${MANIFEST_PATH}"`, { stdio: 'inherit' }); console.log('✅ Manifest validation passed'); } catch (error) { console.error('❌ Manifest validation failed:', error.message); process.exit(1); } // Step 8: Pack the bundle console.log('📦 Creating .mcpb bundle...'); const outputFile = path.join(PROJECT_ROOT, `${manifest.name}-${manifest.version}.mcpb`); try { execSync(`npx @anthropic-ai/mcpb pack "${BUNDLE_DIR}" "${outputFile}"`, { stdio: 'inherit' }); console.log('✅ MCPB bundle created successfully!'); console.log(`📁 Bundle location: ${outputFile}`); } catch (error) { console.error('❌ Bundle creation failed:', error.message); process.exit(1); } console.log(''); console.log('🎉 Desktop Commander MCPB bundle is ready!'); console.log(''); console.log('Next steps:'); console.log('1. Test the bundle by installing it in Claude Desktop:'); console.log(' Settings → Extensions → Advanced Settings → Install Extension'); console.log(`2. Select the file: ${outputFile}`); console.log('3. Configure any settings and test the functionality'); console.log(''); console.log('To submit to Anthropic directory:'); console.log('- Ensure privacy policy is accessible at the GitHub URL'); console.log('- Complete destructive operation annotations (✅ Done)'); console.log('- Submit via Anthropic desktop extensions interest form');
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
scripts/build-ui-runtime.cjs
JavaScript
#!/usr/bin/env node /** * Build script that compiles and stages browser UI assets used by MCP tool pages. It centralizes bundling/runtime generation so UI resources are deterministic in local dev and CI. */ const path = require('path'); const fs = require('fs/promises'); const { build } = require('esbuild'); const target = process.argv[2]; const TARGETS = { 'file-preview': { entry: 'src/ui/file-preview/src/main.ts', output: 'dist/ui/file-preview/preview-runtime.js', staticDir: 'src/ui/file-preview', styleLayers: [ 'src/ui/styles/base.css', 'src/ui/styles/components/tool-header.css', 'src/ui/styles/apps/file-preview.css' ] } }; const STATIC_FILES = ['index.html']; const projectRoot = path.resolve(__dirname, '..'); const selectedTargets = target ? [target] : Object.keys(TARGETS); if (target && !TARGETS[target]) { console.error( `Usage: node scripts/build-ui-runtime.cjs [${Object.keys(TARGETS).join('|')}]` ); process.exit(1); } async function buildTarget(targetName) { const { entry, output, staticDir, styleLayers } = TARGETS[targetName]; const outputPath = path.join(projectRoot, output); const outputDir = path.dirname(outputPath); await fs.mkdir(outputDir, { recursive: true }); for (const fileName of STATIC_FILES) { await fs.copyFile( path.join(projectRoot, staticDir, fileName), path.join(outputDir, fileName) ); } const styles = await Promise.all( styleLayers.map((layerPath) => fs.readFile(path.join(projectRoot, layerPath), 'utf8')) ); await fs.writeFile(path.join(outputDir, 'styles.css'), `${styles.join('\n\n')}\n`, 'utf8'); await build({ entryPoints: [path.join(projectRoot, entry)], bundle: true, format: 'iife', platform: 'browser', target: ['es2020'], outfile: outputPath, minify: false, sourcemap: false }); } async function main() { for (const targetName of selectedTargets) { await buildTarget(targetName); } } main().catch((error) => { console.error(error); process.exit(1); });
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
scripts/clear-fuzzy-logs.js
JavaScript
#!/usr/bin/env node import { fuzzySearchLogger } from '../dist/utils/fuzzySearchLogger.js'; // Simple argument parsing const args = process.argv.slice(2); let skipConfirmation = false; // Parse arguments for (let i = 0; i < args.length; i++) { if (args[i] === '--yes' || args[i] === '-y') { skipConfirmation = true; } } if (args.includes('--help') || args.includes('-h')) { console.log(`Clear fuzzy search logs Usage: node clear-fuzzy-logs.js [options] Options: -y, --yes Skip confirmation prompt -h, --help Show this help message`); process.exit(0); } async function clearLogs() { try { const logPath = await fuzzySearchLogger.getLogPath(); if (!skipConfirmation) { console.log(`About to clear fuzzy search logs at: ${logPath}`); console.log('This action cannot be undone. Continue? (y/N)'); process.stdin.setRawMode(true); process.stdin.resume(); const answer = await new Promise((resolve) => { process.stdin.on('data', (key) => { process.stdin.setRawMode(false); resolve(key.toString().toLowerCase()); }); }); if (answer !== 'y') { console.log('Operation cancelled.'); process.exit(0); } } await fuzzySearchLogger.clearLog(); console.log(`✅ Fuzzy search logs cleared successfully.`); console.log(`Log file location: ${logPath}`); } catch (error) { console.error('Failed to clear fuzzy search logs:', error.message); process.exit(1); } } clearLogs();
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
scripts/download-all-ripgrep.cjs
JavaScript
#!/usr/bin/env node /** * Download all ripgrep binaries for cross-platform MCPB bundles * * This script downloads ripgrep binaries for all supported platforms * and places them in node_modules/@vscode/ripgrep/bin/ with platform-specific names. */ const https = require('https'); const fs = require('fs'); const path = require('path'); const { promisify } = require('util'); const yauzl = require('yauzl'); const { pipeline } = require('stream'); const streamPipeline = promisify(pipeline); // Ripgrep versions from @vscode/ripgrep const VERSION = 'v13.0.0-10'; const MULTI_ARCH_VERSION = 'v13.0.0-4'; // All supported platforms const PLATFORMS = [ { name: 'x86_64-apple-darwin', ext: 'tar.gz', version: VERSION }, { name: 'aarch64-apple-darwin', ext: 'tar.gz', version: VERSION }, { name: 'x86_64-pc-windows-msvc', ext: 'zip', version: VERSION }, { name: 'aarch64-pc-windows-msvc', ext: 'zip', version: VERSION }, { name: 'i686-pc-windows-msvc', ext: 'zip', version: VERSION }, { name: 'x86_64-unknown-linux-musl', ext: 'tar.gz', version: VERSION }, { name: 'aarch64-unknown-linux-musl', ext: 'tar.gz', version: VERSION }, { name: 'i686-unknown-linux-musl', ext: 'tar.gz', version: VERSION }, { name: 'arm-unknown-linux-gnueabihf', ext: 'tar.gz', version: MULTI_ARCH_VERSION }, { name: 'powerpc64le-unknown-linux-gnu', ext: 'tar.gz', version: MULTI_ARCH_VERSION }, { name: 's390x-unknown-linux-gnu', ext: 'tar.gz', version: VERSION } ]; const TEMP_DIR = path.join(__dirname, '../.ripgrep-downloads'); const OUTPUT_DIR = path.join(__dirname, '../node_modules/@vscode/ripgrep/bin'); function ensureDir(dir) { if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } } async function downloadFile(url, dest) { return new Promise((resolve, reject) => { console.log(` 📥 ${path.basename(dest)}...`); https.get(url, { headers: { 'User-Agent': 'vscode-ripgrep', 'Accept': 'application/octet-stream' } }, (response) => { if (response.statusCode === 302 || response.statusCode === 301) { // Follow redirect downloadFile(response.headers.location, dest).then(resolve).catch(reject); return; } if (response.statusCode !== 200) { reject(new Error(`Failed to download: ${response.statusCode}`)); return; } const file = fs.createWriteStream(dest); response.pipe(file); file.on('finish', () => { file.close(); resolve(); }); file.on('error', (err) => { fs.unlink(dest, () => reject(err)); }); }).on('error', reject); }); } async function extractZip(zipPath, outputDir, targetBinary) { return new Promise((resolve, reject) => { yauzl.open(zipPath, { lazyEntries: true }, (err, zipfile) => { if (err) return reject(err); zipfile.readEntry(); zipfile.on('entry', (entry) => { if (entry.fileName.endsWith('rg.exe')) { zipfile.openReadStream(entry, (err, readStream) => { if (err) return reject(err); const outputPath = path.join(outputDir, targetBinary); const writeStream = fs.createWriteStream(outputPath); readStream.pipe(writeStream); writeStream.on('close', () => { zipfile.close(); resolve(); }); writeStream.on('error', reject); }); } else { zipfile.readEntry(); } }); zipfile.on('end', resolve); zipfile.on('error', reject); }); }); } async function extractTarGz(tarPath, outputDir, targetBinary) { return new Promise((resolve, reject) => { const { execSync } = require('child_process'); const tempExtractDir = path.join(TEMP_DIR, 'extract-' + Date.now()); try { ensureDir(tempExtractDir); // Extract tar.gz execSync(`tar -xzf "${tarPath}" -C "${tempExtractDir}"`, { stdio: 'pipe' }); // Find the rg binary const files = fs.readdirSync(tempExtractDir, { recursive: true }); const rgFile = files.find(f => f.endsWith('/rg') || f === 'rg'); if (rgFile) { const sourcePath = path.join(tempExtractDir, rgFile); const destPath = path.join(outputDir, targetBinary); fs.copyFileSync(sourcePath, destPath); fs.chmodSync(destPath, 0o755); } // Cleanup fs.rmSync(tempExtractDir, { recursive: true, force: true }); resolve(); } catch (error) { reject(error); } }); } async function downloadAndExtractPlatform(platform) { const { name, ext, version } = platform; const fileName = `ripgrep-${version}-${name}.${ext}`; const url = `https://github.com/microsoft/ripgrep-prebuilt/releases/download/${version}/${fileName}`; const tempFile = path.join(TEMP_DIR, fileName); // Determine output binary name const isWindows = name.includes('windows'); const binaryName = isWindows ? `rg-${name}.exe` : `rg-${name}`; const outputPath = path.join(OUTPUT_DIR, binaryName); // Skip if binary already exists if (fs.existsSync(outputPath)) { console.log(` ✓ ${name} (cached)`); return; } try { // Download if not already cached if (!fs.existsSync(tempFile)) { await downloadFile(url, tempFile); } // Extract ensureDir(OUTPUT_DIR); if (ext === 'zip') { await extractZip(tempFile, OUTPUT_DIR, binaryName); } else { await extractTarGz(tempFile, OUTPUT_DIR, binaryName); } console.log(` ✓ ${name}`); } catch (error) { console.error(` ✗ Failed: ${name} - ${error.message}`); throw error; } } async function main() { console.log('🌍 Downloading ripgrep binaries for all platforms...\n'); ensureDir(TEMP_DIR); ensureDir(OUTPUT_DIR); // Download and extract all platforms for (const platform of PLATFORMS) { await downloadAndExtractPlatform(platform); } console.log('\n✅ All ripgrep binaries downloaded successfully!'); console.log(`📁 Binaries location: ${OUTPUT_DIR}`); console.log('\nFiles created:'); const files = fs.readdirSync(OUTPUT_DIR).filter(f => f.startsWith('rg-')); files.forEach(f => console.log(` - ${f}`)); } // Run if called directly if (require.main === module) { main().catch((error) => { console.error('❌ Error:', error); process.exit(1); }); } module.exports = { downloadAndExtractPlatform, PLATFORMS };
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
scripts/export-fuzzy-logs.js
JavaScript
#!/usr/bin/env node import { fuzzySearchLogger } from '../dist/utils/fuzzySearchLogger.js'; import fs from 'fs/promises'; // Simple argument parsing const args = process.argv.slice(2); let format = 'csv'; let outputFile = null; let limit = 1000; // Parse arguments for (let i = 0; i < args.length; i++) { if (args[i] === '--format' || args[i] === '-f') { format = args[i + 1]?.toLowerCase() || 'csv'; } if (args[i] === '--output' || args[i] === '-o') { outputFile = args[i + 1]; } if (args[i] === '--limit' || args[i] === '-l') { limit = parseInt(args[i + 1], 10) || 1000; } if (args[i].startsWith('--format=')) { format = args[i].split('=')[1]?.toLowerCase() || 'csv'; } if (args[i].startsWith('--output=')) { outputFile = args[i].split('=')[1]; } if (args[i].startsWith('--limit=')) { limit = parseInt(args[i].split('=')[1], 10) || 1000; } } if (args.includes('--help') || args.includes('-h')) { console.log(`Export fuzzy search logs to CSV or JSON format Usage: node export-fuzzy-logs.js [options] Options: -f, --format <format> Export format (csv|json) (default: csv) -o, --output <file> Output file path (auto-generated if not specified) -l, --limit <number> Maximum number of logs to export (default: 1000) -h, --help Show this help message`); process.exit(0); } async function exportLogs() { try { const logs = await fuzzySearchLogger.getRecentLogs(limit); const logPath = await fuzzySearchLogger.getLogPath(); if (logs.length === 0) { console.log(`No fuzzy search logs found. Log file location: ${logPath}`); return; } // Parse logs into structured data const parsedLogs = logs.map(log => { const parts = log.split('\t'); if (parts.length >= 16) { const [ timestamp, searchText, foundText, similarity, executionTime, exactMatchCount, expectedReplacements, fuzzyThreshold, belowThreshold, diff, searchLength, foundLength, fileExtension, characterCodes, uniqueCharacterCount, diffLength ] = parts; return { timestamp, searchText: searchText.replace(/\\n/g, '\n').replace(/\\t/g, '\t'), foundText: foundText.replace(/\\n/g, '\n').replace(/\\t/g, '\t'), similarity: parseFloat(similarity), executionTime: parseFloat(executionTime), exactMatchCount: parseInt(exactMatchCount), expectedReplacements: parseInt(expectedReplacements), fuzzyThreshold: parseFloat(fuzzyThreshold), belowThreshold: belowThreshold === 'true', diff: diff.replace(/\\n/g, '\n').replace(/\\t/g, '\t'), searchLength: parseInt(searchLength), foundLength: parseInt(foundLength), fileExtension, characterCodes, uniqueCharacterCount: parseInt(uniqueCharacterCount), diffLength: parseInt(diffLength) }; } return null; }).filter(Boolean); // Generate output filename if not provided if (!outputFile) { const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); outputFile = `fuzzy-search-logs-${timestamp}.${format}`; } // Export based on format let content; if (format === 'json') { content = JSON.stringify(parsedLogs, null, 2); } else if (format === 'csv') { // Create CSV headers const headers = Object.keys(parsedLogs[0]); const csvHeaders = headers.join(','); // Create CSV rows const csvRows = parsedLogs.map(log => { return headers.map(header => { let value = log[header]; if (typeof value === 'string') { // Escape quotes and wrap in quotes if contains comma, newline, or quote value = value.replace(/"/g, '""'); if (value.includes(',') || value.includes('\n') || value.includes('"')) { value = `"${value}"`; } } return value; }).join(','); }); content = [csvHeaders, ...csvRows].join('\n'); } else { throw new Error(`Unsupported format: ${format}. Use 'csv' or 'json'.`); } // Write to file await fs.writeFile(outputFile, content); console.log(`✅ Exported ${parsedLogs.length} fuzzy search logs to: ${outputFile}`); console.log(`Format: ${format.toUpperCase()}`); console.log(`Source log file: ${logPath}`); } catch (error) { console.error('Failed to export fuzzy search logs:', error.message); process.exit(1); } } exportLogs();
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
scripts/publish-release.cjs
JavaScript
#!/usr/bin/env node /** * Desktop Commander - Complete Release Publishing Script with State Tracking * * This script handles the entire release process: * 1. Version bump * 2. Build project and MCPB bundle * 3. Commit and tag * 4. Publish to NPM * 5. Publish to MCP Registry * 6. Verify publications * * Features automatic resume from failed steps and state tracking. */ const { execSync } = require('child_process'); const fs = require('fs'); const path = require('path'); // State file path const STATE_FILE = path.join(process.cwd(), '.release-state.json'); // Colors for output const colors = { reset: '\x1b[0m', red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m', blue: '\x1b[34m', cyan: '\x1b[36m', }; // Helper functions for colored output function printStep(message) { console.log(`${colors.blue}==>${colors.reset} ${message}`); } function printSuccess(message) { console.log(`${colors.green}✓${colors.reset} ${message}`); } function printError(message) { console.error(`${colors.red}✗${colors.reset} ${message}`); } function printWarning(message) { console.log(`${colors.yellow}⚠${colors.reset} ${message}`); } function printInfo(message) { console.log(`${colors.cyan}ℹ${colors.reset} ${message}`); } // State management functions function loadState() { if (fs.existsSync(STATE_FILE)) { try { return JSON.parse(fs.readFileSync(STATE_FILE, 'utf8')); } catch (error) { printWarning('Could not parse state file, starting fresh'); return null; } } return null; } function saveState(state) { fs.writeFileSync(STATE_FILE, JSON.stringify(state, null, 2)); } function clearState() { if (fs.existsSync(STATE_FILE)) { fs.unlinkSync(STATE_FILE); printSuccess('Release state cleared'); } else { printInfo('No release state to clear'); } } function markStepComplete(state, step) { state.completedSteps.push(step); state.lastStep = step; saveState(state); } function isStepComplete(state, step) { return state && state.completedSteps.includes(step); } // Execute command with error handling function exec(command, options = {}) { try { return execSync(command, { encoding: 'utf8', stdio: options.silent ? 'pipe' : 'inherit', ...options }); } catch (error) { if (options.ignoreError) { return options.silent ? '' : null; } throw error; } } // Execute command silently and return output function execSilent(command, options = {}) { return exec(command, { silent: true, ...options }); } /** * Calculate alpha version from current version * - "0.2.28" → "0.2.29-alpha.0" * - "0.2.29-alpha.0" → "0.2.29-alpha.1" * - "0.2.29-alpha.5" → "0.2.29-alpha.6" */ function getAlphaVersion(currentVersion) { const alphaMatch = currentVersion.match(/^(\d+\.\d+\.\d+)-alpha\.(\d+)$/); if (alphaMatch) { // Already an alpha, increment the alpha number const baseVersion = alphaMatch[1]; const alphaNum = parseInt(alphaMatch[2], 10) + 1; return `${baseVersion}-alpha.${alphaNum}`; } else { // Regular version, bump patch and add -alpha.0 const [major, minor, patch] = currentVersion.split('.').map(Number); return `${major}.${minor}.${patch + 1}-alpha.0`; } } /** * Update version in package.json, server.json, and version.ts */ function updateVersionFiles(newVersion) { // Update package.json const pkgPath = path.join(process.cwd(), 'package.json'); const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')); pkg.version = newVersion; fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\n'); // Update server.json const serverJsonPath = path.join(process.cwd(), 'server.json'); const serverJson = JSON.parse(fs.readFileSync(serverJsonPath, 'utf8')); serverJson.version = newVersion; if (serverJson.packages && serverJson.packages.length > 0) { serverJson.packages.forEach(p => { if (p.registryType === 'npm' && p.identifier === '@wonderwhy-er/desktop-commander') { p.version = newVersion; } }); } fs.writeFileSync(serverJsonPath, JSON.stringify(serverJson, null, 2) + '\n'); // Update version.ts const versionTsPath = path.join(process.cwd(), 'src', 'version.ts'); fs.writeFileSync(versionTsPath, `export const VERSION = '${newVersion}';\n`); } // Parse command line arguments function parseArgs() { const args = process.argv.slice(2); const options = { bumpType: 'patch', skipTests: false, dryRun: false, help: false, clearState: false, skipBump: false, skipBuild: false, skipMcpb: false, skipGit: false, skipNpm: false, skipMcp: false, alpha: false, }; for (const arg of args) { switch (arg) { case '--minor': options.bumpType = 'minor'; break; case '--major': options.bumpType = 'major'; break; case '--skip-tests': options.skipTests = true; break; case '--skip-bump': options.skipBump = true; break; case '--skip-build': options.skipBuild = true; break; case '--skip-mcpb': options.skipMcpb = true; break; case '--skip-git': options.skipGit = true; break; case '--skip-npm': options.skipNpm = true; break; case '--skip-mcp': options.skipMcp = true; break; case '--npm-only': // Skip everything except NPM publish options.skipMcpb = true; options.skipGit = true; options.skipMcp = true; break; case '--alpha': options.alpha = true; break; case '--mcp-only': // Skip everything except MCP Registry publish options.skipBump = true; options.skipBuild = true; options.skipMcpb = true; options.skipGit = true; options.skipNpm = true; break; case '--clear-state': options.clearState = true; break; case '--dry-run': options.dryRun = true; break; case '--help': case '-h': options.help = true; break; default: printError(`Unknown option: ${arg}`); console.log("Run 'node scripts/publish-release.cjs --help' for usage information."); process.exit(1); } } return options; } // Show help message function showHelp() { console.log('Usage: node scripts/publish-release.cjs [OPTIONS]'); console.log(''); console.log('Options:'); console.log(' --minor Bump minor version (default: patch)'); console.log(' --major Bump major version (default: patch)'); console.log(' --skip-tests Skip running tests'); console.log(' --skip-bump Skip version bumping'); console.log(' --skip-build Skip building (if tests also skipped)'); console.log(' --skip-mcpb Skip building MCPB bundle'); console.log(' --skip-git Skip git commit and tag'); console.log(' --skip-npm Skip NPM publishing'); console.log(' --skip-mcp Skip MCP Registry publishing'); console.log(' --npm-only Only publish to NPM (skip MCPB, git, MCP Registry)'); console.log(' --alpha Publish as alpha version (e.g., 0.2.29-alpha.0)'); console.log(' --mcp-only Only publish to MCP Registry (skip all other steps)'); console.log(' --clear-state Clear release state and start fresh'); console.log(' --dry-run Simulate the release without publishing'); console.log(' --help, -h Show this help message'); console.log(''); console.log('State Management:'); console.log(' The script automatically tracks completed steps and resumes from failures.'); console.log(' Use --clear-state to reset and start from the beginning.'); console.log(''); console.log('Examples:'); console.log(' node scripts/publish-release.cjs # Patch release (0.2.16 -> 0.2.17)'); console.log(' node scripts/publish-release.cjs --minor # Minor release (0.2.16 -> 0.3.0)'); console.log(' node scripts/publish-release.cjs --major # Major release (0.2.16 -> 1.0.0)'); console.log(' node scripts/publish-release.cjs --dry-run # Test without publishing'); console.log(' node scripts/publish-release.cjs --mcp-only # Only publish to MCP Registry'); console.log(' node scripts/publish-release.cjs --npm-only --alpha # Alpha release to NPM only'); console.log(' node scripts/publish-release.cjs --clear-state # Reset state and start over'); } // ============================================================================= // PRE-FLIGHT CHECKS - Run before any publishing to catch issues early // ============================================================================= /** * Check if mcp-publisher is installed and check for updates */ function checkMcpPublisher() { printInfo('Checking mcp-publisher...'); const mcpPublisherPath = execSilent('which mcp-publisher', { ignoreError: true }).trim(); if (!mcpPublisherPath) { printError('mcp-publisher not found. Install it with: brew install mcp-publisher'); return false; } // Get current version (output goes to stderr with timestamp prefix) const versionOutput = execSilent('mcp-publisher --version 2>&1', { ignoreError: true }); const versionMatch = versionOutput.match(/mcp-publisher\s+(\d+\.\d+\.\d+)/); const currentVersion = versionMatch ? versionMatch[1] : 'unknown'; printSuccess(`mcp-publisher found: v${currentVersion}`); // Check for updates via brew try { const brewInfo = execSilent('brew info --json=v2 mcp-publisher 2>/dev/null', { ignoreError: true }); if (brewInfo) { const info = JSON.parse(brewInfo); const latestVersion = info.formulae?.[0]?.versions?.stable; if (latestVersion && latestVersion !== currentVersion && currentVersion !== 'unknown') { printWarning(`mcp-publisher update available: v${currentVersion} → v${latestVersion}`); printWarning('Run: brew upgrade mcp-publisher'); } } } catch (e) { // Ignore errors checking for updates } return true; } /** * Get the latest schema version from mcp-publisher */ function getLatestSchemaVersion() { // Create a temp file to get the schema version mcp-publisher uses const tempDir = execSilent('mktemp -d', { ignoreError: true }).trim(); if (!tempDir) return null; try { execSilent(`cd ${tempDir} && mcp-publisher init 2>/dev/null`, { ignoreError: true }); const tempServerJson = path.join(tempDir, 'server.json'); if (fs.existsSync(tempServerJson)) { const content = JSON.parse(fs.readFileSync(tempServerJson, 'utf8')); execSilent(`rm -rf ${tempDir}`, { ignoreError: true }); return content.$schema; } } catch (e) { // Ignore errors } execSilent(`rm -rf ${tempDir}`, { ignoreError: true }); return null; } /** * Update server.json schema version if needed */ function updateServerJsonSchema() { const serverJsonPath = path.join(process.cwd(), 'server.json'); if (!fs.existsSync(serverJsonPath)) { printError('server.json not found'); return false; } const serverJson = JSON.parse(fs.readFileSync(serverJsonPath, 'utf8')); const currentSchema = serverJson.$schema; printInfo('Checking server.json schema version...'); // Get latest schema from mcp-publisher const latestSchema = getLatestSchemaVersion(); if (latestSchema && currentSchema !== latestSchema) { printWarning(`Updating server.json schema:`); printWarning(` Old: ${currentSchema}`); printWarning(` New: ${latestSchema}`); serverJson.$schema = latestSchema; fs.writeFileSync(serverJsonPath, JSON.stringify(serverJson, null, 2) + '\n'); printSuccess('server.json schema updated'); return true; // Schema was updated } printSuccess(`server.json schema is current`); return false; // No update needed } /** * Validate server.json using mcp-publisher */ function validateServerJson() { printInfo('Validating server.json...'); try { const result = execSilent('mcp-publisher validate 2>&1', { ignoreError: true }); // Check for errors in output if (result.toLowerCase().includes('error') || result.toLowerCase().includes('failed') || result.toLowerCase().includes('invalid')) { printError('server.json validation failed:'); console.log(result); return false; } printSuccess('server.json validation passed'); return true; } catch (error) { printError('Failed to validate server.json'); return false; } } /** * Check MCP Registry authentication and token expiration */ function checkMcpAuth() { printInfo('Checking MCP Registry authentication...'); // First check if we can validate locally const validateResult = execSilent('mcp-publisher validate 2>&1', { ignoreError: true }); // If validation mentions auth issues, warn about it if (validateResult.toLowerCase().includes('unauthorized') || validateResult.toLowerCase().includes('not logged in') || validateResult.toLowerCase().includes('authentication')) { printWarning('MCP Registry authentication may be required.'); printWarning('If publish fails, run: mcp-publisher login github'); return false; } printSuccess('Local validation passed'); return true; } /** * Check if MCP Registry JWT token is valid and not expired * Makes a lightweight API call to verify the token works */ function checkMcpTokenExpiration() { printInfo('Checking MCP Registry token validity...'); try { // mcp-publisher stores token in ~/.mcp_publisher_token const homeDir = process.env.HOME || process.env.USERPROFILE; const tokenPath = path.join(homeDir, '.mcp_publisher_token'); if (!fs.existsSync(tokenPath)) { printError('MCP Registry token not found. Please run: mcp-publisher login github'); return false; } const authData = JSON.parse(fs.readFileSync(tokenPath, 'utf8')); const token = authData.token; if (!token) { printError('No token found in auth file. Run: mcp-publisher login github'); return false; } // Decode JWT to check expiration (JWT format: header.payload.signature) const parts = token.split('.'); if (parts.length !== 3) { printWarning('Invalid token format. Run: mcp-publisher login github'); return false; } // Decode the payload (second part) - handle base64url encoding const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/'); const payload = JSON.parse(Buffer.from(base64, 'base64').toString('utf8')); if (payload.exp) { const expirationDate = new Date(payload.exp * 1000); const now = new Date(); const hoursUntilExpiry = (expirationDate - now) / (1000 * 60 * 60); if (expirationDate <= now) { printError(`MCP Registry token expired on ${expirationDate.toLocaleString()}`); printError('Please refresh your token: mcp-publisher login github'); return false; } if (hoursUntilExpiry < 1) { printWarning(`MCP Registry token expires in ${Math.round(hoursUntilExpiry * 60)} minutes`); printWarning('Consider refreshing: mcp-publisher login github'); } else if (hoursUntilExpiry < 24) { printWarning(`MCP Registry token expires in ${Math.round(hoursUntilExpiry)} hours`); } printSuccess(`MCP Registry token valid until ${expirationDate.toLocaleString()}`); return true; } // No expiration in token - assume it's valid printSuccess('MCP Registry token found (no expiration set)'); return true; } catch (error) { printWarning(`Could not check token: ${error.message}`); printWarning('Publish may fail if token is expired. If so, run: mcp-publisher login github'); return true; // Don't block, just warn } } /** * Run all pre-flight checks * Returns true if all critical checks pass */ function runPreFlightChecks(options) { console.log(''); console.log('╔══════════════════════════════════════════════════════════╗'); console.log('║ 🔍 PRE-FLIGHT CHECKS ║'); console.log('╚══════════════════════════════════════════════════════════╝'); console.log(''); let allPassed = true; let schemaUpdated = false; // Check mcp-publisher installation and version (skip if not publishing to MCP) if (!options.skipMcp) { if (!checkMcpPublisher()) { allPassed = false; } // Update schema if needed if (allPassed) { schemaUpdated = updateServerJsonSchema(); } // Validate server.json if (allPassed && !validateServerJson()) { allPassed = false; } // Check MCP auth and token expiration if (allPassed) { checkMcpAuth(); if (!checkMcpTokenExpiration()) { allPassed = false; } } } else { printInfo('Skipping MCP Registry checks (--skip-mcp or --npm-only)'); } // Check NPM auth if (allPassed && !options.skipNpm) { printInfo('Checking NPM authentication...'); const npmUser = execSilent('npm whoami 2>/dev/null', { ignoreError: true }).trim(); if (!npmUser) { printError('Not logged into NPM. Please run: npm login'); allPassed = false; } else { printSuccess(`NPM authenticated as: ${npmUser}`); } } console.log(''); if (allPassed) { printSuccess('All pre-flight checks passed!'); if (schemaUpdated) { printWarning('Note: server.json schema was updated - this will be included in the release commit'); } } else { printError('Pre-flight checks failed. Please fix the issues above before releasing.'); } console.log(''); return allPassed; } // Main release function async function publishRelease() { const options = parseArgs(); if (options.help) { showHelp(); return; } // Handle clear state command if (options.clearState) { clearState(); return; } // Check if we're in the right directory const packageJsonPath = path.join(process.cwd(), 'package.json'); if (!fs.existsSync(packageJsonPath)) { printError('package.json not found. Please run this script from the project root.'); process.exit(1); } // Run pre-flight checks before anything else (unless resuming) const existingState = loadState(); if (!existingState) { if (!runPreFlightChecks(options)) { process.exit(1); } } // Load or create state let state = loadState(); const isResume = state !== null; if (!state) { state = { startTime: new Date().toISOString(), completedSteps: [], lastStep: null, version: null, bumpType: options.bumpType, }; } console.log(''); console.log('╔══════════════════════════════════════════════════════════╗'); console.log('║ Desktop Commander Release Publisher ║'); console.log('╚══════════════════════════════════════════════════════════╝'); console.log(''); // Show resume information if (isResume) { console.log(`${colors.cyan}╔══════════════════════════════════════════════════════════╗${colors.reset}`); console.log(`${colors.cyan}║ 📋 RESUMING FROM PREVIOUS RUN ║${colors.reset}`); console.log(`${colors.cyan}╚══════════════════════════════════════════════════════════╝${colors.reset}`); console.log(''); printInfo(`Started: ${state.startTime}`); printInfo(`Last completed step: ${state.lastStep || 'none'}`); printInfo(`Completed steps: ${state.completedSteps.join(', ') || 'none'}`); if (state.version) { printInfo(`Target version: ${state.version}`); } console.log(''); printWarning('Will skip already completed steps automatically'); printInfo('Use --clear-state to start fresh'); console.log(''); } // Get current version const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); const currentVersion = packageJson.version; printStep(`Current version: ${currentVersion}`); if (!isResume) { printStep(`Bump type: ${options.alpha ? 'alpha' : options.bumpType}`); } if (options.alpha) { printWarning('ALPHA MODE - Will publish with alpha tag'); } if (options.dryRun) { printWarning('DRY RUN MODE - No changes will be published'); console.log(''); } try { let newVersion = state.version || currentVersion; // Step 1: Bump version const shouldSkipBump = options.skipBump || isStepComplete(state, 'bump'); if (!shouldSkipBump) { printStep('Step 1/6: Bumping version...'); if (options.alpha) { // Alpha version: calculate and update directly newVersion = getAlphaVersion(currentVersion); updateVersionFiles(newVersion); } else { // Guard: fail fast if current version is alpha but --alpha flag not provided if (currentVersion.includes('-alpha')) { printError(`Current version "${currentVersion}" is an alpha version.`); printError('Use --alpha for alpha releases, or manually set a stable version in package.json first.'); process.exit(1); } // Regular version: use npm run bump const bumpCommand = options.bumpType === 'minor' ? 'npm run bump:minor' : options.bumpType === 'major' ? 'npm run bump:major' : 'npm run bump'; exec(bumpCommand); const newPackageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')); newVersion = newPackageJson.version; } state.version = newVersion; markStepComplete(state, 'bump'); printSuccess(`Version bumped: ${currentVersion} → ${newVersion}`); } else if (isStepComplete(state, 'bump')) { printInfo('Step 1/6: Version bump already completed ✓'); } else { printWarning('Step 1/6: Version bump skipped (manual override)'); } console.log(''); // Step 2: Run tests or build const shouldSkipBuild = options.skipBuild || isStepComplete(state, 'build'); if (!shouldSkipBuild) { if (!options.skipTests) { printStep('Step 2/6: Running tests (includes build)...'); exec('npm test'); printSuccess('All tests passed'); } else { printStep('Step 2/6: Building project...'); exec('npm run build'); printSuccess('Project built successfully'); } markStepComplete(state, 'build'); } else if (isStepComplete(state, 'build')) { printInfo('Step 2/6: Build already completed ✓'); } else { printWarning('Step 2/6: Build skipped (manual override)'); } console.log(''); // Step 3: Build MCPB bundle const shouldSkipMcpb = options.skipMcpb || isStepComplete(state, 'mcpb'); if (!shouldSkipMcpb) { printStep('Step 3/6: Building MCPB bundle...'); exec('npm run build:mcpb'); markStepComplete(state, 'mcpb'); printSuccess('MCPB bundle created'); } else if (isStepComplete(state, 'mcpb')) { printInfo('Step 3/6: MCPB bundle already created ✓'); } else { printWarning('Step 3/6: MCPB bundle build skipped (manual override)'); } console.log(''); // Step 4: Commit and tag const shouldSkipGit = options.skipGit || isStepComplete(state, 'git'); if (!shouldSkipGit) { printStep('Step 4/6: Creating git commit and tag...'); // Check if there are changes to commit const gitStatus = execSilent('git status --porcelain', { ignoreError: true }); const hasChanges = gitStatus.includes('package.json') || gitStatus.includes('server.json') || gitStatus.includes('src/version.ts'); if (!hasChanges) { printWarning('No changes to commit (version files already committed)'); } else { exec('git add package.json server.json src/version.ts'); const commitMsg = `Release v${newVersion} Automated release commit with version bump from ${currentVersion} to ${newVersion}`; if (options.dryRun) { printWarning(`Would commit: ${commitMsg.split('\n')[0]}`); } else { exec(`git commit -m "${commitMsg}"`); printSuccess('Changes committed'); } } // Create and push tag const tagName = `v${newVersion}`; if (options.dryRun) { printWarning(`Would create tag: ${tagName}`); printWarning(`Would push to origin: main and ${tagName}`); } else { // Check if tag already exists locally const existingTag = execSilent(`git tag -l "${tagName}"`, { ignoreError: true }).trim(); if (existingTag === tagName) { printWarning(`Tag ${tagName} already exists locally`); } else { exec(`git tag ${tagName}`); printSuccess(`Tag ${tagName} created`); } // Push main (ignore error if already up to date) exec('git push origin main', { ignoreError: true }); // Push tag (check if already on remote first) const remoteTag = execSilent(`git ls-remote --tags origin refs/tags/${tagName}`, { ignoreError: true }).trim(); if (remoteTag) { printWarning(`Tag ${tagName} already exists on remote`); } else { exec(`git push origin ${tagName}`); printSuccess(`Tag ${tagName} pushed to remote`); } } markStepComplete(state, 'git'); } else if (isStepComplete(state, 'git')) { printInfo('Step 4/6: Git commit and tag already completed ✓'); } else { printWarning('Step 4/6: Git commit and tag skipped (manual override)'); } console.log(''); // Step 5: Publish to NPM const shouldSkipNpm = options.skipNpm || isStepComplete(state, 'npm'); if (!shouldSkipNpm) { printStep('Step 5/6: Publishing to NPM...'); // Check NPM authentication const npmUser = execSilent('npm whoami', { ignoreError: true }).trim(); if (!npmUser) { printError('Not logged into NPM. Please run "npm login" first.'); printError('After logging in, run the script again to resume from this step.'); process.exit(1); } printSuccess(`NPM user: ${npmUser}`); if (options.dryRun) { const publishCmd = options.alpha ? 'npm publish --tag alpha' : 'npm publish'; printWarning(`Would publish to NPM: ${publishCmd}`); printWarning('Skipping NPM publish (dry run)'); } else { const publishCmd = options.alpha ? 'npm publish --tag alpha' : 'npm publish'; exec(publishCmd); markStepComplete(state, 'npm'); printSuccess(`Published to NPM${options.alpha ? ' (alpha tag)' : ''}`); // Verify NPM publication await new Promise(resolve => setTimeout(resolve, 3000)); const viewCmd = options.alpha ? 'npm view @wonderwhy-er/desktop-commander dist-tags.alpha' : 'npm view @wonderwhy-er/desktop-commander version'; const npmVersion = execSilent(viewCmd, { ignoreError: true }).trim(); if (npmVersion === newVersion) { printSuccess(`NPM publication verified: v${npmVersion}${options.alpha ? ' (alpha)' : ''}`); } else { printWarning(`NPM version mismatch: expected ${newVersion}, got ${npmVersion} (may take a moment to propagate)`); } } } else if (isStepComplete(state, 'npm')) { printInfo('Step 5/6: NPM publish already completed ✓'); } else { printWarning('Step 5/6: NPM publish skipped (manual override)'); } console.log(''); // Step 6: Publish to MCP Registry const shouldSkipMcp = options.skipMcp || isStepComplete(state, 'mcp'); if (!shouldSkipMcp) { printStep('Step 6/6: Publishing to MCP Registry...'); // Check if mcp-publisher is installed const hasMcpPublisher = execSilent('which mcp-publisher', { ignoreError: true }); if (!hasMcpPublisher) { printError('mcp-publisher not found. Install it with: brew install mcp-publisher'); printError('Or check your PATH if already installed.'); printError('After installing, run the script again to resume from this step.'); process.exit(1); } if (options.dryRun) { printWarning('Would publish to MCP Registry: mcp-publisher publish'); printWarning('Skipping MCP Registry publish (dry run)'); } else { let publishSuccess = false; let retryCount = 0; const maxRetries = 2; while (!publishSuccess && retryCount < maxRetries) { try { exec('mcp-publisher publish'); publishSuccess = true; markStepComplete(state, 'mcp'); printSuccess('Published to MCP Registry'); } catch (error) { const errorMsg = error.message || error.toString(); retryCount++; // Handle expired token - attempt auto-refresh if (errorMsg.includes('401') || errorMsg.includes('expired') || errorMsg.includes('Unauthorized')) { if (retryCount < maxRetries) { printWarning('Authentication token expired. Attempting to refresh...'); try { exec('mcp-publisher login github', { stdio: 'inherit' }); printSuccess('Token refreshed. Retrying publish...'); continue; } catch (loginError) { printError('Could not refresh token automatically.'); printError('Please run manually: mcp-publisher login github'); throw error; } } } // Handle deprecated schema - attempt auto-update if (errorMsg.includes('deprecated schema')) { if (retryCount < maxRetries) { printWarning('Schema version deprecated. Attempting to update...'); if (updateServerJsonSchema()) { printSuccess('Schema updated. Retrying publish...'); continue; } } } // Other errors printError('MCP Registry publish failed!'); if (errorMsg.includes('422')) { printError('Validation error in server.json. Check the error message above for details.'); } throw error; } } // Verify MCP Registry publication await new Promise(resolve => setTimeout(resolve, 3000)); try { const mcpResponse = execSilent('curl -s "https://registry.modelcontextprotocol.io/v0/servers?search=io.github.wonderwhy-er/desktop-commander"'); const mcpData = JSON.parse(mcpResponse); const mcpVersion = mcpData.servers?.[0]?.version || 'unknown'; if (mcpVersion === newVersion) { printSuccess(`MCP Registry publication verified: v${mcpVersion}`); } else { printWarning(`MCP Registry version: ${mcpVersion} (expected ${newVersion}, may take a moment to propagate)`); } } catch (verifyError) { printWarning('Could not verify MCP Registry publication'); } } } else if (isStepComplete(state, 'mcp')) { printInfo('Step 6/6: MCP Registry publish already completed ✓'); } else { printWarning('Step 6/6: MCP Registry publish skipped (manual override)'); } console.log(''); // All steps complete - clear state clearState(); // Success summary const tagName = `v${newVersion}`; console.log('╔══════════════════════════════════════════════════════════╗'); console.log('║ 🎉 Release Complete! 🎉 ║'); console.log('╚══════════════════════════════════════════════════════════╝'); console.log(''); printSuccess(`Version: ${newVersion}`); printSuccess('NPM: https://www.npmjs.com/package/@wonderwhy-er/desktop-commander'); printSuccess('MCP Registry: https://registry.modelcontextprotocol.io/'); printSuccess(`GitHub Tag: https://github.com/wonderwhy-er/DesktopCommanderMCP/releases/tag/${tagName}`); console.log(''); console.log('Next steps:'); console.log(` 1. Create GitHub release at: https://github.com/wonderwhy-er/DesktopCommanderMCP/releases/new?tag=${tagName}`); console.log(' 2. Add release notes with features and fixes'); console.log(' 3. Announce on Discord'); console.log(''); if (options.dryRun) { console.log(''); printWarning('This was a DRY RUN - no changes were published'); printWarning('Run without --dry-run to perform the actual release'); console.log(''); } } catch (error) { console.log(''); printError('Release failed at step: ' + (state.lastStep || 'startup')); printError(error.message); console.log(''); printInfo('State has been saved. Simply run the script again to resume from where it failed.'); printInfo('Use --clear-state to start over from the beginning.'); console.log(''); process.exit(1); } } // Run the script publishRelease().catch(error => { printError('Unexpected error:'); console.error(error); process.exit(1); });
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
scripts/ripgrep-wrapper.js
JavaScript
// Runtime platform detection wrapper for @vscode/ripgrep // This replaces the original index.js to support cross-platform MCPB bundles const os = require('os'); const path = require('path'); const fs = require('fs'); function getTarget() { const arch = process.env.npm_config_arch || os.arch(); switch (os.platform()) { case 'darwin': return arch === 'arm64' ? 'aarch64-apple-darwin' : 'x86_64-apple-darwin'; case 'win32': return arch === 'x64' ? 'x86_64-pc-windows-msvc' : arch === 'arm64' ? 'aarch64-pc-windows-msvc' : 'i686-pc-windows-msvc'; case 'linux': return arch === 'x64' ? 'x86_64-unknown-linux-musl' : arch === 'arm' ? 'arm-unknown-linux-gnueabihf' : arch === 'armv7l' ? 'arm-unknown-linux-gnueabihf' : arch === 'arm64' ? 'aarch64-unknown-linux-musl' : arch === 'ppc64' ? 'powerpc64le-unknown-linux-gnu' : arch === 's390x' ? 's390x-unknown-linux-gnu' : 'i686-unknown-linux-musl'; default: throw new Error('Unknown platform: ' + os.platform()); } } const target = getTarget(); const isWindows = os.platform() === 'win32'; const binaryName = isWindows ? `rg-${target}.exe` : `rg-${target}`; // __dirname is lib/, so go up one level to reach bin/ const rgPath = path.join(__dirname, '..', 'bin', binaryName); // Verify binary exists and ensure executable permissions if (!fs.existsSync(rgPath)) { // Try fallback to original rg location const fallbackPath = path.join(__dirname, '..', 'bin', isWindows ? 'rg.exe' : 'rg'); if (fs.existsSync(fallbackPath)) { // Ensure executable permissions on Unix systems if (!isWindows) { try { fs.chmodSync(fallbackPath, 0o755); } catch (err) { // Ignore permission errors - might not have write access } } module.exports.rgPath = fallbackPath; } else { throw new Error(`ripgrep binary not found for platform ${target}: ${rgPath}`); } } else { // Ensure executable permissions on Unix systems // This fixes issues when extracting from zip archives that don't preserve permissions if (!isWindows) { try { fs.chmodSync(rgPath, 0o755); } catch (err) { // Ignore permission errors - might not have write access } } module.exports.rgPath = rgPath; }
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga
scripts/sync-version.js
JavaScript
import { readFileSync, writeFileSync } from 'fs'; import path from 'path'; function bumpVersion(version, type = 'patch') { const [major, minor, patch] = version.split('.').map(Number); switch(type) { case 'major': return `${major + 1}.0.0`; case 'minor': return `${major}.${minor + 1}.0`; case 'patch': default: return `${major}.${minor}.${patch + 1}`; } } // Read command line arguments const shouldBump = process.argv.includes('--bump'); const bumpType = process.argv.includes('--major') ? 'major' : process.argv.includes('--minor') ? 'minor' : 'patch'; // Read version from package.json const pkg = JSON.parse(readFileSync('package.json', 'utf8')); let version = pkg.version; // Bump version if requested if (shouldBump) { version = bumpVersion(version, bumpType); // Update package.json pkg.version = version; writeFileSync('package.json', JSON.stringify(pkg, null, 2) + '\n'); } // Update server.json const serverJson = JSON.parse(readFileSync('server.json', 'utf8')); serverJson.version = version; // Also update the package version in the packages array if (serverJson.packages && serverJson.packages.length > 0) { serverJson.packages.forEach(pkg => { if (pkg.registryType === 'npm' && pkg.identifier === '@wonderwhy-er/desktop-commander') { pkg.version = version; } }); } writeFileSync('server.json', JSON.stringify(serverJson, null, 2) + '\n'); // Update version.ts const versionFileContent = `export const VERSION = '${version}';\n`; writeFileSync('src/version.ts', versionFileContent); console.log(`Version ${version} synchronized${shouldBump ? ' and bumped' : ''} across package.json, server.json, and version.ts`);
wonderwhy-er/DesktopCommanderMCP
5,467
This is MCP server for Claude that gives it terminal control, file system search and diff file editing capabilities
TypeScript
wonderwhy-er
Eduard Ruzga