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
include/enet-plus/server_host.h
C/C++ Header
// Copyright (c) 2013 Andrey Konovalov #ifndef ENET_PLUS_SERVER_HOST_HPP_ #define ENET_PLUS_SERVER_HOST_HPP_ #include "enet-plus/base/macros.h" #include "enet-plus/base/pstdint.h" #include "enet-plus/host.h" #include "enet-plus/dll.h" struct _ENetHost; namespace enet { class Enet; class Event; // A server host for communicating with client hosts. // You can create a 'ServerHost' using 'Enet::CreateServerHost'. class ServerHost : public Host { friend class Enet; public: ENET_PLUS_DECL ~ServerHost(); // Initializes 'ServerHost'. 'ServerHost' starts on port 'port'. // You may specify 'peer_count' - the maximum allowable number of // connected peers, 'channel_count' - the number of channels to be used. // You may specify incoming and outgoing bandwidth of the server in bytes // per second. Specifying '0' for these two options will cause ENet to rely // entirely upon its dynamic throttling algorithm to manage bandwidth. ENET_PLUS_DECL bool Initialize( uint16_t port, size_t peer_count = 32, size_t channel_count = 1, uint32_t incoming_bandwidth = 0, uint32_t outgoing_bandwidth = 0); // Cleans up. Automatically called in the destructor. ENET_PLUS_DECL void Finalize(); // Broadcast data from 'data' with length of 'length' to all Peer's on // selected channel, associated with 'channel_id'. // Returns 'true' on success, returns 'false' on error. ENET_PLUS_DECL bool Broadcast( const char* data, size_t length, bool reliable = true, uint8_t channel_id = 0); // Look in 'host.hpp' for the description. // ENET_PLUS_DECL virtual bool Service(Event* event, uint32_t timeout); // Look in 'host.hpp' for the description. // ENET_PLUS_DECL virtual void Flush(); private: // Creates an uninitialized 'ServerHost'. ServerHost(); enum { STATE_INITIALIZED, STATE_FINALIZED } _state; DISALLOW_COPY_AND_ASSIGN(ServerHost); }; } // namespace enet #endif // ENET_PLUS_SERVER_HOST_HPP_
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
include/windows/stdint.h
C/C++ Header
/* ISO C9x 7.18 Integer types <stdint.h> * Based on ISO/IEC SC22/WG14 9899 Committee draft (SC22 N2794) * * THIS SOFTWARE IS NOT COPYRIGHTED * * Contributor: Danny Smith <danny_r_smith_2001@yahoo.co.nz> * * This source code is offered for use in the public domain. You may * use, modify or distribute it freely. * * This code is distributed in the hope that it will be useful but * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY * DISCLAIMED. This includes but is not limited to warranties of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * Date: 2000-12-02 * * mwb: This was modified in the following ways: * * - make it compatible with Visual C++ 6 (which uses * non-standard keywords and suffixes for 64-bit types) * - some environments need stddef.h included (for wchar stuff?) * - handle the fact that Microsoft's limits.h header defines * SIZE_MAX * - make corrections for SIZE_MAX, INTPTR_MIN, INTPTR_MAX, UINTPTR_MAX, * PTRDIFF_MIN, PTRDIFF_MAX, SIG_ATOMIC_MIN, and SIG_ATOMIC_MAX * to be 64-bit aware. */ #ifndef _STDINT_H #define _STDINT_H #define __need_wint_t #define __need_wchar_t #include <wchar.h> #include <stddef.h> #if _MSC_VER && (_MSC_VER < 1300) /* using MSVC 6 or earlier - no "long long" type, but might have _int64 type */ #define __STDINT_LONGLONG __int64 #define __STDINT_LONGLONG_SUFFIX i64 #else #define __STDINT_LONGLONG long long #define __STDINT_LONGLONG_SUFFIX LL #endif #if !defined( PASTE) #define PASTE2( x, y) x##y #define PASTE( x, y) PASTE2( x, y) #endif /* PASTE */ /* 7.18.1.1 Exact-width integer types */ typedef signed char int8_t; typedef unsigned char uint8_t; typedef short int16_t; typedef unsigned short uint16_t; typedef int int32_t; typedef unsigned uint32_t; typedef __STDINT_LONGLONG int64_t; typedef unsigned __STDINT_LONGLONG uint64_t; /* 7.18.1.2 Minimum-width integer types */ typedef signed char int_least8_t; typedef unsigned char uint_least8_t; typedef short int_least16_t; typedef unsigned short uint_least16_t; typedef int int_least32_t; typedef unsigned uint_least32_t; typedef __STDINT_LONGLONG int_least64_t; typedef unsigned __STDINT_LONGLONG uint_least64_t; /* 7.18.1.3 Fastest minimum-width integer types * Not actually guaranteed to be fastest for all purposes * Here we use the exact-width types for 8 and 16-bit ints. */ typedef char int_fast8_t; typedef unsigned char uint_fast8_t; typedef short int_fast16_t; typedef unsigned short uint_fast16_t; typedef int int_fast32_t; typedef unsigned int uint_fast32_t; typedef __STDINT_LONGLONG int_fast64_t; typedef unsigned __STDINT_LONGLONG uint_fast64_t; /* 7.18.1.4 Integer types capable of holding object pointers */ #ifndef _INTPTR_T_DEFINED #define _INTPTR_T_DEFINED #ifdef _WIN64 typedef __STDINT_LONGLONG intptr_t #else typedef int intptr_t; #endif /* _WIN64 */ #endif /* _INTPTR_T_DEFINED */ #ifndef _UINTPTR_T_DEFINED #define _UINTPTR_T_DEFINED #ifdef _WIN64 typedef unsigned __STDINT_LONGLONG uintptr_t #else typedef unsigned int uintptr_t; #endif /* _WIN64 */ #endif /* _UINTPTR_T_DEFINED */ /* 7.18.1.5 Greatest-width integer types */ typedef __STDINT_LONGLONG intmax_t; typedef unsigned __STDINT_LONGLONG uintmax_t; /* 7.18.2 Limits of specified-width integer types */ #if !defined ( __cplusplus) || defined (__STDC_LIMIT_MACROS) /* 7.18.2.1 Limits of exact-width integer types */ #define INT8_MIN (-128) #define INT16_MIN (-32768) #define INT32_MIN (-2147483647 - 1) #define INT64_MIN (PASTE( -9223372036854775807, __STDINT_LONGLONG_SUFFIX) - 1) #define INT8_MAX 127 #define INT16_MAX 32767 #define INT32_MAX 2147483647 #define INT64_MAX (PASTE( 9223372036854775807, __STDINT_LONGLONG_SUFFIX)) #define UINT8_MAX 0xff /* 255U */ #define UINT16_MAX 0xffff /* 65535U */ #define UINT32_MAX 0xffffffff /* 4294967295U */ #define UINT64_MAX (PASTE( 0xffffffffffffffffU, __STDINT_LONGLONG_SUFFIX)) /* 18446744073709551615ULL */ /* 7.18.2.2 Limits of minimum-width integer types */ #define INT_LEAST8_MIN INT8_MIN #define INT_LEAST16_MIN INT16_MIN #define INT_LEAST32_MIN INT32_MIN #define INT_LEAST64_MIN INT64_MIN #define INT_LEAST8_MAX INT8_MAX #define INT_LEAST16_MAX INT16_MAX #define INT_LEAST32_MAX INT32_MAX #define INT_LEAST64_MAX INT64_MAX #define UINT_LEAST8_MAX UINT8_MAX #define UINT_LEAST16_MAX UINT16_MAX #define UINT_LEAST32_MAX UINT32_MAX #define UINT_LEAST64_MAX UINT64_MAX /* 7.18.2.3 Limits of fastest minimum-width integer types */ #define INT_FAST8_MIN INT8_MIN #define INT_FAST16_MIN INT16_MIN #define INT_FAST32_MIN INT32_MIN #define INT_FAST64_MIN INT64_MIN #define INT_FAST8_MAX INT8_MAX #define INT_FAST16_MAX INT16_MAX #define INT_FAST32_MAX INT32_MAX #define INT_FAST64_MAX INT64_MAX #define UINT_FAST8_MAX UINT8_MAX #define UINT_FAST16_MAX UINT16_MAX #define UINT_FAST32_MAX UINT32_MAX #define UINT_FAST64_MAX UINT64_MAX /* 7.18.2.4 Limits of integer types capable of holding object pointers */ #ifdef _WIN64 #define INTPTR_MIN INT64_MIN #define INTPTR_MAX INT64_MAX #define UINTPTR_MAX UINT64_MAX #else #define INTPTR_MIN INT32_MIN #define INTPTR_MAX INT32_MAX #define UINTPTR_MAX UINT32_MAX #endif /* _WIN64 */ /* 7.18.2.5 Limits of greatest-width integer types */ #define INTMAX_MIN INT64_MIN #define INTMAX_MAX INT64_MAX #define UINTMAX_MAX UINT64_MAX /* 7.18.3 Limits of other integer types */ #define PTRDIFF_MIN INTPTR_MIN #define PTRDIFF_MAX INTPTR_MAX #define SIG_ATOMIC_MIN INTPTR_MIN #define SIG_ATOMIC_MAX INTPTR_MAX /* we need to check for SIZE_MAX already defined because MS defines it in limits.h */ #ifndef SIZE_MAX #define SIZE_MAX UINTPTR_MAX #endif #ifndef WCHAR_MIN /* also in wchar.h */ #define WCHAR_MIN 0 #define WCHAR_MAX ((wchar_t)-1) /* UINT16_MAX */ #endif /* * wint_t is unsigned short for compatibility with MS runtime */ #define WINT_MIN 0 #define WINT_MAX ((wint_t)-1) /* UINT16_MAX */ #endif /* !defined ( __cplusplus) || defined __STDC_LIMIT_MACROS */ /* 7.18.4 Macros for integer constants */ #if !defined ( __cplusplus) || defined (__STDC_CONSTANT_MACROS) /* 7.18.4.1 Macros for minimum-width integer constants Accoding to Douglas Gwyn <gwyn@arl.mil>: "This spec was changed in ISO/IEC 9899:1999 TC1; in ISO/IEC 9899:1999 as initially published, the expansion was required to be an integer constant of precisely matching type, which is impossible to accomplish for the shorter types on most platforms, because C99 provides no standard way to designate an integer constant with width less than that of type int. TC1 changed this to require just an integer constant *expression* with *promoted* type." */ #define INT8_C(val) ((int8_t) + (val)) #define UINT8_C(val) ((uint8_t) + (val##U)) #define INT16_C(val) ((int16_t) + (val)) #define UINT16_C(val) ((uint16_t) + (val##U)) #define INT32_C(val) val##L #define UINT32_C(val) val##UL #define INT64_C(val) (PASTE( val, __STDINT_LONGLONG_SUFFIX)) #define UINT64_C(val)(PASTE( PASTE( val, U), __STDINT_LONGLONG_SUFFIX)) /* 7.18.4.2 Macros for greatest-width integer constants */ #define INTMAX_C(val) INT64_C(val) #define UINTMAX_C(val) UINT64_C(val) #endif /* !defined ( __cplusplus) || defined __STDC_CONSTANT_MACROS */ #endif
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
premake4.lua
Lua
newaction { trigger = 'clean', description = 'Cleans up the project.', shortname = "clean", execute = function() os.rmdir("bin") os.rmdir("build") end } saved_config = {} function save_config() saved_config = configuration().terms end function restore_config() configuration(saved_config) end function windows_libdir(base_path) save_config() for _, arch in pairs({"x32", "x64"}) do for _, conf in pairs({"debug", "release"}) do for _, plat in pairs({"vs2008"}) do local conf_path = plat .. "/" .. arch .. "/" .. conf configuration { "windows", arch, conf, plat } libdirs { path.join(base_path, conf_path) } end end end restore_config() end solution "enet-plus" configurations { "debug", "release" } platforms { "x32", "x64" } location "build" targetdir "bin" flags { "FatalWarnings", "NoRTTI" } configuration { "linux" } flags { "NoExceptions" } configuration { "windows" } includedirs { "include/windows" } defines { "WIN32", "_WIN32" } defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_DEPRECATE" } configuration { "debug" } defines { "DEBUG" } flags { "Symbols" } configuration { "release" } defines { "NDEBUG" } flags { "Optimize" } project "enet-plus" kind "SharedLib" language "C++" defines { "ENET_PLUS_DLL" } includedirs { "include" } files { "src/enet-plus/**.cpp", "include/enet-plus/**.h" } configuration "linux" links { "enet" } linkoptions { "-Wl,-soname,libenet-plus.so.0" } targetextension ".so.0.1" prelinkcommands { "cd ../bin;" .. "ln -s libenet-plus.so.0.1 libenet-plus.so.0;" .. "ln -s libenet-plus.so.0 libenet-plus.so;" .. "cd ../build" } configuration "windows" includedirs { "third-party/enet/include" } windows_libdir("third-party/enet/bin") links { "ws2_32", "winmm" } links { "enet" } project "sample-client" kind "ConsoleApp" language "C++" targetname "sample-client" includedirs { "include" } files { "src/sample-client/**.cpp" } links { "enet-plus" } project "sample-server" kind "ConsoleApp" language "C++" targetname "sample-server" includedirs { "include" } files { "src/sample-server/**.cpp" } links { "enet-plus" }
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
server.sh
Shell
#!/bin/sh cd bin export LD_LIBRARY_PATH=`pwd` cd .. ./bin/sample-server
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
src/enet-plus/client_host.cpp
C++
// Copyright (c) 2013 Andrey Konovalov #include "enet-plus/client_host.h" #include <string> #include <enet/enet.h> #include "enet-plus/base/pstdint.h" #include "enet-plus/peer.h" #include "enet-plus/host.h" namespace enet { ClientHost::~ClientHost() { if (_state == STATE_INITIALIZED) { Finalize(); } } bool ClientHost::Initialize( size_t channel_count, uint32_t incoming_bandwidth, uint32_t outgoing_bandwidth ) { bool rv = Host::Initialize("", 0, 1, channel_count, incoming_bandwidth, outgoing_bandwidth); if (rv == false) { return false; } _state = STATE_INITIALIZED; return true; } void ClientHost::Finalize() { CHECK(_state == STATE_INITIALIZED); _state = STATE_FINALIZED; }; Peer* ClientHost::Connect( std::string server_ip, uint16_t port, size_t channel_count ) { CHECK(_state == STATE_INITIALIZED); ENetAddress address; if (enet_address_set_host(&address, server_ip.c_str()) != 0) { // THROW_ERROR("Unable to set enet host address!"); return NULL; } address.port = port; // XXX: type cast. ENetPeer* enet_peer = enet_host_connect(_host, &address, channel_count, 0); if (enet_peer == NULL) { // THROW_ERROR("Enet host is unable to connect!"); return NULL; } Peer* peer = Host::_GetPeer(enet_peer); CHECK(peer != NULL); return peer; } ClientHost::ClientHost() : Host(), _state(STATE_FINALIZED) { } } // namespace enet
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
src/enet-plus/enet.cpp
C++
// Copyright (c) 2013 Andrey Konovalov #include "enet-plus/enet.h" #include <enet/enet.h> // XXX: Windows sucks. #undef CreateEvent #include "enet-plus/base/macros.h" #include "enet-plus/base/pstdint.h" #include "enet-plus/host.h" #include "enet-plus/server_host.h" #include "enet-plus/client_host.h" #include "enet-plus/event.h" namespace enet { Enet::Enet() : _state(STATE_FINALIZED) { } Enet::~Enet() { if (_state == STATE_INITIALIZED) { Finalize(); } } bool Enet::Initialize() { CHECK(_state == STATE_FINALIZED); if (enet_initialize() != 0) { // THROW_ERROR("Unable to initialize enet!"); return false; } _state = STATE_INITIALIZED; return true; } void Enet::Finalize() { CHECK(_state == STATE_INITIALIZED); enet_deinitialize(); _state = STATE_FINALIZED; } ServerHost* Enet::CreateServerHost( uint16_t port, size_t peer_count, size_t channel_count, uint32_t incoming_bandwith, uint32_t outgoing_bandwith ) { CHECK(_state == STATE_INITIALIZED); ServerHost* server = new ServerHost(); CHECK(server != NULL); bool rv = server->Initialize(port, peer_count, channel_count, incoming_bandwith, outgoing_bandwith); return rv ? server : NULL; } ClientHost* Enet::CreateClientHost( size_t channel_count, uint32_t incoming_bandwith, uint32_t outgoing_bandwith ) { CHECK(_state == STATE_INITIALIZED); ClientHost* client = new ClientHost(); CHECK(client != NULL); bool rv = client->Initialize(channel_count, incoming_bandwith, outgoing_bandwith); return rv ? client : NULL; } Event* Enet::CreateEvent() { Event* event = new Event; CHECK(event != NULL); return event; } } // namespace enet
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
src/enet-plus/event.cpp
C++
// Copyright (c) 2013 Andrey Konovalov #include "enet-plus/event.h" #include <string> #include <vector> #include <enet/enet.h> #include "enet-plus/base/pstdint.h" #include "enet-plus/host.h" #include "enet-plus/peer.h" namespace enet { Event::~Event() { _DestroyPacket(); delete _event; } Event::EventType Event::GetType() const { if (_event->type == ENET_EVENT_TYPE_CONNECT) { return Event::TYPE_CONNECT; } if (_event->type == ENET_EVENT_TYPE_DISCONNECT) { return Event::TYPE_DISCONNECT; } if (_event->type == ENET_EVENT_TYPE_RECEIVE) { return Event::TYPE_RECEIVE; } return Event::TYPE_NONE; } uint8_t Event::GetChannelId() const { CHECK(_event->type != ENET_EVENT_TYPE_NONE); return _event->channelID; } void Event::GetData(std::vector<char>* output) const { CHECK(_event->type == ENET_EVENT_TYPE_RECEIVE); CHECK(_is_packet_destroyed == false); output->assign(_event->packet->data, _event->packet->data + _event->packet->dataLength); } Peer* Event::GetPeer() { CHECK(_event->type != ENET_EVENT_TYPE_NONE); CHECK(_host != NULL); Peer* peer = _host->_GetPeer(_event->peer); CHECK(peer != NULL); return peer; } Event::Event() : _is_packet_destroyed(true) { _event = new ENetEvent(); CHECK(_event != NULL); } void Event::_DestroyPacket() { if (!_is_packet_destroyed && _event->type == ENET_EVENT_TYPE_RECEIVE) { enet_packet_destroy(_event->packet); _is_packet_destroyed = true; } } } // namespace enet
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
src/enet-plus/host.cpp
C++
// Copyright (c) 2013 Andrey Konovalov #include "enet-plus/host.h" #include <map> #include <string> #include <enet/enet.h> #include "enet-plus/base/pstdint.h" #include "enet-plus/event.h" #include "enet-plus/peer.h" namespace enet { Host::~Host() { if (_state == STATE_INITIALIZED) { Finalize(); } }; bool Host::Initialize( const std::string& ip, uint16_t port, size_t peer_count, size_t channel_count, uint32_t incoming_bandwidth, uint32_t outgoing_bandwidth ) { ENetAddress* address_ptr = NULL; ENetAddress address; if (ip != "" || port != 0) { if (ip != "") { if (enet_address_set_host(&address, ip.c_str()) != 0) { // THROW_ERROR("Unable to set enet host address!"); return false; } } else { address.host = ENET_HOST_ANY; } address.port = port; // XXX: type cast. address_ptr = &address; } _host = enet_host_create(address_ptr, peer_count, channel_count, incoming_bandwidth, outgoing_bandwidth); if (_host == NULL) { // THROW_ERROR("Unable to create enet host!"); return false; } _state = STATE_INITIALIZED; return true; } void Host::Finalize() { CHECK(_state == STATE_INITIALIZED); enet_host_destroy(_host); std::map<_ENetPeer*, Peer*>::iterator itr; for (itr = _peers.begin(); itr != _peers.end(); ++itr) { delete itr->second; } _state = STATE_FINALIZED; }; bool Host::Service(Event* event, uint32_t timeout) { CHECK(_state == STATE_INITIALIZED); if (event != NULL) { event->_DestroyPacket(); } int rv = enet_host_service(_host, (event == NULL) ? NULL : event->_event, timeout); if (rv < 0) { // THROW_ERROR("Unable to service enet host!"); return false; } if (rv > 0) { event->_is_packet_destroyed = false; } if (event != NULL) { event->_host = this; } return true; } void Host::Flush() { CHECK(_state == STATE_INITIALIZED); enet_host_flush(_host); } Host::Host() : _state(STATE_FINALIZED), _host(NULL) { } Peer* Host::_GetPeer(_ENetPeer* enet_peer) { CHECK(enet_peer != NULL); if (_peers.count(enet_peer) == 0) { Peer* peer = new Peer(enet_peer); CHECK(peer != NULL); _peers[enet_peer] = peer; } return _peers[enet_peer]; } } // namespace enet
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
src/enet-plus/peer.cpp
C++
// Copyright (c) 2013 Andrey Konovalov #include "enet-plus/peer.h" #include <string> #include <enet/enet.h> #include "enet-plus/base/macros.h" #include "enet-plus/base/pstdint.h" namespace enet { bool Peer::Send( const char* data, size_t length, bool reliable, uint8_t channel_id ) { enet_uint32 flags = 0; if (reliable) { flags = flags | ENET_PACKET_FLAG_RELIABLE; } ENetPacket* packet = enet_packet_create(data, length, flags); if (packet == NULL) { // THROW_ERROR("Unable to create enet packet!"); return false; } if (enet_peer_send(_peer, channel_id, packet) != 0) { enet_packet_destroy(packet); // THROW_ERROR("Unable to send enet packet!"); return false; } return true; } std::string Peer::GetIp() const { const size_t BUFFER_SIZE = 32; char buffer[BUFFER_SIZE]; if (enet_address_get_host_ip(&_peer->address, buffer, BUFFER_SIZE) != 0) { // THROW_ERROR("Unable to get enet host ip!"); buffer[0] = 0; } return std::string(buffer); } uint16_t Peer::GetPort() const { return _peer->address.port; // XXX: type cast. } void Peer::Disconnect() { enet_peer_disconnect(_peer, 0); } void Peer::DisconnectNow() { enet_peer_disconnect_now(_peer, 0); } void Peer::DisconnectLater() { enet_peer_disconnect_later(_peer, 0); } void Peer::Reset() { enet_peer_reset(_peer); } void Peer::SetData(void* data) { _peer->data = data; } void* Peer::GetData() const { return _peer->data; } Peer::Peer(ENetPeer* peer) : _peer(peer) { CHECK(peer != NULL); } } // namespace enet
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
src/enet-plus/server_host.cpp
C++
// Copyright (c) 2013 Andrey Konovalov #include "enet-plus/server_host.h" #include <enet/enet.h> #include "enet-plus/base/pstdint.h" #include "enet-plus/event.h" #include "enet-plus/host.h" namespace enet { ServerHost::~ServerHost() { if (_state == STATE_INITIALIZED) { Finalize(); } }; bool ServerHost::Initialize( uint16_t port, size_t peer_count, size_t channel_count, uint32_t incoming_bandwidth, uint32_t outgoing_bandwidth ) { bool rv = Host::Initialize("", port, peer_count, channel_count, incoming_bandwidth, outgoing_bandwidth); if (rv == false) { return false; } _state = STATE_INITIALIZED; return true; } void ServerHost::Finalize() { CHECK(_state == STATE_INITIALIZED); _state = STATE_FINALIZED; }; bool ServerHost::Broadcast( const char* data, size_t length, bool reliable, uint8_t channel_id ) { CHECK(_state == STATE_INITIALIZED); CHECK(data != NULL); CHECK(length > 0); enet_uint32 flags = 0; if (reliable) { flags = flags | ENET_PACKET_FLAG_RELIABLE; } ENetPacket* packet = enet_packet_create(data, length, flags); if (packet == NULL) { // THROW_ERROR("Unable to create enet packet!"); return false; } enet_host_broadcast(_host, channel_id, packet); return true; } ServerHost::ServerHost() : Host(), _state(STATE_FINALIZED) { } } // namespace enet
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
src/sample-client/client.cpp
C++
// Copyright (c) 2013 Andrey Konovalov #include <vector> #include "enet-plus/enet.h" int main() { enet::Enet enet; bool rv = enet.Initialize(); CHECK(rv == true); enet::ClientHost* client = enet.CreateClientHost(); CHECK(client != NULL); enet::Peer* peer = client->Connect("127.0.0.1", 4242); CHECK(peer != NULL); enet::Event* event = enet.CreateEvent(); uint32_t timeout = 100; rv = client->Service(event, timeout); CHECK(rv == true); CHECK(event->GetType() == enet::Event::TYPE_CONNECT); printf("Connected to %s:%u.\n", event->GetPeer()->GetIp().c_str(), event->GetPeer()->GetPort()); rv = client->Service(event, timeout); CHECK(rv == true); CHECK(event->GetType() == enet::Event::TYPE_RECEIVE); std::vector<char> msg; event->GetData(&msg); msg.push_back(0); printf("Message received: %s\n", &msg[0]); char message[] = "Hello world!"; rv = peer->Send(message, sizeof(message), true); CHECK(rv == true); rv = client->Service(event, timeout); CHECK(rv == true); printf("Message sent: %s\n", message); peer->Disconnect(); rv = client->Service(event, timeout); CHECK(rv == true); CHECK(event->GetType() == enet::Event::TYPE_DISCONNECT); printf("Disconnected from %s:%u.\n", event->GetPeer()->GetIp().c_str(), event->GetPeer()->GetPort()); delete event; delete client; return 0; }
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
src/sample-server/server.cpp
C++
// Copyright (c) 2013 Andrey Konovalov #include <vector> #include "enet-plus/enet.h" int main() { enet::Enet enet; bool rv = enet.Initialize(); CHECK(rv == true); enet::ServerHost* server = enet.CreateServerHost(4242); CHECK(server != NULL); enet::Event* event = enet.CreateEvent(); printf("Server started.\n"); uint32_t timeout = 100; std::vector<char> data; bool is_running = true; int counter = 0; while (is_running) { bool rv = server->Service(event, timeout); CHECK(rv == true); switch (event->GetType()) { case enet::Event::TYPE_CONNECT: { printf("Client %s:%u connected.\n", event->GetPeer()->GetIp().c_str(), event->GetPeer()->GetPort()); enet::Peer* peer = event->GetPeer(); char msg[] = "Ohaio!"; data.assign(msg, msg + sizeof(msg)); bool rv = peer->Send(&data[0], data.size()); CHECK(rv == true); break; } case enet::Event::TYPE_RECEIVE: { event->GetData(&data); data.push_back(0); printf("From %s:%u: %s\n", event->GetPeer()->GetIp().c_str(), event->GetPeer()->GetPort(), &data[0]); break; } case enet::Event::TYPE_DISCONNECT: { printf("Client %s:%u disconnected.\n", event->GetPeer()->GetIp().c_str(), event->GetPeer()->GetPort()); counter += 1; if (counter == 3) { is_running = false; } break; } } } printf("Server finished.\n"); delete event; delete server; return EXIT_SUCCESS; }
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
valgrind-client.sh
Shell
#!/bin/sh cd bin export LD_LIBRARY_PATH=`pwd` cd .. valgrind ./bin/sample-client
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
valgrind-server.sh
Shell
#!/bin/sh cd bin export LD_LIBRARY_PATH=`pwd` cd .. valgrind ./bin/sample-server
xairy/enet-plus
4
C++ wrapper for ENet
Python
xairy
Andrey Konovalov
msp/__init__.py
Python
from cell_parser import * from schedule_parser import *
xairy/mipt-schedule-parser
2
A parser for MIPT .xls schedule
Python
xairy
Andrey Konovalov
msp/cell_parser.py
Python
#!/usr/bin/python #coding: utf-8 from __future__ import unicode_literals import fileinput import regex import string import sys import unicodedata import xlrd import os __author__ = "Andrey Konovalov" __copyright__ = "Copyright (C) 2014 Andrey Konovalov" __license__ = "MIT" __version__ = "0.1" # ['ii', 'ee'] -> ['ii ee', 'ii ee.', 'ii. ee', 'ii. ee.', # 'Ii ee', 'Ii ee.', 'Ii. ee', 'Ii. ee.', # 'ii Ee', 'ii Ee.', 'ii. Ee', 'ii. Ee.', # 'Ii Ee', 'Ii Ee.', 'Ii. Ee', 'Ii. Ee.'] def DotCapitalJoin(list): if list == []: return [''] result = [] head_lower = list[0] head_upper = list[0][0].upper() + list[0][1:] tail_list = DotCapitalJoin(list[1:]) for elem in tail_list: result.append((head_upper + '. ' + elem).rstrip()) result.append((head_upper + ' ' + elem).rstrip()) result.append((head_lower + '. ' + elem).rstrip()) result.append((head_lower + ' ' + elem).rstrip()) return result # 'ieg' -> ['ieg', 'Ieg', 'iEg', 'IEg', 'ieG', 'IeG', 'iEG', 'IEG'] def CapitalVary(s): if s == '': return [''] result = [] head_lower = s[0].lower() head_upper = s[0].upper() tail_list = CapitalVary(s[1:]) for elem in tail_list: result.append(head_lower + elem) result.append(head_upper + elem) return result gk = ['ГК'] + CapitalVary('ГК') lk = ['ЛК'] + CapitalVary('ЛК') nk = ['НК'] + CapitalVary('НК') kpm = ['КПМ'] + CapitalVary('КПМ') rtk = ['РТК'] + CapitalVary('РТК') buildings = gk + lk + nk + kpm + rtk bh = ['Б. Хим.'] + DotCapitalJoin(['б', 'хим']) bf = ['Б. Физ.'] + DotCapitalJoin(['б', 'физ']) gf = ['Гл. Физ.'] + DotCapitalJoin(['гл', 'физ']) az = ['Акт. Зал'] + DotCapitalJoin(['акт', 'зал']) cz = ['Чит. Зал'] + DotCapitalJoin(['чит', 'зал']) lecture_rooms = bh + bf + gf + az + cz def DotEscape(list): result = [] for elem in list: result.append(elem.replace('.', '\.')) return result first_teacher_re = regex.compile( '(?P<teacher>' + \ '(?P<surname>[А-ЯЁ][а-яё]+(?:\-[А-ЯЁ][а-яё]+)?)' + ' ' + \ '(?P<first_initial>[А-ЯЁ])\.?' + ' ' + \ '(?P<second_initial>[А-ЯЁ])\.?' + \ ')' + \ '(?:[^а-яА-ЯёЁ]|$)' ) second_teacher_re = regex.compile( '(?:/|\-)' + \ '(?:[^/\-]*? |)' + \ '(?P<teacher>' + \ '(?P<surname>[А-ЯЁ][а-яё]+(?:\-[А-ЯЁ][а-яё]+)?)' + \ ')' + \ ' ?(?:/|\-)' ) building_room_re = regex.compile( '(?P<location>' + \ '(?P<room>[0-9]+а?)' + ' ?' + \ '(?P<building>' + '|'.join(buildings) + ')' + \ ')' + \ '(?:[^а-яА-ЯёЁ]|$)' ) lecture_room_re = regex.compile( '(?P<location>' + \ '(?P<room>' + '|'.join(DotEscape(lecture_rooms)) + ')' + \ ')' + \ '(?:[^а-яА-ЯёЁ]|$)' ) subject_res = [] subject_names = [[]] this_dir, this_filename = os.path.split(__file__) subjects_path = os.path.join(this_dir, "data", "subjects") with open(subjects_path) as subject_file: while True: line = subject_file.readline().decode('utf-8') if line == '': break; line = line.rstrip() if len(line) > 0: subject_names[-1].append(line) else: assert len(subject_names[-1]) > 0 subject_re = regex.compile( \ '(?P<subject>' + '|'.join(subject_names[-1]) + ')' \ ) subject_res.append(subject_re) subject_names.append([]) # Removes consecutive whitespaces, adds a space after each dot. def Simplify(s): s = s.replace('.', '. ') s = ' '.join(s.split()) return s unicode_punctuation_dict = dict((i, ' ') for i in xrange(sys.maxunicode) if unicodedata.category(unichr(i)).startswith('P')) # Does what Simplify() does, removes all punctuation and lowers case. def Normalize(s): s = s.replace('.', '. ') s = s.translate(unicode_punctuation_dict) s = s.lower() s = ' '.join(s.split()) return s def GetTeachers(value): value = Simplify(value) teacher_entries = [] while True: m = first_teacher_re.search(value) if m == None: break teacher = m.group('teacher') surname = m.group('surname') first_initial = m.group('first_initial') second_initial = m.group('second_initial') start = m.start('teacher') end = m.end('teacher') if len(surname) >= 3: teacher_entries.append((start, (surname, first_initial, second_initial))) value = value[:start] + ('$' * len(teacher)) + value[end:] m = second_teacher_re.search(value) if m != None and not(m.partial): teacher = m.group('teacher') surname = m.group('surname') start = m.start('teacher') end = m.end('teacher') if len(surname) >= 4: teacher_entries.append((start, (surname, None, None))) value = value[:start] + ('$' * len(teacher)) + value[end:] teacher_entries.sort() teacher_list = [teacher for (offset, teacher) in teacher_entries] return teacher_list def GetLocations(value): value = Simplify(value) location_entries = [] while True: m = building_room_re.search(value) if m == None: break location = m.group('location') room = m.group('room') building = m.group('building') for building_kind in [gk, lk, nk, kpm, rtk]: if building in building_kind: building = building_kind[0] start = m.start('location') end = m.end('location') location_entries.append((start, (room, building))) value = value[:start] + ('$' * len(location)) + value[end:] while True: m = lecture_room_re.search(value) if m == None: break location = m.group('location') room = m.group('room') for room_kind in [bh, bf, gf, az, cz]: if room in room_kind: room = room_kind[0] start = m.start('location') end = m.end('location') location_entries.append((start, (room, None))) value = value[:start] + ('$' * len(location)) + value[end:] location_entries.sort() unique_locations = [] for (offset, location) in location_entries: if location not in unique_locations: unique_locations.append(location) return unique_locations def GetSubjects(value): value = Normalize(value) subject_entries = [] for i in xrange(len(subject_res)): subject_re = subject_res[i] subject_name = subject_names[i][0] while True: m = subject_re.search(value) if m == None: break subject = m.group('subject') start = m.start('subject') end = m.end('subject') subject_entries.append((start, subject_name)) value = value[:start] + ('$' * len(subject)) + value[end:] subject_entries.sort() subjects = [subject for (offset, subject) in subject_entries] return subjects def TeacherToStr(teacher): s = teacher[0] if teacher[1] != None and teacher[2] != None: s += ' ' + teacher[1] + '. ' + teacher[2] + '.' return s def LocationToStr(location): s = location[0] if location[1] != None: s += ' ' + location[1] return s def PrintValueInfo(value): subjects = GetSubjects(value) locations= GetLocations(value) teachers = GetTeachers(value) # Subjects are strings as they are. locations = [LocationToStr(location) for location in locations] teachers = [TeacherToStr(teacher) for teacher in teachers] print '\t'.join(subjects).encode('utf-8') print '\t'.join(locations).encode('utf-8') print '\t'.join(teachers).encode('utf-8') if __name__ == '__main__': for value in fileinput.input(): value = value.decode('utf-8').rstrip() PrintValueInfo(value)
xairy/mipt-schedule-parser
2
A parser for MIPT .xls schedule
Python
xairy
Andrey Konovalov
msp/full_parser.py
Python
#!/usr/bin/python #coding: utf-8 from __future__ import unicode_literals import sets import sys import xlrd import schedule_parser import cell_parser __author__ = "Andrey Konovalov" __copyright__ = "Copyright (C) 2014 Andrey Konovalov" __license__ = "MIT" __version__ = "0.1" def PrintFullSchedule(file): schedule = schedule_parser.Schedule() schedule.Parse(file) for department_index in xrange(schedule.GetDepartmentCount()): schedule_tables = [] for weekday_index in xrange(6): schedule_tables.append(schedule.GetScheduleTable(department_index, weekday_index)) group_count = schedule.GetGroupCount(department_index) for group_index in xrange(group_count): print schedule.GetGroup(department_index, group_index) for weekday_index in xrange(6): for values in schedule_tables[weekday_index][group_index]: print ('%d\t%s' % (values[0][0][1], values[0][0][0])).encode('utf-8') cell_parser.PrintValueInfo(values[0][0][0]) print ('%d\t%s' % (values[1][0][1], values[1][0][0])).encode('utf-8') cell_parser.PrintValueInfo(values[1][0][0]) print ('%d\t%s' % (values[0][1][1], values[0][1][0])).encode('utf-8') cell_parser.PrintValueInfo(values[0][1][0]) print ('%d\t%s' % (values[1][1][1], values[1][1][0])).encode('utf-8') cell_parser.PrintValueInfo(values[1][1][0]) if __name__ == '__main__': assert len(sys.argv) == 2 PrintFullSchedule(sys.argv[1])
xairy/mipt-schedule-parser
2
A parser for MIPT .xls schedule
Python
xairy
Andrey Konovalov
msp/schedule_parser.py
Python
#!/usr/bin/python #coding: utf-8 from __future__ import unicode_literals import sys import xlrd __author__ = "Andrey Konovalov" __copyright__ = "Copyright (C) 2014 Andrey Konovalov" __license__ = "MIT" __version__ = "0.1" DAYS = 'Дни' HOURS = 'Часы' MONDAY = 'Понедельник' TUESDAY = 'Вторник' WEDNESDAY = 'Среда' THURSDAY = 'Четверг' FRIDAY = 'Пятница' SATURDAY = 'Суббота' WEEKDAYS = [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY] PAIRS_PER_DAY = 7 class Schedule: def __init__(self): pass def Parse(self, file): self.workbook = xlrd.open_workbook(file, formatting_info=True) self.worksheet = self.workbook.sheet_by_index(0) self.ParseWeekdays() self.ParseDepartments() self.ParseHours() self.ParseGroups() def ParseWeekdays(self): self.weekday_ranges = [] for day in WEEKDAYS: ranges = [] for (rb, re, cb, ce) in self.worksheet.merged_cells: if self.worksheet.cell_value(rb, cb) == day: ranges.append((rb, re)) assert len(ranges) > 0 for i in xrange(len(ranges) - 1): assert ranges[i] == ranges[i + 1] self.weekday_ranges.append(ranges[0]) def ParseDepartments(self): self.department_ranges = [] days_cols = [] hours_cols = [] rows = [] for row in xrange(self.worksheet.nrows): for col in xrange(self.worksheet.ncols): if self.worksheet.cell_value(row, col) == DAYS: days_cols.append(col) rows.append(row) if self.worksheet.cell_value(row, col) == HOURS: hours_cols.append(col) rows.append(row) assert len(days_cols) == len(hours_cols) for k in xrange(len(days_cols)): beg = hours_cols[k] + 1 end = days_cols[k + 1] if (k + 1 < len(days_cols)) else self.worksheet.ncols self.department_ranges.append((beg, end)) assert len(rows) > 0 for k in xrange(len(rows) - 1): assert rows[k] == rows[k + 1] self.departments_row = rows[0] self.hours_column = hours_cols[0] def ParseHours(self): self.hours_ranges = [] for weekday_range in self.weekday_ranges: weekday_hours_ranges = [] last = weekday_range[0] for row in xrange(weekday_range[0] + 1, weekday_range[1]): value = self.worksheet.cell_value(row, self.hours_column) if value != '': weekday_hours_ranges.append((last, row)) last = row weekday_hours_ranges.append((last, weekday_range[1])) self.hours_ranges.append(weekday_hours_ranges) def ParseGroups(self): self.groups = [] self.group_ranges = [] for department in xrange(self.GetDepartmentCount()): dep_groups = [] dep_group_ranges = [] dep_range = self.department_ranges[department] dep_row = self.departments_row for column in xrange(dep_range[0], dep_range[1]): beg, end = 0, 0 group = self.worksheet.cell_value(dep_row, column) if group != '': dep_groups.append(group) beg, end = column, column + 1 while end < self.worksheet.ncols and len(self.worksheet.cell_value(dep_row, end)) == 0: end += 1 dep_group_ranges.append((beg, end)) self.groups.append(dep_groups) self.group_ranges.append(dep_group_ranges) def GetWeekdayRange(self, weekday_index): return self.weekday_ranges[weekday_index] def GetDepartmentCount(self): return len(self.department_ranges) def GetDepartmentRange(self, department_index): return self.department_ranges[department_index] def GetDepartmentsRow(self): return self.departments_row def GetHoursColumn(self): return self.hours_column def GetHoursRanges(self, weekday_index): return self.hours_ranges[weekday_index] def GetGroupCount(self, department_index): return len(self.groups[department_index]) def GetGroupList(self, department_index): return self.groups[department_index] def GetGroup(self, department_index, group_index): return self.groups[department_index][group_index] def GetGroupRange(self, department_index, group_index): return self.group_ranges[department_index][group_index] def GetWeekdayByRow(self, row): for index in xrange(len(self.weekday_ranges)): wr = self.weekday_ranges[index] if wr[0] <= row and row < wr[1]: return index assert False def GetPairByRow(self, row): weekday_index = self.GetWeekdayByRow(row) hours_ranges = self.hours_ranges[weekday_index] for index in xrange(len(hours_ranges)): hr = hours_ranges[index] if hr[0] <= row and row < hr[1]: return (index, row - hr[0]) assert False def GetDepartmentIndexByColumn(self, column): for index in xrange(len(self.department_ranges)): dr = self.department_ranges[index] if dr[0] <= column and column < dr[1]: return index assert False def GetGroupIndexByColumn(self, column): department_index = self.GetDepartmentIndexByColumn(column) group_ranges = self.group_ranges[department_index] for index in xrange(len(group_ranges)): gr = group_ranges[index] if gr[0] <= column and column < gr[1]: return (index, column - gr[0]) assert False def GetCellColor(self, row, column): cell = self.worksheet.cell(row, column) xfx = self.worksheet.cell_xf_index(row, column) xf = self.workbook.xf_list[xfx] bgx = xf.background.pattern_colour_index rgb = self.workbook.colour_map[bgx] # (204, 255, 204) -> 0 : empty, (204, 255, 255) -> 1 : seminar, # (255, 153, 204) -> 2 : lecture, (255, 255, 153) -> 3 : other if rgb == (204, 255, 204): return 0 elif rgb == (204, 255, 255): return 1 elif rgb == (255, 153, 204): return 2 elif rgb == (255, 255, 153): return 3 return -1 def GetScheduleTable(self, department_index, weekday_index): dr = self.department_ranges[department_index] wr = self.weekday_ranges[weekday_index] groups_count = len(self.groups[department_index]) schedule_table = [[[[('', 0), ('', 0)], [('', 0), ('', 0)]] for i in xrange(PAIRS_PER_DAY)] for i in xrange(groups_count)] for (rb, re, cb, ce) in self.worksheet.merged_cells: if wr[0] <= rb and re <= wr[1] and dr[0] <= cb and ce <= dr[1]: value = self.worksheet.cell_value(rb, cb) color = self.GetCellColor(rb, cb) if value == '': continue for row in xrange(rb, re): for column in xrange(cb, ce): p1, p2 = self.GetPairByRow(row) g1, g2 = self.GetGroupIndexByColumn(column) schedule_table[g1][p1][g2][p2] = (value, color) hr = self.hours_ranges[weekday_index][p1] gr = self.group_ranges[department_index][g1] if p2 == 0 and hr[1] - hr[0] == 1: schedule_table[g1][p1][g2][1] = (value, color) if g2 == 0 and gr[1] - gr[0] == 1: schedule_table[g1][p1][1][p2] = (value, color) if p2 == 0 and hr[1] - hr[0] == 1 and g2 == 0 and gr[1] - gr[0] == 1: schedule_table[g1][p1][1][1] = (value, color) for row in xrange(wr[0], wr[1]): for column in xrange(dr[0], dr[1]): value = self.worksheet.cell_value(row, column) color = self.GetCellColor(row, column) if value == '': continue p1, p2 = self.GetPairByRow(row) g1, g2 = self.GetGroupIndexByColumn(column) schedule_table[g1][p1][g2][p2] = (value, color) hr = self.hours_ranges[weekday_index][p1] gr = self.group_ranges[department_index][g1] if p2 == 0 and hr[1] - hr[0] == 1: schedule_table[g1][p1][g2][1] = (value, color) if g2 == 0 and gr[1] - gr[0] == 1: schedule_table[g1][p1][1][p2] = (value, color) if p2 == 0 and hr[1] - hr[0] == 1 and g2 == 0 and gr[1] - gr[0] == 1: schedule_table[g1][p1][1][1] = (value, color) return schedule_table # Events # XXX(xairy): returns list of groups, not subgroups. def GetGroupsByColumnRange(self, rng): d1 = self.GetDepartmentIndexByColumn(rng[0]) d2 = self.GetDepartmentIndexByColumn(rng[1] - 1) assert d1 == d2 groups = [] for column in xrange(rng[0], rng[1]): g1, g2 = self.GetGroupIndexByColumn(column) group = self.GetGroup(d1, g1) if group not in groups: groups.append(group) return groups # FIXME(xairy): naive implementation, sometimes doesn't work correctly. def GetPairRangeByRowRange(self, rng): start = self.GetPairByRow(rng[0]) end = self.GetPairByRow(rng[1] - 1) return start[0], end[0] # FIXME(xairy): naive implementation, sometimes doesn't work correctly. def GetEvents(self, department_index, weekday_index): dr = self.department_ranges[department_index] wr = self.weekday_ranges[weekday_index] # event = {'start': ..., 'end': ..., 'groups': [...], 'value': ...} events = [] merged_cells = [] for (rb, re, cb, ce) in self.worksheet.merged_cells: if wr[0] <= rb and re <= wr[1] and dr[0] <= cb and ce <= dr[1]: merged_cells.append((rb, re, cb, ce)) value = self.worksheet.cell_value(rb, cb) if value == '': continue color = self.GetCellColor(rb, cb) groups = self.GetGroupsByColumnRange((cb, ce)) start, end = self.GetPairRangeByRowRange((rb, re)) events.append({}) events[-1]['value'] = value events[-1]['start'] = start events[-1]['end'] = end events[-1]['groups'] = groups events[-1]['color'] = color for row in xrange(wr[0], wr[1]): for column in xrange(dr[0], dr[1]): in_merged = False for (rb, re, cb, ce) in merged_cells: if rb <= row < re and cb <= column < ce: in_merged = True break if in_merged: continue value = self.worksheet.cell_value(row, column) if value == '': continue color = self.GetCellColor(row, column) groups = self.GetGroupsByColumnRange((column, column + 1)) start, end = self.GetPairRangeByRowRange((row, row + 1)) events.append({}) events[-1]['value'] = value events[-1]['start'] = start events[-1]['end'] = end events[-1]['groups'] = groups events[-1]['color'] = color return events def PrintEvents(file): schedule = Schedule() schedule.Parse(file) events = schedule.GetEvents(7, 0) for event in events: print event['start'], event['end'], event['groups'], event['value'] def PrintSchedule(file): schedule = Schedule() schedule.Parse(file) for department_index in xrange(schedule.GetDepartmentCount()): schedule_tables = [] for weekday_index in xrange(6): schedule_tables.append(schedule.GetScheduleTable(department_index, weekday_index)) group_count = schedule.GetGroupCount(department_index) for group_index in xrange(group_count): print schedule.GetGroup(department_index, group_index) for weekday_index in xrange(6): for values in schedule_tables[weekday_index][group_index]: print ('%d\t%s' % (values[0][0][1], values[0][0][0])).encode('utf-8') print ('%d\t%s' % (values[1][0][1], values[1][0][0])).encode('utf-8') print ('%d\t%s' % (values[0][1][1], values[0][1][0])).encode('utf-8') print ('%d\t%s' % (values[1][1][1], values[1][1][0])).encode('utf-8') if __name__ == '__main__': assert len(sys.argv) == 2 PrintSchedule(sys.argv[1])
xairy/mipt-schedule-parser
2
A parser for MIPT .xls schedule
Python
xairy
Andrey Konovalov
msp/test/__init__.py
Python
import cell_tests import schedule_tests import unittest def suite(): loader = unittest.TestLoader() suite = unittest.TestSuite() suite.addTest(cell_tests.suite()) suite.addTest(schedule_tests.suite()) return suite if __name__ == '__main__': unittest.TextTestRunner(verbosity=2).run(suite())
xairy/mipt-schedule-parser
2
A parser for MIPT .xls schedule
Python
xairy
Andrey Konovalov
msp/test/cell_tests.py
Python
#!/usr/bin/python #coding: utf-8 from __future__ import unicode_literals import unittest import xlrd import msp.cell_parser as cell_parser __author__ = "Andrey Konovalov" __copyright__ = "Copyright (C) 2014 Andrey Konovalov" __license__ = "MIT" __version__ = "0.1" class LocationsTest(unittest.TestCase): def setUp(self): self.cases = [ \ ( \ 'МСС /211 ГК , 532 ГК/', \ [('211', 'ГК'), ('532', 'ГК')] \ ), ( \ 'Теория игр и принятие решений / Доцент Меньшиков И. С. - для "кт" и "эк" - обязательно; для "мф" - а. к. -1 110 КПМ', \ [('110', 'КПМ')] \ ), ( \ 'Механика сплошных сред Проф. Жмур В. В. -211 ГК проф. Рыжак Е. И. - 532 ГК', \ [('211', 'ГК'), ('532', 'ГК')] \ ), ( \ 'Альтерн. курсы 1 из 4-х: 1 Физика низкотемпературной плазмы 117 ГК 2. Биофизика 113 ГК', \ [('117', 'ГК'), ('113', 'ГК')] \ ), ( \ 'Лин методы в р/т /Доц. Григорьев А. А. /117 ГК', \ [('117', 'ГК')] \ ), ( \ 'Теоретическая физика 202 НК, Б. Физ. , 123 ГК, 432 ГК, 521 ГК, 532 ГК, 507а ГК, 509 ГК, 511 ГК', \ [('202', 'НК'), ('Б. Физ.', None), ('123', 'ГК'), ('432', 'ГК'), ('521', 'ГК'), ('532', 'ГК'), \ ('507а', 'ГК'), ('509', 'ГК'), ('511', 'ГК')] \ ), ( \ 'Функциональный анализ ( 31б, 32а, 33, 34в, 36бв)/Доцент Боговский М. Е. / 430 ГК ' + \ 'Уравнения математической физики (31а, 32б, 34аб, 35, 36а) /Доцент Шаньков В. В. /Акт. зал', \ [('430', 'ГК'), ('Акт. Зал', None)] \ ), ( \ 'Физические основы фотоники и нанофотоники /Профессор Фомичёв А. А. / 113 ГК', \ [('113', 'ГК')] \ ), ( \ 'Вычислительная математика /Лобачев/ 202 НК', \ [('202', 'НК')] \ ), ( \ 'Сетевые технологии /Ст. преп. Подлесных / 113 ГК', \ [('113', 'ГК')] \ ), ( \ 'Основы физики конденсированного состояния /К. ф. -м. н. Куксин А. Ю/ 516а ГК -альт. курс', \ [('516а', 'ГК')] \ ), ( \ 'Теоретическая физика Б. Хим. , 430 ГК, 113 ГК', \ [('Б. Хим.', None), ('430', 'ГК'), ('113', 'ГК')] \ ), ( \ 'Диф. ур-ния Б. Хим', \ [('Б. Хим.', None)] \ ), ( \ 'оодкдз/401кпм КПМ401 КПМ', \ [('401', 'КПМ')] \ ), ( \ 'Общеинженерная подготовка /Нечетная неделя/ 301ЛК', \ [('301', 'ЛК')] \ ), ( \ 'Теория вероятностей Чит. зал', \ [('Чит. Зал', None)] \ ), ( \ 'Теор. физика 511 Гк', \ [('511', 'ГК')] \ ), ( \ 'Общая химия /К.х.н., Доцент Снигирева Е.М. /Б.Хим/', \ [('Б. Хим.', None)] \ ), ( \ '', \ [] \ ) \ ] def runTest(self): for i in xrange(len(self.cases)): self.assertEqual(cell_parser.GetLocations(self.cases[i][0]), self.cases[i][1]) class TeachersTest(unittest.TestCase): def setUp(self): self.cases = [ \ ( \ 'МСС /211 ГК , 532 ГК/', \ [] \ ), ( \ 'Теория игр и принятие решений / Доцент Меньшиков И. С. - для "кт" и "эк" - обязательно; для "мф" - а. к. -1 110 КПМ', \ [('Меньшиков', 'И', 'С')] \ ), ( \ 'Механика сплошных сред Проф. Жмур В. В. -211 ГК проф. Рыжак Е. И. - 532 ГК', \ [('Жмур', 'В', 'В'), ('Рыжак', 'Е', 'И')] \ ), ( \ 'Альтерн. курсы 1 из 4-х: 1 Физика низкотемпературной плазмы 117 ГК 2. Биофизика 113 ГК', \ [] \ ), ( \ 'Лин методы в р/т /Доц. Григорьев А. А. /117 ГК', \ [('Григорьев', 'А', 'А')] \ ), ( \ 'Теоретическая физика 202 НК, Б. Физ. , 123 ГК, 432 ГК, 521 ГК, 532 ГК, 507а ГК, 509 ГК, 511 ГК', \ [] \ ), ( \ 'Функциональный анализ ( 31б, 32а, 33, 34в, 36бв)/Доцент Боговский М. Е. / 430 ГК ' + \ 'Уравнения математической физики (31а, 32б, 34аб, 35, 36а) /Доцент Шаньков В. В. /Акт. зал', \ [('Боговский', 'М', 'Е'), ('Шаньков', 'В', 'В')] \ ), ( \ 'Физические основы фотоники и нанофотоники /Профессор Фомичёв А. А. / 113 ГК', \ [('Фомичёв', 'А', 'А')] \ ), ( \ 'Вычислительная математика /Лобачев/ 202 НК', \ [('Лобачев', None, None)] \ ), (\ 'Сетевые технологии /Ст. преп. Подлесных / 113 ГК', \ [('Подлесных', None, None)] \ ), ( \ 'Основы физики конденсированного состояния /К. ф. -м. н. Куксин А. Ю/ 516а ГК -альт. курс', \ [('Куксин', 'А', 'Ю')] \ ), ( \ 'Теоретическая физика Б. Хим. , 430 ГК, 113 ГК', \ [] \ ), ( \ 'Диф. ур-ния Б. Хим', \ [] \ ), ( \ 'оодкдз/401кпм КПМ401 КПМ', \ [] \ ), ( \ 'Общеинженерная подготовка /Нечетная неделя/ 301ЛК', \ [] \ ), ( \ 'МСС-Доц. Извеков-430 ГК, Доцент Березникова М. В. . -211 ГК; Проф. Рыжак Е. И. - 532 ГК', \ [('Извеков', None, None), ('Березникова', 'М', 'В'), ('Рыжак', 'Е', 'И')] \ ), ( \ 'Выпуклый анализ 432 ГК (кроме 91а) ПМФ - обязательно ПМИ-альт.курс', \ [] \ ), ( \ 'Методы асимптотического и нелинейного анализа /Проф. Тер-Крикоров А.М./110 КПМ' + \ ' - для "мф"-обязательно, для "кт" и "эк" -а.к.-1', \ [('Тер-Крикоров', 'А', 'М')] \ ), ( \ 'Общая химия /К.х.н., Доцент Снигирева Е.М. /Б.Хим/', \ [('Снигирева', 'Е', 'М')] \ ), ( \ '', \ [] \ ) \ ] def runTest(self): for i in xrange(len(self.cases)): self.assertEqual(cell_parser.GetTeachers(self.cases[i][0]), self.cases[i][1]) class SubjectsTest(unittest.TestCase): def setUp(self): self.cases = [ \ ( \ 'МСС /211 ГК , 532 ГК/', \ ['Механика сплошных сред'] \ ), ( \ 'Теория игр и принятие решений / Доцент Меньшиков И. С. - для "кт" и "эк" - обязательно; для "мф" - а. к. -1 110 КПМ', \ ['Теория игр и принятие решений'] \ ), ( \ 'Механика сплошных сред Проф. Жмур В. В. -211 ГК проф. Рыжак Е. И. - 532 ГК', \ ['Механика сплошных сред'] \ ), ( \ 'Альтерн. курсы 1 из 4-х: 1 Физика низкотемпературной плазмы 117 ГК 2. Биофизика 113 ГК', \ ['Физика низкотемпературной плазмы', 'Биофизика'] \ ), ( \ 'Лин методы в р/т /Доц. Григорьев А. А. /117 ГК', \ ['Линейные методы в радиотехнике'] \ ), ( \ 'Теоретическая физика 202 НК, Б. Физ. , 123 ГК, 432 ГК, 521 ГК, 532 ГК, 507а ГК, 509 ГК, 511 ГК', \ ['Теоретическая физика'] \ ), ( \ 'Функциональный анализ ( 31б, 32а, 33, 34в, 36бв)/Доцент Боговский М. Е. / 430 ГК ' + \ 'Уравнения математической физики (31а, 32б, 34аб, 35, 36а) /Доцент Шаньков В. В. /Акт. зал', \ ['Функциональный анализ', 'Уравнения математической физики'] \ ), ( \ 'Физические основы фотоники и нанофотоники /Профессор Фомичёв А. А. / 113 ГК', \ ['Физические основы фотоники и нанофотоники'] \ ), ( \ 'Вычислительная математика /Лобачев/ 202 НК', \ ['Вычислительная математика'] \ ), (\ 'Сетевые технологии /Ст. преп. Подлесных / 113 ГК', \ ['Сетевые технологии'] \ ), ( \ 'Основы физики конденсированного состояния /К. ф. -м. н. Куксин А. Ю/ 516а ГК -альт. курс', \ ['Основы физики конденсированного состояния'] \ ), ( \ 'Теоретическая физика Б. Хим. , 430 ГК, 113 ГК', \ ['Теоретическая физика'] \ ), ( \ 'Диф. ур-ния Б. Хим', \ ['Дифференциальные уравнения'] \ ), ( \ 'оодкдз/401кпм КПМ401 КПМ', \ ['ООДКДЗ'] \ ), ( \ 'Общеинженерная подготовка /Нечетная неделя/ 301ЛК', \ ['Общеинженерная подготовка'] \ ), ( \ 'Химия: лаб. практикум', \ ['Химия: Лабораторный практикум'] \ ), ( \ ' Лабораторный практикум(нечет нед) Общая физика (чет нед) 523ГК', \ ['Лабораторный практикум', 'Общая физика'] \ ), ( \ 'Формальные языки и трансляции /Асс. Сорокин А.А./ Б.Физ', \ ['Формальные языки и трансляции'] \ ), ( \ '', \ [] \ ) \ ] def runTest(self): for i in xrange(len(self.cases)): self.assertEqual(cell_parser.GetSubjects(self.cases[i][0]), self.cases[i][1]) def suite(): loader = unittest.TestLoader() suite = unittest.TestSuite() suite.addTest(LocationsTest()) suite.addTest(TeachersTest()) suite.addTest(SubjectsTest()) return suite if __name__ == '__main__': unittest.TextTestRunner(verbosity=2).run(suite())
xairy/mipt-schedule-parser
2
A parser for MIPT .xls schedule
Python
xairy
Andrey Konovalov
msp/test/schedule_tests.py
Python
#!/usr/bin/python #coding: utf-8 from __future__ import unicode_literals import os import unittest import xlrd import msp.schedule_parser as schedule_parser __author__ = "Andrey Konovalov" __copyright__ = "Copyright (C) 2014 Andrey Konovalov" __license__ = "MIT" __version__ = "0.1" this_dir, this_filename = os.path.split(__file__) SCHEDULE_PATH = os.path.join(this_dir, "..", "data", "2013_fall", "4kurs.xls") class WeekdayRangeTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetWeekdayRange(0), (4, 11)) self.assertEqual(self.schedule.GetWeekdayRange(1), (12, 19)) self.assertEqual(self.schedule.GetWeekdayRange(2), (20, 27)) self.assertEqual(self.schedule.GetWeekdayRange(3), (28, 37)) self.assertEqual(self.schedule.GetWeekdayRange(4), (38, 47)) self.assertEqual(self.schedule.GetWeekdayRange(5), (48, 57)) class DepartmentCountTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetDepartmentCount(), 9) class DepartmentRangeTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetDepartmentRange(0), (2, 11)) self.assertEqual(self.schedule.GetDepartmentRange(1), (13, 20)) self.assertEqual(self.schedule.GetDepartmentRange(2), (22, 32)) self.assertEqual(self.schedule.GetDepartmentRange(3), (34, 36)) self.assertEqual(self.schedule.GetDepartmentRange(4), (38, 43)) self.assertEqual(self.schedule.GetDepartmentRange(5), (45, 53)) self.assertEqual(self.schedule.GetDepartmentRange(6), (55, 62)) self.assertEqual(self.schedule.GetDepartmentRange(7), (64, 71)) self.assertEqual(self.schedule.GetDepartmentRange(8), (73, 77)) class DepartmentsRowTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetDepartmentsRow(), 3) class HoursColumnTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetHoursColumn(), 1) class HoursRangesTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetHoursRanges(0), [(4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10), (10, 11)]) self.assertEqual(self.schedule.GetHoursRanges(3), [(28, 30), (30, 31), (31, 32), (32, 34), (34, 35), (35, 36), (36, 37)]) self.assertEqual(self.schedule.GetHoursRanges(5), [(48, 49), (49, 50), (50, 52), (52, 53), (53, 54), (54, 56), (56, 57)]) class GroupCountTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetGroupCount(0), 9) self.assertEqual(self.schedule.GetGroupCount(1), 7) self.assertEqual(self.schedule.GetGroupCount(2), 8) self.assertEqual(self.schedule.GetGroupCount(3), 2) self.assertEqual(self.schedule.GetGroupCount(4), 5) self.assertEqual(self.schedule.GetGroupCount(5), 8) self.assertEqual(self.schedule.GetGroupCount(6), 7) self.assertEqual(self.schedule.GetGroupCount(7), 7) self.assertEqual(self.schedule.GetGroupCount(8), 4) class GroupListTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetGroupList(0), ['011', '012', '013', '014', '015', '016', '017', '018', '019']) self.assertEqual(self.schedule.GetGroupList(1), ['021', '022', '023', '024', '025', '026', '028']) self.assertEqual(self.schedule.GetGroupList(3), ['041', '042']) self.assertEqual(self.schedule.GetGroupList(8), ['0111', '0112', '0113', '0114']) class GroupRangeTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetGroupRange(0, 0), (2, 3)) self.assertEqual(self.schedule.GetGroupRange(0, 1), (3, 4)) self.assertEqual(self.schedule.GetGroupRange(2, 1), (23, 25)) self.assertEqual(self.schedule.GetGroupRange(2, 2), (25, 26)) self.assertEqual(self.schedule.GetGroupRange(2, 3), (26, 28)) self.assertEqual(self.schedule.GetGroupRange(5, 3), (48, 49)) self.assertEqual(self.schedule.GetGroupRange(8, 0), (73, 74)) self.assertEqual(self.schedule.GetGroupRange(8, 3), (76, 77)) class WeekdayByRowTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetWeekdayByRow(4), 0) self.assertEqual(self.schedule.GetWeekdayByRow(5), 0) self.assertEqual(self.schedule.GetWeekdayByRow(10), 0) self.assertEqual(self.schedule.GetWeekdayByRow(13), 1) self.assertEqual(self.schedule.GetWeekdayByRow(25), 2) self.assertEqual(self.schedule.GetWeekdayByRow(26), 2) self.assertEqual(self.schedule.GetWeekdayByRow(28), 3) self.assertEqual(self.schedule.GetWeekdayByRow(44), 4) self.assertEqual(self.schedule.GetWeekdayByRow(48), 5) self.assertEqual(self.schedule.GetWeekdayByRow(56), 5) class PairByRowTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetPairByRow(4), (0, 0)) self.assertEqual(self.schedule.GetPairByRow(5), (1, 0)) self.assertEqual(self.schedule.GetPairByRow(10), (6, 0)) self.assertEqual(self.schedule.GetPairByRow(12), (0, 0)) self.assertEqual(self.schedule.GetPairByRow(28), (0, 0)) self.assertEqual(self.schedule.GetPairByRow(29), (0, 1)) self.assertEqual(self.schedule.GetPairByRow(30), (1, 0)) self.assertEqual(self.schedule.GetPairByRow(33), (3, 1)) self.assertEqual(self.schedule.GetPairByRow(56), (6, 0)) class DepartmentByColumnTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetDepartmentIndexByColumn(2), 0) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(3), 0) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(10), 0) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(13), 1) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(18), 1) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(19), 1) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(22), 2) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(24), 2) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(31), 2) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(39), 4) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(64), 7) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(70), 7) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(73), 8) self.assertEqual(self.schedule.GetDepartmentIndexByColumn(76), 8) class GroupByColumnTest(unittest.TestCase): def setUp(self): self.schedule = schedule_parser.Schedule() self.schedule.Parse(SCHEDULE_PATH) def runTest(self): self.assertEqual(self.schedule.GetGroupIndexByColumn(2), (0, 0)) self.assertEqual(self.schedule.GetGroupIndexByColumn(3), (1, 0)) self.assertEqual(self.schedule.GetGroupIndexByColumn(10), (8, 0)) self.assertEqual(self.schedule.GetGroupIndexByColumn(23), (1, 0)) self.assertEqual(self.schedule.GetGroupIndexByColumn(24), (1, 1)) self.assertEqual(self.schedule.GetGroupIndexByColumn(25), (2, 0)) self.assertEqual(self.schedule.GetGroupIndexByColumn(26), (3, 0)) self.assertEqual(self.schedule.GetGroupIndexByColumn(27), (3, 1)) self.assertEqual(self.schedule.GetGroupIndexByColumn(76), (3, 0)) def suite(): loader = unittest.TestLoader() suite = unittest.TestSuite() suite.addTest(WeekdayRangeTest()) suite.addTest(DepartmentCountTest()) suite.addTest(DepartmentRangeTest()) suite.addTest(DepartmentsRowTest()) suite.addTest(HoursColumnTest()) suite.addTest(HoursRangesTest()) suite.addTest(GroupCountTest()) suite.addTest(GroupListTest()) suite.addTest(GroupRangeTest()) suite.addTest(WeekdayByRowTest()) suite.addTest(PairByRowTest()) suite.addTest(DepartmentByColumnTest()) suite.addTest(GroupByColumnTest()) return suite if __name__ == '__main__': unittest.TextTestRunner(verbosity=2).run(suite())
xairy/mipt-schedule-parser
2
A parser for MIPT .xls schedule
Python
xairy
Andrey Konovalov
setup.py
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages setup(name='mipt-schedule-parser', version='0.1.0', description='Parses standard mipt schedule xls file.', author='Andrey Konovalov', author_email='adech.fo@gmail.com', url='https://github.com/xairy/mipt-schedule-parser', license='MIT license, see LICENSE', long_description=open('README.md').read(), install_requires=[ "xlrd >= 0.6.1", "regex >= 0.1.0", ], packages=find_packages(), package_data={'msp': ['data/subjects', 'data/2013_fall/*', 'data/2014_spring/*', 'data/2014_fall/*']}, include_package_data=True, test_suite = 'msp.test.suite' )
xairy/mipt-schedule-parser
2
A parser for MIPT .xls schedule
Python
xairy
Andrey Konovalov
tools/extracter.py
Python
#!/usr/bin/python #coding: utf-8 from __future__ import unicode_literals import sets import sys import xlrd from cell_parser import * __author__ = "Andrey Konovalov" __copyright__ = "Copyright (C) 2014 Andrey Konovalov" __license__ = "MIT" __version__ = "0.1" files = [ '2014_spring/1.xls', '2014_spring/2.xls', '2014_spring/3.xls', '2014_spring/4.xls', '2014_spring/5.xls' ] def GetValues(file): workbook = xlrd.open_workbook(file, formatting_info=True) worksheet = workbook.sheet_by_index(0) values = sets.Set() for (rb, re, cb, ce) in worksheet.merged_cells: for row in xrange(worksheet.nrows): for col in xrange(worksheet.ncols): value = worksheet.cell_value(row, col) if len(value) >= 4: #value = value.encode('utf-8') values.add(value) return values def StripValues(values): stripped_values = sets.Set() all_values = sets.Set() for file in files: all_values.update(GetValues(file)) for value in sorted(all_values): print value.encode('utf-8')
xairy/mipt-schedule-parser
2
A parser for MIPT .xls schedule
Python
xairy
Andrey Konovalov
tools/find_teacher.py
Python
#!/usr/bin/python #coding: utf-8 from __future__ import unicode_literals import fileinput import regex import sets import sys import urllib2 __author__ = "Andrey Konovalov" __copyright__ = "Copyright (C) 2014 Andrey Konovalov" __license__ = "MIT" __version__ = "0.1" teacher_entry_re = regex.compile( '\<a href="(?P<link>[^"]+)" ' + 'title="(?P<name>[^ ]+ [^ ]+ [^ ]+)">[^\<]+</a> ' + '</div> <div class=\'searchresult\'></div>' ) surname = 'Иванов' initials = ['', ''] def FindTeacher(surname, initials): body = urllib2.urlopen( ('http://wikimipt.org/index.php?search=' + surname).encode('utf-8') ).read().decode('utf-8') results = [] while True: m = teacher_entry_re.search(body) if m == None: break body = body[:m.start('name')] + body[m.end('name'):] results.append((m.group('name'), m.group('link'))) links = [] for result in results: name = result[0].split() if len(name) == 3 and name[0] == surname: if name[1][0] == initials[0] and name[2][0] == initials[1]: links.append('http://wikimipt.org' + result[1]) if initials[0] == '' and initials[1] == '': links.append('http://wikimipt.org' + result[1]) return links if __name__ == '__main__': for name in fileinput.input(): name = name.decode('utf-8').rstrip().split() surname = name[0] initials = ['', ''] if len(name) == 1 else [name[1], name[2]] links = FindTeacher(surname, initials) print ' '.join(links).encode('utf-8')
xairy/mipt-schedule-parser
2
A parser for MIPT .xls schedule
Python
xairy
Andrey Konovalov
tools/scheme.sql
SQL
create table classes( `group` text, subgroup integer, week_day integer, class_number integer, class_half integer, subjects text, locations text, teachers text, `type` integer, raw_data text );
xairy/mipt-schedule-parser
2
A parser for MIPT .xls schedule
Python
xairy
Andrey Konovalov
tools/to_db.py
Python
#!/usr/bin/env python #coding: utf-8 from __future__ import unicode_literals, division, print_function import sys import schedule_parser import cell_parser __author__ = "Alexander Konovalov" __copyright__ = "Copyright (C) 2014 Alexander Konovalov" __license__ = "MIT" __version__ = "0.1" def ParseCell(value): subjects = cell_parser.GetSubjects(value) locations = cell_parser.GetLocations(value) teachers = cell_parser.GetTeachers(value) # Subjects are strings as they are. locations = [cell_parser.LocationToStr(location) for location in locations] teachers = [cell_parser.TeacherToStr(teacher) for teacher in teachers] return ('$'.join(subjects), '$'.join(locations), '$'.join(teachers)) def LoadScheduleToDb(file, conn, cur, cb): schedule = schedule_parser.Schedule() schedule.Parse(file) for department_index in xrange(schedule.GetDepartmentCount()): schedule_tables = [] for weekday_index in xrange(6): schedule_tables.append(schedule.GetScheduleTable(department_index, weekday_index)) group_count = schedule.GetGroupCount(department_index) for group_index in xrange(group_count): group = schedule.GetGroup(department_index, group_index) for weekday_index in xrange(6): classes = schedule_tables[weekday_index][group_index] class_count = len(classes) for class_number in xrange(class_count): for subgroup in xrange(2): for class_half in xrange(2): raw_data = classes[class_number][subgroup][class_half][0] class_type = classes[class_number][subgroup][class_half][1] subjects, locations, teachers = ParseCell(raw_data) cb(cur, (group, subgroup, weekday_index, class_number, class_half, subjects, locations, teachers, class_type, raw_data)) if __name__ == '__main__': args = sys.argv[1:] assert len(args) >= 2 path = args[0] conn = None cur = None add = None if args[1] == "sqlite3": assert len(args) == 3 def add_sqlite3(cur, args): group, subgroup, weekday_index, class_number,\ class_half, subjects, locations, teachers,\ class_type, raw_data = args cur.execute("insert into classes values (" + ":group," + ":subgroup," + ":week_day," + ":class_number," + ":class_half," + ":subjects," + ":locations," + ":teachers," + ":type," + ":raw_data)", {"group": group, "subgroup": subgroup, "week_day": weekday_index, "class_number": class_number, "class_half": class_half, "subjects": subjects, "locations": locations, "teachers": teachers, "type": class_type, "raw_data": raw_data}) import sqlite3 conn = sqlite3.connect(args[2]) cur = conn.cursor() add = add_sqlite3 elif args[1] == "mysql": assert len(args) == 5 def add_mysql(cur, args): group, subgroup, weekday_index, class_number,\ class_half, subjects, locations, teachers,\ class_type, raw_data = args cur.execute("insert into classes values (" + "%(group)s," + "%(subgroup)s," + "%(week_day)s," + "%(class_number)s," + "%(class_half)s," + "%(subjects)s," + "%(locations)s," + "%(teachers)s," + "%(type)s," + "%(raw_data)s)", {"group": group, "subgroup": subgroup, "week_day": weekday_index, "class_number": class_number, "class_half": class_half, "subjects": subjects, "locations": locations, "teachers": teachers, "type": class_type, "raw_data": raw_data}) import MySQLdb import getpass passwd = getpass.getpass() conn = MySQLdb.connect( host=args[2], user=args[3], passwd=passwd, db=args[4], charset='utf8') cur = conn.cursor() add = add_mysql else: assert False LoadScheduleToDb(path, conn, cur, add) conn.commit() cur.close() conn.close()
xairy/mipt-schedule-parser
2
A parser for MIPT .xls schedule
Python
xairy
Andrey Konovalov
src/app.rs
Rust
use piston_window::*; use field; use settings; struct Vec2f { x: f64, y: f64, } pub struct App { settings: settings::Settings, mouse_coords: Vec2f, field: field::Field, selected_cell: Option<field::Coords>, conflicting_cell: Option<field::Coords>, } impl App { pub fn new(settings: settings::Settings) -> App { App { settings, mouse_coords: Vec2f { x: 0.0, y: 0.0 }, field: field::Field::new(), selected_cell: None, conflicting_cell: None, } } pub fn on_render_new(&mut self, c: Context, g: &mut G2d, cache: &mut Glyphs) { clear([1.0; 4], g); let pointed_cell = field::Coords { x: (self.mouse_coords.x / self.settings.cell_size.x).floor() as u8, y: (self.mouse_coords.y / self.settings.cell_size.y).floor() as u8, }; rectangle( [0.95, 0.95, 0.95, 1.0], [ (pointed_cell.x as f64) * self.settings.cell_size.x, (pointed_cell.y as f64) * self.settings.cell_size.y, self.settings.cell_size.x, self.settings.cell_size.y, ], c.transform, g, ); for y in 0..9 { for x in 0..9 { let cell = self.field.get_cell(x, y); if cell.fixed { rectangle( [0.9, 0.9, 0.9, 1.0], [ (x as f64) * self.settings.cell_size.x, (y as f64) * self.settings.cell_size.y, self.settings.cell_size.x, self.settings.cell_size.y, ], c.transform, g, ); } } } if let Some(ref cell) = self.selected_cell { if let Some(digit) = self.field.get_cell(cell.x, cell.y).digit { for y in 0..9 { for x in 0..9 { if let Some(other_digit) = self.field.get_cell(x, y).digit { if other_digit == digit { rectangle( [0.8, 0.8, 0.9, 1.0], [ (x as f64) * self.settings.cell_size.x, (y as f64) * self.settings.cell_size.y, self.settings.cell_size.x, self.settings.cell_size.y, ], c.transform, g, ); } } } } } } if let Some(ref cell) = self.conflicting_cell { rectangle( [0.9, 0.8, 0.8, 1.0], [ (cell.x as f64) * self.settings.cell_size.x, (cell.y as f64) * self.settings.cell_size.y, self.settings.cell_size.x, self.settings.cell_size.y, ], c.transform, g, ); } if let Some(ref cell) = self.selected_cell { rectangle( [0.8, 0.9, 0.8, 1.0], [ (cell.x as f64) * self.settings.cell_size.x, (cell.y as f64) * self.settings.cell_size.y, self.settings.cell_size.x, self.settings.cell_size.y, ], c.transform, g, ); } for y in 0..9 { for x in 0..9 { if let Some(ref digit) = self.field.cells[y][x].digit { let transform = c.transform.trans( (x as f64) * self.settings.cell_size.x + self.settings.text_offset.x, (y as f64) * self.settings.cell_size.y + self.settings.text_offset.y, ); let text = graphics::Text::new(self.settings.font_size); text.draw(&digit.to_string(), cache, &c.draw_state, transform, g) .unwrap(); } } } for n in 1..9 { let mut thick = 2.0; if n % 3 == 0 { thick = 8.0; } rectangle( [0.0, 0.0, 0.0, 1.0], [ (n as f64) * self.settings.cell_size.x - thick / 2.0, 0.0, thick / 2.0, self.settings.wind_size.y, ], c.transform, g, ); rectangle( [0.0, 0.0, 0.0, 1.0], [ 0.0, (n as f64) * self.settings.cell_size.y - thick / 2.0, self.settings.wind_size.x, thick / 2.0, ], c.transform, g, ); } } pub fn on_button_press(&mut self, button: &Button) { match button { Button::Keyboard(key) => { self.on_key_down(key); } Button::Mouse(button) => { self.on_mouse_click(button); } Button::Controller(_) => {} Button::Hat(_) => {} } } fn on_key_down(&mut self, pressed_key: &Key) { let key_digit_mapping = [ (Key::D1, 1), (Key::D2, 2), (Key::D3, 3), (Key::D4, 4), (Key::D5, 5), (Key::D6, 6), (Key::D7, 7), (Key::D8, 8), (Key::D9, 9), (Key::NumPad1, 1), (Key::NumPad2, 2), (Key::NumPad3, 3), (Key::NumPad4, 4), (Key::NumPad5, 5), (Key::NumPad6, 6), (Key::NumPad7, 7), (Key::NumPad8, 8), (Key::NumPad9, 9), ]; for &(key, digit) in key_digit_mapping.iter() { if pressed_key == &key { if let Some(ref cell) = self.selected_cell { if !self.field.get_cell(cell.x, cell.y).fixed { match self.field.find_conflict(cell, digit) { Some(coords) => { self.conflicting_cell = Some(coords); } None => { self.field.get_cell(cell.x, cell.y).digit = Some(digit); self.conflicting_cell = None; } } } } } } if pressed_key == &Key::Backspace { if let Some(ref cell) = self.selected_cell { if !self.field.get_cell(cell.x, cell.y).fixed { self.field.get_cell(cell.x, cell.y).digit = None; self.conflicting_cell = None; } } } if pressed_key == &Key::S { self.field.fill_solution(); self.conflicting_cell = None; self.selected_cell = None; } if pressed_key == &Key::R { self.field.fill_random(); self.conflicting_cell = None; self.selected_cell = None; } if pressed_key == &Key::Up { match self.selected_cell { Some(ref mut cell) => { if cell.y > 0 { cell.y -= 1; } } None => self.selected_cell = Some(field::Coords { x: 0, y: 0 }), } } if pressed_key == &Key::Down { match self.selected_cell { Some(ref mut cell) => { if cell.y < 8 { cell.y += 1; } } None => self.selected_cell = Some(field::Coords { x: 0, y: 0 }), } } if pressed_key == &Key::Left { match self.selected_cell { Some(ref mut cell) => { if cell.x > 0 { cell.x -= 1; } } None => self.selected_cell = Some(field::Coords { x: 0, y: 0 }), } } if pressed_key == &Key::Right { match self.selected_cell { Some(ref mut cell) => { if cell.x < 8 { cell.x += 1; } } None => self.selected_cell = Some(field::Coords { x: 0, y: 0 }), } } } fn on_mouse_click(&mut self, button: &MouseButton) { if let &MouseButton::Left = button { self.selected_cell = Some(field::Coords { x: (self.mouse_coords.x / self.settings.cell_size.x) as u8, y: (self.mouse_coords.y / self.settings.cell_size.y) as u8, }); } } pub fn on_mouse_move(&mut self, args: &[f64; 2]) { self.mouse_coords.x = args[0]; self.mouse_coords.y = args[1]; } }
xairy/rust-sudoku
21
Sudoku game written in Rust with Piston
Rust
xairy
Andrey Konovalov
src/field.rs
Rust
use rand; use rand::seq::SliceRandom; use rand::Rng; pub struct Coords { pub x: u8, pub y: u8, } #[derive(Copy, Clone)] pub struct Cell { pub digit: Option<u8>, pub fixed: bool, } #[derive(Copy, Clone)] pub struct Field { pub cells: [[Cell; 9]; 9], } impl Field { pub fn new() -> Field { let mut field = Field { cells: [[Cell { digit: None, fixed: false, }; 9]; 9], }; field.fill_random(); field } pub fn get_cell(&mut self, x: u8, y: u8) -> &mut Cell { &mut self.cells[y as usize][x as usize] } pub fn find_conflict(&mut self, coords: &Coords, digit: u8) -> Option<Coords> { for x in 0..9 { if x != coords.x { if let Some(cell_digit) = self.get_cell(x, coords.y).digit { if cell_digit == digit { return Some(Coords { x, y: coords.y }); } } } } for y in 0..9 { if y != coords.y { if let Some(cell_digit) = self.get_cell(coords.x, y).digit { if cell_digit == digit { return Some(Coords { x: coords.x, y }); } } } } let section = Coords { x: coords.x / 3, y: coords.y / 3, }; for x in section.x * 3..(section.x + 1) * 3 { for y in section.y * 3..(section.y + 1) * 3 { if x != coords.x || y != coords.y { if let Some(cell_digit) = self.get_cell(x, y).digit { if cell_digit == digit { return Some(Coords { x, y }); } } } } } None } pub fn clear(&mut self) { for y in 0..9 { for x in 0..9 { self.cells[x][y] = Cell { digit: None, fixed: false, }; } } } pub fn fill_random(&mut self) { self.clear(); let x = rand::thread_rng().gen_range(0u8..9u8); let y = rand::thread_rng().gen_range(0u8..9u8); let digit = rand::thread_rng().gen_range(1u8..10u8); self.get_cell(x, y).digit = Some(digit); let solution = self.find_solution().unwrap(); self.cells = solution.cells; loop { let mut x; let mut y; let digit; loop { x = rand::thread_rng().gen_range(0u8..9u8); y = rand::thread_rng().gen_range(0u8..9u8); if self.get_cell(x, y).digit.is_none() { continue; } digit = self.get_cell(x, y).digit.unwrap(); self.get_cell(x, y).digit = None; break; } let solutions = self.find_solutions(2); if solutions.len() == 1 { continue; } self.get_cell(x, y).digit = Some(digit); break; } // FIXME(xairy): generates perfect sudoku, but slow. /* let mut cells = Vec::new(); for y in 0..9 { for x in 0..9 { cells.push((x, y)); } } rand::thread_rng().shuffle(&mut cells); for &(x, y) in cells.iter() { let digit = self.get_cell(x, y).digit.unwrap(); self.get_cell(x, y).digit = None; let solutions = self.find_solutions(2); if solutions.len() > 1 { self.get_cell(x, y).digit = Some(digit); } } */ for y in 0..9 { for x in 0..9 { if self.get_cell(x, y).digit.is_some() { self.get_cell(x, y).fixed = true; } } } } pub fn fill_solution(&mut self) { if let Some(s) = self.find_solution() { self.cells = s.cells; } } pub fn find_solution(&mut self) -> Option<Field> { let solutions = self.find_solutions(1); solutions.first().copied() } fn find_solutions(&mut self, stop_at: u32) -> Vec<Field> { let mut solutions = Vec::new(); let mut field = *self; field.find_solutions_impl(&mut solutions, stop_at); solutions } fn find_solutions_impl(&mut self, solutions: &mut Vec<Field>, stop_at: u32) -> bool { let mut empty_cell: Option<Coords> = None; 'outer: for y in 0..9 { for x in 0..9 { if self.get_cell(x, y).digit.is_none() { empty_cell = Some(Coords { x, y }); break 'outer; } } } if empty_cell.is_none() { solutions.push(*self); return solutions.len() >= (stop_at as usize); } let coords = empty_cell.unwrap(); let mut digits: Vec<u8> = (1..10).collect(); digits.shuffle(&mut rand::thread_rng()); for &digit in digits.iter() { if self.find_conflict(&coords, digit).is_none() { self.get_cell(coords.x, coords.y).digit = Some(digit); if self.find_solutions_impl(solutions, stop_at) { return true; } self.get_cell(coords.x, coords.y).digit = None; } } false } }
xairy/rust-sudoku
21
Sudoku game written in Rust with Piston
Rust
xairy
Andrey Konovalov
src/main.rs
Rust
extern crate piston_window; extern crate rand; use piston_window::*; use std::path::Path; mod app; mod field; mod settings; fn main() { let settings = settings::Settings::new(); let opengl = OpenGL::V3_2; let mut window: PistonWindow = WindowSettings::new( "Sudoku", [(settings.wind_size.x as u32), (settings.wind_size.y as u32)], ) .exit_on_esc(true) .resizable(false) .graphics_api(opengl) .build() .unwrap(); let font_path = Path::new("assets/Verdana.ttf"); let mut cache = window.load_font(font_path).unwrap(); let mut app = app::App::new(settings); while let Some(e) = window.next() { window.draw_2d(&e, |c, g, device| { app.on_render_new(c, g, &mut cache); cache.factory.encoder.flush(device); }); if let Some(button) = e.press_args() { app.on_button_press(&button); } if let Some(args) = e.mouse_cursor_args() { app.on_mouse_move(&args); } } }
xairy/rust-sudoku
21
Sudoku game written in Rust with Piston
Rust
xairy
Andrey Konovalov
src/settings.rs
Rust
pub struct Vec2f { pub x: f64, pub y: f64 } pub struct Settings { pub wind_size: Vec2f, pub cell_size: Vec2f, pub font_size: u32, pub text_offset: Vec2f } impl Settings { pub fn new() -> Settings { Settings { wind_size: Vec2f{ x: 900.0, y: 900.0 }, cell_size: Vec2f{ x: 100.0, y: 100.0 }, font_size: 64, text_offset: Vec2f{ x: 30.0, y: 75.0 } } } }
xairy/rust-sudoku
21
Sudoku game written in Rust with Piston
Rust
xairy
Andrey Konovalov
scripts/convert.js
JavaScript
const fs = require('fs'); const path = require('path'); const strings = fs.readFileSync(path.resolve(__dirname, '../data/strings.txt'), 'utf8').split('\n'); fs.writeFileSync(path.resolve(__dirname, '../src/strings.json'), JSON.stringify(strings, null, 2));
xcatliu/beian.js
0
模拟代码中字符串备案的情形
xcatliu
xcatliu
Tencent
src/index.ts
TypeScript
import beian_strings from './strings.json'; /** * 获取一个经过备案的字符串,如果此字符串未备案,将抛出错误 */ function sb(str: string): string { if(beian_strings.includes(str)) { return str; } else { throw new Error(`字符串 "${str}" 没有经过备案,暂时无法使用`); } } export default sb;
xcatliu/beian.js
0
模拟代码中字符串备案的情形
xcatliu
xcatliu
Tencent
test/blah.test.js
JavaScript
const sb = require('../dist/beian.js.cjs.production.min.js').default; describe('sb', () => { it('works', () => { expect(sb('hello world')).toEqual('hello world'); }); it('no works', () => { expect(() => sb('bye world')).toThrow(); }); });
xcatliu/beian.js
0
模拟代码中字符串备案的情形
xcatliu
xcatliu
Tencent
.eslintrc.js
JavaScript
module.exports = { extends: ['next/core-web-vitals', 'prettier'], rules: { 'import/order': [ 'warn', { groups: ['builtin', 'external', 'internal', 'parent', 'sibling', 'index'], pathGroups: [ { pattern: '@/**', group: 'parent', }, ], 'newlines-between': 'always', alphabetize: { order: 'asc', caseInsensitive: true, }, // 调试了好久 pathGroups 都不生效,最后终于在这个 github issue 里找到解决办法了 // https://github.com/import-js/eslint-plugin-import/issues/1682#issuecomment-608969468 pathGroupsExcludedImportTypes: [], }, ], 'import/no-duplicates': 'warn', // sort-imports 只用开启 memberSort,因为其他的功能都由 import/order 规则实现 'sort-imports': [ 'warn', { ignoreCase: true, ignoreDeclarationSort: true, ignoreMemberSort: false, }, ], 'react/self-closing-comp': 'error', }, overrides: [ { files: ['*.ts', '*.tsx'], parser: '@typescript-eslint/parser', plugins: ['@typescript-eslint'], parserOptions: { project: true, tsconfigRootDir: __dirname, }, rules: { '@typescript-eslint/consistent-type-imports': 'warn', }, }, ], };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
.prettierrc.js
JavaScript
// .prettierrc.js module.exports = { // 一行最多 120 字符 printWidth: 120, // 使用 2 个空格缩进 tabWidth: 2, // 不使用缩进符,而使用空格 useTabs: false, // 行尾需要有分号 semi: true, // 使用单引号 singleQuote: true, // 对象的 key 仅在必要时用引号 quoteProps: 'as-needed', // jsx 不使用单引号,而使用双引号 jsxSingleQuote: false, // 末尾需要有逗号 trailingComma: 'all', // 大括号内的首尾需要空格 bracketSpacing: true, // jsx 标签的反尖括号需要换行 bracketSameLine: false, // 箭头函数,只有一个参数的时候,也需要括号 arrowParens: 'always', // 每个文件格式化的范围是文件的全部内容 rangeStart: 0, rangeEnd: Infinity, // 不需要写文件开头的 @prettier requirePragma: false, // 不需要自动在文件开头插入 @prettier insertPragma: false, // 使用默认的折行标准 proseWrap: 'preserve', // 根据显示样式决定 html 要不要折行 htmlWhitespaceSensitivity: 'css', // vue 文件中的 script 和 style 内不用缩进 vueIndentScriptAndStyle: false, // 换行符使用 lf endOfLine: 'lf', // 格式化嵌入的内容 embeddedLanguageFormatting: 'auto', // html, vue, jsx 中每个属性占一行 singleAttributePerLine: false, };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/api/chat/route.ts
TypeScript
import { createParser } from 'eventsource-parser'; import { cookies } from 'next/headers'; import type { NextRequest } from 'next/server'; import { NextResponse } from 'next/server'; import type { ChatResponseChunk } from '@/utils/constants'; import { HttpHeaderJson, HttpMethod, HttpStatus } from '@/utils/constants'; import { env } from '@/utils/env'; import { getApiKey } from '@/utils/getApiKey'; export const config = { runtime: 'edge', }; export async function POST(req: NextRequest) { if (env.NODE_ENV === 'development') { return NextResponse.json( { error: { code: HttpStatus.BadRequest, message: '中国地区直接请求 OpenAI 接口可能导致封号,所以 dev 环境下跳过了请求。如需发送请求,请将 app/api/chat/route.ts 文件中的相关代码注释掉。', }, }, { status: HttpStatus.BadRequest }, ); } const apiKey = getApiKey(cookies().get('apiKey')?.value); let apiURL = ''; switch (env.CHATGPT_NEXT_API_PROVIDER) { case 'openai': apiURL = `https://${env.CHATGPT_NEXT_API_HOST}/v1/chat/completions`; break; case 'azure': apiURL = `${env.CHATGPT_NEXT_API_AzureAPIURL}/${env.CHATGPT_NEXT_API_AzureAPIURLPath}`; break; default: apiURL = 'unknown'; } const fetchResult = await fetch(apiURL, { method: HttpMethod.POST, headers: { ...HttpHeaderJson, Authorization: `Bearer ${apiKey}`, 'api-key': apiKey ?? '', }, // 直接透传,组装逻辑完全由前端实现 body: req.body, }); // 如果 fetch 返回错误 if (!fetchResult.ok) { // https://stackoverflow.com/a/29082416/2777142 // 当状态码为 401 且响应头包含 Www-Authenticate 时,浏览器会弹一个框要求输入用户名和密码,故这里需要过滤此 header if (fetchResult.status === HttpStatus.Unauthorized && fetchResult.headers.get('Www-Authenticate')) { const wwwAuthenticateValue = fetchResult.headers.get('Www-Authenticate') ?? ''; fetchResult.headers.delete('Www-Authenticate'); fetchResult.headers.set('X-Www-Authenticate', wwwAuthenticateValue); } return fetchResult; } // 生成一个 ReadableStream const stream = new ReadableStream({ async start(controller) { const encoder = new TextEncoder(); const decoder = new TextDecoder(); // 使用 eventsource-parser 库来解析 fetchResult.body const parser = createParser((event) => { if (event.type === 'event') { // 如果接收到的消息是 [DONE] 则表示流式响应结束了 // https://platform.openai.com/docs/api-reference/chat/create#chat/create-stream if (event.data === '[DONE]') { controller.close(); return; } try { // 每个 event.data 都是 JSON 字符串 const chunkJSON: ChatResponseChunk = JSON.parse(event.data); // 获取 delta.content const content = (chunkJSON.choices[0].delta as { content: string }).content; if (content) { controller.enqueue(encoder.encode(content)); } } catch (e) { controller.error(e); } } }); for await (const chunk of fetchResult.body as any as IterableIterator<Uint8Array>) { parser.feed(decoder.decode(chunk)); } }, }); return new Response(stream); }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/api/models/route.ts
TypeScript
import { cookies } from 'next/headers'; import type { NextRequest } from 'next/server'; import { NextResponse } from 'next/server'; import { exampleModelsResponse, HttpHeaderJson, HttpMethod, HttpStatus } from '@/utils/constants'; import { env } from '@/utils/env'; import { getApiKey } from '@/utils/getApiKey'; export const config = { runtime: 'edge', }; /** * 获取可用的 models */ export async function GET(req: NextRequest) { // 测试环境返回 example if (env.NODE_ENV === 'development') { return NextResponse.json(exampleModelsResponse, { status: HttpStatus.OK }); } // 正式环境透传即可 const apiKey = getApiKey(cookies().get('apiKey')?.value); const fetchResult = await fetch(`https://${env.CHATGPT_NEXT_API_HOST}/v1/models`, { method: HttpMethod.GET, headers: { ...HttpHeaderJson, Authorization: `Bearer ${apiKey}`, }, }); // https://stackoverflow.com/a/29082416/2777142 // 当状态码为 401 且响应头包含 Www-Authenticate 时,浏览器会弹一个框要求输入用户名和密码,故这里需要过滤此 header if (fetchResult.status === HttpStatus.Unauthorized && fetchResult.headers.get('Www-Authenticate')) { const wwwAuthenticateValue = fetchResult.headers.get('Www-Authenticate') ?? ''; fetchResult.headers.delete('Www-Authenticate'); fetchResult.headers.set('X-Www-Authenticate', wwwAuthenticateValue); } return fetchResult; }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/components/AttachImage.tsx
TypeScript (TSX)
'use client'; import { XMarkIcon } from '@heroicons/react/24/outline'; import Image from 'next/image'; import type { FC } from 'react'; import { useContext } from 'react'; import { ChatContext } from '@/context/ChatContext'; import { AttachImageButton } from './buttons/AttachImageButton'; export const AttachImage: FC = () => { const { images, deleteImage } = useContext(ChatContext)!; return ( <div className="flex flex-row-reverse items-end"> <AttachImageButton /> {[...images].reverse().map((imageProp, index) => ( <div key={index} className="attach-image-container relative mr-[-28px] z-10 cursor-pointer"> <XMarkIcon className="attach-image-delete absolute top-0 right-0 w-5 h-5 p-0.5 m-0.5 rounded-sm hidden" onClick={() => { // 因为前面将 images revert 了,所以这里需要计算真正的 index deleteImage(images.length - 1 - index); }} /> <Image {...imageProp} className="h-16 w-14 object-cover rounded border-[0.5px] border-gray" alt="图片" /> </div> ))} </div> ); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/components/History.tsx
TypeScript (TSX)
'use client'; import { PlusIcon } from '@heroicons/react/24/outline'; import classNames from 'classnames'; import dayjs from 'dayjs'; import type { FC } from 'react'; import { useContext } from 'react'; import type { HistoryItem } from '@/context/ChatContext'; import { ChatContext } from '@/context/ChatContext'; import { SettingsContext } from '@/context/SettingsContext'; import type { Model } from '@/utils/constants'; import { AllModels, FULL_SPACE } from '@/utils/constants'; import { exportJSON } from '@/utils/export'; import { last } from '@/utils/last'; import { getContentText } from '@/utils/message'; import { DeleteHistoryButton } from './buttons/DeleteHistoryButton'; /** * 聊天记录 */ export const History = () => { const { messages, history, historyIndex, abortSendMessage, startNewChat } = useContext(ChatContext)!; const { settings, setSettings } = useContext(SettingsContext)!; if (messages.length === 0 && (history === undefined || history.length === 0)) { return <div className="my-4 text-center text-gray text-sm">暂无聊天记录</div>; } return ( <> <div className={classNames('history-item-new justify-between hidden md:flex', { 'bg-gray-300 dark:bg-gray-700': historyIndex === 'empty', })} > <div className="leading-[3.5rem]"> 模型: <select value={settings.newChatModel} onChange={(e) => setSettings({ newChatModel: e.target.value as Model, ...(historyIndex === 'empty' ? { model: e.target.value as Model, } : {}), }) } > {AllModels.map((model) => ( <option key={model} disabled={!settings.availableModels.includes(model)}> {model} </option> ))} </select> </div> <button className={classNames('ml-0', { hidden: historyIndex === 'empty', })} onClick={() => { abortSendMessage(); startNewChat(); }} > <PlusIcon /> </button> </div> <ul> {historyIndex === 'current' && <HistoryItemComp historyIndex={historyIndex} isActive={true} />} {history?.map((_, index) => ( <HistoryItemComp key={index} historyIndex={index} isActive={historyIndex === index} /> ))} </ul> <ExportHistory /> </> ); }; /** * 单条聊天记录 */ export const HistoryItemComp: FC<{ historyIndex: 'current' | number; isActive: boolean }> = ({ historyIndex, isActive, }) => { const { messages, history, loadHistory, abortSendMessage } = useContext(ChatContext)!; const { settings } = useContext(SettingsContext)!; let historyItem: HistoryItem; if (historyIndex === 'current') { historyItem = { model: settings.model, messages }; } else if (history === undefined) { return null; } else { historyItem = history[historyIndex]; } return ( <li className={classNames('history-item', { 'hover:bg-gray-200 dark:hover:bg-gray-800': !isActive, 'bg-gray-300 dark:bg-gray-700': isActive, })} onClick={() => { if (historyIndex !== 'current') { abortSendMessage(); loadHistory(historyIndex); } }} > <h3 className="overflow-hidden whitespace-nowrap truncate">{getContentText(historyItem.messages[0])}</h3> <p className={classNames('mt-1 text-gray text-[15px] overflow-hidden whitespace-nowrap truncate', { 'pr-8 md:pr-0': isActive, })} > {historyItem.messages.length > 1 ? getContentText(last(historyItem.messages)) : FULL_SPACE} </p> <DeleteHistoryButton className={classNames('md:hidden', { hidden: !isActive, 'bg-gray-300 dark:bg-gray-700': isActive, 'bg-gray-200 dark:bg-gray-800': !isActive, })} historyIndex={historyIndex} /> </li> ); }; /** * 导出聊天记录 */ export const ExportHistory = () => { const { messages, history } = useContext(ChatContext)!; const { settings } = useContext(SettingsContext)!; let historyWithCurrentMessages = history ?? []; // 如果当前有消息,则将当前消息放入聊天记录中 if (messages.length > 0) { historyWithCurrentMessages = [{ model: settings.model, messages }, ...historyWithCurrentMessages]; } return ( <div className="my-4 text-center text-gray text-sm"> 聊天记录仅会保存在浏览器缓存 <br /> 为避免丢失,请尽快 <a className="text-gray-link" onClick={() => { exportJSON(historyWithCurrentMessages, `ChatGPT-Next-${dayjs().format('YYYYMMDD-HHmmss')}.json`); }} > 导出聊天记录 </a> </div> ); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/components/Menu.tsx
TypeScript (TSX)
'use client'; import { AdjustmentsHorizontalIcon, InboxStackIcon } from '@heroicons/react/24/outline'; import classNames from 'classnames'; import type { FC, ReactNode } from 'react'; import { useCallback, useContext } from 'react'; import { DeviceContext } from '@/context/DeviceContext'; import { MenuContext, MenuKey } from '@/context/MenuContext'; import { useDarkMode } from '@/hooks/useDarkMode'; import { sleep } from '@/utils/sleep'; import { LoginButton } from './buttons/LoginButton'; import { MenuEntryButton } from './buttons/MenuEntryButton'; import { History } from './History'; import { Settings } from './Settings'; /** * 菜单栏 */ export const Menu = () => { const { isWeChat } = useContext(DeviceContext)!; const { isMenuShow } = useContext(MenuContext)!; useDarkMode(); return ( <> <div className={classNames('fixed z-20 top-0 right-0 md:hidden', { absolute: isWeChat, hidden: isMenuShow })}> <MenuEntryButton /> </div> <MenuMask> <MenuTabs /> <MenuTabsContent /> <MenuFooter /> </MenuMask> </> ); }; /** * 菜单栏蒙层 */ const MenuMask: FC<{ children: ReactNode }> = ({ children }) => { const { windowHeight, isMobile } = useContext(DeviceContext)!; const { isMenuShow, setIsMenuShow } = useContext(MenuContext)!; const onTouchMask = useCallback(async () => { setIsMenuShow(false); // 由于 transform 的 fixed 定位失效问题,这里需要手动设置和取消 form-container 的 top await sleep(300); const formContainer = document.getElementById('form-container'); if (formContainer) { formContainer.style.top = 'unset'; } }, [setIsMenuShow]); return ( <> <div // 这是蒙层 className={classNames('fixed z-20 top-0 left-0 w-screen bg-[rgba(0,0,0,0.4)] md:hidden', { hidden: !isMenuShow, })} style={{ height: windowHeight }} onTouchStart={onTouchMask} onClick={onTouchMask} /> <div // 这是菜单栏内容 // 293px 是 768px 的黄金分割点,293 + 16 * 2 = 325 className={classNames('fixed left-[100vw] w-[calc(100vw-6.25rem)] md:block md:static md:w-[325px]', { hidden: !isMenuShow, })} > <div className={`w-inherit fixed flex flex-col bg-gray-100 border-l border-gray md:h-screen md:tall:h-[calc(100vh-12rem)] md:border-l-0 md:border-r dark:bg-gray-900`} style={isMobile ? { height: windowHeight } : {}} > {children} </div> </div> </> ); }; const IconMap = { [MenuKey.InboxStack]: InboxStackIcon, [MenuKey.AdjustmentsHorizontal]: AdjustmentsHorizontalIcon, }; /** * 菜单栏 tabs */ const MenuTabs = () => { const { currentMenu, setCurrentMenu } = useContext(MenuContext)!; return ( <menu className={`w-inherit flex z-10 justify-end bg-chat-100 border-b-[0.5px] border-gray md:flex-row-reverse md:px-4 md:border-r`} > {[MenuKey.InboxStack, MenuKey.AdjustmentsHorizontal].map((key) => { const Icon = IconMap[key]; return ( <button key={key} className={classNames({ 'text-gray-700 hover:text-gray-700': currentMenu === key, 'dark:text-gray-200 dark:hover:text-gray-200': currentMenu === key, })} onClick={() => setCurrentMenu(key)} > <Icon /> </button> ); })} <div className="grow" /> <LoginButton /> </menu> ); }; /** * 菜单栏 tabs 内容 */ const MenuTabsContent = () => { const { currentMenu } = useContext(MenuContext)!; return ( <div className="grow overflow-y-auto md:px-4"> {currentMenu === MenuKey.InboxStack && <History />} {currentMenu === MenuKey.AdjustmentsHorizontal && <Settings />} </div> ); }; /** * 菜单栏底部 */ const MenuFooter = () => { return ( <div className={`flex-none px-4 py-5 text-center text-gray text-sm border-t-[0.5px] border-gray pb-[calc(1.25rem+env(safe-area-inset-bottom))]`} > 由{' '} <a className="text-gray-link" href="https://github.com/xcatliu/chatgpt-next" target="_blank"> ChatGPT Next </a>{' '} 驱动 </div> ); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/components/Message.tsx
TypeScript (TSX)
'use client'; import { UserIcon } from '@heroicons/react/24/outline'; import classNames from 'classnames'; import Image from 'next/image'; import type { FC, ReactNode } from 'react'; import { useCallback, useContext, useState } from 'react'; import { MessageDetailContext } from '@/context/MessageDetailContext'; import { SettingsContext } from '@/context/SettingsContext'; import { MessageContentType, Model, Role } from '@/utils/constants'; import type { ChatResponse, MessageContentItemImageUrl, MessageContentItemText, Message as MessageType, StructuredMessageContentItem, } from '@/utils/constants'; import { formatMessage, FormatMessageMode } from '@/utils/formatMessage'; import { getContent, getRole } from '@/utils/message'; import { disableScroll, scrollToTop } from '@/utils/scroll'; import { ChatGPTIcon } from './icons/ChatGPTIcon'; /** * 单个消息气泡 */ export const Message: FC<MessageType | ChatResponse> = (props) => { const role = getRole(props); const content = getContent(props); const isError = !!(props as MessageType).isError; const isUser = role === Role.user; const isAssistant = role === Role.assistant; let structuredMessageContent: StructuredMessageContentItem[] = []; if (typeof content === 'string') { structuredMessageContent.push({ type: MessageContentType.text, text: content, }); } else { structuredMessageContent = content; } return ( <> {structuredMessageContent.map((messageContent, index) => { if (messageContent.type === MessageContentType.text) { return ( <MessageContentItemTextComp key={index} {...messageContent} isAssistant={isAssistant} isUser={isUser} isError={isError} /> ); } if (messageContent.type === MessageContentType.image_url) { return ( <MessageContentItemImageUrlComp key={index} {...messageContent} isAssistant={isAssistant} isUser={isUser} /> ); } return null; })} </> ); }; /** * 文本消息 */ export const MessageContentItemTextComp: FC< MessageContentItemText & { isAssistant: boolean; isUser: boolean; isError: boolean; } > = (props) => { const { text, isAssistant, isUser, isError } = props; const { settings } = useContext(SettingsContext)!; const { setMessageDetail, setFormatMessageMode } = useContext(MessageDetailContext)!; const [lastTapTime, setLastTapTime] = useState(0); const handleTap = useCallback(() => { const currentTime = new Date().getTime(); const tapLength = currentTime - lastTapTime; if (tapLength < 500 && tapLength > 0) { scrollToTop(); disableScroll(); setMessageDetail(text); setFormatMessageMode(isAssistant ? FormatMessageMode.partial : FormatMessageMode.zero); // 处理双击事件 } else { // 处理单击事件 } setLastTapTime(currentTime); }, [lastTapTime, setLastTapTime, text, setMessageDetail, isAssistant, setFormatMessageMode]); return ( <div className={classNames('relative px-3 my-4 flex', { 'flex-row-reverse': isUser, })} > {isAssistant ? ( <ChatGPTIcon className={classNames('rounded w-10 h-10 p-1 text-white', { 'bg-[#1aa181]': settings.model.startsWith('gpt-5'), 'bg-[#a969f8]': settings.model.startsWith('gpt-4') || settings.model.startsWith('gpt-o1'), })} /> ) : ( <UserIcon className="rounded w-10 h-10 p-1.5 text-black bg-white dark:bg-gray-200" /> )} <div className={classNames('relative mx-3 px-3 py-2 max-w-[calc(100%-6rem)] rounded break-words', { 'message-chatgpt bg-chat-bubble dark:bg-chat-bubble-dark': isAssistant, 'text-gray-900 bg-chat-bubble-green dark:bg-chat-bubble-green-dark': isUser, 'text-red-500': isError, })} dangerouslySetInnerHTML={{ __html: formatMessage(text, isAssistant ? FormatMessageMode.partial : FormatMessageMode.zero), }} onTouchEnd={handleTap} /> {/* 三角箭头 */} <div className={classNames('absolute mx-2.5 my-3.5 border-solid border-y-transparent border-y-[6px]', { 'right-12 border-r-0 border-l-[6px] border-l-chat-bubble-green dark:border-l-chat-bubble-green-dark': isUser, 'left-12 border-l-0 border-r-[6px] border-r-chat-bubble dark:border-r-chat-bubble-dark': isAssistant, })} /> </div> ); }; /** * 图片消息 */ export const MessageContentItemImageUrlComp: FC< MessageContentItemImageUrl & { isAssistant: boolean; isUser: boolean; } > = (props) => { const { image_url, isAssistant, isUser } = props; const { settings } = useContext(SettingsContext)!; return ( <div className={classNames('relative px-3 my-4 flex', { 'flex-row-reverse': isUser, })} > {isAssistant ? ( <ChatGPTIcon className={classNames('rounded w-10 h-10 p-1 text-white', { 'bg-[#1aa181]': settings.model.startsWith('gpt-5'), 'bg-[#a969f8]': settings.model.startsWith('gpt-4') || settings.model.startsWith('gpt-o1'), })} /> ) : ( <UserIcon className="rounded w-10 h-10 p-1.5 text-black bg-white dark:bg-gray-200" /> )} <Image src={image_url.url} alt="图片" className="mx-3 max-w-[calc(100%-6rem)]" width={image_url.width / 4 ?? 192} height={image_url.height / 4 ?? 192} /> </div> ); }; /** * 系统消息 */ export const SystemMessage: FC<{ children: ReactNode }> = ({ children }) => { return <div className="px-14 my-4 text-center text-gray text-sm">{children}</div>; };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/components/MessageDetail.tsx
TypeScript (TSX)
'use client'; import { XMarkIcon } from '@heroicons/react/24/outline'; import classNames from 'classnames'; import React, { useContext } from 'react'; import { DeviceContext } from '@/context/DeviceContext'; import { MessageDetailContext } from '@/context/MessageDetailContext'; import { formatMessage, FormatMessageMode } from '@/utils/formatMessage'; import { enableScroll } from '@/utils/scroll'; export const MessageDetail = () => { const { messageDetail, setMessageDetail, formatMessageMode, setFormatMessageMode } = useContext(MessageDetailContext)!; const { windowWidth, windowHeight } = useContext(DeviceContext)!; if (messageDetail === undefined) { return null; } return ( <div className="fixed z-30 top-0 left-0 pt-0 pb-4 bg-chat-bubble dark:bg-chat-bubble-dark overflow-auto" style={{ width: windowWidth, height: windowHeight, }} > <div className="flex"> <div className="flex-grow" /> <button className="flex" onClick={() => { const revertFormatMessageMode = { [FormatMessageMode.zero]: FormatMessageMode.partial, [FormatMessageMode.partial]: FormatMessageMode.zero, }; setFormatMessageMode(revertFormatMessageMode[formatMessageMode]); }} > <span className={classNames('px-0.5 -mx-[3px] -my-[1px] border rounded text-sm', { 'border-gray-300 text-gray-300': formatMessageMode === FormatMessageMode.zero, 'border-green-600 text-green-600': formatMessageMode === FormatMessageMode.partial, })} > md </span> </button> <button className="text-gray-700 dark:text-gray-200" onClick={() => { setMessageDetail(undefined); enableScroll(); }} > <XMarkIcon /> </button> </div> <div className="px-3 py-2 message-chatgpt" dangerouslySetInnerHTML={{ __html: formatMessage(messageDetail, formatMessageMode), }} /> </div> ); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/components/Messages.tsx
TypeScript (TSX)
'use client'; import { useContext, useEffect } from 'react'; import { ChatContext } from '@/context/ChatContext'; import { SettingsContext } from '@/context/SettingsContext'; import { Role } from '@/utils/constants'; // import { exampleMessages } from '@/utils/exampleMessages'; import { initEventListenerScroll } from '@/utils/scroll'; import { Message, SystemMessage } from './Message'; const SYSTEM_MESSAGE = ( <> 本页面会将数据发送给 OpenAI <br /> 请注意隐私风险,禁止发送违法内容 </> ); const WELCOME_MESSAGE = '你好!有什么我可以帮助你的吗?'; const LOADING_MESSAGE = '正在努力思考...'; export const Messages = () => { const { settings } = useContext(SettingsContext)!; let { isLoading, messages, history, historyIndex, startNewChat, abortSendMessage } = useContext(ChatContext)!; // 初始化滚动事件 useEffect(initEventListenerScroll, []); // 如果当前在浏览聊天记录,则展示该聊天记录的 messages if (history && typeof historyIndex === 'number') { messages = history[historyIndex].messages; } // messages = exampleMessages; return ( <div className="md:grow" style={{ display: 'flow-root' }}> <SystemMessage>{SYSTEM_MESSAGE}</SystemMessage> <Message role={Role.assistant} content={WELCOME_MESSAGE} /> {!settings.model.startsWith('o1') && [...(settings.systemMessage ? [settings.systemMessage] : []), ...(settings.prefixMessages ?? [])].map( (message, index) => ( <SystemMessage key={index}> {message.role}: {message.content} </SystemMessage> ), )} {messages.map((message, index) => ( <Message key={index} {...message} /> ))} {isLoading && <Message role={Role.assistant} content={LOADING_MESSAGE} />} {messages.length > 1 && ( <SystemMessage> 连续对话会加倍消耗 tokens, <a className="text-gray-link" onClick={() => { abortSendMessage(); startNewChat(); }} > 开启新对话 </a> </SystemMessage> )} </div> ); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/components/Settings.tsx
TypeScript (TSX)
'use client'; import { useContext } from 'react'; import { ChatContext } from '@/context/ChatContext'; import { SettingsContext } from '@/context/SettingsContext'; import type { Model } from '@/utils/constants'; import { AllModels, Role } from '@/utils/constants'; /** * 聊天记录 */ export const Settings = () => { const { settings, setSettings, resetSettings } = useContext(SettingsContext)!; const { historyIndex } = useContext(ChatContext)!; return ( <div> <h2 className="m-4 text-lg">配置选项</h2> <div className="m-4"> 模型: <select value={settings.model} onChange={(e) => setSettings({ model: e.target.value as Model, ...(historyIndex === 'empty' ? { newChatModel: e.target.value as Model, } : {}), }) } disabled={historyIndex !== 'empty'} > {AllModels.map((model) => ( <option key={model} disabled={!settings.availableModels.includes(model)}> {model} </option> ))} </select> {historyIndex !== 'empty' && <p className="mt-1 ml-12 text-sm text-gray">已开启的对话不支持修改模型</p>} </div> <div className="m-4"> 历史长度: <input className="w-36 mr-2" type="range" step={2} min={0} max={20} value={settings.maxHistoryLength} onChange={(e) => setSettings({ maxHistoryLength: Number(e.target.value) })} /> {settings.maxHistoryLength} </div> <div className="m-4"> 温度: <input className="w-36 mr-2" type="range" step={0.1} min={0} max={2} value={settings.temperature ?? 1} onChange={(e) => setSettings({ temperature: Number(e.target.value) })} /> {settings.temperature ?? 1} </div> <div className="m-4"> top_p: <input className="w-36 mr-2" type="range" step={0.1} min={0} max={1} value={settings.top_p ?? 1} onChange={(e) => setSettings({ top_p: Number(e.target.value) })} /> {settings.top_p ?? 1} </div> <div className="m-4"> 存在惩罚: <input className="w-36 mr-2" type="range" step={0.1} min={-2} max={2} value={settings.presence_penalty ?? 0} onChange={(e) => setSettings({ presence_penalty: Number(e.target.value) })} /> {settings.presence_penalty ?? 0} </div> <div className="m-4"> 频率惩罚: <input className="w-36 mr-2" type="range" step={0.1} min={-2} max={2} value={settings.frequency_penalty ?? 0} onChange={(e) => setSettings({ frequency_penalty: Number(e.target.value) })} /> {settings.frequency_penalty ?? 0} </div> <div className="m-4"> 系统消息: <input className="block px-3 py-2 my-2 w-full border border-gray" disabled={settings.model.startsWith('o1')} placeholder={settings.model.startsWith('o1') ? 'o1 模型不支持系统消息' : undefined} type="text" value={settings.systemMessage?.content ?? ''} onChange={(e) => { if (e.target.value === '') { setSettings({ systemMessage: undefined }); } else { setSettings({ systemMessage: { role: Role.system, content: e.target.value } }); } }} /> </div> <div className="m-4"> 前置消息: <input className="block px-3 py-2 my-2 w-full border border-gray" type="text" value={settings.prefixMessages?.[0].content ?? ''} onChange={(e) => { if (e.target.value === '') { setSettings({ prefixMessages: undefined }); } else { setSettings({ prefixMessages: [{ role: Role.user, content: e.target.value }] }); } }} /> </div> <input className="m-4 mt-0 px-3 py-2" type="button" onClick={() => resetSettings()} value="重置所有配置" /> </div> ); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/components/TextareaForm.tsx
TypeScript (TSX)
'use client'; import classNames from 'classnames'; import type { FC, FormEvent, KeyboardEvent } from 'react'; import { useCallback, useContext, useEffect, useRef, useState } from 'react'; import { ChatContext } from '@/context/ChatContext'; import { DeviceContext } from '@/context/DeviceContext'; import { LoginContext } from '@/context/LoginContext'; import { SettingsContext } from '@/context/SettingsContext'; import { VisionModels } from '@/utils/constants'; import { readImageFile } from '@/utils/image'; import { isDomChildren } from '@/utils/isDomChildren'; import { AttachImage } from './AttachImage'; export const TextareaForm: FC = () => { const { isMobile } = useContext(DeviceContext)!; const { isLogged } = useContext(LoginContext)!; const { settings } = useContext(SettingsContext)!; const { images, appendImages, sendMessage, abortSendMessage } = useContext(ChatContext)!; // 是否正在中文输入 const [isComposing, setIsComposing] = useState(false); const [isTextareaEmpty, setIsTextareaEmpty] = useState(true); const formContainerRef = useRef<HTMLDivElement>(null); const placeholderRef = useRef<HTMLDivElement>(null); const textareaRef = useRef<HTMLTextAreaElement>(null); // touchstart textarea 外部时,执行 blur useEffect(() => { document.addEventListener('touchstart', (e) => { const targetElement = e.target as HTMLElement; // 如果 textarea 当前不是 focus 状态,则跳过 if (textareaRef.current !== document.activeElement) { return; } // 如果触碰的是 form 内,则跳过 if (isDomChildren(formContainerRef.current, targetElement)) { return; } // 如果触碰的是 form 外,则 blur textarea textareaRef.current?.blur(); }); }, []); /** * Handle pasting images into the textarea */ const handlePaste = useCallback( async (e: React.ClipboardEvent<HTMLTextAreaElement>) => { // 仅在 vision 模式下支持粘贴图片 if (!VisionModels.includes(settings.model)) { return; } const items = e.clipboardData?.items; if (items) { for (let i = 0; i < items.length; i++) { if (items[i].type.indexOf('image') === 0) { const file = items[i].getAsFile(); if (file == null) { throw new Error('Expected file'); } const image = await readImageFile(file); appendImages(image); } } } }, [settings, appendImages], ); /** * 更新 textarea 的 empty 状态 */ const updateIsTextareaEmpty = useCallback(() => { const value = textareaRef.current?.value?.trim(); if (value) { setIsTextareaEmpty(false); } else { setIsTextareaEmpty(true); } }, []); /** * 更新 textarea 的高度 */ const updateTextareaHeight = useCallback(() => { const textareaElement = textareaRef.current; if (!textareaElement) { return; } // https://stackoverflow.com/a/24676492/2777142 textareaElement.style.height = '5px'; // 260 是十行半的高度,8 + 24 * 10.5 = 260 const newHeight = Math.min(textareaElement.scrollHeight, 260); textareaElement.style.height = `${newHeight}px`; if (placeholderRef.current) { placeholderRef.current.style.height = `${newHeight}px`; } }, []); useEffect(() => { updateTextareaHeight(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [images.length]); /** * 输入内容触发 */ const onChange = useCallback(() => { updateTextareaHeight(); // 保持滚动到最底下,bug 太多,先关闭 // scrollToBottom(); updateIsTextareaEmpty(); }, [updateTextareaHeight, updateIsTextareaEmpty]); /** 中文输入法控制 */ const onCompositionStart = useCallback(() => setIsComposing(true), []); const onCompositionEnd = useCallback(() => { setIsComposing(false); // 由于 onChange 和 onCompositionEnd 的时序问题,这里也需要调用 updateSubmitDisabled updateIsTextareaEmpty(); }, [updateIsTextareaEmpty]); /** * 提交表单处理 */ const formOnSubmit = useCallback( async (e?: FormEvent<HTMLFormElement>) => { e?.preventDefault(); const value = textareaRef.current?.value?.trim(); // 提交后清空内容 if (textareaRef.current?.value) { textareaRef.current.value = ''; } updateTextareaHeight(); updateIsTextareaEmpty(); abortSendMessage(); await sendMessage(value); }, [sendMessage, abortSendMessage, updateTextareaHeight, updateIsTextareaEmpty], ); /** * 修改回车默认行为 */ const onKeyDone = useCallback( (e: KeyboardEvent<HTMLTextAreaElement>) => { // 如果正在中文输入,则跳过 keyDone 事件 if (isComposing) { return; } // [Ctrl/Cmd + Enter] 发送消息 if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); formOnSubmit(); return; } // PC 端,回车发送消息 if (!isMobile && e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.altKey) { e.preventDefault(); formOnSubmit(); return; } }, [isMobile, isComposing, formOnSubmit], ); return ( <> <div className="pb-[env(safe-area-inset-bottom)] pt-5 md:pt-8"> <div placeholder="" className="h-10 md:h-16" ref={placeholderRef} /> </div> <div className={`w-inherit fixed z-10 bottom-0 px-3 pt-2.5 bg-gray-100 border-t-[0.5px] border-gray pb-[calc(0.625rem+env(safe-area-inset-bottom))] md:tall:bottom-24 md:px-[1.75rem] md:-mx-4 md:py-4 dark:bg-gray-900`} ref={formContainerRef} id="form-container" > <form className="flex space-x-2" onSubmit={formOnSubmit}> <textarea className={classNames( `flex-grow px-3 py-2 resize-none bg-chat-bubble placeholder:text-gray-400 disabled:bg-gray-200 disabled:cursor-not-allowed md:min-h-[4rem] dark:bg-chat-bubble-dark dark:disabled:bg-gray-700 dark:placeholder:text-gray-500`, { 'min-h-[4rem]': images.length > 0, }, )} ref={textareaRef} disabled={!isLogged} placeholder={isLogged ? '' : isMobile ? '请点击右上角设置密钥' : '请点击左上角钥匙按钮设置密钥'} onChange={onChange} onKeyDown={onKeyDone} onCompositionStart={onCompositionStart} onCompositionEnd={onCompositionEnd} onPaste={handlePaste} rows={1} /> {VisionModels.includes(settings.model) && <AttachImage />} <div className="flex items-end"> <input className={classNames('px-3 py-2 h-10 md:h-16', { 'h-16': images.length > 0, })} type="submit" disabled={isTextareaEmpty && images.length === 0} value="发送" /> </div> </form> </div> </> ); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/components/Title.tsx
TypeScript (TSX)
import { headers } from 'next/headers'; import { isWeChat as utilIsWeChat } from '@/utils/device'; export const Title = () => { const userAgent = headers().get('user-agent') ?? ''; const isWeChat = utilIsWeChat(userAgent); if (isWeChat) { return null; } return ( <> <div placeholder="" className="h-14" /> <h1 className={`w-inherit fixed z-10 top-0 py-3.5 bg-chat-bg text-center text-lg border-b-[0.5px] border-gray md:tall:top-24 md:-mx-4 dark:bg-chat-bg-dark`} > ChatGPT Next </h1> </> ); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/components/buttons/AttachImageButton.tsx
TypeScript (TSX)
import { PhotoIcon, PlusIcon } from '@heroicons/react/24/outline'; import classNames from 'classnames'; import type { FC } from 'react'; import { useContext } from 'react'; import { ChatContext } from '@/context/ChatContext'; import { LoginContext } from '@/context/LoginContext'; import { MAX_GPT_VISION_IMAGES } from '@/utils/constants'; import { readImageFile } from '@/utils/image'; /** * 添加图片 */ export const AttachImageButton: FC<{}> = () => { const { images, appendImages } = useContext(ChatContext)!; const { isLogged } = useContext(LoginContext)!; return ( <> <label htmlFor="input-attach-image" className={classNames('button-attach-image flex items-center w-10 h-10 md:w-14 md:h-16', { disabled: !isLogged || images.length >= MAX_GPT_VISION_IMAGES, 'justify-center': images.length === 0, 'justify-end w-14 h-16': images.length > 0, })} > {images.length === 0 ? <PhotoIcon className="w-9 h-9 p-2" /> : <PlusIcon className="w-9 h-9 p-2" />} </label> <input id="input-attach-image" type="file" multiple accept="image/jpeg, image/png" disabled={!isLogged || images.length >= MAX_GPT_VISION_IMAGES} className="hidden" onChange={async (e) => { const files = e.target.files; // 确保文件已被选择 if (files === null || files.length === 0) { return; } const images = await Promise.all(Array.from(files).map(readImageFile)); appendImages(...images); // https://stackoverflow.com/a/56258902 e.target.value = ''; }} /> </> ); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/components/buttons/DeleteHistoryButton.tsx
TypeScript (TSX)
import { TrashIcon } from '@heroicons/react/24/outline'; import classNames from 'classnames'; import type { FC } from 'react'; import { useContext } from 'react'; import { ChatContext } from '@/context/ChatContext'; /** * 删除聊天记录 */ export const DeleteHistoryButton: FC<{ className?: string; historyIndex: 'current' | number }> = ({ className, historyIndex, }) => { const { deleteHistory } = useContext(ChatContext)!; return ( <button className={classNames(className, 'absolute bottom-0 right-0')} onClick={(e) => { // 点击删除时,阻止冒泡 e.stopPropagation(); deleteHistory(historyIndex); }} > <TrashIcon /> </button> ); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/components/buttons/LoginButton.tsx
TypeScript (TSX)
import { KeyIcon } from '@heroicons/react/24/outline'; import classNames from 'classnames'; import { useCallback, useContext } from 'react'; import { LoginContext } from '@/context/LoginContext'; import { sleep } from '@/utils/sleep'; /** * 登录按钮 */ export const LoginButton = () => { const { isLogged, login, logout } = useContext(LoginContext)!; /** * 点击钥匙按钮,弹出重新登录框 */ const onKeyIconClick = useCallback(async () => { // 如果未登录,则弹窗登录 if (!isLogged) { await login(); return; } // 如果已登录,则弹窗登出 const logoutResult = await logout(); // 如果登出成功,则继续弹窗要求用户登录 if (logoutResult) { await sleep(100); await login(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [isLogged]); return ( <button className={classNames({ 'text-green-600 hover:text-green-700': isLogged, 'text-red-500 hover:text-red-600': !isLogged, })} onClick={onKeyIconClick} > <KeyIcon /> </button> ); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/components/buttons/MenuEntryButton.tsx
TypeScript (TSX)
import { AdjustmentsHorizontalIcon, InboxStackIcon } from '@heroicons/react/24/outline'; import { useContext } from 'react'; import { ChatContext } from '@/context/ChatContext'; import { LoginContext } from '@/context/LoginContext'; import { MenuContext, MenuKey } from '@/context/MenuContext'; import { scrollToTop } from '@/utils/scroll'; import { LoginButton } from './LoginButton'; /** * 显示菜单栏的入口按钮,仅在移动端需要显示/隐藏菜单栏 */ export const MenuEntryButton = () => { const { isLogged } = useContext(LoginContext)!; const { history } = useContext(ChatContext)!; const { setIsMenuShow, setCurrentMenu } = useContext(MenuContext)!; if (!isLogged) { return <LoginButton />; } if (history === undefined) { return null; } if (history.length > 0) { return ( <button onClick={() => { scrollToTop(); setCurrentMenu(MenuKey.InboxStack); setIsMenuShow(true); }} > <InboxStackIcon /> </button> ); } return ( <button onClick={() => { scrollToTop(); setCurrentMenu(MenuKey.AdjustmentsHorizontal); setIsMenuShow(true); }} > <AdjustmentsHorizontalIcon /> </button> ); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/components/icons/ChatGPTIcon.tsx
TypeScript (TSX)
import type { FC } from 'react'; import React from 'react'; export const ChatGPTIcon: FC<{ className?: string; }> = ({ className }) => ( <svg width="41" height="41" viewBox="0 0 41 41" fill="none" xmlns="http://www.w3.org/2000/svg" strokeWidth="1.5" className={className} role="img" > <title>ChatGPT</title> <text x="-9999" y="-9999"> ChatGPT </text> <path d="M37.5324 16.8707C37.9808 15.5241 38.1363 14.0974 37.9886 12.6859C37.8409 11.2744 37.3934 9.91076 36.676 8.68622C35.6126 6.83404 33.9882 5.3676 32.0373 4.4985C30.0864 3.62941 27.9098 3.40259 25.8215 3.85078C24.8796 2.7893 23.7219 1.94125 22.4257 1.36341C21.1295 0.785575 19.7249 0.491269 18.3058 0.500197C16.1708 0.495044 14.0893 1.16803 12.3614 2.42214C10.6335 3.67624 9.34853 5.44666 8.6917 7.47815C7.30085 7.76286 5.98686 8.3414 4.8377 9.17505C3.68854 10.0087 2.73073 11.0782 2.02839 12.312C0.956464 14.1591 0.498905 16.2988 0.721698 18.4228C0.944492 20.5467 1.83612 22.5449 3.268 24.1293C2.81966 25.4759 2.66413 26.9026 2.81182 28.3141C2.95951 29.7256 3.40701 31.0892 4.12437 32.3138C5.18791 34.1659 6.8123 35.6322 8.76321 36.5013C10.7141 37.3704 12.8907 37.5973 14.9789 37.1492C15.9208 38.2107 17.0786 39.0587 18.3747 39.6366C19.6709 40.2144 21.0755 40.5087 22.4946 40.4998C24.6307 40.5054 26.7133 39.8321 28.4418 38.5772C30.1704 37.3223 31.4556 35.5506 32.1119 33.5179C33.5027 33.2332 34.8167 32.6547 35.9659 31.821C37.115 30.9874 38.0728 29.9178 38.7752 28.684C39.8458 26.8371 40.3023 24.6979 40.0789 22.5748C39.8556 20.4517 38.9639 18.4544 37.5324 16.8707ZM22.4978 37.8849C20.7443 37.8874 19.0459 37.2733 17.6994 36.1501C17.7601 36.117 17.8666 36.0586 17.936 36.0161L25.9004 31.4156C26.1003 31.3019 26.2663 31.137 26.3813 30.9378C26.4964 30.7386 26.5563 30.5124 26.5549 30.2825V19.0542L29.9213 20.998C29.9389 21.0068 29.9541 21.0198 29.9656 21.0359C29.977 21.052 29.9842 21.0707 29.9867 21.0902V30.3889C29.9842 32.375 29.1946 34.2791 27.7909 35.6841C26.3872 37.0892 24.4838 37.8806 22.4978 37.8849ZM6.39227 31.0064C5.51397 29.4888 5.19742 27.7107 5.49804 25.9832C5.55718 26.0187 5.66048 26.0818 5.73461 26.1244L13.699 30.7248C13.8975 30.8408 14.1233 30.902 14.3532 30.902C14.583 30.902 14.8088 30.8408 15.0073 30.7248L24.731 25.1103V28.9979C24.7321 29.0177 24.7283 29.0376 24.7199 29.0556C24.7115 29.0736 24.6988 29.0893 24.6829 29.1012L16.6317 33.7497C14.9096 34.7416 12.8643 35.0097 10.9447 34.4954C9.02506 33.9811 7.38785 32.7263 6.39227 31.0064ZM4.29707 13.6194C5.17156 12.0998 6.55279 10.9364 8.19885 10.3327C8.19885 10.4013 8.19491 10.5228 8.19491 10.6071V19.808C8.19351 20.0378 8.25334 20.2638 8.36823 20.4629C8.48312 20.6619 8.64893 20.8267 8.84863 20.9404L18.5723 26.5542L15.206 28.4979C15.1894 28.5089 15.1703 28.5155 15.1505 28.5173C15.1307 28.5191 15.1107 28.516 15.0924 28.5082L7.04046 23.8557C5.32135 22.8601 4.06716 21.2235 3.55289 19.3046C3.03862 17.3858 3.30624 15.3413 4.29707 13.6194ZM31.955 20.0556L22.2312 14.4411L25.5976 12.4981C25.6142 12.4872 25.6333 12.4805 25.6531 12.4787C25.6729 12.4769 25.6928 12.4801 25.7111 12.4879L33.7631 17.1364C34.9967 17.849 36.0017 18.8982 36.6606 20.1613C37.3194 21.4244 37.6047 22.849 37.4832 24.2684C37.3617 25.6878 36.8382 27.0432 35.9743 28.1759C35.1103 29.3086 33.9415 30.1717 32.6047 30.6641C32.6047 30.5947 32.6047 30.4733 32.6047 30.3889V21.188C32.6066 20.9586 32.5474 20.7328 32.4332 20.5338C32.319 20.3348 32.154 20.1698 31.955 20.0556ZM35.3055 15.0128C35.2464 14.9765 35.1431 14.9142 35.069 14.8717L27.1045 10.2712C26.906 10.1554 26.6803 10.0943 26.4504 10.0943C26.2206 10.0943 25.9948 10.1554 25.7963 10.2712L16.0726 15.8858V11.9982C16.0715 11.9783 16.0753 11.9585 16.0837 11.9405C16.0921 11.9225 16.1048 11.9068 16.1207 11.8949L24.1719 7.25025C25.4053 6.53903 26.8158 6.19376 28.2383 6.25482C29.6608 6.31589 31.0364 6.78077 32.2044 7.59508C33.3723 8.40939 34.2842 9.53945 34.8334 10.8531C35.3826 12.1667 35.5464 13.6095 35.3055 15.0128ZM14.2424 21.9419L10.8752 19.9981C10.8576 19.9893 10.8423 19.9763 10.8309 19.9602C10.8195 19.9441 10.8122 19.9254 10.8098 19.9058V10.6071C10.8107 9.18295 11.2173 7.78848 11.9819 6.58696C12.7466 5.38544 13.8377 4.42659 15.1275 3.82264C16.4173 3.21869 17.8524 2.99464 19.2649 3.1767C20.6775 3.35876 22.0089 3.93941 23.1034 4.85067C23.0427 4.88379 22.937 4.94215 22.8668 4.98473L14.9024 9.58517C14.7025 9.69878 14.5366 9.86356 14.4215 10.0626C14.3065 10.2616 14.2466 10.4877 14.2479 10.7175L14.2424 21.9419ZM16.071 17.9991L20.4018 15.4978L24.7325 17.9975V22.9985L20.4018 25.4983L16.071 22.9985V17.9991Z" fill="currentColor" /> </svg> );
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/context/ChatContext.tsx
TypeScript (TSX)
'use client'; import omit from 'lodash.omit'; import type { FC, ReactNode } from 'react'; import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'; import { fetchApiChat } from '@/utils/api'; import { getCache, setCache } from '@/utils/cache'; import type { ChatResponse, Message, StructuredMessageContentItem } from '@/utils/constants'; import { MAX_GPT_VISION_IMAGES, MessageContentType, Model, Role } from '@/utils/constants'; import type { ResError } from '@/utils/error'; import type { ImageProp } from '@/utils/image'; import { isMessage } from '@/utils/message'; import { gapToBottom, getIsScrolling, scrollToBottom } from '@/utils/scroll'; import { sleep } from '@/utils/sleep'; import { MenuContext, MenuKey } from './MenuContext'; import type { SettingsState } from './SettingsContext'; import { SettingsContext } from './SettingsContext'; /** * 聊天记录 */ export interface HistoryItem { model: Model; messages: (Message | ChatResponse)[]; } /** * 对话相关的 Context */ export const ChatContext = createContext<{ sendMessage: (content?: string) => Promise<void>; abortSendMessage: () => void; isLoading: boolean; messages: (Message | ChatResponse)[]; images: ImageProp[]; appendImages: (...images: ImageProp[]) => void; deleteImage: (index: number) => void; history: HistoryItem[] | undefined; historyIndex: 'empty' | 'current' | number; loadHistory: (historyIndex: number) => void; deleteHistory: (historyIndex: 'current' | number) => void; startNewChat: () => void; } | null>(null); export const ChatProvider: FC<{ children: ReactNode }> = ({ children }) => { const { setIsMenuShow, setCurrentMenu } = useContext(MenuContext)!; const { settings, setSettings } = useContext(SettingsContext)!; const [isLoading, setIsLoading] = useState(false); const [messages, setMessages] = useState<(Message | ChatResponse)[]>([]); const [images, setImages] = useState<ImageProp[]>([]); const [history, setHistory] = useState<HistoryItem[] | undefined>(undefined); // 当前选中的对话在 history 中的 index,empty 表示未选中,current 表示选中的是当前对话 const [historyIndex, setHistoryIndex] = useState<'empty' | 'current' | number>('empty'); // 控制请求中断 const [abortController, setAbortController] = useState<AbortController>(); // 页面加载后从 cache 中读取 history 和 messages // 如果 messages 不为空,则将最近的一条消息写入 history useEffect(() => { let history = getCache<HistoryItem[]>('history'); let messages = getCache<(Message | ChatResponse)[]>('messages'); let settings = getCache<SettingsState>('settings'); // 如果检测到缓存中有上次还未存储到 cache 的 message,则加入到 history 中 if (messages && messages.length > 0) { history = [{ model: settings?.model ?? Model['gpt-4o'], messages }, ...(history ?? [])]; setHistory(history); setCache('history', history); setMessages([]); setCache('messages', []); } // 根据 history 是否存在决定当前 menu tab 是什么 if (history === undefined) { // 如果不存在 history,则当前 menu 是参数配置 tab setHistory([]); setCurrentMenu(MenuKey.AdjustmentsHorizontal); } else { // 如果存在 history,则当前 menu 是聊天记录 tab setHistory(history); setCurrentMenu(MenuKey.InboxStack); } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); /** * 发送消息 */ const sendMessage = useCallback( async (content?: string) => { // 如果是空消息 if ((content === undefined || content.length === 0) && images.length === 0) { return; } // 先获取旧的 messages 的备份 let newMessages = [...messages]; // 如果当前是在浏览聊天记录,则激活历史消息 if (typeof historyIndex === 'number') { const newHistory = [...(history ?? [])]; newMessages = [...newHistory.splice(historyIndex, 1)[0].messages]; setHistory(newHistory); setCache('history', newHistory); setMessages(newMessages); setCache('messages', newMessages); } let newMessage: Message; // 没图片时,插入单条文字消息 if (images.length === 0) { newMessage = { role: Role.user, content: content as string, }; } // 有图片时则插入混合消息 else { newMessage = { role: Role.user, content: images.map((image) => ({ type: MessageContentType.image_url, image_url: { url: image.src, width: image.width, height: image.height, }, })), }; // 如果有文字,则在最前面插入文字消息 if (content) { newMessage.content = [ { type: MessageContentType.text, text: content, }, ...(newMessage.content as StructuredMessageContentItem[]), ]; } } // 先插入一条用户消息 newMessages = [...newMessages, newMessage]; setMessages(newMessages); setCache('messages', newMessages); // 清空已上传的图片 setImages([]); setIsLoading(true); setHistoryIndex('current'); await sleep(16); scrollToBottom(); try { // stream 模式下,由前端组装消息 let partialContent = ''; const fetchApiChatMessages = newMessages // 过滤掉 isError 的消息 .filter((message) => !(message as Message).isError) .slice(-(settings.maxHistoryLength + 1)) .map((message) => { return isMessage(message) ? message : message.choices[0].message; }); // 如果有前置消息,则写入到最前面 if (settings.prefixMessages && settings.prefixMessages.length > 0) { fetchApiChatMessages.unshift(...settings.prefixMessages); } // 如果有系统消息,则写入到最前面 if (!settings.model.startsWith('o1') && settings.systemMessage) { fetchApiChatMessages.unshift(settings.systemMessage); } // 创建一个新的 abortController const newAbortController = new AbortController(); setAbortController(newAbortController); // TODO 收到完整消息后,写入 cache 中 const fullContent = await fetchApiChat({ ...omit(settings, 'newChatModel', 'maxHistoryLength', 'systemMessage', 'prefixMessages', 'availableModels'), messages: fetchApiChatMessages, stream: true, onMessage: (content) => { // stream 模式下,由前端组装消息 partialContent += content; setIsLoading(false); setMessages([...newMessages, { role: Role.assistant, content: partialContent }]); // 如果当前滚动位置距离最底端少于等于 72(即 3 行)并且当前用户没有正在滚动,则保持滚动到最底端 if (gapToBottom() <= 72 && !getIsScrolling()) { scrollToBottom(); } }, signal: newAbortController.signal, }); // 收到完整消息后,重新设置 messages newMessages = [...newMessages, { role: Role.assistant, content: fullContent }]; setMessages(newMessages); setCache('messages', newMessages); // 如果当前滚动位置距离最底端少于等于 72(即 3 行)并且当前用户没有正在滚动,则保持滚动到最底端 if (gapToBottom() <= 72 && !getIsScrolling()) { scrollToBottom(); } } catch (e: any) { // 如果是调用 abortController.abort() 捕获到的 error 则不处理 if (e.name === 'AbortError') { return; } // 发生错误时,展示错误消息 setIsLoading(false); setMessages([ ...newMessages, { isError: true, role: Role.assistant, content: (e as ResError).message || (e as ResError).code.toString() }, ]); } }, [settings, messages, images, history, historyIndex, setAbortController], ); /** * 中断请求 */ const abortSendMessage = useCallback(() => { abortController?.abort(); }, [abortController]); /** * 加载聊天记录 */ const loadHistory = useCallback( async (index: number) => { if (historyIndex === index) { return; } const newModel = history?.[index].model ?? Model['gpt-4o']; if (historyIndex === 'empty') { setHistoryIndex(index); setSettings({ model: newModel, }); setIsMenuShow(false); await sleep(16); scrollToBottom(); return; } // 如果当前是在浏览历史,则直接切换 historyIndex if (typeof historyIndex === 'number') { setHistoryIndex(index); setSettings({ model: newModel, }); setIsMenuShow(false); await sleep(16); scrollToBottom(); return; } // 如果当前有正在进行的聊天,则将正在进行的聊天归档到 history 中 if (historyIndex === 'current') { const newHistory = [{ model: settings.model, messages }, ...(history ?? [])]; setHistory(newHistory); setCache('history', newHistory); setMessages([]); setCache('messages', []); // 此时因为将 current 进行归档了,所以需要 +1 setHistoryIndex(index + 1); setSettings({ model: newModel, }); setIsMenuShow(false); await sleep(16); scrollToBottom(); } }, [setIsMenuShow, historyIndex, messages, history, settings.model, setSettings], ); /** 删除单条聊天记录 */ const deleteHistory = useCallback( async (deleteIndex: 'current' | number) => { // 如果删除的是还没有写入 history 的当前聊天,则直接删除 messages if (deleteIndex === 'current') { setMessages([]); setCache('messages', []); const newIndex = history && history.length > 0 ? 0 : 'empty'; setHistoryIndex(newIndex); if (typeof newIndex === 'number') { const newModel = history?.[newIndex].model ?? Model['gpt-4o']; setSettings({ model: newModel, }); } return; } const newHistory = history?.filter((_, index) => index !== deleteIndex) ?? []; setHistory(newHistory); setCache('history', newHistory); // 如果删除的是当前显示的 history,则选择最近的一条聊天记录展示 if (deleteIndex === historyIndex) { // 选择最近的一条聊天记录展示 const newIndex = newHistory && newHistory.length > 0 ? Math.min(deleteIndex, newHistory.length - 1) : 'empty'; setHistoryIndex(newIndex); if (typeof newIndex === 'number') { const newModel = newHistory[newIndex].model ?? Model['gpt-4o']; setSettings({ model: newModel, }); } } }, [history, historyIndex, setSettings], ); /** 开启新对话 */ const startNewChat = useCallback(() => { let newHistory = [...(history ?? [])]; if (messages.length > 0) { newHistory = [{ model: settings.model, messages }, ...newHistory]; } setHistory(newHistory); setCache('history', newHistory); setMessages([]); setCache('messages', []); setHistoryIndex('empty'); setSettings({ model: settings.newChatModel, }); }, [messages, history, settings.model, settings.newChatModel, setSettings]); const appendImages = useCallback( (...newImages: ImageProp[]) => { const finalImages = [...images, ...newImages]; if (finalImages.length > MAX_GPT_VISION_IMAGES) { setImages(finalImages.slice(0, MAX_GPT_VISION_IMAGES)); alert(`最多只能发送 ${MAX_GPT_VISION_IMAGES} 张图片,超出的图片已删除`); return; } setImages(finalImages); }, [images], ); const deleteImage = useCallback( (index: number) => { const finalImages = [...images]; finalImages.splice(index, 1); setImages(finalImages); }, [images], ); return ( <ChatContext.Provider value={{ sendMessage, abortSendMessage, isLoading, messages, images, appendImages, deleteImage, history, historyIndex, loadHistory, deleteHistory, startNewChat, }} > {children} </ChatContext.Provider> ); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/context/DeviceContext.tsx
TypeScript (TSX)
'use client'; import { setCookie } from 'cookies-next'; import throttle from 'lodash.throttle'; import type { FC, ReactNode } from 'react'; import { createContext, useCallback, useEffect, useState } from 'react'; /** * 设备相关 Context */ export const DeviceContext = createContext<{ isWeChat: boolean; isMobile: boolean; windowWidth: number | '100vw'; windowHeight: number | '100vh'; } | null>(null); export const DeviceProvider: FC<{ children: ReactNode; isWeChat: boolean; uaIsMobile: boolean; windowWidth: number | '100vw'; windowHeight: number | '100vh'; }> = ({ children, isWeChat, uaIsMobile, windowWidth: propsWindowWidth, windowHeight: propsWindowHeight }) => { const [windowWidth, setWindowWidth] = useState<number | '100vw'>(propsWindowWidth); // 由于移动端的 height:100vh 不靠谱,故需要精确的数值用于设置高度 const [windowHeight, setWindowHeight] = useState<number | '100vh'>(propsWindowHeight); const isMobile = typeof windowWidth === 'number' ? windowWidth < 1125 : uaIsMobile; /** * 重置 window 宽高计算 */ const resetWindowWidthHeight = useCallback(() => { // 通过计算获取高度 // https://stackoverflow.com/a/52936500/2777142 setCookie('windowWidth', window.innerWidth); setCookie('windowHeight', window.innerHeight); setWindowWidth(window.innerWidth); setWindowHeight(window.innerHeight); // 设置精确的高度以控制滚动条 document.body.style.minHeight = `${window.innerHeight}px`; }, []); useEffect(() => { resetWindowWidthHeight(); window.addEventListener('resize', throttle(resetWindowWidthHeight, 100)); }, [resetWindowWidthHeight]); return ( <DeviceContext.Provider value={{ windowWidth, windowHeight, isWeChat, isMobile }}> {children} </DeviceContext.Provider> ); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/context/LoginContext.tsx
TypeScript (TSX)
'use client'; import { setCookie } from 'cookies-next'; import { useSearchParams } from 'next/navigation'; import type { FC, ReactNode } from 'react'; import { createContext, useCallback, useContext, useEffect, useState } from 'react'; import { getCache, setCache } from '@/utils/cache'; import { login as utilsLogin, logout as utilsLogout } from '@/utils/login'; import { SettingsContext } from './SettingsContext'; /** * 登录相关的 Context */ export const LoginContext = createContext<{ isLogged: boolean; login: () => Promise<boolean>; logout: () => Promise<boolean>; } | null>(null); export const LoginProvider: FC<{ children: ReactNode; cookieApiKey?: string }> = ({ children, cookieApiKey }) => { const { initAvailableModels } = useContext(SettingsContext)!; const [isLogged, setIsLogged] = useState(!!cookieApiKey); const queryApiKey = useSearchParams().get('api-key'); useEffect(() => { // 如果 query 中传入了 apiKey,则覆盖 cookie 和 localStorage if (queryApiKey) { setIsLogged(true); setCookie('apiKey', queryApiKey); setCache('apiKey', queryApiKey); return; } // 如果 query 中不存在 apiKey,则优先从 localStorage 中拿取 apiKey,并将其缓存在 cookie 中 const cacheApiKey = getCache('apiKey'); if (cacheApiKey) { setIsLogged(true); setCookie('apiKey', cacheApiKey); return; } // 如果 cookie 中存在 apiKey,则将其缓存在 localStorage 中 if (cookieApiKey) { setIsLogged(true); setCache('apiKey', cookieApiKey); return; } // 如果所有地方都不存在 apiKey,则弹出登录框 login(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const login = useCallback(async () => { const isLogged = await utilsLogin(); setIsLogged(isLogged); if (isLogged) { initAvailableModels(); } return isLogged; }, [initAvailableModels]); const logout = useCallback(async () => { const logoutResult = await utilsLogout(); setIsLogged(!logoutResult); return logoutResult; }, []); return <LoginContext.Provider value={{ isLogged, login, logout }}>{children}</LoginContext.Provider>; };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/context/MenuContext.tsx
TypeScript (TSX)
'use client'; import type { FC, ReactNode } from 'react'; import { createContext, useCallback, useState } from 'react'; /** * 菜单栏的 Key,直接用图标的名字表示 */ export enum MenuKey { /** 聊天记录 tab */ InboxStack = 'InboxStack', /** 参数配置 tab */ AdjustmentsHorizontal = 'AdjustmentsHorizontal', } /** * 菜单栏的 Context */ export const MenuContext = createContext<{ isMenuShow: boolean; setIsMenuShow: (isMenuShow: boolean) => void; currentMenu: MenuKey | undefined; setCurrentMenu: (currentMenu: MenuKey | undefined) => void; } | null>(null); export const MenuProvider: FC<{ children: ReactNode }> = ({ children }) => { const [isMenuShow, setStateIsMenuShow] = useState(false); const [currentMenu, setCurrentMenu] = useState<MenuKey | undefined>(undefined); /** * 设置菜单栏的显示隐藏 */ const setIsMenuShow = useCallback((isMenuShow: boolean) => { // 如果想隐藏,则去掉 html 上的样式,然后设置 state if (!isMenuShow) { document.documentElement.classList.remove('show-menu'); setStateIsMenuShow(isMenuShow); return; } // 如果想展示,则先设置 state,再设置样式 setStateIsMenuShow(isMenuShow); // 由于 transform 的 fixed 定位失效问题,这里需要手动设置和取消 form-container 的 top const formContainer = document.getElementById('form-container'); if (formContainer) { formContainer.style.top = `${getComputedStyle(formContainer).top}px`; } document.documentElement.classList.add('show-menu'); }, []); return ( <MenuContext.Provider value={{ isMenuShow, setIsMenuShow, currentMenu, setCurrentMenu, }} > {children} </MenuContext.Provider> ); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/context/MessageDetailContext.tsx
TypeScript (TSX)
'use client'; import type { FC, ReactNode } from 'react'; import { createContext, useState } from 'react'; import { FormatMessageMode } from '@/utils/formatMessage'; /** * 双击展开消息详情的 Context */ export const MessageDetailContext = createContext<{ messageDetail: string | undefined; setMessageDetail: (messageDetail: string | undefined) => void; formatMessageMode: FormatMessageMode; setFormatMessageMode: (formatMessageMode: FormatMessageMode) => void; } | null>(null); export const MessageDetailProvider: FC<{ children: ReactNode }> = ({ children }) => { const [messageDetail, setMessageDetail] = useState<string | undefined>(undefined); const [formatMessageMode, setFormatMessageMode] = useState<FormatMessageMode>(FormatMessageMode.partial); return ( <MessageDetailContext.Provider value={{ messageDetail, setMessageDetail, formatMessageMode, setFormatMessageMode, }} > {children} </MessageDetailContext.Provider> ); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/context/SettingsContext.tsx
TypeScript (TSX)
'use client'; import type { FC, ReactNode } from 'react'; import { createContext, useCallback, useEffect, useReducer } from 'react'; import { fetchApiModels } from '@/utils/api'; import { getCache, setCache } from '@/utils/cache'; import type { ChatRequest, SimpleStringMessage } from '@/utils/constants'; import { AllModels, Model } from '@/utils/constants'; export interface SettingsState extends Omit<ChatRequest, 'messages'> { newChatModel: Model; maxHistoryLength: number; systemMessage?: SimpleStringMessage; prefixMessages?: SimpleStringMessage[]; availableModels: Model[]; } const INITIAL_SETTINGS: SettingsState = { newChatModel: Model['gpt-4o'], model: Model['gpt-4o'], maxHistoryLength: 6, availableModels: [Model['gpt-4o']], }; enum SettingsActionType { RESET, REPLACE_SETTINGS, SET_SETTINGS, } const settingsReducer = (settings: SettingsState, action: { type: SettingsActionType; payload?: any }) => { let newSettings = { ...settings }; // 重置默认值 if (action.type === SettingsActionType.RESET) { newSettings = { newChatModel: settings.availableModels[0], model: settings.availableModels[0], maxHistoryLength: settings.maxHistoryLength, availableModels: settings.availableModels, }; } // 覆盖配置 else if (action.type === SettingsActionType.REPLACE_SETTINGS) { newSettings = action.payload; } // 合并配置 else if (action.type === SettingsActionType.SET_SETTINGS) { newSettings = { ...newSettings, ...action.payload }; } setCache('settings', newSettings); return newSettings; }; /** * 配置的 Context */ export const SettingsContext = createContext<{ settings: SettingsState; setSettings: (partialSettings: Partial<SettingsState>) => void; resetSettings: () => void; initAvailableModels: () => void; } | null>(null); export const SettingsProvider: FC<{ children: ReactNode; isLogged: boolean }> = ({ children, isLogged }) => { const [settings, dispatch] = useReducer(settingsReducer, INITIAL_SETTINGS); // 页面加载后从 cache 中读取 settings useEffect(() => { let settings = { ...INITIAL_SETTINGS, ...getCache<SettingsState>('settings'), }; dispatch({ type: SettingsActionType.REPLACE_SETTINGS, payload: settings, }); // 每次页面加载的时候都请求一次 /api/models 来获取该 apiKey 可用的模型 if (isLogged) { initAvailableModels(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const setSettings = useCallback((partialSettings: Partial<SettingsState>) => { dispatch({ type: SettingsActionType.SET_SETTINGS, payload: partialSettings, }); }, []); const resetSettings = useCallback(() => { dispatch({ type: SettingsActionType.RESET, }); }, []); const initAvailableModels = useCallback(async () => { // 请求 /api/models 来获取该 apiKey 可用的模型 try { const apiModelsResponse = await fetchApiModels(); // 需要过滤 AllModels 中的模型 const availableModels = apiModelsResponse.data .map(({ id }) => id) .filter((model) => AllModels.includes(model)) .sort((a, b) => AllModels.indexOf(a) - AllModels.indexOf(b)); dispatch({ type: SettingsActionType.SET_SETTINGS, payload: { availableModels }, }); } catch (e: any) { alert(e.message); } }, []); return ( <SettingsContext.Provider value={{ settings, setSettings, resetSettings, initAvailableModels, }} > {children} </SettingsContext.Provider> ); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/global-error.tsx
TypeScript (TSX)
'use client'; // https://beta.nextjs.org/docs/routing/error-handling export default function GlobalError({ error, reset }: { error: Error; reset: () => void }) { return ( <html> <body> <h2>Something went wrong!</h2> <p>{error.message}</p> <button onClick={() => reset()}>Try again</button> </body> </html> ); }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/globals.css
CSS
@tailwind base; @tailwind components; @tailwind utilities; html { /* 移动端全屏应用,大屏下白色背景墙 */ @apply bg-chat-bg md:bg-white text-gray-900; @apply dark:bg-chat-bg-dark dark:md:bg-gray-800 dark:text-gray-200; } body { /* 移动端菜单从右侧滑出,需要整个 body 偏移 */ @apply transition-transform; } /* 打开菜单后,禁用滚动 */ html.show-menu { @apply overflow-hidden; } /* 打开菜单后,整个 body 滑向左边 */ html.show-menu body { @apply translate-x-[calc(6.25rem-100vw)]; } select { @apply dark:text-gray-900; } .text-gray { @apply text-gray-400; @apply dark:text-gray-500; } .text-gray-link { @apply text-gray-400 hover:text-gray-500 cursor-pointer underline; @apply dark:text-gray-500 dark:hover:text-gray-400; } .border-gray { @apply border-gray-300; @apply dark:border-gray-700; } button { @apply w-10 h-10 m-2 p-[0.625rem]; @apply cursor-pointer text-gray-400 hover:text-gray-500 disabled:hover:text-gray-400; @apply dark:text-gray-500 dark:hover:text-gray-400 disabled:hover:dark:text-gray-500; } /* 按钮和输入框统一样式 */ input, button, textarea, .button-attach-image { @apply rounded; @apply focus-visible:outline focus-visible:outline-1 focus-visible:outline-amber-500; } input[type='button'], .button-attach-image { @apply cursor-pointer bg-white hover:bg-gray-200; @apply disabled:cursor-not-allowed disabled:bg-gray-200 disabled:text-gray-400; @apply dark:bg-gray-800 dark:hover:bg-gray-700; @apply dark:disabled:bg-gray-700 dark:disabled:text-gray-500; } input[type='submit'] { @apply cursor-pointer bg-[#57be6b] text-white; @apply disabled:cursor-not-allowed disabled:bg-gray-200 disabled:text-gray-400; @apply dark:disabled:bg-gray-700 dark:disabled:text-gray-500; } .button-attach-image.disabled { @apply cursor-not-allowed bg-gray-200 text-gray-400; @apply dark:bg-gray-700 dark:text-gray-500; } /* 用于 fixed 宽度设置 */ .w-inherit { width: inherit; } /* message-chatgpt 内部样式 */ .message-chatgpt p, .message-chatgpt pre[class*='language-'] { @apply mt-6 first:mt-0; white-space: pre-wrap; } .message-chatgpt pre[class*='language-'], .message-chatgpt code[class*='language-'] { text-shadow: none; } .message-chatgpt pre[class*='language-'] { @apply text-sm px-3 pt-9 pb-2 mb-0 bg-gray-100 rounded; @apply dark:bg-gray-800; } .message-chatgpt code[class*='language-'] { @apply text-sm p-0; @apply dark:bg-gray-800; } .message-chatgpt code { @apply text-sm bg-gray-100 py-0.5 px-[3px]; @apply dark:bg-gray-700; } .message-chatgpt a:-webkit-any-link { @apply cursor-pointer underline; } .message-chatgpt .prism-title { @apply absolute w-[calc(100%-1.5rem)] -ml-3 -mt-9 px-3 h-7 leading-7 bg-gray-200 text-gray-400 rounded-t; @apply dark:bg-gray-700 dark:text-gray-400; } .message-chatgpt .prism-copy { @apply float-right cursor-pointer hover:text-gray-500; @apply dark:hover:text-gray-300; } .attach-image-container:hover .attach-image-delete { @apply block bg-white bg-opacity-50; } .attach-image-container .attach-image-delete:hover { @apply bg-opacity-100; } .history-item { @apply p-4 border-b-[0.5px] relative cursor-default border-gray md:-mx-4 md:px-8; } .history-item:hover button { @apply block; } .history-item-new { @apply pl-4 border-b-[0.5px] relative cursor-default border-gray md:-mx-4 md:pl-8 md:pr-4; }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/hooks/useDarkMode.ts
TypeScript
import { useEffect } from 'react'; export const useDarkMode = () => { useEffect(() => { const link = document.createElement('link'); link.rel = 'stylesheet'; if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) { // 暗色模式 link.href = '/prism-dark.css'; } else { // 浅色模式 link.href = '/prism-light.css'; } document.head.appendChild(link); let darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)'); darkModeQuery.addEventListener('change', (e) => { if (e.matches) { // 暗色模式 link.href = '/prism-dark.css'; } else { // 浅色模式 link.href = '/prism-light.css'; } }); }, []); };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/layout.tsx
TypeScript (TSX)
import './globals.css'; import npmIsMobile from 'is-mobile'; import type { Metadata } from 'next'; import { cookies, headers } from 'next/headers'; import { ChatProvider } from '@/context/ChatContext'; import { DeviceProvider } from '@/context/DeviceContext'; import { LoginProvider } from '@/context/LoginContext'; import { MenuProvider } from '@/context/MenuContext'; import { MessageDetailProvider } from '@/context/MessageDetailContext'; import { SettingsProvider } from '@/context/SettingsContext'; import { isWeChat as utilIsWeChat } from '@/utils/device'; export const metadata: Metadata = { title: 'ChatGPT Next', description: '微信风格的 ChatGPT,基于 Next.js 构建,私有化部署的最佳选择!', icons: { icon: '/chatgpt-icon-green.png', apple: '/chatgpt-icon-green.png' }, viewport: { width: 'device-width', initialScale: 1, viewportFit: 'cover' }, }; export default function RootLayout({ children }: { children: React.ReactNode }) { const userAgent = headers().get('user-agent') ?? ''; const isWeChat = utilIsWeChat(userAgent); const uaIsMobile = isWeChat || npmIsMobile({ ua: userAgent }); const cookiesWindowWidth = cookies().get('windowWidth')?.value; const windowWidth = cookiesWindowWidth ? Number(cookiesWindowWidth) : '100vw'; const cookiesWindowHeight = cookies().get('windowHeight')?.value; const windowHeight = cookiesWindowHeight ? Number(cookiesWindowHeight) : '100vh'; const cookieApiKey = cookies().get('apiKey')?.value; return ( <html lang="zh-CN"> <body> <DeviceProvider isWeChat={isWeChat} uaIsMobile={uaIsMobile} windowWidth={windowWidth} windowHeight={windowHeight} > <SettingsProvider isLogged={!!cookieApiKey}> <LoginProvider cookieApiKey={cookieApiKey}> <MenuProvider> <ChatProvider> <MessageDetailProvider>{children}</MessageDetailProvider> </ChatProvider> </MenuProvider> </LoginProvider> </SettingsProvider> </DeviceProvider> <script async src="/prism.js" /> </body> </html> ); }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/page.tsx
TypeScript (TSX)
import { Menu } from '@/components/Menu'; import { MessageDetail } from '@/components/MessageDetail'; import { Messages } from '@/components/Messages'; import { TextareaForm } from '@/components/TextareaForm'; import { Title } from '@/components/Title'; export default function Home() { return ( <div className="mx-auto md:w-[1125px] md:min-h-screen md:flex md:tall:py-24"> <div className="hidden md:tall:block fixed top-0 w-inherit z-10 h-24 bg-white dark:bg-gray-800" /> <Menu /> <main className="w-full bg-chat-bg dark:bg-chat-bg-dark md:w-[50rem] md:px-4 md:flex md:flex-col"> <Title /> <Messages /> <TextareaForm /> </main> <div className="hidden md:tall:block fixed bottom-0 w-inherit z-10 h-24 bg-white dark:bg-gray-800" /> <MessageDetail /> </div> ); }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/api.ts
TypeScript
import type { ChatRequest, ModelsResponse } from './constants'; import { HttpHeaderJson, HttpMethod } from './constants'; import { ResError } from './error'; import { stream2string } from './stream'; /** * 请求 /api/chat 接口 * 参数和 OpenAI 官方的接口参数一致,apiKey 在服务端自动添加 * 可以传入 onMessage 来流式的获取响应 */ export const fetchApiChat = async ({ onMessage, signal, ...chatRequest }: { /** * 接受 stream 消息的回调函数 */ onMessage?: (content: string) => void; /** * 控制请求中断的 AbortSignal */ signal?: AbortSignal; } & Partial<ChatRequest>) => { const fetchResult = await fetch('/api/chat', { method: HttpMethod.POST, headers: HttpHeaderJson, body: JSON.stringify(chatRequest), signal, }); // 如果返回错误,则直接抛出错误 if (!fetchResult.ok) { throw await getError(fetchResult); } // 使用 stream2string 来读取内容 return await stream2string(fetchResult.body, onMessage); }; /** * 请求 /api/models 接口 * 获取可用的模型列表 */ export const fetchApiModels = async (): Promise<ModelsResponse> => { const fetchResult = await fetch('/api/models', { method: HttpMethod.GET, headers: HttpHeaderJson, }); // 如果返回错误,则直接抛出错误 if (!fetchResult.ok) { throw await getError(fetchResult); } return await fetchResult.json(); }; /** * 处理 fetchResult 的错误 */ async function getError(fetchResult: Response) { const error = new ResError({ code: fetchResult.status, message: fetchResult.statusText, }); try { let fetchResultJson = await fetchResult.json(); // 使用 resJson.error 覆盖 error Object.assign(error, fetchResultJson, fetchResultJson.error); } catch (e) {} return error; }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/cache.ts
TypeScript
export function setCache(key: string, value: any) { localStorage.setItem(key, JSON.stringify(value)); } export function getCache<T = any>(key: string): T | undefined { return JSON.parse(localStorage.getItem(key) ?? 'null') ?? undefined; } export function removeCache(key: string) { localStorage.removeItem(key); }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/constants.ts
TypeScript
export enum HttpMethod { GET = 'GET', POST = 'POST', } export enum HttpStatus { OK = 200, BadRequest = 400, Unauthorized = 401, MethodNotAllowed = 405, } export const HttpHeaderJson = { 'Content-Type': 'application/json', }; /** * 全角空格,用于 html 中的占位符 */ export const FULL_SPACE = ' '; /** * 使用 gpt-4-vision 时单次可传输的最多图片数量 */ export const MAX_GPT_VISION_IMAGES = 9; /** * 角色 * 参考 https://github.com/openai/openai-node/blob/master/api.ts */ export enum Role { system = 'system', user = 'user', assistant = 'assistant', } /** * ChatGPT 模型 */ export enum Model { 'gpt-4o' = 'gpt-4o', 'gpt-4o-mini' = 'gpt-4o-mini', 'gpt-5' = 'gpt-5', 'gpt-5-mini' = 'gpt-5-mini', 'gpt-5-nano' = 'gpt-5-nano', } export const AllModels = [ Model['gpt-4o'], Model['gpt-4o-mini'], Model['gpt-5'], Model['gpt-5-mini'], Model['gpt-5-nano'], ]; /** 支持发送图片的模型 */ export const VisionModels = [ Model['gpt-4o'], Model['gpt-4o-mini'], Model['gpt-5'], Model['gpt-5-mini'], Model['gpt-5-nano'], ]; export enum MessageContentType { text = 'text', image_url = 'image_url', } export interface MessageContentItemText { type: MessageContentType.text; text: string; } export interface MessageContentItemImageUrl { type: MessageContentType.image_url; image_url: { url: string; width: number; height: number; }; } /** * 结构化的 MessageContent */ export type StructuredMessageContentItem = MessageContentItemText | MessageContentItemImageUrl; /** * 单条消息 */ export interface Message { isError?: boolean; role: Role; content: string | StructuredMessageContentItem[]; } /** * 简单文本消息 * @TODO 实现 isSimpleStringMessage 方法 */ export interface SimpleStringMessage { isError?: boolean; role: Role; content: string; } /** * /v1/chat/completions 的请求体 * https://platform.openai.com/docs/api-reference/chat */ export interface ChatRequest { /** * 模型 */ model: Model; /** * 消息列表 * 一般第一条消息是 system,后面是 user 或 assistant * * @example * [ * {"role": "system", "content": "You are a helpful assistant."}, * {"role": "user", "content": "Who won the world series in 2020?"}, * {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."}, * {"role": "user", "content": "Where was it played?"} * ] */ messages: Message[]; /** * 温度,取值范围 0-2 * * 用于控制生成文本的多样性。 * 较高的温度会导致模型更加随机地选择下一个单词,从而生成更加多样化的文本。 * 相反,较低的温度会使模型更倾向于选择概率最高的单词,因此生成的文本更加可预测。 * 举例来说,当设置为 0 时,同样的输入每次都会生成完全同样的输出。 * * 建议 temperature 和 top_p 只设置一个。 * * @default 1 */ temperature?: number; /** * 高概率采样,取值范围 0-1 * * 用于控制生成文本时考虑的词汇数量,从而使得生成的文本更加精细。 * 在生成每个词时,模型会计算出所有可能的下一个词,并将概率按降序排列,然后通过 top_p 来决定哪些词可能被选中。 * 举例来说,当设置成 0.1 时,只有概率为 top 10% 的词可能被选中。 * * 建议 temperature 和 top_p 只设置一个。 * * @default 1 */ top_p?: number; /** * 生成的选项数量 * * @default 1 */ n?: number; /** * 是否使用流式响应 * * @default false */ stream?: boolean; /** * 结束语,最多设置四个,如果 ChatGPT 的回复中包含某个结束语,则停止生成 */ stop?: string | string[]; /** * tokens 限制 */ max_tokens?: number; /** * 存在惩罚,取值范围 -2.0 到 2.0 * * 用于惩罚模型生成那些已经出现在先前生成的文本中的 token(单词或标点符号等)。 * 这可以确保生成的文本更加多样化,避免了模型在生成新文本时重复使用相同的 token。 * presence_penalty 越高,模型生成的文本中就越不可能包含之前已经使用过的 token。 * * @default 0; */ presence_penalty?: number; /** * 频率惩罚,取值范围 -2.0 到 2.0 * * 用于惩罚模型生成频率较高的 token,从而使得生成的文本更加多样化。 * 与 presence_penalty 相似,frequency_penalty 越高,模型生成的文本中就越不可能包含频率较高的 token。 * * @default 0; */ frequency_penalty?: number; /** * 逻辑偏差 * * 用于控制模型生成特定 token 的概率,以满足特定的文本生成需求。 * 通过设置不同的 logit_bias 值,可以让模型生成更符合预期的文本内容。 * 例如,如果需要模型生成描述科技行业的文本,可以设置 logit_bias 为某些科技相关的词语,这样就能够促使模型更多地生成涉及科技领域的单词和内容。 * * @example * 假设我们使用 OpenAI 的文本生成 API 来生成一篇关于食品的描述性文章。 * 如果我们希望文章中包含更多与甜点相关的单词和句子,可以使用 logit_bias 参数来调整模型生成特定单词的概率。 * 例如,我们可以将 logit_bias 参数设置为以下内容: * "logit_bias": { * "cupcake": 10, * "cookie": 5, * "cake": 8 * } */ logit_bias?: Record<string, number>; /** * 用户,OpenAI 用来监控和识别滥用的字段一般不需要传 */ user?: string; } /** * /v1/chat/completions 的响应体 * https://platform.openai.com/docs/api-reference/chat */ export interface ChatResponse { id: string; model: Model; object: 'chat.completion'; created: number; choices: { index: number; message: Message; finish_reason: null | 'stop'; }[]; usage: { prompt_tokens: number; completion_tokens: number; total_tokens: number; }; } /** * 传入 stream: true 之后 /v1/chat/completions 的流式响应 * https://platform.openai.com/docs/api-reference/chat/create#chat/create-stream */ export interface ChatResponseChunk { id: string; model: Model; object: 'chat.completion.chunk'; created: number; // https://github.com/openai/openai-cookbook/blob/main/examples/How_to_stream_completions.ipynb choices: { index: number; delta: { role: Role } | { content: string } | {}; finish_reason: null | 'stop'; }[]; } /** * /v1/chat/completions 的报错响应 */ export interface ChatResponseError { error?: { code: string; message: string; param: null; type: string; }; } /** * /v1/models 的响应体 * https://platform.openai.com/docs/api-reference/models */ export interface ModelsResponse { data: { created: number; id: Model; object: 'model'; owned_by: 'openai'; parent: null; permission: { 0: { allow_create_engine: boolean; allow_fine_tuning: boolean; allow_logprobs: boolean; allow_sampling: boolean; allow_search_indices: boolean; allow_view: boolean; created: number; group: null; id: string; is_blocking: boolean; object: 'model_permission'; organization: '*'; }; }; root: Model; }[]; object: 'list'; } /** * /v1/models 的响应体示例 */ export const exampleModelsResponse: ModelsResponse = { data: [ { created: 1677610602, id: Model['gpt-4o'], object: 'model', owned_by: 'openai', parent: null, permission: { 0: { allow_create_engine: false, allow_fine_tuning: false, allow_logprobs: true, allow_sampling: true, allow_search_indices: false, allow_view: true, created: 1684434433, group: null, id: 'modelperm-Gsp3SyIu7GamHB3McQv3rMf5', is_blocking: false, object: 'model_permission', organization: '*', }, }, root: Model['gpt-4o'], }, ], object: 'list', };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/device.ts
TypeScript
/** * 通过 ua 判断是否为微信,支持传入 ua,这样就可以在 ssr 时运行 * https://gist.github.com/GiaoGiaoCat/fff34c063cf0cf227d65 */ export function isWeChat(userAgent?: string) { if (userAgent) { return /micromessenger/.test(userAgent.toLowerCase()); } if (typeof window !== 'undefined') { return /micromessenger/.test(window.navigator.userAgent.toLowerCase()); } return false; }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/env.ts
TypeScript
export const env = { NODE_ENV: process.env.NODE_ENV, /** apiKey 別名 */ OPENAI_API_KEY_ALIAS: process.env.OPENAI_API_KEY_ALIAS ?? undefined, /** 禁止陌生人通过他自己的 apiKey 访问 */ CHATGPT_NEXT_DISABLE_PUBLIC: process.env.CHATGPT_NEXT_DISABLE_PUBLIC ?? 'false', /** 配置 API 请求的 host(包含端口) */ CHATGPT_NEXT_API_HOST: process.env.CHATGPT_NEXT_API_HOST ?? 'api.openai.com', /** API提供商: openai/azure */ CHATGPT_NEXT_API_PROVIDER: process.env.CHATGPT_NEXT_API_PROVIDER ?? 'openai', /** azure api url */ CHATGPT_NEXT_API_AzureAPIURL: process.env.CHATGPT_NEXT_API_AzureAPIURL, /** azure api url path */ CHATGPT_NEXT_API_AzureAPIURLPath: process.env.CHATGPT_NEXT_API_AzureAPIURLPath, };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/error.ts
TypeScript
interface ResErrorBody { code: string | number; message: string; } export class ResError extends Error implements ResErrorBody { public code!: string | number; public message!: string; public constructor(errorBody: ResErrorBody) { super(); Object.assign(this, errorBody); } }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/exampleMessages.ts
TypeScript
export const exampleMessages: any = [ { role: 'user', content: 'github actions 如何在修改某些文件时不触发', }, { role: 'assistant', content: 'GitHub Actions 中可以通过配置“忽略文件”来避免在某些文件修改时触发 Workflow。\n\n具体的操作步骤为:\n\n1. 在仓库根目录创建 `.github/workflows` 文件夹\n\n2. 在该文件夹下创建一个名为 `your-workflow.yml` 的 Workflow 文件,例如:\n\n ```yaml\n name: Your Workflow\n on:\n push:\n branches:\n - master\n jobs:\n your-job:\n runs-on: ubuntu-latest\n steps:\n - name: Do something\n run: echo "Hello, world!"\n ```\n \n3. 在 `your-workflow.yml` 文件的 `on` 字段下的 `push` 事件中添加 `paths` 字段,示例如下:\n\n ```yaml\n name: Your Workflow\n on:\n push:\n branches:\n - master\n paths:\n - \'!**/file1.txt\'\n - \'!**/dir/file2.txt\'\n jobs:\n your-job:\n runs-on: ubuntu-latest\n steps:\n - name: Do something\n run: echo "Hello, world!"\n ```\n\n 注意: \n\n `paths` 字段可以配置一个或多个文件或目录路径,支持 `*` 和 `**` 通配符。\n\n 在 `paths` 中以 `!` 开头的路径表示排除不需要监视的文件或目录。\n\n 在示例中,`!**/file1.txt` 和 `!**/dir/file2.txt` 表示不监视项目根目录下的 `file1.txt` 文件和 `dir` 目录下的 `file2.txt` 文件。\n\n 如果没有特殊要求,也可以不使用 `paths` 字段,这样 Workflow 将监视全部文件及目录变化,包括触发 Workflow 的文件修改事件。', }, ];
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/export.ts
TypeScript
/** * 导出 json */ export function exportJSON(data: any, filename: string) { const jsonData = JSON.stringify(data, null, 2); const a = document.createElement('a'); const file = new Blob([jsonData], { type: 'application/json' }); a.href = URL.createObjectURL(file); a.download = filename; a.click(); URL.revokeObjectURL(a.href); }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/formatMessage.ts
TypeScript
import MarkdownIt from 'markdown-it'; // @ts-ignore import katex from 'markdown-it-katex'; import { sleep } from './sleep'; /** 多种 markdown-it 配置 */ const markdownItMap = { zero: new MarkdownIt('zero'), partial: new MarkdownIt('zero', { breaks: true, linkify: true, // 使用 Prism 解析代码 highlight: (str: string, l) => { let lang = l ?? 'plain'; if (typeof (window as any).Prism.languages[lang] === 'undefined') { lang = 'plain'; } const grammar = (window as any).Prism.languages[lang]; // https://github.com/PrismJS/prism/issues/1171#issuecomment-631470253 (window as any).Prism.hooks.run('before-highlight', { grammar }); return `<pre class="language-${lang}"><div class="prism-title">${l}<a class="prism-copy">拷贝代码</a></div><code class="language-${lang}">${( window as any ).Prism.highlight(str, grammar, lang)}</code></pre>`; }, }) .enable(['code', 'fence']) .enable(['autolink', 'backticks', 'image', 'link', 'newline']) .use(katex), }; // 实现「拷贝代码」功能 if (typeof window !== 'undefined') { window.document.addEventListener('click', (e) => { // @ts-ignore if (e.target?.classList?.contains('prism-copy')) { // @ts-ignore const text: string = e.target.parentNode?.nextSibling?.innerText; navigator.clipboard .writeText(text) .then(async () => { // @ts-ignore e.target.innerHTML = '<span style="margin-right:3px">拷贝成功</span>✅'; await sleep(1000); // @ts-ignore e.target.innerText = '拷贝代码'; }) .catch((err) => { alert(`拷贝代码时出错:${err.message}`); }); } }); } export enum FormatMessageMode { /** 只处理换行符、空格、html 转义 */ zero = 'zero', /** 只处理一部分 md 语法,如 link、image、code 等 */ partial = 'partial', /** 完整的 markdown 处理 */ // full = 'full', } /** * 格式化消息 */ export function formatMessage(message?: string, mode = FormatMessageMode.zero) { let result = message?.trim(); if (!result) { return ''; } // 仅在 zero 模式下保留换行和空格 if (mode === FormatMessageMode.zero) { // 由于多个换行符和空格在 markdown 中会被合并成一个,为了保留内容的格式,这里自行处理 result = result.replace(/\n/g, '==BREAK=PLACEHOLDER=='); // 遇到连续的 2个或 2个以上空格时,先替换,但保留第一个空格 // result = result.replace(/ {2,}/g, (match) => ' ' + '==SPACE=PLACEHOLDER=='.repeat(match.length - 1)); // 遇到连续的 2个或 2个以上空格时,替换成 nbsp result = result.replace(/ {2,}/g, (match) => '==SPACE=PLACEHOLDER=='.repeat(match.length)); } result = markdownItMap[mode].render(result).trim(); if (mode === FormatMessageMode.zero) { result = result.replace(/==SPACE=PLACEHOLDER==/g, '&nbsp;'); result = result.replace(/==BREAK=PLACEHOLDER==/g, '<br>'); } return result; }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/getApiKey.ts
TypeScript
import { env } from './env'; /** * 传入的 apiKey 可能是 alias,这个函数会返回真正的 apiKey */ export function getApiKey(apiKey?: string): string | undefined { if (!apiKey) { return undefined; } // 从 getOpenaiApiKeyAliasMap 中拿取真实的 apiKey let realApiKey = apiKey; const openaiApiKeyAliasMap = getOpenaiApiKeyAliasMap(); // 如果 getOpenaiApiKeyAliasMap 中存在这个 alias,则获取其中真实的 apiKey if (openaiApiKeyAliasMap[apiKey]) { realApiKey = openaiApiKeyAliasMap[apiKey]; return realApiKey; } // 如果禁止了陌生人通过他自己的 apiKey 访问 if (env.CHATGPT_NEXT_DISABLE_PUBLIC === 'true') { return undefined; } return realApiKey; } /** * 根据配置的环境变量 OPENAI_API_KEY_ALIAS,获取 alias 配置 */ function getOpenaiApiKeyAliasMap() { if (!env.OPENAI_API_KEY_ALIAS) { return {}; } let openaiApiKeyAliasMap: Record<string, string> = {}; /** * alias 是这样的结构 firstkey:sk-xxxx|secondkey:sk-yyyy * 这里通过两轮 split 来拆分成多组 alias */ const aliasList = env.OPENAI_API_KEY_ALIAS.split('|'); for (const oneAlias of aliasList) { const [key, value] = oneAlias.split(':'); openaiApiKeyAliasMap[key] = value; } return openaiApiKeyAliasMap; }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/image.ts
TypeScript
export interface ImageProp { src: string; width: number; height: number; } /** * 图片按照这个方式缩放: * Image inputs are metered and charged in tokens, just as text inputs are. * The token cost of a given image is determined by two factors: its size, and the detail option on each image_url block. * All images with detail: low cost 85 tokens each. * detail: high images are first scaled to fit within a 2048 x 2048 square, maintaining their aspect ratio. * Then, they are scaled such that the shortest side of the image is 768px long. * Finally, we count how many 512px squares the image consists of. * Each of those squares costs 170 tokens. Another 85 tokens are always added to the final total. */ export function smallImageSize({ width, height }: { width: number; height: number }) { const isWidthLongerThanHeight = width > height; /** 长边 */ let longerSide = isWidthLongerThanHeight ? width : height; /** 短边 */ let shorterSide = isWidthLongerThanHeight ? height : width; /** 若长边大于 2048 */ if (longerSide > 2048) { shorterSide = (shorterSide / longerSide) * 2048; longerSide = 2048; } /** 若短边大于 768 */ if (shorterSide > 768) { longerSide = (longerSide / shorterSide) * 768; shorterSide = 768; } /** 取整数 */ longerSide = Math.round(longerSide); shorterSide = Math.round(shorterSide); return { width: isWidthLongerThanHeight ? longerSide : shorterSide, height: isWidthLongerThanHeight ? shorterSide : longerSide, }; } /** * 压缩图片为 openai 接受的尺寸 */ export async function compressImage(imgSrc: string): Promise<ImageProp> { return new Promise((resolve) => { const img = new Image(); img.src = imgSrc; img.onload = () => { // 创建一个canvas元素 const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d')!; const originalSize = { width: img.width, height: img.height, }; const size = smallImageSize(originalSize); // 如果不需要压缩尺寸 if (originalSize.width === size.width && originalSize.height === size.height) { return resolve({ src: imgSrc, ...size, }); } // 设置canvas尺寸 canvas.width = size.width; canvas.height = size.height; // 绘制图片到canvas ctx.drawImage(img, 0, 0, size.width, size.height); // 压缩图片的质量 const quality = 0.8; // 压缩质量设置为0.8 const compressedImage = canvas.toDataURL('image/jpeg', quality); resolve({ src: compressedImage, ...size, }); }; }); } /** * 读取上传的图片文件 */ export async function readImageFile(file: File): Promise<ImageProp> { return new Promise((resolve) => { // 创建FileReader来读取此文件 const reader = new FileReader(); // 设置当读取操作完成时触发的回调函数 reader.onload = async (readerEvent) => { // 获取文件内容 base64 编码 const fileContent = readerEvent.target?.result as string; // 压缩图片大小为 openai 接受的大小 const imageProp = await compressImage(fileContent); resolve(imageProp); }; // 读取文件并转换为Base64编码 reader.readAsDataURL(file); }); }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/isDomChildren.ts
TypeScript
/** 判断 child 是不是 ancestor 的子节点 */ export function isDomChildren(ancestor: HTMLElement | null, target: HTMLElement | null) { if (!ancestor || !target) { return false; } let parent: HTMLElement | null = target; do { parent = parent.parentElement; if (parent === ancestor) { return true; } } while (parent !== null); return false; }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/last.ts
TypeScript
export function last<T>(arr: T[]) { return arr[arr.length - 1]; }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/login.ts
TypeScript
import { getCookie, removeCookies, setCookie } from 'cookies-next'; import { removeCache, setCache } from '@/utils/cache'; import { sleep } from './sleep'; /** 开始登录 */ export function login() { // 如果已登录,则提前结束 if (getCookie('apiKey')) { return true; } return new Promise<boolean>(async (resolve) => { // 如果未登录,则弹窗让用户输入密钥 const apiKey = window.prompt('请输入密钥'); // 由于 prompt 时序问题,需要 sleep await sleep(16); // 如果用户输入了密钥,则设置 cookie,登录成功 if (apiKey) { // 同时存储在 cookie 和 localStorage 中,防止微信中容易丢失 cookie setCookie('apiKey', apiKey); setCache('apiKey', apiKey); // @ts-ignore 第二个参数 ts 不支持传 null,但其实是可以传的,表示不修改标题 history.replaceState(null, null, '/'); return resolve(true); } // 如果没有输入 key,则登录失败 return resolve(false); }); } /** 登出 */ export function logout() { // 如果未登录,则提前结束 if (!getCookie('apiKey')) { return true; } return new Promise<boolean>(async (resolve) => { // 如果已登录,则弹窗提示用户是否登出 const logoutConfirmed = window.confirm( `当前密钥是 ****${(getCookie('apiKey') as string).slice(-4)}\n是否要登出以重新输入?`, ); // 由于 prompt 时序问题,需要 sleep await sleep(16); // 如果确认要登出,则删除 cookie,登出成功 if (logoutConfirmed) { removeCookies('apiKey'); removeCache('apiKey'); // @ts-ignore 第二个参数 ts 不支持传 null,但其实是可以传的,表示不修改标题 history.replaceState(null, null, '/'); return resolve(true); } // 如果取消登出,则登出失败 return resolve(false); }); }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/message.ts
TypeScript
import { MessageContentType } from './constants'; import type { ChatResponse, Message, MessageContentItemText, StructuredMessageContentItem } from './constants'; /** * 判断传入的 message 是简单的 Message 还是完整的 ChatResponse */ export function isMessage(message: Message | ChatResponse): message is Message { if ((message as Message).content !== undefined) { return true; } return false; } /** * 从 message 中提取 content */ export function getContent(message: Message | ChatResponse): string | StructuredMessageContentItem[] { return isMessage(message) ? message.content : message.choices[0].message.content; } /** * 从 message 中提取供侧边栏展示的 contentText */ export function getContentText(message: Message | ChatResponse): string { const content = getContent(message); if (typeof content === 'string') { return content; } const isFirstContentItemImageUrl = content[0].type === MessageContentType.image_url; const firstTextContentItem = content.find(({ type }) => type === MessageContentType.text) as | MessageContentItemText | undefined; const textList = []; if (isFirstContentItemImageUrl) { textList.push('[图片]'); } if (firstTextContentItem) { textList.push(firstTextContentItem.text); } return textList.join(' '); } /** * 从 message 中提取 role */ export function getRole(message: Message | ChatResponse) { return isMessage(message) ? message.role : message.choices[0].message.role; }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/scroll.ts
TypeScript
let isScrolling = false; let isScriptScrolling = false; let scrollTimeoutId: any = null; export function initEventListenerScroll() { const scrollHandler = () => { // 如果是脚本滚动,则直接返回 if (isScriptScrolling) { return; } isScrolling = true; clearTimeout(scrollTimeoutId); scrollTimeoutId = setTimeout(() => (isScrolling = false), 100); }; window.addEventListener('scroll', scrollHandler); return () => window.removeEventListener('scroll', scrollHandler); } /** * 获取当前是否在滚动中 */ export function getIsScrolling() { return isScrolling; } /** * 当前滚动位置距离最底端有多少 */ export function gapToBottom() { return document.documentElement.scrollHeight - window.innerHeight - window.scrollY; } export function scrollToBottom() { isScriptScrolling = true; window.scrollTo(0, document.body.scrollHeight); setTimeout(() => (isScriptScrolling = false), 0); } export function scrollToTop() { isScriptScrolling = true; window.scrollTo(0, 0); setTimeout(() => (isScriptScrolling = false), 0); } export function disableScroll() { window.document.body.style.overflow = 'hidden'; } export function enableScroll() { window.document.body.style.overflow = 'visible'; }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/sleep.ts
TypeScript
export function sleep(time: number) { return new Promise<void>((resolve) => { setTimeout(resolve, time); }); }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
app/utils/stream.ts
TypeScript
/** * 将 ReadableStream 转为字符串 */ export async function stream2string(stream: ReadableStream | undefined | null, onMessage?: (content: string) => void) { if (!stream) { return ''; } const reader = stream.getReader(); const decoder = new TextDecoder('utf-8'); let result = ''; while (true) { const { done, value } = await reader.read(); if (done) { break; } const trunk = decoder.decode(value, { stream: true }); onMessage?.(trunk); result += trunk; } reader.releaseLock(); return result; }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
bak/messageUpgrade.ts
TypeScript
/** * 由于变更了数据格式,所以这个文件做了兼容 */ import { Role } from './constants'; import type { Message } from './constants'; export interface MessageOld { avatar: 'user' | 'ChatGPT'; chatMessage: { text: string; role: Role; id: string; parentMessageId: string; detail: { id: string; object: string; created: number; model: string; choices: { delta: {}; index: number; finish_reason: string; }[]; }; }; } export function isOldMessage(message: any): message is MessageOld { if (message === undefined) { return false; } if (message.chatMessage) { return true; } return false; } export function upgradeMessage(message: any): Message { if (isOldMessage(message)) { return { role: message.avatar === 'user' ? Role.user : Role.assistant, content: message.chatMessage.text, }; } return message; }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
bak/object.ts
TypeScript
export function isObject(value: any) { if (typeof value === 'object' && value !== null) { return true; } return false; } /** * 递归的去除对象中的所有 undefined、null 和空对象 * TODO 没有处理循环引用 */ export function cleanObject(value: any) { // 如果是一个普通值,则直接返回该值 if (!Array.isArray(value) && !isObject(value)) { return value; } // 如果是一个数组 if (Array.isArray(value)) { const newArray: any[] = []; // 针对数组的每一项,递归的执行 cleanObject value.forEach((item) => { const newItem = cleanObject(item); // 如果 cleanObject 的结果是空,则放弃该项 if (newItem === undefined || newItem === null) { return; } // 如果 cleanObject 的结果不为空,则加入到 newArray 中 newArray.push(newItem); }); // 检查 newArray 是否为空数组,如果是空数组,则直接返回空 if (newArray.length === 0) { return null; } // 如果不是空数组,则返回 newArray return newArray; } // 如果是一个对象 const newObject: Record<string, any> = {}; Object.keys(value).forEach((key) => { const newValue = cleanObject(value[key]); // 如果 cleanObject 的结果是空,则放弃该项 if (newValue === undefined || newValue === null) { return; } // 如果 cleanObject 的结果不为空,则加入到 newObject 中 newObject[key] = newValue; }); // 检查 newObject 是否为空对象,如果是空对象,则直接返回空 if (Object.keys(newObject).length === 0) { return null; } // 如果不是空对象,则返回 newObject return newObject; } /** * 将 object 重新生成,递归的按照字母排序 key * TODO 没有处理循环引用 */ export function sortObjectKeys(value: any): any { // 如果是一个普通值,则直接返回该值 if (!Array.isArray(value) && !isObject(value)) { return value; } // 如果是一个数组,不要调换其顺序,但需要递归的调用 sortObjectKeys if (Array.isArray(value)) { return value.map((item) => sortObjectKeys(item)); } // 如果是一个对象,递归的按照字母排序 key const sortedKeys = Object.keys(value).sort(); return Object.fromEntries(sortedKeys.map((key) => [key, sortObjectKeys(value[key])])); } /** * 序列化一个对象,去除空值,按照字母排序 key,保证相同对象得到相同的字符串 */ export function serializeObject(obj: any) { // 去除空值 const cleanedObject = cleanObject(obj); // 如果为空,则返回空字符串 if (cleanedObject === undefined || cleanedObject === null) { return ''; } // 对去除了空值的对象进行 key 排序 const sortedObject = sortObjectKeys(cleanedObject); // 序列化对象并返回 return JSON.stringify(sortedObject); }
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
bin.js
JavaScript
#!/usr/bin/env node const { spawn } = require('child_process'); // 获取命令行参数 const args = process.argv.slice(2); spawn('npm', ['start', ...args], { stdio: 'inherit', cwd: __dirname, });
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
next.config.js
JavaScript
/** @type {import('next').NextConfig} */ const nextConfig = { experimental: { appDir: true, }, }; module.exports = nextConfig;
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
postcss.config.js
JavaScript
module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, }, };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
public/prism-dark.css
CSS
/* PrismJS 1.29.0 https://prismjs.com/download.html#themes=prism-tomorrow&languages=markup+css+clike+javascript+bash+c+csharp+cpp+css-extras+go+java+javadoclike+jsdoc+latex+markup-templating+matlab+perl+php+python+jsx+tsx+ruby+rust+sql+swift+typescript+visual-basic+yaml&plugins=autolinker */ code[class*=language-],pre[class*=language-]{color:#ccc;background:0 0;font-family:Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#2d2d2d}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.block-comment,.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#999}.token.punctuation{color:#ccc}.token.attr-name,.token.deleted,.token.namespace,.token.tag{color:#e2777a}.token.function-name{color:#6196cc}.token.boolean,.token.function,.token.number{color:#f08d49}.token.class-name,.token.constant,.token.property,.token.symbol{color:#f8c555}.token.atrule,.token.builtin,.token.important,.token.keyword,.token.selector{color:#cc99cd}.token.attr-value,.token.char,.token.regex,.token.string,.token.variable{color:#7ec699}.token.entity,.token.operator,.token.url{color:#67cdcc}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help}.token.inserted{color:green} .token a{color:inherit}
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
public/prism-light.css
CSS
/* PrismJS 1.29.0 https://prismjs.com/download.html#themes=prism&languages=markup+css+clike+javascript+bash+c+csharp+cpp+css-extras+go+java+javadoclike+jsdoc+latex+markup-templating+matlab+perl+php+python+jsx+tsx+ruby+rust+sql+swift+typescript+visual-basic+yaml&plugins=autolinker */ code[class*=language-],pre[class*=language-]{color:#000;background:0 0;text-shadow:0 1px #fff;font-family:Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}code[class*=language-] ::-moz-selection,code[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection,pre[class*=language-]::-moz-selection{text-shadow:none;background:#b3d4fc}code[class*=language-] ::selection,code[class*=language-]::selection,pre[class*=language-] ::selection,pre[class*=language-]::selection{text-shadow:none;background:#b3d4fc}@media print{code[class*=language-],pre[class*=language-]{text-shadow:none}}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#f5f2f0}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#708090}.token.punctuation{color:#999}.token.namespace{opacity:.7}.token.boolean,.token.constant,.token.deleted,.token.number,.token.property,.token.symbol,.token.tag{color:#905}.token.attr-name,.token.builtin,.token.char,.token.inserted,.token.selector,.token.string{color:#690}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url{color:#9a6e3a;background:hsla(0,0%,100%,.5)}.token.atrule,.token.attr-value,.token.keyword{color:#07a}.token.class-name,.token.function{color:#dd4a68}.token.important,.token.regex,.token.variable{color:#e90}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help} .token a{color:inherit}
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
public/prism.js
JavaScript
/* PrismJS 1.29.0 https://prismjs.com/download.html#themes=prism&languages=markup+css+clike+javascript+bash+c+csharp+cpp+css-extras+go+java+javadoclike+jsdoc+latex+markup-templating+matlab+perl+php+python+jsx+tsx+ruby+rust+sql+swift+typescript+visual-basic+yaml&plugins=autolinker */ var _self="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{},Prism=function(e){var n=/(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i,t=0,r={},a={manual:e.Prism&&e.Prism.manual,disableWorkerMessageHandler:e.Prism&&e.Prism.disableWorkerMessageHandler,util:{encode:function e(n){return n instanceof i?new i(n.type,e(n.content),n.alias):Array.isArray(n)?n.map(e):n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/\u00a0/g," ")},type:function(e){return Object.prototype.toString.call(e).slice(8,-1)},objId:function(e){return e.__id||Object.defineProperty(e,"__id",{value:++t}),e.__id},clone:function e(n,t){var r,i;switch(t=t||{},a.util.type(n)){case"Object":if(i=a.util.objId(n),t[i])return t[i];for(var l in r={},t[i]=r,n)n.hasOwnProperty(l)&&(r[l]=e(n[l],t));return r;case"Array":return i=a.util.objId(n),t[i]?t[i]:(r=[],t[i]=r,n.forEach((function(n,a){r[a]=e(n,t)})),r);default:return n}},getLanguage:function(e){for(;e;){var t=n.exec(e.className);if(t)return t[1].toLowerCase();e=e.parentElement}return"none"},setLanguage:function(e,t){e.className=e.className.replace(RegExp(n,"gi"),""),e.classList.add("language-"+t)},currentScript:function(){if("undefined"==typeof document)return null;if("currentScript"in document)return document.currentScript;try{throw new Error}catch(r){var e=(/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(r.stack)||[])[1];if(e){var n=document.getElementsByTagName("script");for(var t in n)if(n[t].src==e)return n[t]}return null}},isActive:function(e,n,t){for(var r="no-"+n;e;){var a=e.classList;if(a.contains(n))return!0;if(a.contains(r))return!1;e=e.parentElement}return!!t}},languages:{plain:r,plaintext:r,text:r,txt:r,extend:function(e,n){var t=a.util.clone(a.languages[e]);for(var r in n)t[r]=n[r];return t},insertBefore:function(e,n,t,r){var i=(r=r||a.languages)[e],l={};for(var o in i)if(i.hasOwnProperty(o)){if(o==n)for(var s in t)t.hasOwnProperty(s)&&(l[s]=t[s]);t.hasOwnProperty(o)||(l[o]=i[o])}var u=r[e];return r[e]=l,a.languages.DFS(a.languages,(function(n,t){t===u&&n!=e&&(this[n]=l)})),l},DFS:function e(n,t,r,i){i=i||{};var l=a.util.objId;for(var o in n)if(n.hasOwnProperty(o)){t.call(n,o,n[o],r||o);var s=n[o],u=a.util.type(s);"Object"!==u||i[l(s)]?"Array"!==u||i[l(s)]||(i[l(s)]=!0,e(s,t,o,i)):(i[l(s)]=!0,e(s,t,null,i))}}},plugins:{},highlightAll:function(e,n){a.highlightAllUnder(document,e,n)},highlightAllUnder:function(e,n,t){var r={callback:t,container:e,selector:'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'};a.hooks.run("before-highlightall",r),r.elements=Array.prototype.slice.apply(r.container.querySelectorAll(r.selector)),a.hooks.run("before-all-elements-highlight",r);for(var i,l=0;i=r.elements[l++];)a.highlightElement(i,!0===n,r.callback)},highlightElement:function(n,t,r){var i=a.util.getLanguage(n),l=a.languages[i];a.util.setLanguage(n,i);var o=n.parentElement;o&&"pre"===o.nodeName.toLowerCase()&&a.util.setLanguage(o,i);var s={element:n,language:i,grammar:l,code:n.textContent};function u(e){s.highlightedCode=e,a.hooks.run("before-insert",s),s.element.innerHTML=s.highlightedCode,a.hooks.run("after-highlight",s),a.hooks.run("complete",s),r&&r.call(s.element)}if(a.hooks.run("before-sanity-check",s),(o=s.element.parentElement)&&"pre"===o.nodeName.toLowerCase()&&!o.hasAttribute("tabindex")&&o.setAttribute("tabindex","0"),!s.code)return a.hooks.run("complete",s),void(r&&r.call(s.element));if(a.hooks.run("before-highlight",s),s.grammar)if(t&&e.Worker){var c=new Worker(a.filename);c.onmessage=function(e){u(e.data)},c.postMessage(JSON.stringify({language:s.language,code:s.code,immediateClose:!0}))}else u(a.highlight(s.code,s.grammar,s.language));else u(a.util.encode(s.code))},highlight:function(e,n,t){var r={code:e,grammar:n,language:t};if(a.hooks.run("before-tokenize",r),!r.grammar)throw new Error('The language "'+r.language+'" has no grammar.');return r.tokens=a.tokenize(r.code,r.grammar),a.hooks.run("after-tokenize",r),i.stringify(a.util.encode(r.tokens),r.language)},tokenize:function(e,n){var t=n.rest;if(t){for(var r in t)n[r]=t[r];delete n.rest}var a=new s;return u(a,a.head,e),o(e,a,n,a.head,0),function(e){for(var n=[],t=e.head.next;t!==e.tail;)n.push(t.value),t=t.next;return n}(a)},hooks:{all:{},add:function(e,n){var t=a.hooks.all;t[e]=t[e]||[],t[e].push(n)},run:function(e,n){var t=a.hooks.all[e];if(t&&t.length)for(var r,i=0;r=t[i++];)r(n)}},Token:i};function i(e,n,t,r){this.type=e,this.content=n,this.alias=t,this.length=0|(r||"").length}function l(e,n,t,r){e.lastIndex=n;var a=e.exec(t);if(a&&r&&a[1]){var i=a[1].length;a.index+=i,a[0]=a[0].slice(i)}return a}function o(e,n,t,r,s,g){for(var f in t)if(t.hasOwnProperty(f)&&t[f]){var h=t[f];h=Array.isArray(h)?h:[h];for(var d=0;d<h.length;++d){if(g&&g.cause==f+","+d)return;var v=h[d],p=v.inside,m=!!v.lookbehind,y=!!v.greedy,k=v.alias;if(y&&!v.pattern.global){var x=v.pattern.toString().match(/[imsuy]*$/)[0];v.pattern=RegExp(v.pattern.source,x+"g")}for(var b=v.pattern||v,w=r.next,A=s;w!==n.tail&&!(g&&A>=g.reach);A+=w.value.length,w=w.next){var E=w.value;if(n.length>e.length)return;if(!(E instanceof i)){var P,L=1;if(y){if(!(P=l(b,A,e,m))||P.index>=e.length)break;var S=P.index,O=P.index+P[0].length,j=A;for(j+=w.value.length;S>=j;)j+=(w=w.next).value.length;if(A=j-=w.value.length,w.value instanceof i)continue;for(var C=w;C!==n.tail&&(j<O||"string"==typeof C.value);C=C.next)L++,j+=C.value.length;L--,E=e.slice(A,j),P.index-=A}else if(!(P=l(b,0,E,m)))continue;S=P.index;var N=P[0],_=E.slice(0,S),M=E.slice(S+N.length),W=A+E.length;g&&W>g.reach&&(g.reach=W);var z=w.prev;if(_&&(z=u(n,z,_),A+=_.length),c(n,z,L),w=u(n,z,new i(f,p?a.tokenize(N,p):N,k,N)),M&&u(n,w,M),L>1){var I={cause:f+","+d,reach:W};o(e,n,t,w.prev,A,I),g&&I.reach>g.reach&&(g.reach=I.reach)}}}}}}function s(){var e={value:null,prev:null,next:null},n={value:null,prev:e,next:null};e.next=n,this.head=e,this.tail=n,this.length=0}function u(e,n,t){var r=n.next,a={value:t,prev:n,next:r};return n.next=a,r.prev=a,e.length++,a}function c(e,n,t){for(var r=n.next,a=0;a<t&&r!==e.tail;a++)r=r.next;n.next=r,r.prev=n,e.length-=a}if(e.Prism=a,i.stringify=function e(n,t){if("string"==typeof n)return n;if(Array.isArray(n)){var r="";return n.forEach((function(n){r+=e(n,t)})),r}var i={type:n.type,content:e(n.content,t),tag:"span",classes:["token",n.type],attributes:{},language:t},l=n.alias;l&&(Array.isArray(l)?Array.prototype.push.apply(i.classes,l):i.classes.push(l)),a.hooks.run("wrap",i);var o="";for(var s in i.attributes)o+=" "+s+'="'+(i.attributes[s]||"").replace(/"/g,"&quot;")+'"';return"<"+i.tag+' class="'+i.classes.join(" ")+'"'+o+">"+i.content+"</"+i.tag+">"},!e.document)return e.addEventListener?(a.disableWorkerMessageHandler||e.addEventListener("message",(function(n){var t=JSON.parse(n.data),r=t.language,i=t.code,l=t.immediateClose;e.postMessage(a.highlight(i,a.languages[r],r)),l&&e.close()}),!1),a):a;var g=a.util.currentScript();function f(){a.manual||a.highlightAll()}if(g&&(a.filename=g.src,g.hasAttribute("data-manual")&&(a.manual=!0)),!a.manual){var h=document.readyState;"loading"===h||"interactive"===h&&g&&g.defer?document.addEventListener("DOMContentLoaded",f):window.requestAnimationFrame?window.requestAnimationFrame(f):window.setTimeout(f,16)}return a}(_self);"undefined"!=typeof module&&module.exports&&(module.exports=Prism),"undefined"!=typeof global&&(global.Prism=Prism); Prism.languages.markup={comment:{pattern:/<!--(?:(?!<!--)[\s\S])*?-->/,greedy:!0},prolog:{pattern:/<\?[\s\S]+?\?>/,greedy:!0},doctype:{pattern:/<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,greedy:!0,inside:{"internal-subset":{pattern:/(^[^\[]*\[)[\s\S]+(?=\]>$)/,lookbehind:!0,greedy:!0,inside:null},string:{pattern:/"[^"]*"|'[^']*'/,greedy:!0},punctuation:/^<!|>$|[[\]]/,"doctype-tag":/^DOCTYPE/i,name:/[^\s<>'"]+/}},cdata:{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,greedy:!0},tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"special-attr":[],"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{punctuation:[{pattern:/^=/,alias:"attr-equals"},{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:[{pattern:/&[\da-z]{1,8};/i,alias:"named-entity"},/&#x?[\da-f]{1,8};/i]},Prism.languages.markup.tag.inside["attr-value"].inside.entity=Prism.languages.markup.entity,Prism.languages.markup.doctype.inside["internal-subset"].inside=Prism.languages.markup,Prism.hooks.add("wrap",(function(a){"entity"===a.type&&(a.attributes.title=a.content.replace(/&amp;/,"&"))})),Object.defineProperty(Prism.languages.markup.tag,"addInlined",{value:function(a,e){var s={};s["language-"+e]={pattern:/(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,lookbehind:!0,inside:Prism.languages[e]},s.cdata=/^<!\[CDATA\[|\]\]>$/i;var t={"included-cdata":{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,inside:s}};t["language-"+e]={pattern:/[\s\S]+/,inside:Prism.languages[e]};var n={};n[a]={pattern:RegExp("(<__[^>]*>)(?:<!\\[CDATA\\[(?:[^\\]]|\\](?!\\]>))*\\]\\]>|(?!<!\\[CDATA\\[)[^])*?(?=</__>)".replace(/__/g,(function(){return a})),"i"),lookbehind:!0,greedy:!0,inside:t},Prism.languages.insertBefore("markup","cdata",n)}}),Object.defineProperty(Prism.languages.markup.tag,"addAttribute",{value:function(a,e){Prism.languages.markup.tag.inside["special-attr"].push({pattern:RegExp("(^|[\"'\\s])(?:"+a+")\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s'\">=]+(?=[\\s>]))","i"),lookbehind:!0,inside:{"attr-name":/^[^\s=]+/,"attr-value":{pattern:/=[\s\S]+/,inside:{value:{pattern:/(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,lookbehind:!0,alias:[e,"language-"+e],inside:Prism.languages[e]},punctuation:[{pattern:/^=/,alias:"attr-equals"},/"|'/]}}}})}}),Prism.languages.html=Prism.languages.markup,Prism.languages.mathml=Prism.languages.markup,Prism.languages.svg=Prism.languages.markup,Prism.languages.xml=Prism.languages.extend("markup",{}),Prism.languages.ssml=Prism.languages.xml,Prism.languages.atom=Prism.languages.xml,Prism.languages.rss=Prism.languages.xml; !function(s){var e=/(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;s.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:RegExp("@[\\w-](?:[^;{\\s\"']|\\s+(?!\\s)|"+e.source+")*?(?:;|(?=\\s*\\{))"),inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,lookbehind:!0,alias:"selector"},keyword:{pattern:/(^|[^\w-])(?:and|not|only|or)(?![\w-])/,lookbehind:!0}}},url:{pattern:RegExp("\\burl\\((?:"+e.source+"|(?:[^\\\\\r\n()\"']|\\\\[^])*)\\)","i"),greedy:!0,inside:{function:/^url/i,punctuation:/^\(|\)$/,string:{pattern:RegExp("^"+e.source+"$"),alias:"url"}}},selector:{pattern:RegExp("(^|[{}\\s])[^{}\\s](?:[^{};\"'\\s]|\\s+(?![\\s{])|"+e.source+")*(?=\\s*\\{)"),lookbehind:!0},string:{pattern:e,greedy:!0},property:{pattern:/(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,lookbehind:!0},important:/!important\b/i,function:{pattern:/(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,lookbehind:!0},punctuation:/[(){};:,]/},s.languages.css.atrule.inside.rest=s.languages.css;var t=s.languages.markup;t&&(t.tag.addInlined("style","css"),t.tag.addAttribute("style","css"))}(Prism); Prism.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,boolean:/\b(?:false|true)\b/,function:/\b\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/}; Prism.languages.javascript=Prism.languages.extend("clike",{"class-name":[Prism.languages.clike["class-name"],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,lookbehind:!0}],keyword:[{pattern:/((?:^|\})\s*)catch\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],function:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,number:{pattern:RegExp("(^|[^\\w$])(?:NaN|Infinity|0[bB][01]+(?:_[01]+)*n?|0[oO][0-7]+(?:_[0-7]+)*n?|0[xX][\\dA-Fa-f]+(?:_[\\dA-Fa-f]+)*n?|\\d+(?:_\\d+)*n|(?:\\d+(?:_\\d+)*(?:\\.(?:\\d+(?:_\\d+)*)?)?|\\.\\d+(?:_\\d+)*)(?:[Ee][+-]?\\d+(?:_\\d+)*)?)(?![\\w$])"),lookbehind:!0},operator:/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/}),Prism.languages.javascript["class-name"][0].pattern=/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/,Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:RegExp("((?:^|[^$\\w\\xA0-\\uFFFF.\"'\\])\\s]|\\b(?:return|yield))\\s*)/(?:(?:\\[(?:[^\\]\\\\\r\n]|\\\\.)*\\]|\\\\.|[^/\\\\\\[\r\n])+/[dgimyus]{0,7}|(?:\\[(?:[^[\\]\\\\\r\n]|\\\\.|\\[(?:[^[\\]\\\\\r\n]|\\\\.|\\[(?:[^[\\]\\\\\r\n]|\\\\.)*\\])*\\])*\\]|\\\\.|[^/\\\\\\[\r\n])+/[dgimyus]{0,7}v[dgimyus]{0,7})(?=(?:\\s|/\\*(?:[^*]|\\*(?!/))*\\*/)*(?:$|[\r\n,.;:})\\]]|//))"),lookbehind:!0,greedy:!0,inside:{"regex-source":{pattern:/^(\/)[\s\S]+(?=\/[a-z]*$)/,lookbehind:!0,alias:"language-regex",inside:Prism.languages.regex},"regex-delimiter":/^\/|\/$/,"regex-flags":/^[a-z]+$/}},"function-variable":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,alias:"function"},parameter:[{pattern:/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,lookbehind:!0,inside:Prism.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/}),Prism.languages.insertBefore("javascript","string",{hashbang:{pattern:/^#!.*/,greedy:!0,alias:"comment"},"template-string":{pattern:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:"punctuation"},rest:Prism.languages.javascript}},string:/[\s\S]+/}},"string-property":{pattern:/((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,lookbehind:!0,greedy:!0,alias:"property"}}),Prism.languages.insertBefore("javascript","operator",{"literal-property":{pattern:/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,lookbehind:!0,alias:"property"}}),Prism.languages.markup&&(Prism.languages.markup.tag.addInlined("script","javascript"),Prism.languages.markup.tag.addAttribute("on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)","javascript")),Prism.languages.js=Prism.languages.javascript; !function(e){var t="\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b",a={pattern:/(^(["']?)\w+\2)[ \t]+\S.*/,lookbehind:!0,alias:"punctuation",inside:null},n={bash:a,environment:{pattern:RegExp("\\$"+t),alias:"constant"},variable:[{pattern:/\$?\(\([\s\S]+?\)\)/,greedy:!0,inside:{variable:[{pattern:/(^\$\(\([\s\S]+)\)\)/,lookbehind:!0},/^\$\(\(/],number:/\b0x[\dA-Fa-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[Ee]-?\d+)?/,operator:/--|\+\+|\*\*=?|<<=?|>>=?|&&|\|\||[=!+\-*/%<>^&|]=?|[?~:]/,punctuation:/\(\(?|\)\)?|,|;/}},{pattern:/\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,greedy:!0,inside:{variable:/^\$\(|^`|\)$|`$/}},{pattern:/\$\{[^}]+\}/,greedy:!0,inside:{operator:/:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,punctuation:/[\[\]]/,environment:{pattern:RegExp("(\\{)"+t),lookbehind:!0,alias:"constant"}}},/\$(?:\w+|[#?*!@$])/],entity:/\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|U[0-9a-fA-F]{8}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{1,2})/};e.languages.bash={shebang:{pattern:/^#!\s*\/.*/,alias:"important"},comment:{pattern:/(^|[^"{\\$])#.*/,lookbehind:!0},"function-name":[{pattern:/(\bfunction\s+)[\w-]+(?=(?:\s*\(?:\s*\))?\s*\{)/,lookbehind:!0,alias:"function"},{pattern:/\b[\w-]+(?=\s*\(\s*\)\s*\{)/,alias:"function"}],"for-or-select":{pattern:/(\b(?:for|select)\s+)\w+(?=\s+in\s)/,alias:"variable",lookbehind:!0},"assign-left":{pattern:/(^|[\s;|&]|[<>]\()\w+(?:\.\w+)*(?=\+?=)/,inside:{environment:{pattern:RegExp("(^|[\\s;|&]|[<>]\\()"+t),lookbehind:!0,alias:"constant"}},alias:"variable",lookbehind:!0},parameter:{pattern:/(^|\s)-{1,2}(?:\w+:[+-]?)?\w+(?:\.\w+)*(?=[=\s]|$)/,alias:"variable",lookbehind:!0},string:[{pattern:/((?:^|[^<])<<-?\s*)(\w+)\s[\s\S]*?(?:\r?\n|\r)\2/,lookbehind:!0,greedy:!0,inside:n},{pattern:/((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s[\s\S]*?(?:\r?\n|\r)\3/,lookbehind:!0,greedy:!0,inside:{bash:a}},{pattern:/(^|[^\\](?:\\\\)*)"(?:\\[\s\S]|\$\([^)]+\)|\$(?!\()|`[^`]+`|[^"\\`$])*"/,lookbehind:!0,greedy:!0,inside:n},{pattern:/(^|[^$\\])'[^']*'/,lookbehind:!0,greedy:!0},{pattern:/\$'(?:[^'\\]|\\[\s\S])*'/,greedy:!0,inside:{entity:n.entity}}],environment:{pattern:RegExp("\\$?"+t),alias:"constant"},variable:n.variable,function:{pattern:/(^|[\s;|&]|[<>]\()(?:add|apropos|apt|apt-cache|apt-get|aptitude|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cargo|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|composer|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|docker|docker-compose|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|java|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|node|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|podman|podman-compose|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|sysctl|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vcpkg|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,lookbehind:!0},keyword:{pattern:/(^|[\s;|&]|[<>]\()(?:case|do|done|elif|else|esac|fi|for|function|if|in|select|then|until|while)(?=$|[)\s;|&])/,lookbehind:!0},builtin:{pattern:/(^|[\s;|&]|[<>]\()(?:\.|:|alias|bind|break|builtin|caller|cd|command|continue|declare|echo|enable|eval|exec|exit|export|getopts|hash|help|let|local|logout|mapfile|printf|pwd|read|readarray|readonly|return|set|shift|shopt|source|test|times|trap|type|typeset|ulimit|umask|unalias|unset)(?=$|[)\s;|&])/,lookbehind:!0,alias:"class-name"},boolean:{pattern:/(^|[\s;|&]|[<>]\()(?:false|true)(?=$|[)\s;|&])/,lookbehind:!0},"file-descriptor":{pattern:/\B&\d\b/,alias:"important"},operator:{pattern:/\d?<>|>\||\+=|=[=~]?|!=?|<<[<-]?|[&\d]?>>|\d[<>]&?|[<>][&=]?|&[>&]?|\|[&|]?/,inside:{"file-descriptor":{pattern:/^\d/,alias:"important"}}},punctuation:/\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,number:{pattern:/(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,lookbehind:!0}},a.inside=e.languages.bash;for(var s=["comment","function-name","for-or-select","assign-left","parameter","string","environment","function","keyword","builtin","boolean","file-descriptor","operator","punctuation","number"],o=n.variable[1].inside,i=0;i<s.length;i++)o[s[i]]=e.languages.bash[s[i]];e.languages.sh=e.languages.bash,e.languages.shell=e.languages.bash}(Prism); Prism.languages.c=Prism.languages.extend("clike",{comment:{pattern:/\/\/(?:[^\r\n\\]|\\(?:\r\n?|\n|(?![\r\n])))*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},string:{pattern:/"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"/,greedy:!0},"class-name":{pattern:/(\b(?:enum|struct)\s+(?:__attribute__\s*\(\([\s\S]*?\)\)\s*)?)\w+|\b[a-z]\w*_t\b/,lookbehind:!0},keyword:/\b(?:_Alignas|_Alignof|_Atomic|_Bool|_Complex|_Generic|_Imaginary|_Noreturn|_Static_assert|_Thread_local|__attribute__|asm|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|inline|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|typeof|union|unsigned|void|volatile|while)\b/,function:/\b[a-z_]\w*(?=\s*\()/i,number:/(?:\b0x(?:[\da-f]+(?:\.[\da-f]*)?|\.[\da-f]+)(?:p[+-]?\d+)?|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?)[ful]{0,4}/i,operator:/>>=?|<<=?|->|([-+&|:])\1|[?:~]|[-+*/%&|^!=<>]=?/}),Prism.languages.insertBefore("c","string",{char:{pattern:/'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n]){0,32}'/,greedy:!0}}),Prism.languages.insertBefore("c","string",{macro:{pattern:/(^[\t ]*)#\s*[a-z](?:[^\r\n\\/]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|\\(?:\r\n|[\s\S]))*/im,lookbehind:!0,greedy:!0,alias:"property",inside:{string:[{pattern:/^(#\s*include\s*)<[^>]+>/,lookbehind:!0},Prism.languages.c.string],char:Prism.languages.c.char,comment:Prism.languages.c.comment,"macro-name":[{pattern:/(^#\s*define\s+)\w+\b(?!\()/i,lookbehind:!0},{pattern:/(^#\s*define\s+)\w+\b(?=\()/i,lookbehind:!0,alias:"function"}],directive:{pattern:/^(#\s*)[a-z]+/,lookbehind:!0,alias:"keyword"},"directive-hash":/^#/,punctuation:/##|\\(?=[\r\n])/,expression:{pattern:/\S[\s\S]*/,inside:Prism.languages.c}}}}),Prism.languages.insertBefore("c","function",{constant:/\b(?:EOF|NULL|SEEK_CUR|SEEK_END|SEEK_SET|__DATE__|__FILE__|__LINE__|__TIMESTAMP__|__TIME__|__func__|stderr|stdin|stdout)\b/}),delete Prism.languages.c.boolean; !function(e){function n(e,n){return e.replace(/<<(\d+)>>/g,(function(e,s){return"(?:"+n[+s]+")"}))}function s(e,s,a){return RegExp(n(e,s),a||"")}function a(e,n){for(var s=0;s<n;s++)e=e.replace(/<<self>>/g,(function(){return"(?:"+e+")"}));return e.replace(/<<self>>/g,"[^\\s\\S]")}var t="bool byte char decimal double dynamic float int long object sbyte short string uint ulong ushort var void",r="class enum interface record struct",i="add alias and ascending async await by descending from(?=\\s*(?:\\w|$)) get global group into init(?=\\s*;) join let nameof not notnull on or orderby partial remove select set unmanaged value when where with(?=\\s*{)",o="abstract as base break case catch checked const continue default delegate do else event explicit extern finally fixed for foreach goto if implicit in internal is lock namespace new null operator out override params private protected public readonly ref return sealed sizeof stackalloc static switch this throw try typeof unchecked unsafe using virtual volatile while yield";function l(e){return"\\b(?:"+e.trim().replace(/ /g,"|")+")\\b"}var d=l(r),p=RegExp(l(t+" "+r+" "+i+" "+o)),c=l(r+" "+i+" "+o),u=l(t+" "+r+" "+o),g=a("<(?:[^<>;=+\\-*/%&|^]|<<self>>)*>",2),b=a("\\((?:[^()]|<<self>>)*\\)",2),h="@?\\b[A-Za-z_]\\w*\\b",f=n("<<0>>(?:\\s*<<1>>)?",[h,g]),m=n("(?!<<0>>)<<1>>(?:\\s*\\.\\s*<<1>>)*",[c,f]),k="\\[\\s*(?:,\\s*)*\\]",y=n("<<0>>(?:\\s*(?:\\?\\s*)?<<1>>)*(?:\\s*\\?)?",[m,k]),w=n("[^,()<>[\\];=+\\-*/%&|^]|<<0>>|<<1>>|<<2>>",[g,b,k]),v=n("\\(<<0>>+(?:,<<0>>+)+\\)",[w]),x=n("(?:<<0>>|<<1>>)(?:\\s*(?:\\?\\s*)?<<2>>)*(?:\\s*\\?)?",[v,m,k]),$={keyword:p,punctuation:/[<>()?,.:[\]]/},_="'(?:[^\r\n'\\\\]|\\\\.|\\\\[Uux][\\da-fA-F]{1,8})'",B='"(?:\\\\.|[^\\\\"\r\n])*"';e.languages.csharp=e.languages.extend("clike",{string:[{pattern:s("(^|[^$\\\\])<<0>>",['@"(?:""|\\\\[^]|[^\\\\"])*"(?!")']),lookbehind:!0,greedy:!0},{pattern:s("(^|[^@$\\\\])<<0>>",[B]),lookbehind:!0,greedy:!0}],"class-name":[{pattern:s("(\\busing\\s+static\\s+)<<0>>(?=\\s*;)",[m]),lookbehind:!0,inside:$},{pattern:s("(\\busing\\s+<<0>>\\s*=\\s*)<<1>>(?=\\s*;)",[h,x]),lookbehind:!0,inside:$},{pattern:s("(\\busing\\s+)<<0>>(?=\\s*=)",[h]),lookbehind:!0},{pattern:s("(\\b<<0>>\\s+)<<1>>",[d,f]),lookbehind:!0,inside:$},{pattern:s("(\\bcatch\\s*\\(\\s*)<<0>>",[m]),lookbehind:!0,inside:$},{pattern:s("(\\bwhere\\s+)<<0>>",[h]),lookbehind:!0},{pattern:s("(\\b(?:is(?:\\s+not)?|as)\\s+)<<0>>",[y]),lookbehind:!0,inside:$},{pattern:s("\\b<<0>>(?=\\s+(?!<<1>>|with\\s*\\{)<<2>>(?:\\s*[=,;:{)\\]]|\\s+(?:in|when)\\b))",[x,u,h]),inside:$}],keyword:p,number:/(?:\b0(?:x[\da-f_]*[\da-f]|b[01_]*[01])|(?:\B\.\d+(?:_+\d+)*|\b\d+(?:_+\d+)*(?:\.\d+(?:_+\d+)*)?)(?:e[-+]?\d+(?:_+\d+)*)?)(?:[dflmu]|lu|ul)?\b/i,operator:/>>=?|<<=?|[-=]>|([-+&|])\1|~|\?\?=?|[-+*/%&|^!=<>]=?/,punctuation:/\?\.?|::|[{}[\];(),.:]/}),e.languages.insertBefore("csharp","number",{range:{pattern:/\.\./,alias:"operator"}}),e.languages.insertBefore("csharp","punctuation",{"named-parameter":{pattern:s("([(,]\\s*)<<0>>(?=\\s*:)",[h]),lookbehind:!0,alias:"punctuation"}}),e.languages.insertBefore("csharp","class-name",{namespace:{pattern:s("(\\b(?:namespace|using)\\s+)<<0>>(?:\\s*\\.\\s*<<0>>)*(?=\\s*[;{])",[h]),lookbehind:!0,inside:{punctuation:/\./}},"type-expression":{pattern:s("(\\b(?:default|sizeof|typeof)\\s*\\(\\s*(?!\\s))(?:[^()\\s]|\\s(?!\\s)|<<0>>)*(?=\\s*\\))",[b]),lookbehind:!0,alias:"class-name",inside:$},"return-type":{pattern:s("<<0>>(?=\\s+(?:<<1>>\\s*(?:=>|[({]|\\.\\s*this\\s*\\[)|this\\s*\\[))",[x,m]),inside:$,alias:"class-name"},"constructor-invocation":{pattern:s("(\\bnew\\s+)<<0>>(?=\\s*[[({])",[x]),lookbehind:!0,inside:$,alias:"class-name"},"generic-method":{pattern:s("<<0>>\\s*<<1>>(?=\\s*\\()",[h,g]),inside:{function:s("^<<0>>",[h]),generic:{pattern:RegExp(g),alias:"class-name",inside:$}}},"type-list":{pattern:s("\\b((?:<<0>>\\s+<<1>>|record\\s+<<1>>\\s*<<5>>|where\\s+<<2>>)\\s*:\\s*)(?:<<3>>|<<4>>|<<1>>\\s*<<5>>|<<6>>)(?:\\s*,\\s*(?:<<3>>|<<4>>|<<6>>))*(?=\\s*(?:where|[{;]|=>|$))",[d,f,h,x,p.source,b,"\\bnew\\s*\\(\\s*\\)"]),lookbehind:!0,inside:{"record-arguments":{pattern:s("(^(?!new\\s*\\()<<0>>\\s*)<<1>>",[f,b]),lookbehind:!0,greedy:!0,inside:e.languages.csharp},keyword:p,"class-name":{pattern:RegExp(x),greedy:!0,inside:$},punctuation:/[,()]/}},preprocessor:{pattern:/(^[\t ]*)#.*/m,lookbehind:!0,alias:"property",inside:{directive:{pattern:/(#)\b(?:define|elif|else|endif|endregion|error|if|line|nullable|pragma|region|undef|warning)\b/,lookbehind:!0,alias:"keyword"}}}});var E=B+"|"+_,R=n("/(?![*/])|//[^\r\n]*[\r\n]|/\\*(?:[^*]|\\*(?!/))*\\*/|<<0>>",[E]),z=a(n("[^\"'/()]|<<0>>|\\(<<self>>*\\)",[R]),2),S="\\b(?:assembly|event|field|method|module|param|property|return|type)\\b",j=n("<<0>>(?:\\s*\\(<<1>>*\\))?",[m,z]);e.languages.insertBefore("csharp","class-name",{attribute:{pattern:s("((?:^|[^\\s\\w>)?])\\s*\\[\\s*)(?:<<0>>\\s*:\\s*)?<<1>>(?:\\s*,\\s*<<1>>)*(?=\\s*\\])",[S,j]),lookbehind:!0,greedy:!0,inside:{target:{pattern:s("^<<0>>(?=\\s*:)",[S]),alias:"keyword"},"attribute-arguments":{pattern:s("\\(<<0>>*\\)",[z]),inside:e.languages.csharp},"class-name":{pattern:RegExp(m),inside:{punctuation:/\./}},punctuation:/[:,]/}}});var A=":[^}\r\n]+",F=a(n("[^\"'/()]|<<0>>|\\(<<self>>*\\)",[R]),2),P=n("\\{(?!\\{)(?:(?![}:])<<0>>)*<<1>>?\\}",[F,A]),U=a(n("[^\"'/()]|/(?!\\*)|/\\*(?:[^*]|\\*(?!/))*\\*/|<<0>>|\\(<<self>>*\\)",[E]),2),Z=n("\\{(?!\\{)(?:(?![}:])<<0>>)*<<1>>?\\}",[U,A]);function q(n,a){return{interpolation:{pattern:s("((?:^|[^{])(?:\\{\\{)*)<<0>>",[n]),lookbehind:!0,inside:{"format-string":{pattern:s("(^\\{(?:(?![}:])<<0>>)*)<<1>>(?=\\}$)",[a,A]),lookbehind:!0,inside:{punctuation:/^:/}},punctuation:/^\{|\}$/,expression:{pattern:/[\s\S]+/,alias:"language-csharp",inside:e.languages.csharp}}},string:/[\s\S]+/}}e.languages.insertBefore("csharp","string",{"interpolation-string":[{pattern:s('(^|[^\\\\])(?:\\$@|@\\$)"(?:""|\\\\[^]|\\{\\{|<<0>>|[^\\\\{"])*"',[P]),lookbehind:!0,greedy:!0,inside:q(P,F)},{pattern:s('(^|[^@\\\\])\\$"(?:\\\\.|\\{\\{|<<0>>|[^\\\\"{])*"',[Z]),lookbehind:!0,greedy:!0,inside:q(Z,U)}],char:{pattern:RegExp(_),greedy:!0}}),e.languages.dotnet=e.languages.cs=e.languages.csharp}(Prism); !function(e){var t=/\b(?:alignas|alignof|asm|auto|bool|break|case|catch|char|char16_t|char32_t|char8_t|class|co_await|co_return|co_yield|compl|concept|const|const_cast|consteval|constexpr|constinit|continue|decltype|default|delete|do|double|dynamic_cast|else|enum|explicit|export|extern|final|float|for|friend|goto|if|import|inline|int|int16_t|int32_t|int64_t|int8_t|long|module|mutable|namespace|new|noexcept|nullptr|operator|override|private|protected|public|register|reinterpret_cast|requires|return|short|signed|sizeof|static|static_assert|static_cast|struct|switch|template|this|thread_local|throw|try|typedef|typeid|typename|uint16_t|uint32_t|uint64_t|uint8_t|union|unsigned|using|virtual|void|volatile|wchar_t|while)\b/,n="\\b(?!<keyword>)\\w+(?:\\s*\\.\\s*\\w+)*\\b".replace(/<keyword>/g,(function(){return t.source}));e.languages.cpp=e.languages.extend("c",{"class-name":[{pattern:RegExp("(\\b(?:class|concept|enum|struct|typename)\\s+)(?!<keyword>)\\w+".replace(/<keyword>/g,(function(){return t.source}))),lookbehind:!0},/\b[A-Z]\w*(?=\s*::\s*\w+\s*\()/,/\b[A-Z_]\w*(?=\s*::\s*~\w+\s*\()/i,/\b\w+(?=\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>\s*::\s*\w+\s*\()/],keyword:t,number:{pattern:/(?:\b0b[01']+|\b0x(?:[\da-f']+(?:\.[\da-f']*)?|\.[\da-f']+)(?:p[+-]?[\d']+)?|(?:\b[\d']+(?:\.[\d']*)?|\B\.[\d']+)(?:e[+-]?[\d']+)?)[ful]{0,4}/i,greedy:!0},operator:/>>=?|<<=?|->|--|\+\+|&&|\|\||[?:~]|<=>|[-+*/%&|^!=<>]=?|\b(?:and|and_eq|bitand|bitor|not|not_eq|or|or_eq|xor|xor_eq)\b/,boolean:/\b(?:false|true)\b/}),e.languages.insertBefore("cpp","string",{module:{pattern:RegExp('(\\b(?:import|module)\\s+)(?:"(?:\\\\(?:\r\n|[^])|[^"\\\\\r\n])*"|<[^<>\r\n]*>|'+"<mod-name>(?:\\s*:\\s*<mod-name>)?|:\\s*<mod-name>".replace(/<mod-name>/g,(function(){return n}))+")"),lookbehind:!0,greedy:!0,inside:{string:/^[<"][\s\S]+/,operator:/:/,punctuation:/\./}},"raw-string":{pattern:/R"([^()\\ ]{0,16})\([\s\S]*?\)\1"/,alias:"string",greedy:!0}}),e.languages.insertBefore("cpp","keyword",{"generic-function":{pattern:/\b(?!operator\b)[a-z_]\w*\s*<(?:[^<>]|<[^<>]*>)*>(?=\s*\()/i,inside:{function:/^\w+/,generic:{pattern:/<[\s\S]+/,alias:"class-name",inside:e.languages.cpp}}}}),e.languages.insertBefore("cpp","operator",{"double-colon":{pattern:/::/,alias:"punctuation"}}),e.languages.insertBefore("cpp","class-name",{"base-clause":{pattern:/(\b(?:class|struct)\s+\w+\s*:\s*)[^;{}"'\s]+(?:\s+[^;{}"'\s]+)*(?=\s*[;{])/,lookbehind:!0,greedy:!0,inside:e.languages.extend("cpp",{})}}),e.languages.insertBefore("inside","double-colon",{"class-name":/\b[a-z_]\w*\b(?!\s*::)/i},e.languages.cpp["base-clause"])}(Prism); !function(e){var a,n=/("|')(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/;e.languages.css.selector={pattern:e.languages.css.selector.pattern,lookbehind:!0,inside:a={"pseudo-element":/:(?:after|before|first-letter|first-line|selection)|::[-\w]+/,"pseudo-class":/:[-\w]+/,class:/\.[-\w]+/,id:/#[-\w]+/,attribute:{pattern:RegExp("\\[(?:[^[\\]\"']|"+n.source+")*\\]"),greedy:!0,inside:{punctuation:/^\[|\]$/,"case-sensitivity":{pattern:/(\s)[si]$/i,lookbehind:!0,alias:"keyword"},namespace:{pattern:/^(\s*)(?:(?!\s)[-*\w\xA0-\uFFFF])*\|(?!=)/,lookbehind:!0,inside:{punctuation:/\|$/}},"attr-name":{pattern:/^(\s*)(?:(?!\s)[-\w\xA0-\uFFFF])+/,lookbehind:!0},"attr-value":[n,{pattern:/(=\s*)(?:(?!\s)[-\w\xA0-\uFFFF])+(?=\s*$)/,lookbehind:!0}],operator:/[|~*^$]?=/}},"n-th":[{pattern:/(\(\s*)[+-]?\d*[\dn](?:\s*[+-]\s*\d+)?(?=\s*\))/,lookbehind:!0,inside:{number:/[\dn]+/,operator:/[+-]/}},{pattern:/(\(\s*)(?:even|odd)(?=\s*\))/i,lookbehind:!0}],combinator:/>|\+|~|\|\|/,punctuation:/[(),]/}},e.languages.css.atrule.inside["selector-function-argument"].inside=a,e.languages.insertBefore("css","property",{variable:{pattern:/(^|[^-\w\xA0-\uFFFF])--(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*/i,lookbehind:!0}});var r={pattern:/(\b\d+)(?:%|[a-z]+(?![\w-]))/,lookbehind:!0},i={pattern:/(^|[^\w.-])-?(?:\d+(?:\.\d+)?|\.\d+)/,lookbehind:!0};e.languages.insertBefore("css","function",{operator:{pattern:/(\s)[+\-*\/](?=\s)/,lookbehind:!0},hexcode:{pattern:/\B#[\da-f]{3,8}\b/i,alias:"color"},color:[{pattern:/(^|[^\w-])(?:AliceBlue|AntiqueWhite|Aqua|Aquamarine|Azure|Beige|Bisque|Black|BlanchedAlmond|Blue|BlueViolet|Brown|BurlyWood|CadetBlue|Chartreuse|Chocolate|Coral|CornflowerBlue|Cornsilk|Crimson|Cyan|DarkBlue|DarkCyan|DarkGoldenRod|DarkGr[ae]y|DarkGreen|DarkKhaki|DarkMagenta|DarkOliveGreen|DarkOrange|DarkOrchid|DarkRed|DarkSalmon|DarkSeaGreen|DarkSlateBlue|DarkSlateGr[ae]y|DarkTurquoise|DarkViolet|DeepPink|DeepSkyBlue|DimGr[ae]y|DodgerBlue|FireBrick|FloralWhite|ForestGreen|Fuchsia|Gainsboro|GhostWhite|Gold|GoldenRod|Gr[ae]y|Green|GreenYellow|HoneyDew|HotPink|IndianRed|Indigo|Ivory|Khaki|Lavender|LavenderBlush|LawnGreen|LemonChiffon|LightBlue|LightCoral|LightCyan|LightGoldenRodYellow|LightGr[ae]y|LightGreen|LightPink|LightSalmon|LightSeaGreen|LightSkyBlue|LightSlateGr[ae]y|LightSteelBlue|LightYellow|Lime|LimeGreen|Linen|Magenta|Maroon|MediumAquaMarine|MediumBlue|MediumOrchid|MediumPurple|MediumSeaGreen|MediumSlateBlue|MediumSpringGreen|MediumTurquoise|MediumVioletRed|MidnightBlue|MintCream|MistyRose|Moccasin|NavajoWhite|Navy|OldLace|Olive|OliveDrab|Orange|OrangeRed|Orchid|PaleGoldenRod|PaleGreen|PaleTurquoise|PaleVioletRed|PapayaWhip|PeachPuff|Peru|Pink|Plum|PowderBlue|Purple|RebeccaPurple|Red|RosyBrown|RoyalBlue|SaddleBrown|Salmon|SandyBrown|SeaGreen|SeaShell|Sienna|Silver|SkyBlue|SlateBlue|SlateGr[ae]y|Snow|SpringGreen|SteelBlue|Tan|Teal|Thistle|Tomato|Transparent|Turquoise|Violet|Wheat|White|WhiteSmoke|Yellow|YellowGreen)(?![\w-])/i,lookbehind:!0},{pattern:/\b(?:hsl|rgb)\(\s*\d{1,3}\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*\)\B|\b(?:hsl|rgb)a\(\s*\d{1,3}\s*,\s*\d{1,3}%?\s*,\s*\d{1,3}%?\s*,\s*(?:0|0?\.\d+|1)\s*\)\B/i,inside:{unit:r,number:i,function:/[\w-]+(?=\()/,punctuation:/[(),]/}}],entity:/\\[\da-f]{1,8}/i,unit:r,number:i})}(Prism); Prism.languages.go=Prism.languages.extend("clike",{string:{pattern:/(^|[^\\])"(?:\\.|[^"\\\r\n])*"|`[^`]*`/,lookbehind:!0,greedy:!0},keyword:/\b(?:break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go(?:to)?|if|import|interface|map|package|range|return|select|struct|switch|type|var)\b/,boolean:/\b(?:_|false|iota|nil|true)\b/,number:[/\b0(?:b[01_]+|o[0-7_]+)i?\b/i,/\b0x(?:[a-f\d_]+(?:\.[a-f\d_]*)?|\.[a-f\d_]+)(?:p[+-]?\d+(?:_\d+)*)?i?(?!\w)/i,/(?:\b\d[\d_]*(?:\.[\d_]*)?|\B\.\d[\d_]*)(?:e[+-]?[\d_]+)?i?(?!\w)/i],operator:/[*\/%^!=]=?|\+[=+]?|-[=-]?|\|[=|]?|&(?:=|&|\^=?)?|>(?:>=?|=)?|<(?:<=?|=|-)?|:=|\.\.\./,builtin:/\b(?:append|bool|byte|cap|close|complex|complex(?:64|128)|copy|delete|error|float(?:32|64)|u?int(?:8|16|32|64)?|imag|len|make|new|panic|print(?:ln)?|real|recover|rune|string|uintptr)\b/}),Prism.languages.insertBefore("go","string",{char:{pattern:/'(?:\\.|[^'\\\r\n]){0,10}'/,greedy:!0}}),delete Prism.languages.go["class-name"]; !function(e){var n=/\b(?:abstract|assert|boolean|break|byte|case|catch|char|class|const|continue|default|do|double|else|enum|exports|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|module|native|new|non-sealed|null|open|opens|package|permits|private|protected|provides|public|record(?!\s*[(){}[\]<>=%~.:,;?+\-*/&|^])|requires|return|sealed|short|static|strictfp|super|switch|synchronized|this|throw|throws|to|transient|transitive|try|uses|var|void|volatile|while|with|yield)\b/,t="(?:[a-z]\\w*\\s*\\.\\s*)*(?:[A-Z]\\w*\\s*\\.\\s*)*",s={pattern:RegExp("(^|[^\\w.])"+t+"[A-Z](?:[\\d_A-Z]*[a-z]\\w*)?\\b"),lookbehind:!0,inside:{namespace:{pattern:/^[a-z]\w*(?:\s*\.\s*[a-z]\w*)*(?:\s*\.)?/,inside:{punctuation:/\./}},punctuation:/\./}};e.languages.java=e.languages.extend("clike",{string:{pattern:/(^|[^\\])"(?:\\.|[^"\\\r\n])*"/,lookbehind:!0,greedy:!0},"class-name":[s,{pattern:RegExp("(^|[^\\w.])"+t+"[A-Z]\\w*(?=\\s+\\w+\\s*[;,=()]|\\s*(?:\\[[\\s,]*\\]\\s*)?::\\s*new\\b)"),lookbehind:!0,inside:s.inside},{pattern:RegExp("(\\b(?:class|enum|extends|implements|instanceof|interface|new|record|throws)\\s+)"+t+"[A-Z]\\w*\\b"),lookbehind:!0,inside:s.inside}],keyword:n,function:[e.languages.clike.function,{pattern:/(::\s*)[a-z_]\w*/,lookbehind:!0}],number:/\b0b[01][01_]*L?\b|\b0x(?:\.[\da-f_p+-]+|[\da-f_]+(?:\.[\da-f_p+-]+)?)\b|(?:\b\d[\d_]*(?:\.[\d_]*)?|\B\.\d[\d_]*)(?:e[+-]?\d[\d_]*)?[dfl]?/i,operator:{pattern:/(^|[^.])(?:<<=?|>>>?=?|->|--|\+\+|&&|\|\||::|[?:~]|[-+*/%&|^!=<>]=?)/m,lookbehind:!0},constant:/\b[A-Z][A-Z_\d]+\b/}),e.languages.insertBefore("java","string",{"triple-quoted-string":{pattern:/"""[ \t]*[\r\n](?:(?:"|"")?(?:\\.|[^"\\]))*"""/,greedy:!0,alias:"string"},char:{pattern:/'(?:\\.|[^'\\\r\n]){1,6}'/,greedy:!0}}),e.languages.insertBefore("java","class-name",{annotation:{pattern:/(^|[^.])@\w+(?:\s*\.\s*\w+)*/,lookbehind:!0,alias:"punctuation"},generics:{pattern:/<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&)|<(?:[\w\s,.?]|&(?!&))*>)*>)*>)*>/,inside:{"class-name":s,keyword:n,punctuation:/[<>(),.:]/,operator:/[?&|]/}},import:[{pattern:RegExp("(\\bimport\\s+)"+t+"(?:[A-Z]\\w*|\\*)(?=\\s*;)"),lookbehind:!0,inside:{namespace:s.inside.namespace,punctuation:/\./,operator:/\*/,"class-name":/\w+/}},{pattern:RegExp("(\\bimport\\s+static\\s+)"+t+"(?:\\w+|\\*)(?=\\s*;)"),lookbehind:!0,alias:"static",inside:{namespace:s.inside.namespace,static:/\b\w+$/,punctuation:/\./,operator:/\*/,"class-name":/\w+/}}],namespace:{pattern:RegExp("(\\b(?:exports|import(?:\\s+static)?|module|open|opens|package|provides|requires|to|transitive|uses|with)\\s+)(?!<keyword>)[a-z]\\w*(?:\\.[a-z]\\w*)*\\.?".replace(/<keyword>/g,(function(){return n.source}))),lookbehind:!0,inside:{punctuation:/\./}}})}(Prism); !function(e){function n(e,n){return"___"+e.toUpperCase()+n+"___"}Object.defineProperties(e.languages["markup-templating"]={},{buildPlaceholders:{value:function(t,a,r,o){if(t.language===a){var c=t.tokenStack=[];t.code=t.code.replace(r,(function(e){if("function"==typeof o&&!o(e))return e;for(var r,i=c.length;-1!==t.code.indexOf(r=n(a,i));)++i;return c[i]=e,r})),t.grammar=e.languages.markup}}},tokenizePlaceholders:{value:function(t,a){if(t.language===a&&t.tokenStack){t.grammar=e.languages[a];var r=0,o=Object.keys(t.tokenStack);!function c(i){for(var u=0;u<i.length&&!(r>=o.length);u++){var g=i[u];if("string"==typeof g||g.content&&"string"==typeof g.content){var l=o[r],s=t.tokenStack[l],f="string"==typeof g?g:g.content,p=n(a,l),k=f.indexOf(p);if(k>-1){++r;var m=f.substring(0,k),d=new e.Token(a,e.tokenize(s,t.grammar),"language-"+a,s),h=f.substring(k+p.length),v=[];m&&v.push.apply(v,c([m])),v.push(d),h&&v.push.apply(v,c([h])),"string"==typeof g?i.splice.apply(i,[u,1].concat(v)):g.content=v}}else g.content&&c(g.content)}return i}(t.tokens)}}}})}(Prism); !function(e){var a=/\/\*[\s\S]*?\*\/|\/\/.*|#(?!\[).*/,t=[{pattern:/\b(?:false|true)\b/i,alias:"boolean"},{pattern:/(::\s*)\b[a-z_]\w*\b(?!\s*\()/i,greedy:!0,lookbehind:!0},{pattern:/(\b(?:case|const)\s+)\b[a-z_]\w*(?=\s*[;=])/i,greedy:!0,lookbehind:!0},/\b(?:null)\b/i,/\b[A-Z_][A-Z0-9_]*\b(?!\s*\()/],i=/\b0b[01]+(?:_[01]+)*\b|\b0o[0-7]+(?:_[0-7]+)*\b|\b0x[\da-f]+(?:_[\da-f]+)*\b|(?:\b\d+(?:_\d+)*\.?(?:\d+(?:_\d+)*)?|\B\.\d+)(?:e[+-]?\d+)?/i,n=/<?=>|\?\?=?|\.{3}|\??->|[!=]=?=?|::|\*\*=?|--|\+\+|&&|\|\||<<|>>|[?~]|[/^|%*&<>.+-]=?/,s=/[{}\[\](),:;]/;e.languages.php={delimiter:{pattern:/\?>$|^<\?(?:php(?=\s)|=)?/i,alias:"important"},comment:a,variable:/\$+(?:\w+\b|(?=\{))/,package:{pattern:/(namespace\s+|use\s+(?:function\s+)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,lookbehind:!0,inside:{punctuation:/\\/}},"class-name-definition":{pattern:/(\b(?:class|enum|interface|trait)\s+)\b[a-z_]\w*(?!\\)\b/i,lookbehind:!0,alias:"class-name"},"function-definition":{pattern:/(\bfunction\s+)[a-z_]\w*(?=\s*\()/i,lookbehind:!0,alias:"function"},keyword:[{pattern:/(\(\s*)\b(?:array|bool|boolean|float|int|integer|object|string)\b(?=\s*\))/i,alias:"type-casting",greedy:!0,lookbehind:!0},{pattern:/([(,?]\s*)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|object|self|static|string)\b(?=\s*\$)/i,alias:"type-hint",greedy:!0,lookbehind:!0},{pattern:/(\)\s*:\s*(?:\?\s*)?)\b(?:array(?!\s*\()|bool|callable|(?:false|null)(?=\s*\|)|float|int|iterable|mixed|never|object|self|static|string|void)\b/i,alias:"return-type",greedy:!0,lookbehind:!0},{pattern:/\b(?:array(?!\s*\()|bool|float|int|iterable|mixed|object|string|void)\b/i,alias:"type-declaration",greedy:!0},{pattern:/(\|\s*)(?:false|null)\b|\b(?:false|null)(?=\s*\|)/i,alias:"type-declaration",greedy:!0,lookbehind:!0},{pattern:/\b(?:parent|self|static)(?=\s*::)/i,alias:"static-context",greedy:!0},{pattern:/(\byield\s+)from\b/i,lookbehind:!0},/\bclass\b/i,{pattern:/((?:^|[^\s>:]|(?:^|[^-])>|(?:^|[^:]):)\s*)\b(?:abstract|and|array|as|break|callable|case|catch|clone|const|continue|declare|default|die|do|echo|else|elseif|empty|enddeclare|endfor|endforeach|endif|endswitch|endwhile|enum|eval|exit|extends|final|finally|fn|for|foreach|function|global|goto|if|implements|include|include_once|instanceof|insteadof|interface|isset|list|match|namespace|never|new|or|parent|print|private|protected|public|readonly|require|require_once|return|self|static|switch|throw|trait|try|unset|use|var|while|xor|yield|__halt_compiler)\b/i,lookbehind:!0}],"argument-name":{pattern:/([(,]\s*)\b[a-z_]\w*(?=\s*:(?!:))/i,lookbehind:!0},"class-name":[{pattern:/(\b(?:extends|implements|instanceof|new(?!\s+self|\s+static))\s+|\bcatch\s*\()\b[a-z_]\w*(?!\\)\b/i,greedy:!0,lookbehind:!0},{pattern:/(\|\s*)\b[a-z_]\w*(?!\\)\b/i,greedy:!0,lookbehind:!0},{pattern:/\b[a-z_]\w*(?!\\)\b(?=\s*\|)/i,greedy:!0},{pattern:/(\|\s*)(?:\\?\b[a-z_]\w*)+\b/i,alias:"class-name-fully-qualified",greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/(?:\\?\b[a-z_]\w*)+\b(?=\s*\|)/i,alias:"class-name-fully-qualified",greedy:!0,inside:{punctuation:/\\/}},{pattern:/(\b(?:extends|implements|instanceof|new(?!\s+self\b|\s+static\b))\s+|\bcatch\s*\()(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,alias:"class-name-fully-qualified",greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/\b[a-z_]\w*(?=\s*\$)/i,alias:"type-declaration",greedy:!0},{pattern:/(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,alias:["class-name-fully-qualified","type-declaration"],greedy:!0,inside:{punctuation:/\\/}},{pattern:/\b[a-z_]\w*(?=\s*::)/i,alias:"static-context",greedy:!0},{pattern:/(?:\\?\b[a-z_]\w*)+(?=\s*::)/i,alias:["class-name-fully-qualified","static-context"],greedy:!0,inside:{punctuation:/\\/}},{pattern:/([(,?]\s*)[a-z_]\w*(?=\s*\$)/i,alias:"type-hint",greedy:!0,lookbehind:!0},{pattern:/([(,?]\s*)(?:\\?\b[a-z_]\w*)+(?=\s*\$)/i,alias:["class-name-fully-qualified","type-hint"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}},{pattern:/(\)\s*:\s*(?:\?\s*)?)\b[a-z_]\w*(?!\\)\b/i,alias:"return-type",greedy:!0,lookbehind:!0},{pattern:/(\)\s*:\s*(?:\?\s*)?)(?:\\?\b[a-z_]\w*)+\b(?!\\)/i,alias:["class-name-fully-qualified","return-type"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}}],constant:t,function:{pattern:/(^|[^\\\w])\\?[a-z_](?:[\w\\]*\w)?(?=\s*\()/i,lookbehind:!0,inside:{punctuation:/\\/}},property:{pattern:/(->\s*)\w+/,lookbehind:!0},number:i,operator:n,punctuation:s};var l={pattern:/\{\$(?:\{(?:\{[^{}]+\}|[^{}]+)\}|[^{}])+\}|(^|[^\\{])\$+(?:\w+(?:\[[^\r\n\[\]]+\]|->\w+)?)/,lookbehind:!0,inside:e.languages.php},r=[{pattern:/<<<'([^']+)'[\r\n](?:.*[\r\n])*?\1;/,alias:"nowdoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<<'[^']+'|[a-z_]\w*;$/i,alias:"symbol",inside:{punctuation:/^<<<'?|[';]$/}}}},{pattern:/<<<(?:"([^"]+)"[\r\n](?:.*[\r\n])*?\1;|([a-z_]\w*)[\r\n](?:.*[\r\n])*?\2;)/i,alias:"heredoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<<(?:"[^"]+"|[a-z_]\w*)|[a-z_]\w*;$/i,alias:"symbol",inside:{punctuation:/^<<<"?|[";]$/}},interpolation:l}},{pattern:/`(?:\\[\s\S]|[^\\`])*`/,alias:"backtick-quoted-string",greedy:!0},{pattern:/'(?:\\[\s\S]|[^\\'])*'/,alias:"single-quoted-string",greedy:!0},{pattern:/"(?:\\[\s\S]|[^\\"])*"/,alias:"double-quoted-string",greedy:!0,inside:{interpolation:l}}];e.languages.insertBefore("php","variable",{string:r,attribute:{pattern:/#\[(?:[^"'\/#]|\/(?![*/])|\/\/.*$|#(?!\[).*$|\/\*(?:[^*]|\*(?!\/))*\*\/|"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*')+\](?=\s*[a-z$#])/im,greedy:!0,inside:{"attribute-content":{pattern:/^(#\[)[\s\S]+(?=\]$)/,lookbehind:!0,inside:{comment:a,string:r,"attribute-class-name":[{pattern:/([^:]|^)\b[a-z_]\w*(?!\\)\b/i,alias:"class-name",greedy:!0,lookbehind:!0},{pattern:/([^:]|^)(?:\\?\b[a-z_]\w*)+/i,alias:["class-name","class-name-fully-qualified"],greedy:!0,lookbehind:!0,inside:{punctuation:/\\/}}],constant:t,number:i,operator:n,punctuation:s}},delimiter:{pattern:/^#\[|\]$/,alias:"punctuation"}}}}),e.hooks.add("before-tokenize",(function(a){/<\?/.test(a.code)&&e.languages["markup-templating"].buildPlaceholders(a,"php",/<\?(?:[^"'/#]|\/(?![*/])|("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|(?:\/\/|#(?!\[))(?:[^?\n\r]|\?(?!>))*(?=$|\?>|[\r\n])|#\[|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$))*?(?:\?>|$)/g)})),e.hooks.add("after-tokenize",(function(a){e.languages["markup-templating"].tokenizePlaceholders(a,"php")}))}(Prism); !function(a){var e=a.languages.javadoclike={parameter:{pattern:/(^[\t ]*(?:\/{3}|\*|\/\*\*)\s*@(?:arg|arguments|param)\s+)\w+/m,lookbehind:!0},keyword:{pattern:/(^[\t ]*(?:\/{3}|\*|\/\*\*)\s*|\{)@[a-z][a-zA-Z-]+\b/m,lookbehind:!0},punctuation:/[{}]/};Object.defineProperty(e,"addSupport",{value:function(e,n){"string"==typeof e&&(e=[e]),e.forEach((function(e){!function(e,n){var t="doc-comment",r=a.languages[e];if(r){var o=r[t];if(o||(o=(r=a.languages.insertBefore(e,"comment",{"doc-comment":{pattern:/(^|[^\\])\/\*\*[^/][\s\S]*?(?:\*\/|$)/,lookbehind:!0,alias:"comment"}}))[t]),o instanceof RegExp&&(o=r[t]={pattern:o}),Array.isArray(o))for(var i=0,s=o.length;i<s;i++)o[i]instanceof RegExp&&(o[i]={pattern:o[i]}),n(o[i]);else n(o)}}(e,(function(a){a.inside||(a.inside={}),a.inside.rest=n}))}))}}),e.addSupport(["java","javascript","php"],e)}(Prism); !function(e){e.languages.typescript=e.languages.extend("javascript",{"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|type)\s+)(?!keyof\b)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?:\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>)?/,lookbehind:!0,greedy:!0,inside:null},builtin:/\b(?:Array|Function|Promise|any|boolean|console|never|number|string|symbol|unknown)\b/}),e.languages.typescript.keyword.push(/\b(?:abstract|declare|is|keyof|readonly|require)\b/,/\b(?:asserts|infer|interface|module|namespace|type)\b(?=\s*(?:[{_$a-zA-Z\xA0-\uFFFF]|$))/,/\btype\b(?=\s*(?:[\{*]|$))/),delete e.languages.typescript.parameter,delete e.languages.typescript["literal-property"];var s=e.languages.extend("typescript",{});delete s["class-name"],e.languages.typescript["class-name"].inside=s,e.languages.insertBefore("typescript","function",{decorator:{pattern:/@[$\w\xA0-\uFFFF]+/,inside:{at:{pattern:/^@/,alias:"operator"},function:/^[\s\S]+/}},"generic-function":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*<(?:[^<>]|<(?:[^<>]|<[^<>]*>)*>)*>(?=\s*\()/,greedy:!0,inside:{function:/^#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*/,generic:{pattern:/<[\s\S]+/,alias:"class-name",inside:s}}}}),e.languages.ts=e.languages.typescript}(Prism); !function(e){var a=e.languages.javascript,n="\\{(?:[^{}]|\\{(?:[^{}]|\\{[^{}]*\\})*\\})+\\}",t="(@(?:arg|argument|param|property)\\s+(?:"+n+"\\s+)?)";e.languages.jsdoc=e.languages.extend("javadoclike",{parameter:{pattern:RegExp(t+"(?:(?!\\s)[$\\w\\xA0-\\uFFFF.])+(?=\\s|$)"),lookbehind:!0,inside:{punctuation:/\./}}}),e.languages.insertBefore("jsdoc","keyword",{"optional-parameter":{pattern:RegExp(t+"\\[(?:(?!\\s)[$\\w\\xA0-\\uFFFF.])+(?:=[^[\\]]+)?\\](?=\\s|$)"),lookbehind:!0,inside:{parameter:{pattern:/(^\[)[$\w\xA0-\uFFFF\.]+/,lookbehind:!0,inside:{punctuation:/\./}},code:{pattern:/(=)[\s\S]*(?=\]$)/,lookbehind:!0,inside:a,alias:"language-javascript"},punctuation:/[=[\]]/}},"class-name":[{pattern:RegExp("(@(?:augments|class|extends|interface|memberof!?|template|this|typedef)\\s+(?:<TYPE>\\s+)?)[A-Z]\\w*(?:\\.[A-Z]\\w*)*".replace(/<TYPE>/g,(function(){return n}))),lookbehind:!0,inside:{punctuation:/\./}},{pattern:RegExp("(@[a-z]+\\s+)"+n),lookbehind:!0,inside:{string:a.string,number:a.number,boolean:a.boolean,keyword:e.languages.typescript.keyword,operator:/=>|\.\.\.|[&|?:*]/,punctuation:/[.,;=<>{}()[\]]/}}],example:{pattern:/(@example\s+(?!\s))(?:[^@\s]|\s+(?!\s))+?(?=\s*(?:\*\s*)?(?:@\w|\*\/))/,lookbehind:!0,inside:{code:{pattern:/^([\t ]*(?:\*\s*)?)\S.*$/m,lookbehind:!0,inside:a,alias:"language-javascript"}}}}),e.languages.javadoclike.addSupport("javascript",e.languages.jsdoc)}(Prism); !function(a){var e=/\\(?:[^a-z()[\]]|[a-z*]+)/i,n={"equation-command":{pattern:e,alias:"regex"}};a.languages.latex={comment:/%.*/,cdata:{pattern:/(\\begin\{((?:lstlisting|verbatim)\*?)\})[\s\S]*?(?=\\end\{\2\})/,lookbehind:!0},equation:[{pattern:/\$\$(?:\\[\s\S]|[^\\$])+\$\$|\$(?:\\[\s\S]|[^\\$])+\$|\\\([\s\S]*?\\\)|\\\[[\s\S]*?\\\]/,inside:n,alias:"string"},{pattern:/(\\begin\{((?:align|eqnarray|equation|gather|math|multline)\*?)\})[\s\S]*?(?=\\end\{\2\})/,lookbehind:!0,inside:n,alias:"string"}],keyword:{pattern:/(\\(?:begin|cite|documentclass|end|label|ref|usepackage)(?:\[[^\]]+\])?\{)[^}]+(?=\})/,lookbehind:!0},url:{pattern:/(\\url\{)[^}]+(?=\})/,lookbehind:!0},headline:{pattern:/(\\(?:chapter|frametitle|paragraph|part|section|subparagraph|subsection|subsubparagraph|subsubsection|subsubsubparagraph)\*?(?:\[[^\]]+\])?\{)[^}]+(?=\})/,lookbehind:!0,alias:"class-name"},function:{pattern:e,alias:"selector"},punctuation:/[[\]{}&]/},a.languages.tex=a.languages.latex,a.languages.context=a.languages.latex}(Prism); Prism.languages.matlab={comment:[/%\{[\s\S]*?\}%/,/%.+/],string:{pattern:/\B'(?:''|[^'\r\n])*'/,greedy:!0},number:/(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:[eE][+-]?\d+)?(?:[ij])?|\b[ij]\b/,keyword:/\b(?:NaN|break|case|catch|continue|else|elseif|end|for|function|if|inf|otherwise|parfor|pause|pi|return|switch|try|while)\b/,function:/\b(?!\d)\w+(?=\s*\()/,operator:/\.?[*^\/\\']|[+\-:@]|[<>=~]=?|&&?|\|\|?/,punctuation:/\.{3}|[.,;\[\](){}!]/}; !function(e){var n="(?:\\((?:[^()\\\\]|\\\\[^])*\\)|\\{(?:[^{}\\\\]|\\\\[^])*\\}|\\[(?:[^[\\]\\\\]|\\\\[^])*\\]|<(?:[^<>\\\\]|\\\\[^])*>)";e.languages.perl={comment:[{pattern:/(^\s*)=\w[\s\S]*?=cut.*/m,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\$])#.*/,lookbehind:!0,greedy:!0}],string:[{pattern:RegExp("\\b(?:q|qq|qw|qx)(?![a-zA-Z0-9])\\s*(?:"+["([^a-zA-Z0-9\\s{(\\[<])(?:(?!\\1)[^\\\\]|\\\\[^])*\\1","([a-zA-Z0-9])(?:(?!\\2)[^\\\\]|\\\\[^])*\\2",n].join("|")+")"),greedy:!0},{pattern:/("|`)(?:(?!\1)[^\\]|\\[\s\S])*\1/,greedy:!0},{pattern:/'(?:[^'\\\r\n]|\\.)*'/,greedy:!0}],regex:[{pattern:RegExp("\\b(?:m|qr)(?![a-zA-Z0-9])\\s*(?:"+["([^a-zA-Z0-9\\s{(\\[<])(?:(?!\\1)[^\\\\]|\\\\[^])*\\1","([a-zA-Z0-9])(?:(?!\\2)[^\\\\]|\\\\[^])*\\2",n].join("|")+")[msixpodualngc]*"),greedy:!0},{pattern:RegExp("(^|[^-])\\b(?:s|tr|y)(?![a-zA-Z0-9])\\s*(?:"+["([^a-zA-Z0-9\\s{(\\[<])(?:(?!\\2)[^\\\\]|\\\\[^])*\\2(?:(?!\\2)[^\\\\]|\\\\[^])*\\2","([a-zA-Z0-9])(?:(?!\\3)[^\\\\]|\\\\[^])*\\3(?:(?!\\3)[^\\\\]|\\\\[^])*\\3",n+"\\s*"+n].join("|")+")[msixpodualngcer]*"),lookbehind:!0,greedy:!0},{pattern:/\/(?:[^\/\\\r\n]|\\.)*\/[msixpodualngc]*(?=\s*(?:$|[\r\n,.;})&|\-+*~<>!?^]|(?:and|cmp|eq|ge|gt|le|lt|ne|not|or|x|xor)\b))/,greedy:!0}],variable:[/[&*$@%]\{\^[A-Z]+\}/,/[&*$@%]\^[A-Z_]/,/[&*$@%]#?(?=\{)/,/[&*$@%]#?(?:(?:::)*'?(?!\d)[\w$]+(?![\w$]))+(?:::)*/,/[&*$@%]\d+/,/(?!%=)[$@%][!"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~]/],filehandle:{pattern:/<(?![<=])\S*?>|\b_\b/,alias:"symbol"},"v-string":{pattern:/v\d+(?:\.\d+)*|\d+(?:\.\d+){2,}/,alias:"string"},function:{pattern:/(\bsub[ \t]+)\w+/,lookbehind:!0},keyword:/\b(?:any|break|continue|default|delete|die|do|else|elsif|eval|for|foreach|given|goto|if|last|local|my|next|our|package|print|redo|require|return|say|state|sub|switch|undef|unless|until|use|when|while)\b/,number:/\b(?:0x[\dA-Fa-f](?:_?[\dA-Fa-f])*|0b[01](?:_?[01])*|(?:(?:\d(?:_?\d)*)?\.)?\d(?:_?\d)*(?:[Ee][+-]?\d+)?)\b/,operator:/-[rwxoRWXOezsfdlpSbctugkTBMAC]\b|\+[+=]?|-[-=>]?|\*\*?=?|\/\/?=?|=[=~>]?|~[~=]?|\|\|?=?|&&?=?|<(?:=>?|<=?)?|>>?=?|![~=]?|[%^]=?|\.(?:=|\.\.?)?|[\\?]|\bx(?:=|\b)|\b(?:and|cmp|eq|ge|gt|le|lt|ne|not|or|xor)\b/,punctuation:/[{}[\];(),:]/}}(Prism); Prism.languages.python={comment:{pattern:/(^|[^\\])#.*/,lookbehind:!0,greedy:!0},"string-interpolation":{pattern:/(?:f|fr|rf)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,greedy:!0,inside:{interpolation:{pattern:/((?:^|[^{])(?:\{\{)*)\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}]|\{(?!\{)(?:[^{}])+\})+\})+\}/,lookbehind:!0,inside:{"format-spec":{pattern:/(:)[^:(){}]+(?=\}$)/,lookbehind:!0},"conversion-option":{pattern:/![sra](?=[:}]$)/,alias:"punctuation"},rest:null}},string:/[\s\S]+/}},"triple-quoted-string":{pattern:/(?:[rub]|br|rb)?("""|''')[\s\S]*?\1/i,greedy:!0,alias:"string"},string:{pattern:/(?:[rub]|br|rb)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,greedy:!0},function:{pattern:/((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,lookbehind:!0},"class-name":{pattern:/(\bclass\s+)\w+/i,lookbehind:!0},decorator:{pattern:/(^[\t ]*)@\w+(?:\.\w+)*/m,lookbehind:!0,alias:["annotation","punctuation"],inside:{punctuation:/\./}},keyword:/\b(?:_(?=\s*:)|and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,builtin:/\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,boolean:/\b(?:False|None|True)\b/,number:/\b0(?:b(?:_?[01])+|o(?:_?[0-7])+|x(?:_?[a-f0-9])+)\b|(?:\b\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\B\.\d+(?:_\d+)*)(?:e[+-]?\d+(?:_\d+)*)?j?(?!\w)/i,operator:/[-+%=]=?|!=|:=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,punctuation:/[{}[\];(),.:]/},Prism.languages.python["string-interpolation"].inside.interpolation.inside.rest=Prism.languages.python,Prism.languages.py=Prism.languages.python; !function(t){var n=t.util.clone(t.languages.javascript),e="(?:\\{<S>*\\.{3}(?:[^{}]|<BRACES>)*\\})";function a(t,n){return t=t.replace(/<S>/g,(function(){return"(?:\\s|//.*(?!.)|/\\*(?:[^*]|\\*(?!/))\\*/)"})).replace(/<BRACES>/g,(function(){return"(?:\\{(?:\\{(?:\\{[^{}]*\\}|[^{}])*\\}|[^{}])*\\})"})).replace(/<SPREAD>/g,(function(){return e})),RegExp(t,n)}e=a(e).source,t.languages.jsx=t.languages.extend("markup",n),t.languages.jsx.tag.pattern=a("</?(?:[\\w.:-]+(?:<S>+(?:[\\w.:$-]+(?:=(?:\"(?:\\\\[^]|[^\\\\\"])*\"|'(?:\\\\[^]|[^\\\\'])*'|[^\\s{'\"/>=]+|<BRACES>))?|<SPREAD>))*<S>*/?)?>"),t.languages.jsx.tag.inside.tag.pattern=/^<\/?[^\s>\/]*/,t.languages.jsx.tag.inside["attr-value"].pattern=/=(?!\{)(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s'">]+)/,t.languages.jsx.tag.inside.tag.inside["class-name"]=/^[A-Z]\w*(?:\.[A-Z]\w*)*$/,t.languages.jsx.tag.inside.comment=n.comment,t.languages.insertBefore("inside","attr-name",{spread:{pattern:a("<SPREAD>"),inside:t.languages.jsx}},t.languages.jsx.tag),t.languages.insertBefore("inside","special-attr",{script:{pattern:a("=<BRACES>"),alias:"language-javascript",inside:{"script-punctuation":{pattern:/^=(?=\{)/,alias:"punctuation"},rest:t.languages.jsx}}},t.languages.jsx.tag);var s=function(t){return t?"string"==typeof t?t:"string"==typeof t.content?t.content:t.content.map(s).join(""):""},g=function(n){for(var e=[],a=0;a<n.length;a++){var o=n[a],i=!1;if("string"!=typeof o&&("tag"===o.type&&o.content[0]&&"tag"===o.content[0].type?"</"===o.content[0].content[0].content?e.length>0&&e[e.length-1].tagName===s(o.content[0].content[1])&&e.pop():"/>"===o.content[o.content.length-1].content||e.push({tagName:s(o.content[0].content[1]),openedBraces:0}):e.length>0&&"punctuation"===o.type&&"{"===o.content?e[e.length-1].openedBraces++:e.length>0&&e[e.length-1].openedBraces>0&&"punctuation"===o.type&&"}"===o.content?e[e.length-1].openedBraces--:i=!0),(i||"string"==typeof o)&&e.length>0&&0===e[e.length-1].openedBraces){var r=s(o);a<n.length-1&&("string"==typeof n[a+1]||"plain-text"===n[a+1].type)&&(r+=s(n[a+1]),n.splice(a+1,1)),a>0&&("string"==typeof n[a-1]||"plain-text"===n[a-1].type)&&(r=s(n[a-1])+r,n.splice(a-1,1),a--),n[a]=new t.Token("plain-text",r,null,r)}o.content&&"string"!=typeof o.content&&g(o.content)}};t.hooks.add("after-tokenize",(function(t){"jsx"!==t.language&&"tsx"!==t.language||g(t.tokens)}))}(Prism); !function(e){var a=e.util.clone(e.languages.typescript);e.languages.tsx=e.languages.extend("jsx",a),delete e.languages.tsx.parameter,delete e.languages.tsx["literal-property"];var t=e.languages.tsx.tag;t.pattern=RegExp("(^|[^\\w$]|(?=</))(?:"+t.pattern.source+")",t.pattern.flags),t.lookbehind=!0}(Prism); !function(e){e.languages.ruby=e.languages.extend("clike",{comment:{pattern:/#.*|^=begin\s[\s\S]*?^=end/m,greedy:!0},"class-name":{pattern:/(\b(?:class|module)\s+|\bcatch\s+\()[\w.\\]+|\b[A-Z_]\w*(?=\s*\.\s*new\b)/,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:BEGIN|END|alias|and|begin|break|case|class|def|define_method|defined|do|each|else|elsif|end|ensure|extend|for|if|in|include|module|new|next|nil|not|or|prepend|private|protected|public|raise|redo|require|rescue|retry|return|self|super|then|throw|undef|unless|until|when|while|yield)\b/,operator:/\.{2,3}|&\.|===|<?=>|[!=]?~|(?:&&|\|\||<<|>>|\*\*|[+\-*/%<>!^&|=])=?|[?:]/,punctuation:/[(){}[\].,;]/}),e.languages.insertBefore("ruby","operator",{"double-colon":{pattern:/::/,alias:"punctuation"}});var n={pattern:/((?:^|[^\\])(?:\\{2})*)#\{(?:[^{}]|\{[^{}]*\})*\}/,lookbehind:!0,inside:{content:{pattern:/^(#\{)[\s\S]+(?=\}$)/,lookbehind:!0,inside:e.languages.ruby},delimiter:{pattern:/^#\{|\}$/,alias:"punctuation"}}};delete e.languages.ruby.function;var t="(?:"+["([^a-zA-Z0-9\\s{(\\[<=])(?:(?!\\1)[^\\\\]|\\\\[^])*\\1","\\((?:[^()\\\\]|\\\\[^]|\\((?:[^()\\\\]|\\\\[^])*\\))*\\)","\\{(?:[^{}\\\\]|\\\\[^]|\\{(?:[^{}\\\\]|\\\\[^])*\\})*\\}","\\[(?:[^\\[\\]\\\\]|\\\\[^]|\\[(?:[^\\[\\]\\\\]|\\\\[^])*\\])*\\]","<(?:[^<>\\\\]|\\\\[^]|<(?:[^<>\\\\]|\\\\[^])*>)*>"].join("|")+")",i='(?:"(?:\\\\.|[^"\\\\\r\n])*"|(?:\\b[a-zA-Z_]\\w*|[^\\s\0-\\x7F]+)[?!]?|\\$.)';e.languages.insertBefore("ruby","keyword",{"regex-literal":[{pattern:RegExp("%r"+t+"[egimnosux]{0,6}"),greedy:!0,inside:{interpolation:n,regex:/[\s\S]+/}},{pattern:/(^|[^/])\/(?!\/)(?:\[[^\r\n\]]+\]|\\.|[^[/\\\r\n])+\/[egimnosux]{0,6}(?=\s*(?:$|[\r\n,.;})#]))/,lookbehind:!0,greedy:!0,inside:{interpolation:n,regex:/[\s\S]+/}}],variable:/[@$]+[a-zA-Z_]\w*(?:[?!]|\b)/,symbol:[{pattern:RegExp("(^|[^:]):"+i),lookbehind:!0,greedy:!0},{pattern:RegExp("([\r\n{(,][ \t]*)"+i+"(?=:(?!:))"),lookbehind:!0,greedy:!0}],"method-definition":{pattern:/(\bdef\s+)\w+(?:\s*\.\s*\w+)?/,lookbehind:!0,inside:{function:/\b\w+$/,keyword:/^self\b/,"class-name":/^\w+/,punctuation:/\./}}}),e.languages.insertBefore("ruby","string",{"string-literal":[{pattern:RegExp("%[qQiIwWs]?"+t),greedy:!0,inside:{interpolation:n,string:/[\s\S]+/}},{pattern:/("|')(?:#\{[^}]+\}|#(?!\{)|\\(?:\r\n|[\s\S])|(?!\1)[^\\#\r\n])*\1/,greedy:!0,inside:{interpolation:n,string:/[\s\S]+/}},{pattern:/<<[-~]?([a-z_]\w*)[\r\n](?:.*[\r\n])*?[\t ]*\1/i,alias:"heredoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<[-~]?[a-z_]\w*|\b[a-z_]\w*$/i,inside:{symbol:/\b\w+/,punctuation:/^<<[-~]?/}},interpolation:n,string:/[\s\S]+/}},{pattern:/<<[-~]?'([a-z_]\w*)'[\r\n](?:.*[\r\n])*?[\t ]*\1/i,alias:"heredoc-string",greedy:!0,inside:{delimiter:{pattern:/^<<[-~]?'[a-z_]\w*'|\b[a-z_]\w*$/i,inside:{symbol:/\b\w+/,punctuation:/^<<[-~]?'|'$/}},string:/[\s\S]+/}}],"command-literal":[{pattern:RegExp("%x"+t),greedy:!0,inside:{interpolation:n,command:{pattern:/[\s\S]+/,alias:"string"}}},{pattern:/`(?:#\{[^}]+\}|#(?!\{)|\\(?:\r\n|[\s\S])|[^\\`#\r\n])*`/,greedy:!0,inside:{interpolation:n,command:{pattern:/[\s\S]+/,alias:"string"}}}]}),delete e.languages.ruby.string,e.languages.insertBefore("ruby","number",{builtin:/\b(?:Array|Bignum|Binding|Class|Continuation|Dir|Exception|FalseClass|File|Fixnum|Float|Hash|IO|Integer|MatchData|Method|Module|NilClass|Numeric|Object|Proc|Range|Regexp|Stat|String|Struct|Symbol|TMS|Thread|ThreadGroup|Time|TrueClass)\b/,constant:/\b[A-Z][A-Z0-9_]*(?:[?!]|\b)/}),e.languages.rb=e.languages.ruby}(Prism); !function(e){for(var a="/\\*(?:[^*/]|\\*(?!/)|/(?!\\*)|<self>)*\\*/",t=0;t<2;t++)a=a.replace(/<self>/g,(function(){return a}));a=a.replace(/<self>/g,(function(){return"[^\\s\\S]"})),e.languages.rust={comment:[{pattern:RegExp("(^|[^\\\\])"+a),lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/b?"(?:\\[\s\S]|[^\\"])*"|b?r(#*)"(?:[^"]|"(?!\1))*"\1/,greedy:!0},char:{pattern:/b?'(?:\\(?:x[0-7][\da-fA-F]|u\{(?:[\da-fA-F]_*){1,6}\}|.)|[^\\\r\n\t'])'/,greedy:!0},attribute:{pattern:/#!?\[(?:[^\[\]"]|"(?:\\[\s\S]|[^\\"])*")*\]/,greedy:!0,alias:"attr-name",inside:{string:null}},"closure-params":{pattern:/([=(,:]\s*|\bmove\s*)\|[^|]*\||\|[^|]*\|(?=\s*(?:\{|->))/,lookbehind:!0,greedy:!0,inside:{"closure-punctuation":{pattern:/^\||\|$/,alias:"punctuation"},rest:null}},"lifetime-annotation":{pattern:/'\w+/,alias:"symbol"},"fragment-specifier":{pattern:/(\$\w+:)[a-z]+/,lookbehind:!0,alias:"punctuation"},variable:/\$\w+/,"function-definition":{pattern:/(\bfn\s+)\w+/,lookbehind:!0,alias:"function"},"type-definition":{pattern:/(\b(?:enum|struct|trait|type|union)\s+)\w+/,lookbehind:!0,alias:"class-name"},"module-declaration":[{pattern:/(\b(?:crate|mod)\s+)[a-z][a-z_\d]*/,lookbehind:!0,alias:"namespace"},{pattern:/(\b(?:crate|self|super)\s*)::\s*[a-z][a-z_\d]*\b(?:\s*::(?:\s*[a-z][a-z_\d]*\s*::)*)?/,lookbehind:!0,alias:"namespace",inside:{punctuation:/::/}}],keyword:[/\b(?:Self|abstract|as|async|await|become|box|break|const|continue|crate|do|dyn|else|enum|extern|final|fn|for|if|impl|in|let|loop|macro|match|mod|move|mut|override|priv|pub|ref|return|self|static|struct|super|trait|try|type|typeof|union|unsafe|unsized|use|virtual|where|while|yield)\b/,/\b(?:bool|char|f(?:32|64)|[ui](?:8|16|32|64|128|size)|str)\b/],function:/\b[a-z_]\w*(?=\s*(?:::\s*<|\())/,macro:{pattern:/\b\w+!/,alias:"property"},constant:/\b[A-Z_][A-Z_\d]+\b/,"class-name":/\b[A-Z]\w*\b/,namespace:{pattern:/(?:\b[a-z][a-z_\d]*\s*::\s*)*\b[a-z][a-z_\d]*\s*::(?!\s*<)/,inside:{punctuation:/::/}},number:/\b(?:0x[\dA-Fa-f](?:_?[\dA-Fa-f])*|0o[0-7](?:_?[0-7])*|0b[01](?:_?[01])*|(?:(?:\d(?:_?\d)*)?\.)?\d(?:_?\d)*(?:[Ee][+-]?\d+)?)(?:_?(?:f32|f64|[iu](?:8|16|32|64|size)?))?\b/,boolean:/\b(?:false|true)\b/,punctuation:/->|\.\.=|\.{1,3}|::|[{}[\];(),:]/,operator:/[-+*\/%!^]=?|=[=>]?|&[&=]?|\|[|=]?|<<?=?|>>?=?|[@?]/},e.languages.rust["closure-params"].inside.rest=e.languages.rust,e.languages.rust.attribute.inside.string=e.languages.rust.string}(Prism); Prism.languages.sql={comment:{pattern:/(^|[^\\])(?:\/\*[\s\S]*?\*\/|(?:--|\/\/|#).*)/,lookbehind:!0},variable:[{pattern:/@(["'`])(?:\\[\s\S]|(?!\1)[^\\])+\1/,greedy:!0},/@[\w.$]+/],string:{pattern:/(^|[^@\\])("|')(?:\\[\s\S]|(?!\2)[^\\]|\2\2)*\2/,greedy:!0,lookbehind:!0},identifier:{pattern:/(^|[^@\\])`(?:\\[\s\S]|[^`\\]|``)*`/,greedy:!0,lookbehind:!0,inside:{punctuation:/^`|`$/}},function:/\b(?:AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE)(?=\s*\()/i,keyword:/\b(?:ACTION|ADD|AFTER|ALGORITHM|ALL|ALTER|ANALYZE|ANY|APPLY|AS|ASC|AUTHORIZATION|AUTO_INCREMENT|BACKUP|BDB|BEGIN|BERKELEYDB|BIGINT|BINARY|BIT|BLOB|BOOL|BOOLEAN|BREAK|BROWSE|BTREE|BULK|BY|CALL|CASCADED?|CASE|CHAIN|CHAR(?:ACTER|SET)?|CHECK(?:POINT)?|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMNS?|COMMENT|COMMIT(?:TED)?|COMPUTE|CONNECT|CONSISTENT|CONSTRAINT|CONTAINS(?:TABLE)?|CONTINUE|CONVERT|CREATE|CROSS|CURRENT(?:_DATE|_TIME|_TIMESTAMP|_USER)?|CURSOR|CYCLE|DATA(?:BASES?)?|DATE(?:TIME)?|DAY|DBCC|DEALLOCATE|DEC|DECIMAL|DECLARE|DEFAULT|DEFINER|DELAYED|DELETE|DELIMITERS?|DENY|DESC|DESCRIBE|DETERMINISTIC|DISABLE|DISCARD|DISK|DISTINCT|DISTINCTROW|DISTRIBUTED|DO|DOUBLE|DROP|DUMMY|DUMP(?:FILE)?|DUPLICATE|ELSE(?:IF)?|ENABLE|ENCLOSED|END|ENGINE|ENUM|ERRLVL|ERRORS|ESCAPED?|EXCEPT|EXEC(?:UTE)?|EXISTS|EXIT|EXPLAIN|EXTENDED|FETCH|FIELDS|FILE|FILLFACTOR|FIRST|FIXED|FLOAT|FOLLOWING|FOR(?: EACH ROW)?|FORCE|FOREIGN|FREETEXT(?:TABLE)?|FROM|FULL|FUNCTION|GEOMETRY(?:COLLECTION)?|GLOBAL|GOTO|GRANT|GROUP|HANDLER|HASH|HAVING|HOLDLOCK|HOUR|IDENTITY(?:COL|_INSERT)?|IF|IGNORE|IMPORT|INDEX|INFILE|INNER|INNODB|INOUT|INSERT|INT|INTEGER|INTERSECT|INTERVAL|INTO|INVOKER|ISOLATION|ITERATE|JOIN|KEYS?|KILL|LANGUAGE|LAST|LEAVE|LEFT|LEVEL|LIMIT|LINENO|LINES|LINESTRING|LOAD|LOCAL|LOCK|LONG(?:BLOB|TEXT)|LOOP|MATCH(?:ED)?|MEDIUM(?:BLOB|INT|TEXT)|MERGE|MIDDLEINT|MINUTE|MODE|MODIFIES|MODIFY|MONTH|MULTI(?:LINESTRING|POINT|POLYGON)|NATIONAL|NATURAL|NCHAR|NEXT|NO|NONCLUSTERED|NULLIF|NUMERIC|OFF?|OFFSETS?|ON|OPEN(?:DATASOURCE|QUERY|ROWSET)?|OPTIMIZE|OPTION(?:ALLY)?|ORDER|OUT(?:ER|FILE)?|OVER|PARTIAL|PARTITION|PERCENT|PIVOT|PLAN|POINT|POLYGON|PRECEDING|PRECISION|PREPARE|PREV|PRIMARY|PRINT|PRIVILEGES|PROC(?:EDURE)?|PUBLIC|PURGE|QUICK|RAISERROR|READS?|REAL|RECONFIGURE|REFERENCES|RELEASE|RENAME|REPEAT(?:ABLE)?|REPLACE|REPLICATION|REQUIRE|RESIGNAL|RESTORE|RESTRICT|RETURN(?:ING|S)?|REVOKE|RIGHT|ROLLBACK|ROUTINE|ROW(?:COUNT|GUIDCOL|S)?|RTREE|RULE|SAVE(?:POINT)?|SCHEMA|SECOND|SELECT|SERIAL(?:IZABLE)?|SESSION(?:_USER)?|SET(?:USER)?|SHARE|SHOW|SHUTDOWN|SIMPLE|SMALLINT|SNAPSHOT|SOME|SONAME|SQL|START(?:ING)?|STATISTICS|STATUS|STRIPED|SYSTEM_USER|TABLES?|TABLESPACE|TEMP(?:ORARY|TABLE)?|TERMINATED|TEXT(?:SIZE)?|THEN|TIME(?:STAMP)?|TINY(?:BLOB|INT|TEXT)|TOP?|TRAN(?:SACTIONS?)?|TRIGGER|TRUNCATE|TSEQUAL|TYPES?|UNBOUNDED|UNCOMMITTED|UNDEFINED|UNION|UNIQUE|UNLOCK|UNPIVOT|UNSIGNED|UPDATE(?:TEXT)?|USAGE|USE|USER|USING|VALUES?|VAR(?:BINARY|CHAR|CHARACTER|YING)|VIEW|WAITFOR|WARNINGS|WHEN|WHERE|WHILE|WITH(?: ROLLUP|IN)?|WORK|WRITE(?:TEXT)?|YEAR)\b/i,boolean:/\b(?:FALSE|NULL|TRUE)\b/i,number:/\b0x[\da-f]+\b|\b\d+(?:\.\d*)?|\B\.\d+\b/i,operator:/[-+*\/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?|\b(?:AND|BETWEEN|DIV|ILIKE|IN|IS|LIKE|NOT|OR|REGEXP|RLIKE|SOUNDS LIKE|XOR)\b/i,punctuation:/[;[\]()`,.]/}; Prism.languages.swift={comment:{pattern:/(^|[^\\:])(?:\/\/.*|\/\*(?:[^/*]|\/(?!\*)|\*(?!\/)|\/\*(?:[^*]|\*(?!\/))*\*\/)*\*\/)/,lookbehind:!0,greedy:!0},"string-literal":[{pattern:RegExp('(^|[^"#])(?:"(?:\\\\(?:\\((?:[^()]|\\([^()]*\\))*\\)|\r\n|[^(])|[^\\\\\r\n"])*"|"""(?:\\\\(?:\\((?:[^()]|\\([^()]*\\))*\\)|[^(])|[^\\\\"]|"(?!""))*""")(?!["#])'),lookbehind:!0,greedy:!0,inside:{interpolation:{pattern:/(\\\()(?:[^()]|\([^()]*\))*(?=\))/,lookbehind:!0,inside:null},"interpolation-punctuation":{pattern:/^\)|\\\($/,alias:"punctuation"},punctuation:/\\(?=[\r\n])/,string:/[\s\S]+/}},{pattern:RegExp('(^|[^"#])(#+)(?:"(?:\\\\(?:#+\\((?:[^()]|\\([^()]*\\))*\\)|\r\n|[^#])|[^\\\\\r\n])*?"|"""(?:\\\\(?:#+\\((?:[^()]|\\([^()]*\\))*\\)|[^#])|[^\\\\])*?""")\\2'),lookbehind:!0,greedy:!0,inside:{interpolation:{pattern:/(\\#+\()(?:[^()]|\([^()]*\))*(?=\))/,lookbehind:!0,inside:null},"interpolation-punctuation":{pattern:/^\)|\\#+\($/,alias:"punctuation"},string:/[\s\S]+/}}],directive:{pattern:RegExp("#(?:(?:elseif|if)\\b(?:[ \t]*(?:![ \t]*)?(?:\\b\\w+\\b(?:[ \t]*\\((?:[^()]|\\([^()]*\\))*\\))?|\\((?:[^()]|\\([^()]*\\))*\\))(?:[ \t]*(?:&&|\\|\\|))?)+|(?:else|endif)\\b)"),alias:"property",inside:{"directive-name":/^#\w+/,boolean:/\b(?:false|true)\b/,number:/\b\d+(?:\.\d+)*\b/,operator:/!|&&|\|\||[<>]=?/,punctuation:/[(),]/}},literal:{pattern:/#(?:colorLiteral|column|dsohandle|file(?:ID|Literal|Path)?|function|imageLiteral|line)\b/,alias:"constant"},"other-directive":{pattern:/#\w+\b/,alias:"property"},attribute:{pattern:/@\w+/,alias:"atrule"},"function-definition":{pattern:/(\bfunc\s+)\w+/,lookbehind:!0,alias:"function"},label:{pattern:/\b(break|continue)\s+\w+|\b[a-zA-Z_]\w*(?=\s*:\s*(?:for|repeat|while)\b)/,lookbehind:!0,alias:"important"},keyword:/\b(?:Any|Protocol|Self|Type|actor|as|assignment|associatedtype|associativity|async|await|break|case|catch|class|continue|convenience|default|defer|deinit|didSet|do|dynamic|else|enum|extension|fallthrough|fileprivate|final|for|func|get|guard|higherThan|if|import|in|indirect|infix|init|inout|internal|is|isolated|lazy|left|let|lowerThan|mutating|none|nonisolated|nonmutating|open|operator|optional|override|postfix|precedencegroup|prefix|private|protocol|public|repeat|required|rethrows|return|right|safe|self|set|some|static|struct|subscript|super|switch|throw|throws|try|typealias|unowned|unsafe|var|weak|where|while|willSet)\b/,boolean:/\b(?:false|true)\b/,nil:{pattern:/\bnil\b/,alias:"constant"},"short-argument":/\$\d+\b/,omit:{pattern:/\b_\b/,alias:"keyword"},number:/\b(?:[\d_]+(?:\.[\de_]+)?|0x[a-f0-9_]+(?:\.[a-f0-9p_]+)?|0b[01_]+|0o[0-7_]+)\b/i,"class-name":/\b[A-Z](?:[A-Z_\d]*[a-z]\w*)?\b/,function:/\b[a-z_]\w*(?=\s*\()/i,constant:/\b(?:[A-Z_]{2,}|k[A-Z][A-Za-z_]+)\b/,operator:/[-+*/%=!<>&|^~?]+|\.[.\-+*/%=!<>&|^~?]+/,punctuation:/[{}[\]();,.:\\]/},Prism.languages.swift["string-literal"].forEach((function(e){e.inside.interpolation.inside=Prism.languages.swift})); Prism.languages["visual-basic"]={comment:{pattern:/(?:['‘’]|REM\b)(?:[^\r\n_]|_(?:\r\n?|\n)?)*/i,inside:{keyword:/^REM/i}},directive:{pattern:/#(?:Const|Else|ElseIf|End|ExternalChecksum|ExternalSource|If|Region)(?:\b_[ \t]*(?:\r\n?|\n)|.)+/i,alias:"property",greedy:!0},string:{pattern:/\$?["“”](?:["“”]{2}|[^"“”])*["“”]C?/i,greedy:!0},date:{pattern:/#[ \t]*(?:\d+([/-])\d+\1\d+(?:[ \t]+(?:\d+[ \t]*(?:AM|PM)|\d+:\d+(?::\d+)?(?:[ \t]*(?:AM|PM))?))?|\d+[ \t]*(?:AM|PM)|\d+:\d+(?::\d+)?(?:[ \t]*(?:AM|PM))?)[ \t]*#/i,alias:"number"},number:/(?:(?:\b\d+(?:\.\d+)?|\.\d+)(?:E[+-]?\d+)?|&[HO][\dA-F]+)(?:[FRD]|U?[ILS])?/i,boolean:/\b(?:False|Nothing|True)\b/i,keyword:/\b(?:AddHandler|AddressOf|Alias|And(?:Also)?|As|Boolean|ByRef|Byte|ByVal|Call|Case|Catch|C(?:Bool|Byte|Char|Date|Dbl|Dec|Int|Lng|Obj|SByte|Short|Sng|Str|Type|UInt|ULng|UShort)|Char|Class|Const|Continue|Currency|Date|Decimal|Declare|Default|Delegate|Dim|DirectCast|Do|Double|Each|Else(?:If)?|End(?:If)?|Enum|Erase|Error|Event|Exit|Finally|For|Friend|Function|Get(?:Type|XMLNamespace)?|Global|GoSub|GoTo|Handles|If|Implements|Imports|In|Inherits|Integer|Interface|Is|IsNot|Let|Lib|Like|Long|Loop|Me|Mod|Module|Must(?:Inherit|Override)|My(?:Base|Class)|Namespace|Narrowing|New|Next|Not(?:Inheritable|Overridable)?|Object|Of|On|Operator|Option(?:al)?|Or(?:Else)?|Out|Overloads|Overridable|Overrides|ParamArray|Partial|Private|Property|Protected|Public|RaiseEvent|ReadOnly|ReDim|RemoveHandler|Resume|Return|SByte|Select|Set|Shadows|Shared|short|Single|Static|Step|Stop|String|Structure|Sub|SyncLock|Then|Throw|To|Try|TryCast|Type|TypeOf|U(?:Integer|Long|Short)|Until|Using|Variant|Wend|When|While|Widening|With(?:Events)?|WriteOnly|Xor)\b/i,operator:/[+\-*/\\^<=>&#@$%!]|\b_(?=[ \t]*[\r\n])/,punctuation:/[{}().,:?]/},Prism.languages.vb=Prism.languages["visual-basic"],Prism.languages.vba=Prism.languages["visual-basic"]; !function(e){var n=/[*&][^\s[\]{},]+/,r=/!(?:<[\w\-%#;/?:@&=+$,.!~*'()[\]]+>|(?:[a-zA-Z\d-]*!)?[\w\-%#;/?:@&=+$.~*'()]+)?/,t="(?:"+r.source+"(?:[ \t]+"+n.source+")?|"+n.source+"(?:[ \t]+"+r.source+")?)",a="(?:[^\\s\\x00-\\x08\\x0e-\\x1f!\"#%&'*,\\-:>?@[\\]`{|}\\x7f-\\x84\\x86-\\x9f\\ud800-\\udfff\\ufffe\\uffff]|[?:-]<PLAIN>)(?:[ \t]*(?:(?![#:])<PLAIN>|:<PLAIN>))*".replace(/<PLAIN>/g,(function(){return"[^\\s\\x00-\\x08\\x0e-\\x1f,[\\]{}\\x7f-\\x84\\x86-\\x9f\\ud800-\\udfff\\ufffe\\uffff]"})),d="\"(?:[^\"\\\\\r\n]|\\\\.)*\"|'(?:[^'\\\\\r\n]|\\\\.)*'";function o(e,n){n=(n||"").replace(/m/g,"")+"m";var r="([:\\-,[{]\\s*(?:\\s<<prop>>[ \t]+)?)(?:<<value>>)(?=[ \t]*(?:$|,|\\]|\\}|(?:[\r\n]\\s*)?#))".replace(/<<prop>>/g,(function(){return t})).replace(/<<value>>/g,(function(){return e}));return RegExp(r,n)}e.languages.yaml={scalar:{pattern:RegExp("([\\-:]\\s*(?:\\s<<prop>>[ \t]+)?[|>])[ \t]*(?:((?:\r?\n|\r)[ \t]+)\\S[^\r\n]*(?:\\2[^\r\n]+)*)".replace(/<<prop>>/g,(function(){return t}))),lookbehind:!0,alias:"string"},comment:/#.*/,key:{pattern:RegExp("((?:^|[:\\-,[{\r\n?])[ \t]*(?:<<prop>>[ \t]+)?)<<key>>(?=\\s*:\\s)".replace(/<<prop>>/g,(function(){return t})).replace(/<<key>>/g,(function(){return"(?:"+a+"|"+d+")"}))),lookbehind:!0,greedy:!0,alias:"atrule"},directive:{pattern:/(^[ \t]*)%.+/m,lookbehind:!0,alias:"important"},datetime:{pattern:o("\\d{4}-\\d\\d?-\\d\\d?(?:[tT]|[ \t]+)\\d\\d?:\\d{2}:\\d{2}(?:\\.\\d*)?(?:[ \t]*(?:Z|[-+]\\d\\d?(?::\\d{2})?))?|\\d{4}-\\d{2}-\\d{2}|\\d\\d?:\\d{2}(?::\\d{2}(?:\\.\\d*)?)?"),lookbehind:!0,alias:"number"},boolean:{pattern:o("false|true","i"),lookbehind:!0,alias:"important"},null:{pattern:o("null|~","i"),lookbehind:!0,alias:"important"},string:{pattern:o(d),lookbehind:!0,greedy:!0},number:{pattern:o("[+-]?(?:0x[\\da-f]+|0o[0-7]+|(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?|\\.inf|\\.nan)","i"),lookbehind:!0},tag:r,important:n,punctuation:/---|[:[\]{}\-,|>?]|\.\.\./},e.languages.yml=e.languages.yaml}(Prism); !function(){if("undefined"!=typeof Prism){var i=/\b([a-z]{3,7}:\/\/|tel:)[\w\-+%~/.:=&!$'()*,;@]+(?:\?[\w\-+%~/.:=?&!$'()*,;@]*)?(?:#[\w\-+%~/.:#=?&!$'()*,;@]*)?/,n=/\b\S+@[\w.]+[a-z]{2}/,t=/\[([^\]]+)\]\(([^)]+)\)/,e=["comment","url","attr-value","string"];Prism.plugins.autolinker={processGrammar:function(r){r&&!r["url-link"]&&(Prism.languages.DFS(r,(function(r,a,l){e.indexOf(l)>-1&&!Array.isArray(a)&&(a.pattern||(a=this[r]={pattern:a}),a.inside=a.inside||{},"comment"==l&&(a.inside["md-link"]=t),"attr-value"==l?Prism.languages.insertBefore("inside","punctuation",{"url-link":i},a):a.inside["url-link"]=i,a.inside["email-link"]=n)})),r["url-link"]=i,r["email-link"]=n)}},Prism.hooks.add("before-highlight",(function(i){Prism.plugins.autolinker.processGrammar(i.grammar)})),Prism.hooks.add("wrap",(function(i){if(/-link$/.test(i.type)){i.tag="a";var n=i.content;if("email-link"==i.type&&0!=n.indexOf("mailto:"))n="mailto:"+n;else if("md-link"==i.type){var e=i.content.match(t);n=e[2],i.content=e[1]}i.attributes.href=n;try{i.content=decodeURIComponent(i.content)}catch(i){}}}))}}();
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
tailwind.config.js
JavaScript
const colors = require('tailwindcss/colors'); /** @type {import('tailwindcss').Config} */ module.exports = { content: [ './app/**/*.{js,ts,jsx,tsx}', './pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}', // Or if using `src` directory: './src/**/*.{js,ts,jsx,tsx}', ], theme: { screens: { // 1125 = 768 + 768 * (1 - 0.618) + 16 * 4 // 对话框 + 菜单栏 + 间隔 md: '1125px', }, extend: { screens: { // https://tailwindcss.com/docs/screens#custom-media-queries // 1317 = 800 + 315 + 16 * 6 * 2 tall: { raw: '(min-height: 1317px)' }, // => @media (min-height: 1317px) { ... } }, colors: { // 聊天气泡 'chat-bubble': { DEFAULT: colors.white, dark: '#2c2c2c', }, // 聊天气泡绿色 'chat-bubble-green': { DEFAULT: '#abe987', dark: '#51b170', }, // 聊天背景颜色 'chat-bg': { DEFAULT: '#ededed', dark: '#111111', }, }, }, }, plugins: [], };
xcatliu/chatgpt-next
781
微信风格的 ChatGPT,使用 Next.js 构建,私有化部署的最佳选择!
TypeScript
xcatliu
xcatliu
Tencent
pagic.config.ts
TypeScript
// import { React } from 'https://deno.land/x/pagic/mod.ts'; export default { srcDir: '.', exclude: ['LICENSE'], root: '/my_docs/', theme: 'docs', plugins: ['sidebar', 'prev_next', 'ga', 'gitalk'], title: 'Pagic template docs', description: 'Use this template to create a Pagic site with the docs theme', // To use jsx syntax, please rename this file to pagic.config.tsx // head: <> // <link rel="icon" type="image/png" href="/favicon.png" /> // <script src="/assets/custom.js" /> // </>, nav: [ { text: 'Docs', link: '/my_docs/introduction/index.html', }, { text: 'Pagic', link: 'https://pagic.org/', }, { text: 'About', link: '/my_docs/about/index.html', align: 'right', }, ], github: 'https://github.com/xcatliu/my_docs', sidebar: { '/': [ 'introduction/README.md', { link: 'test_pages/README.md', children: ['test_pages/markdown_test.md', 'test_pages/front_matter.md', 'test_pages/react_hooks_test.tsx'], }, { text: 'Folder', children: [ 'folder/foo.md', { text: 'Custom sidebar text', link: 'folder/bar.md' } ] } ], }, tools: { editOnGitHub: true, backToTop: true, }, ga: { id: 'UA-45256157-17', }, gitalk: { clientID: 'd5690cdd53ff6a9fc9df', clientSecret: 'd026c52e779c6e70963eca753e21d2f53f8d1342', repo: 'pagic_template_docs', owner: 'xcatliu', admin: ['xcatliu'], pagerDirection: 'first', }, port: 8000, };
xcatliu/my_docs
0
TypeScript
xcatliu
xcatliu
Tencent
test_pages/react_hooks_test.tsx
TypeScript (TSX)
import { React } from 'https://deno.land/x/pagic/mod.ts'; const ReactHooksTest = () => { const [count, setCount] = React.useState(0); return ( <> <h1>React hooks test</h1> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Count +1</button> </> ); }; export const frontMatter = { title: 'React hooks test', }; export default ReactHooksTest;
xcatliu/my_docs
0
TypeScript
xcatliu
xcatliu
Tencent
pagic.config.ts
TypeScript
// import { React } from 'https://deno.land/x/pagic/mod.ts'; export default { srcDir: '.', exclude: ['LICENSE'], root: '/pagic_template_docs/', theme: 'docs', plugins: ['sidebar', 'prev_next'], title: 'Pagic template docs', description: 'Use this template to create a Pagic site with the docs theme', // To use jsx syntax, please rename this file to pagic.config.tsx // head: <> // <link rel="icon" type="image/png" href="/favicon.png" /> // <script src="/assets/custom.js" /> // </>, nav: [ { text: 'Docs', link: '/pagic_template_docs/introduction/index.html', }, { text: 'Pagic', link: 'https://pagic.org/', }, { text: 'About', link: '/pagic_template_docs/about/index.html', align: 'right', }, ], github: 'https://github.com/xcatliu/pagic_template_docs', sidebar: { '/': [ 'introduction/README.md', { link: 'test_pages/README.md', children: ['test_pages/markdown_test.md', 'test_pages/front_matter.md', 'test_pages/react_hooks_test.tsx'], }, { text: 'Folder', children: [ 'folder/foo.md', { text: 'Custom sidebar text', link: 'folder/bar.md' } ] } ], }, tools: { editOnGitHub: true, backToTop: true, }, port: 8000, };
xcatliu/pagic_template_docs
14
Use this template to create a Pagic site with the docs theme
TypeScript
xcatliu
xcatliu
Tencent
test_pages/react_hooks_test.tsx
TypeScript (TSX)
import { React } from 'https://deno.land/x/pagic/mod.ts'; const ReactHooksTest = () => { const [count, setCount] = React.useState(0); return ( <> <h1>React hooks test</h1> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Count +1</button> </> ); }; export const frontMatter = { title: 'React hooks test', }; export default ReactHooksTest;
xcatliu/pagic_template_docs
14
Use this template to create a Pagic site with the docs theme
TypeScript
xcatliu
xcatliu
Tencent
serialize.js
JavaScript
/** * 序列化任意一个对象 */ function serialize(obj, options = {}) { const { space, useCircularPath, removeFunction, removeCircular, removeNull, removeUndefined, removeEmpty, removeKeyFilter, removePathFilter, printToConsole, copyToClipboard, } = { space: 0, useCircularPath: false, removeFunction: false, removeCircular: false, removeNull: false, removeUndefined: false, removeEmpty: false, removeKeyFilter: undefined, removePathFilter: undefined, printToConsole: true, copyToClipboard: true, ...options, }; /** 换成对象的路径,方便后续检查是否存在循环引用 */ const objMap = new Map(); /** * 将一个对象转换成可以安全 stringify 的对象 */ function safe(obj, path = "$root", key = '') { if (removeKeyFilter && key && removeKeyFilter(key)) { return "$remove"; } if (removePathFilter && removePathFilter(path)) { return "$remove"; } if (obj === null) { if (removeNull) { return "$remove"; } return null; } if (obj === undefined) { if (removeUndefined) { return "$remove"; } return undefined; } if (typeof obj === "function") { if (removeFunction) { return "$remove"; } return "$function"; } // 产生了循环引用 if (objMap.has(obj)) { if (removeCircular) { return "$remove"; } if (useCircularPath) { return objMap.get(obj); } return "$circular"; } // 如果是对象或数组,则缓存到 objMap 中,方便后续检查是否存在循环引用 if (Array.isArray(obj)) { objMap.set(obj, path); let result = []; obj.forEach((value, index) => { const newValue = safe(value, `${path}[${index}]`); if (newValue === "$remove") { // should be removed } else { result.push(newValue); } }); if (removeEmpty && result.length === 0) { return "$remove"; } return result; } if (typeof obj === "object") { objMap.set(obj, path); let result = {}; Object.entries(obj).forEach(([key, value]) => { const newValue = safe(value, `${path}.${key}`, key); if (newValue === "$remove") { // should be removed } else { result[key] = newValue; } }); if (removeEmpty && Object.keys(result).length === 0) { return "$remove"; } return result; } // 其他情况直接返回 return obj; } let safeObj = safe(obj); let stringResult = ""; if (space === 0) { stringResult = JSON.stringify(safeObj); } else { stringResult = JSON.stringify(safeObj, null, space); } if (printToConsole) { console.log(stringResult); } if (copyToClipboard) { copy(stringResult); } return stringResult; } function copy(text) { const textarea = document.createElement("textarea"); textarea.value = text; document.body.appendChild(textarea); textarea.select(); document.execCommand("copy"); document.body.removeChild(textarea); }
xcatliu/smart-serialize
2
Serialize any object, stringify, print to console, and write to clipboard
JavaScript
xcatliu
xcatliu
Tencent
make-artifacts.sh
Shell
#!/bin/bash make_big_file() { local f="$1" local dest="test-$f.bin" dd if=/dev/urandom of="$dest" bs=16k count=65536 # 1GiB sha256sum "$dest" > "${dest}.sha256" } for i in $(seq 1 10); do make_big_file "$i" & done wait
xen0n/action-gh-release-testground
0
Shell
xen0n
WÁNG Xuěruì
gentoo
src/codemap.rs
Rust
use std::borrow::Cow; use pyo3::{exceptions::PyValueError, prelude::*}; use starlark::codemap::{ CodeMap, FileSpan, Pos, ResolvedFileLine, ResolvedFileSpan, ResolvedPos, ResolvedSpan, Span, }; #[pyclass(module = "xingque", name = "Pos")] pub(crate) struct PyPos(Pos); #[pymethods] impl PyPos { #[new] fn py_new(x: u32) -> Self { Self(Pos::new(x)) } fn __repr__(slf: &Bound<'_, Self>) -> PyResult<String> { let class_name = slf.get_type().qualname()?; Ok(format!("{}({})", class_name, slf.borrow().get())) } fn __eq__(&self, other: &Bound<'_, PyAny>) -> bool { if let Ok(other) = other.downcast::<PyPos>() { self.0 == other.borrow().0 } else if let Ok(other) = other.extract::<u32>() { self.get() == other } else { false } } fn get(&self) -> u32 { self.0.get() } fn __int__(&self) -> u32 { self.get() } fn __add__(&self, other: u32) -> Self { Self(self.0 + other) } fn __iadd__(&mut self, other: u32) { self.0 += other; } } impl<'py> FromPyObject<'py> for PyPos { fn extract_bound(ob: &Bound<'py, PyAny>) -> PyResult<Self> { Ok(Self::py_new(ob.extract()?)) } } #[pyclass(module = "xingque", name = "ResolvedPos", eq, hash, frozen)] #[repr(transparent)] #[derive(PartialEq, Eq, Hash, Clone)] pub(crate) struct PyResolvedPos(ResolvedPos); impl From<ResolvedPos> for PyResolvedPos { fn from(value: ResolvedPos) -> Self { Self(value) } } impl PyResolvedPos { fn repr(&self, class_name: Option<Cow<'_, str>>) -> String { format!( "{}(line={}, column={})", class_name.unwrap_or(Cow::Borrowed("ResolvedPos")), self.0.line, self.0.column ) } } #[pymethods] impl PyResolvedPos { #[new] fn py_new(line: usize, column: usize) -> Self { ResolvedPos { line, column }.into() } fn __repr__(slf: &Bound<'_, Self>) -> PyResult<String> { let class_name = slf.get_type().qualname()?.to_string(); let me = slf.borrow(); Ok(me.repr(Some(Cow::Owned(class_name)))) } #[getter] fn line(&self) -> usize { self.0.line } #[getter] fn column(&self) -> usize { self.0.column } } #[pyclass(module = "xingque", name = "ResolvedSpan", eq, hash, frozen)] #[repr(transparent)] #[derive(PartialEq, Eq, Hash, Clone)] pub(crate) struct PyResolvedSpan(ResolvedSpan); impl From<ResolvedSpan> for PyResolvedSpan { fn from(value: ResolvedSpan) -> Self { Self(value) } } #[pymethods] impl PyResolvedSpan { #[new] fn py_new(begin: &PyResolvedPos, end: &PyResolvedPos) -> Self { ResolvedSpan { begin: begin.0, end: end.0, } .into() } fn __repr__(slf: &Bound<'_, Self>) -> PyResult<String> { let class_name = slf.get_type().qualname()?; let me = slf.borrow(); Ok(format!( "{}(begin={}, end={})", class_name, me.begin().repr(None), me.end().repr(None) )) } #[getter] fn begin(&self) -> PyResolvedPos { self.0.begin.into() } #[getter] fn end(&self) -> PyResolvedPos { self.0.end.into() } fn __contains__(&self, pos: &Bound<'_, PyAny>) -> PyResult<bool> { // TODO: handle Tuple[int, int] if let Ok(pos) = pos.downcast::<PyResolvedPos>() { Ok(self.0.contains(pos.borrow().0)) } else { Err(PyValueError::new_err( "invalid operand type for ResolvedSpan.__contains__", )) } } fn contains(&self, pos: &Bound<'_, PyAny>) -> PyResult<bool> { self.__contains__(pos) } } #[pyclass(module = "xingque", name = "Span", frozen)] pub(crate) struct PySpan(pub(crate) Span); impl From<Span> for PySpan { fn from(value: Span) -> Self { Self(value) } } #[pymethods] impl PySpan { #[new] fn py_new(begin: PyPos, end: PyPos) -> Self { Self(Span::new(begin.0, end.0)) } fn __repr__(slf: &Bound<'_, Self>) -> PyResult<String> { let class_name = slf.get_type().qualname()?; let me = slf.borrow(); Ok(format!( "{}({}, {})", class_name, me.0.begin().get(), me.0.end().get() )) } fn __eq__(&self, other: &Bound<'_, PyAny>) -> bool { match other.downcast::<PySpan>() { Ok(other) => self.0 == other.borrow().0, Err(_) => false, } } #[getter] fn get_begin(&self) -> PyPos { PyPos(self.0.begin()) } #[getter] fn get_end(&self) -> PyPos { PyPos(self.0.end()) } fn merge(&self, other: &Self) -> Self { Self(self.0.merge(other.0)) } fn merge_all(&self) -> Self { // TODO: accept an Iterable todo!(); } fn end_span(&self) -> Self { Self(self.0.end_span()) } fn __contains__(&self, pos: &Bound<'_, PyAny>) -> PyResult<bool> { if let Ok(pos) = pos.downcast::<PyPos>() { Ok(self.0.contains(pos.borrow().0)) } else if let Ok(pos) = pos.extract::<u32>() { Ok(self.0.contains(Pos::new(pos))) } else { Err(PyValueError::new_err( "invalid operand type for Span.__contains__", )) } } fn contains(&self, pos: &Bound<'_, PyAny>) -> PyResult<bool> { self.__contains__(pos) } } #[pyclass(module = "xingque", name = "CodeMap", frozen)] pub(crate) struct PyCodeMap(CodeMap); impl From<CodeMap> for PyCodeMap { fn from(value: CodeMap) -> Self { Self(value) } } #[pymethods] impl PyCodeMap { #[new] fn py_new(filename: String, source: String) -> Self { Self(CodeMap::new(filename, source)) } #[staticmethod] fn empty_static() -> Self { todo!(); } // TODO: is it necessary to wrap id()? fn full_span(&self) -> PySpan { self.0.full_span().into() } fn file_span(&self, span: &PySpan) -> PyFileSpan { self.0.file_span(span.0).into() } #[getter] fn filename(&self) -> &str { self.0.filename() } fn byte_at(&self, pos: &PyPos) -> u8 { self.0.byte_at(pos.0) } fn find_line(&self, pos: &PyPos) -> usize { self.0.find_line(pos.0) } #[getter] fn source(&self) -> &str { self.0.source() } fn source_span(&self, span: &PySpan) -> &str { self.0.source_span(span.0) } fn line_span(&self, line: usize) -> PySpan { PySpan(self.0.line_span(line)) } fn line_span_opt(&self, line: usize) -> Option<PySpan> { self.0.line_span_opt(line).map(PySpan) } fn resolve_span(&self, span: &PySpan) -> PyResolvedSpan { self.0.resolve_span(span.0).into() } fn source_line(&self, line: usize) -> &str { self.0.source_line(line) } fn source_line_at_pos(&self, pos: &PyPos) -> &str { self.0.source_line_at_pos(pos.0) } } #[pyclass(module = "xingque", name = "FileSpan", frozen)] #[derive(Clone)] pub(crate) struct PyFileSpan(FileSpan); impl From<FileSpan> for PyFileSpan { fn from(value: FileSpan) -> Self { Self(value) } } #[pymethods] impl PyFileSpan { #[new] fn py_new(filename: String, source: String) -> Self { FileSpan::new(filename, source).into() } #[getter] fn file(&self) -> PyCodeMap { self.0.file.clone().into() } #[getter] fn span(&self) -> PySpan { self.0.span.into() } #[getter] fn filename(&self) -> &str { self.0.filename() } #[getter] fn source_span(&self) -> &str { self.0.source_span() } fn resolve_span(&self) -> PyResolvedSpan { self.0.resolve_span().into() } fn resolve(&self) -> PyResolvedFileSpan { self.0.resolve().into() } } #[pyclass(module = "xingque", name = "ResolvedFileLine", eq, hash, frozen)] #[repr(transparent)] #[derive(PartialEq, Eq, Hash, Clone)] pub(crate) struct PyResolvedFileLine(ResolvedFileLine); impl From<ResolvedFileLine> for PyResolvedFileLine { fn from(value: ResolvedFileLine) -> Self { Self(value) } } #[pymethods] impl PyResolvedFileLine { #[new] fn py_new(file: String, line: usize) -> Self { ResolvedFileLine { file, line }.into() } fn __repr__(slf: &Bound<'_, Self>) -> PyResult<String> { let class_name = slf.get_type().qualname()?; let me = slf.borrow(); Ok(format!( "{}(file={:?}, line={})", class_name, me.0.file, me.0.line, )) } #[getter] fn get_file(&self) -> &str { &self.0.file } #[getter] fn get_line(&self) -> usize { self.0.line } } #[pyclass(module = "xingque", name = "ResolvedFileSpan", eq, hash, frozen)] #[repr(transparent)] #[derive(PartialEq, Eq, Hash, Clone)] pub(crate) struct PyResolvedFileSpan(ResolvedFileSpan); impl From<ResolvedFileSpan> for PyResolvedFileSpan { fn from(value: ResolvedFileSpan) -> Self { Self(value) } } #[pymethods] impl PyResolvedFileSpan { #[new] fn py_new(file: String, span: &PyResolvedSpan) -> Self { ResolvedFileSpan { file, span: span.0 }.into() } fn __repr__(slf: &Bound<'_, Self>) -> PyResult<String> { let class_name = slf.get_type().qualname()?; let me = slf.borrow(); Ok(format!( "{}(file={:?}, span={})", class_name, me.0.file, me.0.span, )) } #[getter] fn get_file(&self) -> &str { &self.0.file } #[getter] fn get_span(&self) -> PyResolvedSpan { self.0.span.into() } fn begin_file_line(&self) -> PyResolvedFileLine { self.0.begin_file_line().into() } }
xen0n/xingque
7
✨🐦 Typed Python binding to starlark-rust that proxies your objects
Rust
xen0n
WÁNG Xuěruì
gentoo
src/environment.rs
Rust
use pyo3::exceptions::{PyRuntimeError, PyValueError}; use pyo3::prelude::*; use starlark::environment::{FrozenModule, Globals, GlobalsBuilder, LibraryExtension, Module}; use starlark::values::{FrozenStringValue, FrozenValue}; use crate::py2sl::{self, sl_frozen_value_from_py}; use crate::sl2py::{self, py_from_sl_frozen_value}; /// The extra library definitions available in this Starlark implementation, but not in the standard. #[pyclass( module = "xingque", name = "LibraryExtension", rename_all = "SCREAMING_SNAKE_CASE", frozen, eq, hash )] #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub(crate) enum PyLibraryExtension { /// Definitions to support the `struct` type, the `struct()` constructor. StructType, /// Definitions to support the `record` type, the `record()` constructor and `field()` function. RecordType, /// Definitions to support the `enum` type, the `enum()` constructor. EnumType, /// A function `map(f, xs)` which applies `f` to each element of `xs` and returns the result. Map, /// A function `filter(f, xs)` which applies `f` to each element of `xs` and returns those for which `f` returns `True`. /// As a special case, `filter(None, xs)` removes all `None` values. Filter, /// Partially apply a function, `partial(f, *args, **kwargs)` will create a function where those `args` `kwargs` /// are already applied to `f`. Partial, /// Add a function `debug(x)` which shows the Rust `Debug` representation of a value. /// Useful when debugging, but the output should not be considered stable. Debug, /// Add a function `print(x)` which prints to stderr. Print, /// Add a function `pprint(x)` which pretty-prints to stderr. Pprint, /// Add a function `breakpoint()` which will drop into a console-module evaluation prompt. Breakpoint, /// Add a function `json()` which will generate JSON for a module. Json, /// Provides `typing.All`, `typing.Callable` etc. /// Usually used in conjunction with /// `Dialect.enable_types`. Typing, /// Utilities exposing starlark-rust internals. /// These are not for production use. Internal, /// Add a function `call_stack()` which returns a string representation of /// the current call stack. CallStack, // NOTE: keep this in sync with LibraryExtension } impl From<LibraryExtension> for PyLibraryExtension { fn from(value: LibraryExtension) -> Self { match value { LibraryExtension::StructType => Self::StructType, LibraryExtension::RecordType => Self::RecordType, LibraryExtension::EnumType => Self::EnumType, LibraryExtension::Map => Self::Map, LibraryExtension::Filter => Self::Filter, LibraryExtension::Partial => Self::Partial, LibraryExtension::Debug => Self::Debug, LibraryExtension::Print => Self::Print, LibraryExtension::Pprint => Self::Pprint, LibraryExtension::Breakpoint => Self::Breakpoint, LibraryExtension::Json => Self::Json, LibraryExtension::Typing => Self::Typing, LibraryExtension::Internal => Self::Internal, LibraryExtension::CallStack => Self::CallStack, } } } impl From<PyLibraryExtension> for LibraryExtension { fn from(value: PyLibraryExtension) -> Self { match value { PyLibraryExtension::StructType => Self::StructType, PyLibraryExtension::RecordType => Self::RecordType, PyLibraryExtension::EnumType => Self::EnumType, PyLibraryExtension::Map => Self::Map, PyLibraryExtension::Filter => Self::Filter, PyLibraryExtension::Partial => Self::Partial, PyLibraryExtension::Debug => Self::Debug, PyLibraryExtension::Print => Self::Print, PyLibraryExtension::Pprint => Self::Pprint, PyLibraryExtension::Breakpoint => Self::Breakpoint, PyLibraryExtension::Json => Self::Json, PyLibraryExtension::Typing => Self::Typing, PyLibraryExtension::Internal => Self::Internal, PyLibraryExtension::CallStack => Self::CallStack, } } } #[pyclass(module = "xingque", name = "Globals", frozen)] pub(crate) struct PyGlobals(pub(crate) Globals); impl From<Globals> for PyGlobals { fn from(value: Globals) -> Self { Self(value) } } #[pymethods] impl PyGlobals { #[new] fn new() -> Self { Globals::new().into() } #[staticmethod] fn standard() -> Self { Globals::standard().into() } #[staticmethod] fn extended_by(extensions: &Bound<'_, PyAny>) -> PyResult<Self> { let extensions = { let mut tmp = Vec::new(); for x in extensions.iter()? { match x { Ok(x) => match x.extract::<PyLibraryExtension>() { Ok(x) => tmp.push(x.into()), Err(e) => return Err(PyValueError::new_err(e)), }, Err(e) => return Err(PyValueError::new_err(e)), } } tmp }; Ok(Globals::extended_by(&extensions).into()) } fn names(slf: &Bound<'_, Self>) -> PyResult<Py<PyFrozenStringValueIterator>> { Py::new( slf.py(), PyFrozenStringValueIterator::new(slf, Box::new(slf.borrow().0.names())), ) } fn __iter__(slf: &Bound<'_, Self>) -> PyResult<Py<PyGlobalsItemsIterator>> { Py::new( slf.py(), PyGlobalsItemsIterator::new(slf, Box::new(slf.borrow().0.iter())), ) } fn describe(&self) -> String { self.0.describe() } #[getter] fn docstring(&self) -> Option<&str> { self.0.docstring() } // TODO: documentation } #[pyclass(module = "xingque", name = "_FrozenStringValueIterator")] pub(crate) struct PyFrozenStringValueIterator { _parent: PyObject, inner: Box<dyn Iterator<Item = FrozenStringValue> + Send + Sync>, } impl PyFrozenStringValueIterator { fn new( parent: &Bound<'_, PyAny>, value: Box<dyn Iterator<Item = FrozenStringValue> + Send + Sync + '_>, ) -> Self { let parent = parent.clone().unbind(); Self { _parent: parent, // Safety: parent is kept alive by the reference above inner: unsafe { ::core::mem::transmute(value) }, } } } #[pymethods] impl PyFrozenStringValueIterator { fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> { slf } fn __next__(mut slf: PyRefMut<'_, Self>) -> Option<&str> { slf.inner.next().map(|x| x.as_str()) } } #[pyclass(module = "xingque", name = "_GlobalsItemsIterator")] pub(crate) struct PyGlobalsItemsIterator { _parent: Py<PyGlobals>, inner: Box<dyn Iterator<Item = (&'static str, FrozenValue)> + Send + Sync>, } impl PyGlobalsItemsIterator { fn new( parent: &Bound<'_, PyGlobals>, value: Box<dyn Iterator<Item = (&str, FrozenValue)> + Send + Sync + '_>, ) -> Self { let parent = parent.clone().unbind(); Self { _parent: parent, // Safety: parent is kept alive by the reference above inner: unsafe { ::core::mem::transmute(value) }, } } } #[pymethods] impl PyGlobalsItemsIterator { fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> { slf } fn __next__(mut slf: PyRefMut<'_, Self>) -> PyResult<Option<(&str, PyObject)>> { let py = slf.py(); match slf.inner.next() { None => Ok(None), Some((k, v)) => { let v = py_from_sl_frozen_value(py, v)?; Ok(Some((k, v))) } } } } #[pyclass(module = "xingque", name = "GlobalsBuilder")] pub(crate) struct PyGlobalsBuilder(Option<GlobalsBuilder>); impl From<GlobalsBuilder> for PyGlobalsBuilder { fn from(value: GlobalsBuilder) -> Self { Self(Some(value)) } } #[pymethods] impl PyGlobalsBuilder { #[new] fn new() -> Self { GlobalsBuilder::new().into() } #[staticmethod] fn standard() -> Self { GlobalsBuilder::standard().into() } #[staticmethod] fn extended_by(extensions: &Bound<'_, PyAny>) -> PyResult<Self> { let extensions = { let mut tmp = Vec::new(); for x in extensions.iter()? { match x { Ok(x) => match x.extract::<PyLibraryExtension>() { Ok(x) => tmp.push(x.into()), Err(e) => return Err(PyValueError::new_err(e)), }, Err(e) => return Err(PyValueError::new_err(e)), } } tmp }; Ok(GlobalsBuilder::extended_by(&extensions).into()) } fn r#struct(&mut self, name: &str, f: &Bound<'_, PyAny>) -> PyResult<()> { let inner = match &mut self.0 { Some(inner) => inner, None => { return Err(PyRuntimeError::new_err( "this GlobalsBuilder has already been consumed", )) } }; let mut err = None; inner.struct_(name, |gb| { let args = (PySubGlobalsBuilder::new(gb),); err = f.call1(args).err(); }); match err { Some(e) => Err(e), None => Ok(()), } } fn with_<'py>( slf: &'py Bound<'py, Self>, f: &'py Bound<'py, PyAny>, ) -> PyResult<&'py Bound<'py, Self>> { // implement the logic ourselves to avoid having to do ownership dance // it's basically just f(self) and return self let mut me = slf.borrow_mut(); let inner = match &mut me.0 { Some(inner) => inner, None => { return Err(PyRuntimeError::new_err( "this GlobalsBuilder has already been consumed", )) } }; let args = (PySubGlobalsBuilder::new(inner),); let err = f.call1(args).err(); match err { Some(e) => Err(e), None => Ok(slf), } } fn with_struct<'py>( slf: &'py Bound<'py, Self>, name: &str, f: &'py Bound<'py, PyAny>, ) -> PyResult<&'py Bound<'py, Self>> { // implement the logic ourselves to avoid having to do ownership dance // it's basically just self.struct_(name, f) and return self slf.borrow_mut().r#struct(name, f).map(|_| slf) } fn build(&mut self) -> PyResult<PyGlobals> { let inner = match self.0.take() { Some(inner) => inner, None => { return Err(PyRuntimeError::new_err( "this GlobalsBuilder has already been consumed", )) } }; Ok(inner.build().into()) } fn set(&mut self, name: &str, value: &Bound<'_, PyAny>) -> PyResult<()> { let inner = match &mut self.0 { Some(inner) => inner, None => { return Err(PyRuntimeError::new_err( "this GlobalsBuilder has already been consumed", )) } }; let heap = inner.frozen_heap(); inner.set(name, sl_frozen_value_from_py(value, heap)?); Ok(()) } // TODO: set_function // TODO: are those necessary? // // * frozen_heap // * alloc // * set_docstring } // necessary for proper ownership maintenance #[pyclass(module = "xingque", name = "_SubGlobalsBuilder", unsendable)] pub(crate) struct PySubGlobalsBuilder(&'static mut GlobalsBuilder); impl PySubGlobalsBuilder { fn new(ptr: &mut GlobalsBuilder) -> Self { // Safety TODO let ptr: &'static mut GlobalsBuilder = unsafe { ::core::mem::transmute(ptr) }; Self(ptr) } } #[pymethods] impl PySubGlobalsBuilder { fn r#struct(&mut self, name: &str, f: &Bound<'_, PyAny>) -> PyResult<()> { let mut err = None; self.0.struct_(name, |gb| { let args = (PySubGlobalsBuilder::new(gb),); err = f.call1(args).err(); }); match err { Some(e) => Err(e), None => Ok(()), } } fn with_<'py>( slf: &'py Bound<'py, Self>, f: &'py Bound<'py, PyAny>, ) -> PyResult<&'py Bound<'py, Self>> { // implement the logic ourselves to avoid having to do ownership dance // it's basically just f(self) and return self let mut me = slf.borrow_mut(); let args = (PySubGlobalsBuilder::new(me.0),); let err = f.call1(args).err(); match err { Some(e) => Err(e), None => Ok(slf), } } fn with_struct<'py>( slf: &'py Bound<'py, Self>, name: &str, f: &'py Bound<'py, PyAny>, ) -> PyResult<&'py Bound<'py, Self>> { // implement the logic ourselves to avoid having to do ownership dance // it's basically just self.struct_(name, f) and return self slf.borrow_mut().r#struct(name, f).map(|_| slf) } // no build() because it needs to take ownership which is not what we want // to allow for a nested builder fn set(&mut self, name: &str, value: &Bound<'_, PyAny>) -> PyResult<()> { let heap = self.0.frozen_heap(); self.0.set(name, sl_frozen_value_from_py(value, heap)?); Ok(()) } } #[pyclass(module = "xingque", name = "FrozenModule", frozen)] #[derive(Clone)] pub(crate) struct PyFrozenModule(pub(crate) FrozenModule); impl From<FrozenModule> for PyFrozenModule { fn from(value: FrozenModule) -> Self { Self(value) } } #[pymethods] impl PyFrozenModule { #[staticmethod] fn from_globals(globals: &Bound<'_, PyGlobals>) -> PyResult<Self> { Ok(FrozenModule::from_globals(&globals.borrow().0)?.into()) } fn dump_debug(&self) -> String { self.0.dump_debug() } fn get_option(&self, py: Python, name: &str) -> PyResult<PyObject> { match self.0.get_option(name)? { Some(sl) => sl2py::py_from_sl_value(py, sl.value()), None => Ok(py.None()), } } fn get(&self, py: Python, name: &str) -> PyResult<PyObject> { sl2py::py_from_sl_value(py, self.0.get(name)?.value()) } fn names(slf: &Bound<'_, Self>) -> PyResult<Py<PyFrozenStringValueIterator>> { Py::new( slf.py(), PyFrozenStringValueIterator::new(slf, Box::new(slf.borrow().0.names())), ) } fn describe(&self) -> String { self.0.describe() } // TODO: documentation // TODO: aggregated_heap_profile_info #[getter] fn get_extra_value(&self, py: Python) -> PyResult<PyObject> { match self.0.extra_value() { Some(sl) => sl2py::py_from_sl_frozen_value(py, sl), None => Ok(py.None()), } } } #[pyclass(module = "xingque", name = "Module")] pub(crate) struct PyModule(Option<Module>); impl From<Module> for PyModule { fn from(value: Module) -> Self { Self(Some(value)) } } impl PyModule { pub(crate) fn inner(&self) -> PyResult<&Module> { self.0 .as_ref() .ok_or(PyRuntimeError::new_err("this Module is already consumed")) } pub(crate) fn inner_mut(&mut self) -> PyResult<&mut Module> { self.0 .as_mut() .ok_or(PyRuntimeError::new_err("this Module is already consumed")) } pub(crate) fn take_inner(&mut self) -> PyResult<Module> { self.0 .take() .ok_or(PyRuntimeError::new_err("this Module is already consumed")) } } #[pymethods] impl PyModule { #[new] fn py_new() -> Self { Module::new().into() } // TODO: heap // TODO: frozen_heap fn names(slf: &Bound<'_, Self>) -> PyResult<Py<PyFrozenStringValueIterator>> { Py::new( slf.py(), PyFrozenStringValueIterator::new(slf, Box::new(slf.borrow().inner()?.names())), ) } // TODO: names_and_visibilities // TODO: __getitem__/__setitem__? fn get(&self, py: Python, name: &str) -> PyResult<Option<PyObject>> { sl2py::py_from_sl_value_option(py, self.inner()?.get(name)) } fn set(&mut self, name: &str, value: &Bound<'_, PyAny>) -> PyResult<()> { let inner = self.inner_mut()?; inner.set(name, py2sl::sl_value_from_py(value, inner.heap())); Ok(()) } fn freeze(&mut self) -> PyResult<PyFrozenModule> { let inner = self.take_inner()?; Ok(inner.freeze()?.into()) } // TODO: import_public_symbols #[getter] fn get_extra_value(&self, py: Python) -> PyResult<Option<PyObject>> { sl2py::py_from_sl_value_option(py, self.inner()?.extra_value()) } #[setter] fn set_extra_value(&self, value: &Bound<'_, PyAny>) -> PyResult<()> { let inner = self.inner()?; inner.set_extra_value(py2sl::sl_value_from_py(value, inner.heap())); Ok(()) } }
xen0n/xingque
7
✨🐦 Typed Python binding to starlark-rust that proxies your objects
Rust
xen0n
WÁNG Xuěruì
gentoo
src/errors.rs
Rust
use pyo3::prelude::*; use starlark::codemap::FileSpan; use starlark::errors::Frame; use crate::codemap::PyFileSpan; #[pyclass(module = "xingque", name = "Frame", frozen)] #[derive(Clone)] pub(crate) struct PyFrame(Frame); impl From<Frame> for PyFrame { fn from(value: Frame) -> Self { Self(value) } } #[pymethods] impl PyFrame { #[getter] fn name(&self) -> &str { &self.0.name } #[getter] fn location(&self) -> Option<PyFileSpan> { self.0.location.clone().map(FileSpan::into) } // TODO: write_two_lines }
xen0n/xingque
7
✨🐦 Typed Python binding to starlark-rust that proxies your objects
Rust
xen0n
WÁNG Xuěruì
gentoo
src/eval.rs
Rust
use std::collections::{HashMap, HashSet}; use anyhow::anyhow; use pyo3::exceptions::PyRuntimeError; use pyo3::intern; use pyo3::prelude::*; use pyo3::types::{PyDict, PyTuple}; use starlark::codemap::ResolvedFileSpan; use starlark::environment::{FrozenModule, Module}; use starlark::errors::Frame; use starlark::eval::{CallStack, Evaluator, FileLoader, ProfileMode}; use starlark::PrintHandler; use crate::codemap::{PyFileSpan, PyResolvedFileSpan}; use crate::environment::{PyFrozenModule, PyGlobals, PyModule}; use crate::errors::PyFrame; use crate::syntax::PyAstModule; use crate::{py2sl, sl2py}; #[pyclass(module = "xingque", name = "CallStack")] pub(crate) struct PyCallStack(CallStack); impl From<CallStack> for PyCallStack { fn from(value: CallStack) -> Self { Self(value) } } #[pymethods] impl PyCallStack { #[getter] fn frames(&self) -> Vec<PyFrame> { self.0.frames.clone().into_iter().map(Frame::into).collect() } fn is_empty(&self) -> bool { self.0.is_empty() } // into_frames not needed because one doesn't consume values in Python } // it seems the Evaluator contains many thread-unsafe states #[pyclass(module = "xingque", name = "Evaluator", unsendable)] pub(crate) struct PyEvaluator( Evaluator<'static, 'static>, // this reference is necessary for memory safety #[allow(dead_code)] Py<PyModule>, PyObjectFileLoader, PyObjectPrintHandler, ); impl PyEvaluator { fn new(module: Bound<'_, PyModule>) -> PyResult<Self> { let module_ref = module.clone().unbind(); let module = module.borrow(); let module = module.inner()?; let module: &'static Module = unsafe { ::core::mem::transmute(module) }; Ok(Self( Evaluator::new(module), module_ref, PyObjectFileLoader::default(), PyObjectPrintHandler::default(), )) } fn ensure_module_available(&self, py: Python) -> PyResult<()> { self.1.bind(py).borrow().inner().map(|_| ()) } } #[pymethods] impl PyEvaluator { #[new] #[pyo3(signature = (module = None))] fn py_new(py: Python, module: Option<Bound<'_, PyModule>>) -> PyResult<Self> { let module = module.map_or_else(|| Bound::new(py, PyModule::from(Module::new())), Result::Ok)?; Self::new(module) } fn disable_gc(&mut self, py: Python) -> PyResult<()> { self.ensure_module_available(py)?; self.0.disable_gc(); Ok(()) } fn eval_statements( &mut self, py: Python, statements: &Bound<'_, PyAstModule>, ) -> PyResult<PyObject> { self.ensure_module_available(py)?; match self .0 .eval_statements(statements.borrow_mut().take_inner()?) { Ok(sl) => sl2py::py_from_sl_value(py, sl), Err(e) => Err(PyRuntimeError::new_err(e.to_string())), } } fn local_variables(&self, py: Python) -> PyResult<HashMap<String, PyObject>> { self.ensure_module_available(py)?; let vars = self.0.local_variables(); let mut result = HashMap::with_capacity(vars.len()); for (k, v) in vars.into_iter() { result.insert(k.to_string(), sl2py::py_from_sl_value(py, v)?); } Ok(result) } fn verbose_gc(&mut self, py: Python) -> PyResult<()> { self.ensure_module_available(py)?; self.0.verbose_gc(); Ok(()) } fn enable_static_typechecking(&mut self, py: Python, enable: bool) -> PyResult<()> { self.ensure_module_available(py)?; self.0.enable_static_typechecking(enable); Ok(()) } fn set_loader(&mut self, py: Python, loader: &Bound<'_, PyAny>) -> PyResult<()> { self.ensure_module_available(py)?; self.2.set(loader.clone().unbind()); let ptr: &'_ dyn FileLoader = &self.2; // Safety: actually the wrapper object and the evaluator are identically // scoped let ptr: &'static dyn FileLoader = unsafe { ::core::mem::transmute(ptr) }; self.0.set_loader(ptr); Ok(()) } fn enable_profile(&mut self, py: Python, mode: PyProfileMode) -> PyResult<()> { self.ensure_module_available(py)?; self.0.enable_profile(&mode.into())?; Ok(()) } // TODO: write_profile // TODO: gen_profile fn coverage(&self, py: Python) -> PyResult<HashSet<PyResolvedFileSpan>> { self.ensure_module_available(py)?; Ok(self .0 .coverage() .map(|x| x.into_iter().map(ResolvedFileSpan::into).collect())?) } fn enable_terminal_breakpoint_console(&mut self, py: Python) -> PyResult<()> { self.ensure_module_available(py)?; self.0.enable_terminal_breakpoint_console(); Ok(()) } fn call_stack(&self, py: Python) -> PyResult<PyCallStack> { self.ensure_module_available(py)?; Ok(self.0.call_stack().into()) } fn call_stack_top_frame(&self, py: Python) -> PyResult<Option<PyFrame>> { self.ensure_module_available(py)?; Ok(self.0.call_stack_top_frame().map(Frame::into)) } fn call_stack_count(&self, py: Python) -> PyResult<usize> { self.ensure_module_available(py)?; Ok(self.0.call_stack_count()) } fn call_stack_top_location(&self, py: Python) -> PyResult<Option<PyFileSpan>> { self.ensure_module_available(py)?; Ok(self.0.call_stack_top_location().map(PyFileSpan::from)) } fn set_print_handler(&mut self, py: Python, handler: &Bound<'_, PyAny>) -> PyResult<()> { self.ensure_module_available(py)?; let handler: Option<PyObject> = if handler.is_none() { None } else { Some(handler.clone().unbind()) }; self.3.set(handler); let ptr: &'_ dyn PrintHandler = &self.3; // Safety: actually the wrapper object and the evaluator are identically // scoped let ptr: &'static dyn PrintHandler = unsafe { ::core::mem::transmute(ptr) }; self.0.set_print_handler(ptr); Ok(()) } // TODO: heap #[getter] fn module(&self, py: Python) -> PyResult<Py<PyModule>> { self.ensure_module_available(py)?; Ok(self.1.clone_ref(py)) } // TODO: frozen_heap // TODO: set_module_variable_at_some_point (is this okay to expose?) fn set_max_callstack_size(&mut self, py: Python, stack_size: usize) -> PyResult<()> { self.ensure_module_available(py)?; self.0.set_max_callstack_size(stack_size)?; Ok(()) } fn eval_module( &mut self, py: Python, ast: &Bound<'_, PyAstModule>, globals: &Bound<'_, PyGlobals>, ) -> PyResult<PyObject> { self.ensure_module_available(py)?; match self .0 .eval_module(ast.borrow_mut().take_inner()?, &globals.borrow().0) { Ok(sl) => sl2py::py_from_sl_value(py, sl), Err(e) => Err(PyRuntimeError::new_err(e.to_string())), } } #[pyo3(signature = (function, *args, **kwargs))] fn eval_function( &mut self, py: Python, function: &Bound<'_, PyAny>, args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>, ) -> PyResult<PyObject> { self.ensure_module_available(py)?; let heap = self.0.heap(); let to_sl = |x| py2sl::sl_value_from_py(x, heap); let function = to_sl(function); let positional: Vec<_> = args .iter_borrowed() .map(|x| py2sl::sl_value_from_py(&x, heap)) // borrowck doesn't let me use to_sl, sigh .collect(); let named: Vec<_> = if let Some(kwargs) = kwargs { let mut tmp = Vec::with_capacity(kwargs.len()); for (k, v) in kwargs.clone().into_iter() { tmp.push((k.extract::<String>()?, v)); } tmp } else { Vec::new() }; let named: Vec<_> = named.iter().map(|(k, v)| (k.as_str(), to_sl(v))).collect(); match self.0.eval_function(function, &positional, &named) { Ok(sl) => sl2py::py_from_sl_value(py, sl), Err(e) => Err(PyRuntimeError::new_err(e.to_string())), } } } /// How to profile starlark code. #[pyclass( module = "xingque", name = "ProfileMode", rename_all = "SCREAMING_SNAKE_CASE", frozen, eq, hash )] #[derive(Debug, PartialEq, Eq, Hash, Clone)] pub(crate) enum PyProfileMode { /// The heap profile mode provides information about the time spent in each function and allocations /// performed by each function. Enabling this mode the side effect of disabling garbage-collection. /// This profiling mode is the recommended one. HeapSummaryAllocated, /// Like heap summary, but information about retained memory after module is frozen. HeapSummaryRetained, /// Like heap profile, but writes output comparible with /// [flamegraph.pl](https://github.com/brendangregg/FlameGraph/blob/master/flamegraph.pl). HeapFlameAllocated, /// Like heap flame, but information about retained memory after module is frozen. HeapFlameRetained, /// The statement profile mode provides information about time spent in each statement. Statement, /// Code coverage. Coverage, /// The bytecode profile mode provides information about bytecode instructions. Bytecode, /// The bytecode profile mode provides information about bytecode instruction pairs. BytecodePairs, /// Provide output compatible with /// [flamegraph.pl](https://github.com/brendangregg/FlameGraph/blob/master/flamegraph.pl). TimeFlame, /// Profile runtime typechecking. Typecheck, } impl From<ProfileMode> for PyProfileMode { fn from(value: ProfileMode) -> Self { match value { ProfileMode::HeapSummaryAllocated => Self::HeapSummaryAllocated, ProfileMode::HeapSummaryRetained => Self::HeapSummaryRetained, ProfileMode::HeapFlameAllocated => Self::HeapFlameAllocated, ProfileMode::HeapFlameRetained => Self::HeapFlameRetained, ProfileMode::Statement => Self::Statement, ProfileMode::Coverage => Self::Coverage, ProfileMode::Bytecode => Self::Bytecode, ProfileMode::BytecodePairs => Self::BytecodePairs, ProfileMode::TimeFlame => Self::TimeFlame, ProfileMode::Typecheck => Self::Typecheck, // NOTE: check if variants are added after every starlark dep bump! _ => unreachable!(), } } } impl From<PyProfileMode> for ProfileMode { fn from(value: PyProfileMode) -> Self { match value { PyProfileMode::HeapSummaryAllocated => Self::HeapSummaryAllocated, PyProfileMode::HeapSummaryRetained => Self::HeapSummaryRetained, PyProfileMode::HeapFlameAllocated => Self::HeapFlameAllocated, PyProfileMode::HeapFlameRetained => Self::HeapFlameRetained, PyProfileMode::Statement => Self::Statement, PyProfileMode::Coverage => Self::Coverage, PyProfileMode::Bytecode => Self::Bytecode, PyProfileMode::BytecodePairs => Self::BytecodePairs, PyProfileMode::TimeFlame => Self::TimeFlame, PyProfileMode::Typecheck => Self::Typecheck, } } } // it would be good if https://github.com/PyO3/pyo3/issues/1190 is implemented // so we could have stronger typing // but currently duck-typing isn't bad anyway // this is why we don't declare this as a pyclass right now #[derive(Debug, Default)] pub(crate) struct PyObjectFileLoader(Option<PyObject>); impl PyObjectFileLoader { fn set(&mut self, obj: PyObject) { self.0 = Some(obj); } } impl FileLoader for PyObjectFileLoader { fn load(&self, path: &str) -> anyhow::Result<FrozenModule> { if let Some(inner) = self.0.as_ref() { Python::with_gil(|py| { // first check if it's a PyDictFileLoader and forward to its impl if let Ok(x) = inner.downcast_bound::<PyDictFileLoader>(py) { return x.borrow().load(path); } // duck-typing // call the wrapped PyObject's "load" method with the path // and expect the return value to be exactly PyFrozenModule let name = intern!(py, "load"); let args = PyTuple::new_bound(py, &[path]); Ok(inner .call_method_bound(py, name, args, None)? .extract::<PyFrozenModule>(py)? .0) }) } else { // this should never happen because we control the only place where // this struct could possibly get instantiated, and a PyObject is // guaranteed there (remember None is also a non-null PyObject) unreachable!() } } } // a PyDict is wrapped here instead of the ReturnFileLoader (so we effectively // don't wrap ReturnFileLoader but provide equivalent functionality that's // idiomatic in Python), because unfortunately ReturnFileLoader has a lifetime // parameter, but luckily it's basically just a reference to a HashMap and its // logic is trivial. #[pyclass(module = "xingque", name = "DictFileLoader")] pub(crate) struct PyDictFileLoader(Py<PyDict>); #[pymethods] impl PyDictFileLoader { #[new] fn py_new(modules: Py<PyDict>) -> Self { Self(modules) } } impl FileLoader for PyDictFileLoader { fn load(&self, path: &str) -> anyhow::Result<FrozenModule> { let result: anyhow::Result<_> = Python::with_gil(|py| match self.0.bind(py).get_item(path)? { Some(v) => Ok(Some(v.extract::<PyFrozenModule>()?)), None => Ok(None), }); result?.map(|x| x.0).ok_or(anyhow!( "DictFileLoader does not know the module `{}`", path )) } } // it would be good if https://github.com/PyO3/pyo3/issues/1190 is implemented // so we could have stronger typing // but currently duck-typing isn't bad anyway // this is why we don't declare this as a pyclass right now #[derive(Debug, Default)] pub(crate) struct PyObjectPrintHandler(Option<PyObject>); impl PyObjectPrintHandler { fn set(&mut self, obj: Option<PyObject>) { self.0 = obj; } } impl PrintHandler for PyObjectPrintHandler { fn println(&self, text: &str) -> anyhow::Result<()> { if let Some(inner) = self.0.as_ref() { Python::with_gil(|py| { // duck-typing // call the wrapped PyObject's "println" method with the path // and ignore the return value let name = intern!(py, "println"); let args = PyTuple::new_bound(py, &[text]); inner.call_method_bound(py, name, args, None)?; Ok(()) }) } else { // Duplicate of starlark's stdlib::extra::StderrPrintHandler (the default // print handler), because it is unfortunately pub(crate), but the // logic is trivial. eprintln!("{}", text); Ok(()) } } }
xen0n/xingque
7
✨🐦 Typed Python binding to starlark-rust that proxies your objects
Rust
xen0n
WÁNG Xuěruì
gentoo
src/lib.rs
Rust
use pyo3::prelude::*; mod codemap; mod environment; mod errors; mod eval; mod py2sl; mod repr_utils; mod sl2py; mod syntax; mod values; #[pymodule] mod xingque { use super::*; #[pymodule_export] use codemap::PyCodeMap; #[pymodule_export] use codemap::PyFileSpan; #[pymodule_export] use codemap::PyPos; #[pymodule_export] use codemap::PyResolvedFileLine; #[pymodule_export] use codemap::PyResolvedFileSpan; #[pymodule_export] use codemap::PyResolvedPos; #[pymodule_export] use codemap::PyResolvedSpan; #[pymodule_export] use codemap::PySpan; #[pymodule_export] use environment::PyFrozenModule; #[pymodule_export] use environment::PyGlobals; #[pymodule_export] use environment::PyGlobalsBuilder; #[pymodule_export] use environment::PyLibraryExtension; #[pymodule_export] use environment::PyModule; #[pymodule_export] use errors::PyFrame; #[pymodule_export] use eval::PyCallStack; #[pymodule_export] use eval::PyDictFileLoader; #[pymodule_export] use eval::PyEvaluator; #[pymodule_export] use eval::PyProfileMode; #[pymodule_export] use syntax::PyAstModule; #[pymodule_export] use syntax::PyDialect; #[pymodule_export] use syntax::PyDialectTypes; #[pymodule_export] use values::PyFrozenValue; #[pymodule_export] use values::PyHeap; #[pymodule_export] use values::PyHeapSummary; #[pymodule_export] use values::PyValue; #[pymodule_init] fn init(m: &Bound<'_, pyo3::types::PyModule>) -> PyResult<()> { m.add( "VERSION", option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"), )?; m.add("STARLARK_RUST_VERSION", "0.12.0")?; // TODO: query this from Cargo Ok(()) } }
xen0n/xingque
7
✨🐦 Typed Python binding to starlark-rust that proxies your objects
Rust
xen0n
WÁNG Xuěruì
gentoo