@signe/room 0.0.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/decorators.ts","../src/server.ts","../src/utils.ts"],"sourcesContent":["export function action(name: string, bodyValidation?) {\n return function (target: any, propertyKey: string) {\n if (!target.constructor._actionMetadata) {\n target.constructor._actionMetadata = new Map();\n }\n target.constructor._actionMetadata.set(name, {\n key: propertyKey,\n bodyValidation,\n });\n };\n}\n\nexport function Room(options) {\n return function (target: any) {\n target.path = options.path;\n target.maxUsers = options.maxUsers;\n target.throttleStorage = options.throttleStorage;\n };\n}\n","import { createStatesSnapshot, getByPath, load, syncClass } from \"@signe/sync\";\nimport { dset } from \"dset\";\nimport z from \"zod\";\nimport type * as Party from \"./types/party\";\nimport {\n awaitReturn,\n buildObject,\n extractParams,\n isClass,\n throttle,\n} from \"./utils\";\n\nconst Message = z.object({\n action: z.string(),\n value: z.any(),\n});\n\nexport class Server implements Party.Server {\n memoryAll = {};\n subRoom = {};\n rooms = [];\n\n static async onBeforeConnect(request: Party.Request) {\n try {\n request.headers.set(\"X-User-ID\", \"\" + Math.random());\n return request;\n } catch (e) {\n return new Response(\"Unauthorized\", { status: 401 });\n }\n }\n\n constructor(readonly room: Party.Room) {\n for (let room of this.rooms) {\n const params = extractParams(room.path, this.room.id);\n if (params) {\n this.subRoom = new room(this.room, params);\n break;\n }\n }\n\n if (!this.subRoom) {\n throw new Error(\"Room not found\");\n }\n\n const loadMemory = async () => {\n const root = await this.room.storage.get(\".\");\n const memory = await this.room.storage.list();\n const tmpObject: any = root || {};\n for (let [key, value] of memory) {\n if (key == \".\") {\n continue;\n }\n dset(tmpObject, key, value);\n }\n load(this, tmpObject);\n };\n\n loadMemory();\n\n syncClass(this.subRoom, {\n onSync: throttle((values) => {\n const packet = buildObject(values, this.memoryAll);\n this.room.broadcast(\n JSON.stringify({\n type: \"sync\",\n value: packet,\n })\n );\n values.clear();\n }, 500),\n onPersist: throttle(async (values) => {\n for (let path of values) {\n const instance =\n path == \".\" ? this.subRoom : getByPath(this.subRoom, path);\n const itemValue = createStatesSnapshot(instance);\n await this.room.storage.put(path, itemValue);\n }\n values.clear();\n }, this.subRoom['throttleStorage'] ?? 2000),\n });\n }\n\n private getUsersProperty() {\n const meta = this.subRoom.constructor['_propertyMetadata'];\n const propId = meta?.get(\"users\");\n if (propId) {\n return this.subRoom[propId];\n }\n return null;\n }\n\n async onConnect(conn: Party.Connection, ctx: Party.ConnectionContext) {\n const publicId = \"a\" + (\"\" + Math.random()).split(\".\")[1];\n let user = null;\n const signal = this.getUsersProperty();\n if (signal) {\n const { classType } = signal.options;\n user = isClass(classType) ? new classType() : classType(conn, ctx);\n signal()[publicId] = user;\n }\n await awaitReturn(this.subRoom['onJoin']?.(user, conn, ctx));\n conn.setState({ publicId });\n conn.send(\n JSON.stringify({\n type: \"sync\",\n value: {\n pId: publicId,\n ...this.memoryAll,\n },\n })\n );\n }\n\n async onMessage(message: string, sender: Party.Connection) {\n const actions = this.subRoom.constructor['_actionMetadata'];\n const result = Message.safeParse(JSON.parse(message));\n if (!result.success) {\n return;\n }\n if (actions) {\n const signal = this.getUsersProperty();\n const { publicId } = sender.state as any;\n const user = signal?.()[publicId];\n const actionName = actions.get(result.data.action);\n if (actionName) {\n if (actionName.bodyValidation) {\n const bodyResult = actionName.bodyValidation.safeParse(\n result.data.value\n );\n if (!bodyResult.success) {\n return;\n }\n }\n await awaitReturn(\n this.subRoom[actionName.key](user, result.data.value, sender)\n );\n }\n }\n }\n\n async onClose(conn: Party.Connection) {\n const signal = this.getUsersProperty();\n const { publicId } = conn.state as any;\n const user = signal?.()[publicId];\n await awaitReturn(this.subRoom['onLeave']?.(user, conn));\n if (signal) {\n delete signal()[publicId];\n }\n }\n}\n","import { dset } from \"dset\";\n\nexport function isPromise(value: any): boolean {\n return value && value instanceof Promise;\n}\n\nexport async function awaitReturn(val: any) {\n return isPromise(val) ? await val : val;\n}\n\nexport function isClass(obj: any): boolean {\n return (\n typeof obj === \"function\" &&\n obj.prototype &&\n obj.prototype.constructor === obj\n );\n}\n\nexport function throttle<F extends (...args: any[]) => any>(\n func: F,\n wait: number\n): (...args: Parameters<F>) => void {\n let timeout: ReturnType<typeof setTimeout> | null = null;\n let lastArgs: Parameters<F> | null = null;\n\n return function (...args: Parameters<F>) {\n if (!timeout) {\n func(...args);\n timeout = setTimeout(() => {\n if (lastArgs) {\n func(...lastArgs);\n lastArgs = null;\n }\n timeout = null;\n }, wait);\n } else {\n lastArgs = args;\n }\n };\n}\n\nexport function extractParams(\n pattern: string,\n str: string\n): { [key: string]: string } | null {\n const regexPattern = pattern.replace(/{(\\w+)}/g, \"(?<$1>[\\\\w-]+)\");\n\n const regex = new RegExp(`^${regexPattern}$`);\n const match = regex.exec(str);\n\n if (match && match.groups) {\n return match.groups;\n } else {\n return null;\n }\n}\n\nexport function dremove(obj, keys) {\n keys.split && (keys = keys.split(\".\"));\n var i = 0,\n l = keys.length,\n t = { ...obj },\n k;\n\n while (i < l - 1) {\n k = keys[i++];\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") return; // On évite les clés dangereuses\n t = t[k];\n if (typeof t !== \"object\" || t === null) return; // Si l'objet n'existe pas, on arrête\n }\n\n k = keys[i];\n if (\n t &&\n typeof t === \"object\" &&\n !(k === \"__proto__\" || k === \"constructor\" || k === \"prototype\")\n ) {\n delete t[k];\n }\n}\n\nexport function buildObject(valuesMap, allMemory) {\n let memoryObj = {};\n for (let path of valuesMap.keys()) {\n const value = valuesMap.get(path);\n dset(memoryObj, path, value);\n if (path == \"$delete\") {\n dremove(allMemory, value);\n } else {\n dset(allMemory, path, value);\n }\n }\n return memoryObj;\n }"],"mappings":";AAAO,SAAS,OAAO,MAAc,gBAAiB;AACpD,SAAO,SAAU,QAAa,aAAqB;AACjD,QAAI,CAAC,OAAO,YAAY,iBAAiB;AACvC,aAAO,YA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WAAW,GAAG,EAAE,MAAM,OAAO,KAAK,OAAO,MAAM;AAAA,QAC9D;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,QAAQ,MAAwB;AACpC,UAAM,SAAS,KAAK,iBAAiB;AACrC,UAAM,EAAE,SAAS,IAAI,KAAK;AAC1B,UAAM,OAAO,SAAS,EAAE,QAAQ;AAChC,UAAM,YAAY,KAAK,QAAQ,SAAS,IAAI,MAAM,IAAI,CAAC;AACvD,QAAI,QAAQ;AACV,aAAO,OAAO,EAAE,QAAQ;AAAA,IAC1B;AAAA,EACF;AACF;","names":["dset","room","dset"]}
1
+ {"version":3,"sources":["../src/decorators.ts","../../sync/src/utils.ts","../src/mock.ts","../src/server.ts","../../sync/src/core.ts","../../sync/src/load.ts","../src/utils.ts"],"sourcesContent":["export function Action(name: string, bodyValidation?) {\n return function (target: any, propertyKey: string) {\n if (!target.constructor._actionMetadata) {\n target.constructor._actionMetadata = new Map();\n }\n target.constructor._actionMetadata.set(name, {\n key: propertyKey,\n bodyValidation,\n });\n };\n}\n\nexport interface RoomOptions {\n path: string;\n maxUsers?: number;\n throttleStorage?: number;\n throttleSync?: number;\n hibernate?: boolean;\n}\n\nexport function Room(options: RoomOptions) {\n return function (target: any) {\n target.path = options.path;\n target.maxUsers = options.maxUsers;\n target.throttleStorage = options.throttleStorage;\n target.throttleSync = options.throttleSync;\n };\n}\n","/**\n * Checks if the given value is a function.\n *\n * @param {unknown} val - The value to check.\n * @returns {boolean} - True if the value is a function, false otherwise.\n * @example\n * isFunction(function() {}); // true\n * isFunction(() => {}); // true\n * isFunction(123); // false\n */\nexport function isFunction(val: unknown): boolean {\n return {}.toString.call(val) === \"[object Function]\";\n}\n\n/**\n * Checks if the given object is a class.\n *\n * @param {any} obj - The object to check.\n * @returns {boolean} - True if the object is a class, false otherwise.\n * @example\n * class MyClass {}\n * isClass(MyClass); // true\n * isClass(() => {}); // false\n */\nexport function isClass(obj: any): boolean {\n return (\n typeof obj === \"function\" &&\n obj.prototype &&\n obj.prototype.constructor === obj\n );\n}\n\n/**\n * Checks if the given item is an object.\n *\n * @param {any} item - The item to check.\n * @returns {boolean} - True if the item is an object, false otherwise.\n * @example\n * isObject({}); // true\n * isObject(null); // false\n * isObject([]); // false\n */\nexport const isObject = (item: any): boolean =>\n item && typeof item === \"object\" && !Array.isArray(item) && item !== null;\n\n/**\n * Checks if the given value is an instance of a class.\n *\n * @param {unknown} value - The value to check.\n * @returns {boolean} - True if the value is an instance of a class, false otherwise.\n * @example\n * class MyClass {}\n * const instance = new MyClass();\n * isInstanceOfClass(instance); // true\n * isInstanceOfClass({}); // false\n */\nexport function isInstanceOfClass(value: unknown): boolean {\n if (\n value === null ||\n typeof value !== \"object\" ||\n value === undefined ||\n Array.isArray(value)\n ) {\n return false;\n }\n return Object.getPrototypeOf(value) !== Object.prototype;\n}\n\nexport function generateShortUUID(): string {\n const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let uuid = '';\n for (let i = 0; i < 8; i++) {\n const randomIndex = Math.floor(Math.random() * chars.length);\n uuid += chars[randomIndex];\n }\n return uuid;\n}","import { generateShortUUID } from \"../../sync/src/utils\";\n\nclass MockPartySocket {\n private events: Map<string, Function> = new Map();\n id = generateShortUUID()\n \n addEventListener(event, cb) {\n this.events.set(event, cb);\n }\n\n removeEventListener(event, cb) {\n this.events.delete(event);\n }\n\n _trigger(event, data) {\n this.events.get(event)?.(data);\n }\n}\n\nclass MockStorage {\n private storage: Map<string, any> = new Map();\n \n async get(key: string) {\n return this.storage.get(key);\n }\n \n async put(key: string, value: any) {\n this.storage.set(key, value);\n }\n \n async list() {\n return this.storage\n }\n}\n\nclass MockPartyRoom {\n private clients: Map<string, MockPartySocket> = new Map();\n storage = new MockStorage();\n\n constructor(public id?: string) {\n this.id = id || generateShortUUID()\n }\n\n connection(client) {\n const socket = new MockPartySocket();\n this.clients.set(socket.id, client);\n client.id = socket.id;\n }\n\n broadcast(data: any) {\n this.clients.forEach((client) => {\n client._trigger('message', data);\n });\n }\n\n clear() {\n this.clients.clear();\n }\n}\n\nexport class MockConnection {\n state: any = {};\n\n setState(value: any) {\n this.state = value;\n }\n}\n\nexport const ServerIo = MockPartyRoom;\nexport const ClientIo = MockPartySocket;\n","import { dset } from \"dset\";\nimport z from \"zod\";\nimport {\n createStatesSnapshot,\n getByPath,\n load,\n syncClass,\n} from \"../../sync/src\";\nimport { generateShortUUID } from \"../../sync/src/utils\";\nimport type * as Party from \"./types/party\";\nimport {\n awaitReturn,\n buildObject,\n extractParams,\n isClass,\n throttle,\n} from \"./utils\";\n\nconst Message = z.object({\n action: z.string(),\n value: z.any(),\n});\n\ntype CreateRoomOptions = {\n getMemoryAll?: boolean;\n};\n\n/**\n * @class Server\n * @implements {Party.Server}\n * @description Represents a server that manages rooms and connections for a multiplayer game or application.\n * \n * @example\n * ```typescript\n * import { Room, Server, ServerIo } from \"@yourpackage/room\";\n * \n * @Room({ path: \"game\" })\n * class GameRoom {\n * // Room implementation\n * }\n * \n * class MyServer extends Server {\n * rooms = [GameRoom];\n * }\n * \n * const server = new MyServer(new ServerIo(\"game\"));\n * server.onStart();\n * ```\n */\nexport class Server implements Party.Server {\n subRoom = null;\n rooms: any[] = [];\n\n /**\n * @constructor\n * @param {Party.Room} room - The room object representing the current game or application instance.\n * \n * @example\n * ```typescript\n * const server = new MyServer(new ServerIo(\"game\"));\n * ```\n */\n constructor(readonly room: Party.Room) {}\n\n /**\n * @readonly\n * @property {boolean} isHibernate - Indicates whether the server is in hibernate mode.\n * \n * @example\n * ```typescript\n * if (!server.isHibernate) {\n * console.log(\"Server is active\");\n * }\n * ```\n */\n get isHibernate(): boolean {\n return !!this[\"options\"]?.hibernate;\n }\n\n /**\n * @method onStart\n * @async\n * @description Initializes the server and creates the initial room if not in hibernate mode.\n * @returns {Promise<void>}\n * \n * @example\n * ```typescript\n * async function initServer() {\n * await server.onStart();\n * console.log(\"Server started\");\n * }\n * ```\n */\n\n async onStart() {\n // Only create a room if not in hibernate mode\n // This prevents unnecessary resource allocation for inactive rooms\n if (!this.isHibernate) {\n this.subRoom = await this.createRoom();\n }\n }\n\n /**\n * @method createRoom\n * @private\n * @async\n * @param {CreateRoomOptions} [options={}] - Options for creating the room.\n * @returns {Promise<Object>} The created room instance.\n * @throws {Error} If no matching room is found.\n * \n * @example\n * ```typescript\n * // This method is private and called internally\n * async function internalCreateRoom() {\n * const room = await this.createRoom({ getMemoryAll: true });\n * console.log(\"Room created:\", room);\n * }\n * ```\n */\n private async createRoom(options: CreateRoomOptions = {}) {\n let instance\n let init = true\n\n // Find the appropriate room based on the current room ID\n for (let room of this.rooms) {\n const params = extractParams(room.path, this.room.id);\n if (params) {\n instance = new room(this.room, params);\n break;\n }\n }\n\n if (!instance) {\n throw new Error(\"Room not found\");\n }\n\n // Load the room's memory from storage\n // This ensures persistence across server restarts\n const loadMemory = async () => {\n const root = await this.room.storage.get(\".\");\n const memory = await this.room.storage.list();\n const tmpObject: any = root || {};\n for (let [key, value] of memory) {\n if (key == \".\") {\n continue;\n }\n dset(tmpObject, key, value);\n }\n load(instance, tmpObject);\n };\n\n await loadMemory();\n\n instance.$memoryAll = {}\n\n // Sync callback: Broadcast changes to all clients\n const syncCb = (values) => {\n if (options.getMemoryAll) {\n buildObject(values, instance.$memoryAll);\n }\n if (init && this.isHibernate) {\n init = false;\n return;\n }\n const packet = buildObject(values, instance.$memoryAll);\n this.room.broadcast(\n JSON.stringify({\n type: \"sync\",\n value: packet,\n })\n );\n values.clear();\n }\n\n // Persist callback: Save changes to storage\n const persistCb = async (values) => {\n for (let path of values) {\n const _instance =\n path == \".\" ? instance : getByPath(instance, path);\n const itemValue = createStatesSnapshot(_instance);\n await this.room.storage.put(path, itemValue);\n }\n values.clear();\n }\n\n // Set up syncing and persistence with throttling to optimize performance\n syncClass(instance, {\n onSync: throttle(syncCb, instance[\"throttleSync\"] ?? 500),\n onPersist: throttle(persistCb, instance[\"throttleStorage\"] ?? 2000),\n });\n\n return instance\n }\n\n /**\n * @method getSubRoom\n * @private\n * @async\n * @param {Object} [options={}] - Options for getting the sub-room.\n * @returns {Promise<Object>} The sub-room instance.\n * \n * @example\n * ```typescript\n * // This method is private and called internally\n * async function internalGetSubRoom() {\n * const subRoom = await this.getSubRoom();\n * console.log(\"Sub-room retrieved:\", subRoom);\n * }\n * ```\n */\n private async getSubRoom(options = {}) {\n let subRoom\n if (this.isHibernate) {\n subRoom = await this.createRoom(options)\n }\n else {\n subRoom = this.subRoom\n }\n return subRoom\n }\n\n /**\n * @method getUsersProperty\n * @private\n * @param {Object} subRoom - The sub-room instance.\n * @returns {Object|null} The users property of the sub-room, or null if not found.\n * \n * @example\n * ```typescript\n * // This method is private and called internally\n * function internalGetUsers(subRoom) {\n * const users = this.getUsersProperty(subRoom);\n * console.log(\"Users:\", users);\n * }\n * ```\n */\n\n private getUsersProperty(subRoom) {\n const meta = subRoom.constructor[\"_propertyMetadata\"];\n const propId = meta?.get(\"users\");\n if (propId) {\n return subRoom[propId];\n }\n return null;\n }\n\n /**\n * @method onConnect\n * @async\n * @param {Party.Connection} conn - The connection object for the new user.\n * @param {Party.ConnectionContext} ctx - The context of the connection.\n * @description Handles a new user connection, creates a user object, and sends initial sync data.\n * @returns {Promise<void>}\n * \n * @example\n * ```typescript\n * server.onConnect = async (conn, ctx) => {\n * await server.onConnect(conn, ctx);\n * console.log(\"New user connected:\", conn.id);\n * };\n * ```\n */\n async onConnect(conn: Party.Connection, ctx: Party.ConnectionContext) {\n const subRoom = await this.getSubRoom({\n getMemoryAll: true,\n })\n // Generate a unique public ID for the user\n const publicId = generateShortUUID()\n let user = null;\n const signal = this.getUsersProperty(subRoom);\n if (signal) {\n const { classType } = signal.options;\n // Create a new user instance based on the defined class type\n user = isClass(classType) ? new classType() : classType(conn, ctx);\n signal()[publicId] = user;\n }\n // Call the room's onJoin method if it exists\n await awaitReturn(subRoom[\"onJoin\"]?.(user, conn, ctx));\n conn.setState({ publicId });\n // Send initial sync data to the new connection\n conn.send(\n JSON.stringify({\n type: \"sync\",\n value: {\n pId: publicId,\n ...subRoom.$memoryAll,\n },\n })\n );\n }\n\n /**\n * @method onMessage\n * @async\n * @param {string} message - The message received from a user.\n * @param {Party.Connection} sender - The connection object of the sender.\n * @description Processes incoming messages and triggers corresponding actions in the sub-room.\n * @returns {Promise<void>}\n * \n * @example\n * ```typescript\n * server.onMessage = async (message, sender) => {\n * await server.onMessage(message, sender);\n * console.log(\"Message processed from:\", sender.id);\n * };\n * ```\n */\n\n async onMessage(message: string, sender: Party.Connection) {\n let json\n try {\n json = JSON.parse(message)\n }\n catch (e) {\n return;\n }\n // Validate incoming messages\n const result = Message.safeParse(json);\n if (!result.success) {\n return;\n }\n const subRoom = await this.getSubRoom()\n const actions = subRoom.constructor[\"_actionMetadata\"];\n if (actions) {\n const signal = this.getUsersProperty(subRoom);\n const { publicId } = sender.state as any;\n const user = signal?.()[publicId];\n const actionName = actions.get(result.data.action);\n if (actionName) {\n // Validate action body if a validation schema is defined\n if (actionName.bodyValidation) {\n const bodyResult = actionName.bodyValidation.safeParse(\n result.data.value\n );\n if (!bodyResult.success) {\n return;\n }\n }\n // Execute the action\n await awaitReturn(\n subRoom[actionName.key](user, result.data.value, sender)\n );\n }\n }\n }\n\n /**\n * @method onClose\n * @async\n * @param {Party.Connection} conn - The connection object of the disconnecting user.\n * @description Handles user disconnection, removing them from the room and triggering the onLeave event.\n * @returns {Promise<void>}\n * \n * @example\n * ```typescript\n * server.onClose = async (conn) => {\n * await server.onClose(conn);\n * console.log(\"User disconnected:\", conn.id);\n * };\n * ```\n */\n async onClose(conn: Party.Connection) {\n const subRoom = await this.getSubRoom()\n const signal = this.getUsersProperty(subRoom);\n const { publicId } = conn.state as any;\n const user = signal?.()[publicId];\n // Call the room's onLeave method if it exists\n await awaitReturn(subRoom[\"onLeave\"]?.(user, conn));\n if (signal) {\n // Remove the user from the room\n delete signal()[publicId];\n }\n }\n}\n","import {\n ArraySubject,\n ObjectSubject,\n isSignal,\n type WritableSignal,\n} from \"@signe/reactive\";\nimport { isInstanceOfClass, isObject } from \"./utils\";\n\ninterface SyncOptions {\n onSync?: (value: Map<string, any>) => void;\n onPersist?: (value: Set<string>) => void;\n}\n\ninterface TypeOptions {\n syncToClient?: boolean;\n persist?: boolean;\n classType?: any;\n}\n\n/**\n * Synchronizes an instance by adding `$valuesChanges` methods for state management.\n *\n * This function initializes a cache for syncing and persisting values. It adds methods to the instance\n * to set values, mark values for persistence, and check and retrieve values from the cache.\n * Optionally, callbacks can be provided to handle synchronization and persistence events.\n *\n * @param {Record<string, any>} instance - The instance to be synchronized.\n * @param {SyncOptions} [options={}] - Optional synchronization options.\n * @param {Function} [options.onSync] - Callback function to be called on value sync with the current cache.\n * @param {Function} [options.onPersist] - Callback function to be called on value persistence with the current cache.\n *\n * @example\n * class TestClass {\n * @sync() count = signal(0);\n * @sync() text = signal('hello');\n * }\n * const instance = new TestClass();\n * syncClass(instance, {\n * onSync: (cache) => console.log('Sync cache:', cache),\n * onPersist: (cache) => console.log('Persist cache:', cache),\n * });\n */\nexport const syncClass = (instance: any, options: SyncOptions = {}) => {\n const cacheSync = new Map();\n const cachePersist = new Set<string>();\n instance.$valuesChanges = {\n set: (path: string, value: any) => {\n cacheSync.set(path, value);\n options.onSync?.(cacheSync);\n },\n setPersist: (path: string) => {\n if (path == \"\") path = \".\";\n cachePersist.add(path);\n options.onPersist?.(cachePersist);\n },\n has: (path: string) => {\n return cacheSync.has(path);\n },\n get: (path: string) => {\n return cacheSync.get(path);\n },\n };\n createSyncClass(instance);\n};\n\n/**\n * Creates a snapshot of the current state of an instance's signals.\n *\n * This function iterates over the signals stored in the instance's $snapshot property.\n * If a signal's value is not an object or array and the signal's persist option is true or undefined,\n * it adds the signal's value to the returned snapshot object.\n *\n * @param {Record<string, any>} instance - The instance containing the $snapshot map of signals.\n * @returns {Record<string, any>} - An object representing the persisted snapshot of the instance's state.\n *\n * @example\n * ```typescript\n * class TestClass {\n * @sync() count = signal(0);\n * @sync() text = signal('hello');\n * }\n * const instance = new TestClass();\n * syncClass(instance);\n * const snapshot = createStatesSnapshot(instance);\n * console.log(snapshot); // { count: 0, text: 'hello' }\n * ```\n */\nexport function createStatesSnapshot(instance: Record<string, any>): Record<string, any> {\n let persistObject: any = {};\n if (instance.$snapshot) {\n for (const key of instance.$snapshot.keys()) {\n const signal = instance.$snapshot.get(key);\n const persist = signal.options.persist ?? true;\n let value = signal();\n if (isObject(value) || Array.isArray(value)) {\n break;\n }\n if (persist) {\n persistObject[key] = value;\n }\n }\n }\n return persistObject;\n}\n\nexport function setMetadata(target: any, key: string, value: any) {\n const meta = target.constructor._propertyMetadata;\n const propId = meta?.get(key);\n if (propId) {\n if (isSignal(target[propId])) {\n target[propId].set(value);\n } else {\n target[propId] = value;\n }\n }\n}\n\nexport const createSyncClass = (\n currentClass: any,\n parentKey: any = null,\n parentClass = null,\n path = \"\"\n) => {\n currentClass.$path = path;\n if (parentClass) {\n currentClass.$valuesChanges = parentClass.$valuesChanges;\n }\n if (parentKey) {\n setMetadata(currentClass, \"id\", parentKey);\n }\n if (currentClass.$snapshot) {\n for (const key of currentClass.$snapshot.keys()) {\n const signal = currentClass.$snapshot.get(key);\n const syncToClient = signal.options.syncToClient ?? true;\n const persist = signal.options.persist ?? true;\n let value = signal();\n if (isObject(value) || Array.isArray(value)) {\n value = { ...value };\n }\n const newPath = (path ? path + \".\" : \"\") + key;\n if (syncToClient) {\n currentClass.$valuesChanges.set(newPath, value);\n }\n if (persist) {\n if (parentClass) currentClass.$valuesChanges.setPersist(path);\n }\n }\n }\n};\n\nexport const type = (\n _signal: any,\n path: string,\n options: TypeOptions = {},\n currentInstance: any\n): WritableSignal<any> => {\n const syncToClient = options.syncToClient ?? true;\n const persist = options.persist ?? true;\n let init = true;\n _signal.options = options;\n _signal.observable.subscribe((value) => {\n const check = currentInstance.$valuesChanges;\n\n function savePath(propPath, value) {\n if (syncToClient) check.set(propPath, value);\n if (persist) {\n check.setPersist(currentInstance.$path);\n }\n }\n\n if (init) {\n init = false;\n return;\n }\n if (currentInstance.$path !== undefined) {\n const propPath =\n (currentInstance.$path ? currentInstance.$path + \".\" : \"\") + path;\n if (_signal._subject instanceof ObjectSubject) {\n const newPath =\n (currentInstance.$path ? currentInstance.$path + \".\" : \"\") +\n path +\n \".\" +\n value.key;\n\n if (value.type == \"add\") {\n if (isInstanceOfClass(value.value)) {\n createSyncClass(value.value, value.key, currentInstance, newPath);\n } else {\n savePath(newPath, value.value);\n }\n } else if (value.type == \"update\") {\n if (isObject(value.value) || Array.isArray(value.value)) {\n createSyncClass(value.value, value.key, currentInstance, newPath);\n } else {\n savePath(newPath, value.value);\n }\n } else if (value.type == \"remove\") {\n savePath(newPath, \"$delete\");\n }\n } else if (_signal._subject instanceof ArraySubject) {\n const newPath = propPath + \".\" + value.index;\n const firstItem = value.items[0];\n if (value.type == \"add\") {\n if (isInstanceOfClass(firstItem)) {\n createSyncClass(firstItem, value.key, currentInstance, newPath);\n } else {\n savePath(newPath, firstItem);\n }\n } else if (value.type == \"update\") {\n if (isObject(firstItem) || Array.isArray(firstItem)) {\n createSyncClass(firstItem, value.key, currentInstance, newPath);\n } else {\n savePath(newPath, firstItem);\n }\n } else if (value.type == \"remove\") {\n savePath(newPath, \"$delete\");\n }\n } else {\n savePath(propPath, value);\n }\n }\n });\n\n if (!currentInstance.$snapshot) {\n currentInstance.$snapshot = new Map();\n }\n\n currentInstance.$snapshot.set(path, _signal);\n\n return _signal;\n};\n","import { isSignal } from \"@signe/reactive\";\nimport { setMetadata } from \"./core\";\nimport { isClass } from \"./utils\";\n\n/**\n * Loads values into the root instance by paths or from an object.\n * \n * @param {object} rootInstance - The instance into which values will be loaded.\n * @param {object} values - The values to load, either as paths or an object.\n * @param {boolean} [valueIsObject=false] - If true, `values` is treated as an object.\n * @example\n * // Using paths:\n * load(instance, { 'position.x': 10, 'position.y': 20 });\n * \n * // Using an object:\n * load(instance, { position: { x: 10, y: 20 } }, true);\n */\nexport function load(rootInstance: any, values: { [path: string]: any }): void;\nexport function load(\n rootInstance: any,\n values: object,\n valueIsObject: true\n): void;\nexport function load(\n rootInstance: any,\n values: { [path: string]: any } | object,\n valueIsObject?: boolean\n) {\n if (valueIsObject) {\n loadFromObject(rootInstance, values);\n } else {\n loadFromPaths(rootInstance, values);\n }\n}\n\n/**\n * Loads values into the root instance using paths.\n * \n * @param {object} rootInstance - The instance into which values will be loaded.\n * @param {object} values - The values to load, with keys as paths.\n * @example\n * loadFromPaths(instance, { 'position.x': 10, 'position.y': 20 });\n */\nfunction loadFromPaths(rootInstance: any, values: { [path: string]: any }) {\n for (const [path, value] of Object.entries(values)) {\n const parts = path.split(\".\");\n loadValue(rootInstance, parts, value);\n }\n}\n\n/**\n * Recursively loads values from an object into the root instance.\n * \n * @param {object} rootInstance - The instance into which values will be loaded.\n * @param {object} values - The values to load.\n * @param {string} [currentPath=\"\"] - The current path in the recursion.\n * @example\n * loadFromObject(instance, { position: { x: 10, y: 20 } });\n */\nfunction loadFromObject(\n rootInstance: any,\n values: object,\n currentPath: string = \"\"\n) {\n for (const [key, value] of Object.entries(values)) {\n const newPath = currentPath ? `${currentPath}.${key}` : key;\n if (typeof value === \"object\" && !Array.isArray(value)) {\n loadFromObject(rootInstance, value, newPath);\n } else {\n const parts = newPath.split(\".\");\n loadValue(rootInstance, parts, value);\n }\n }\n}\n\n/**\n * Sets a value in the root instance by navigating through the path parts.\n * \n * @param {object} rootInstance - The instance into which the value will be set.\n * @param {string[]} parts - The parts of the path.\n * @param {any} value - The value to set.\n * @example\n * loadValue(instance, ['position', 'x'], 10);\n */\nfunction loadValue(rootInstance: any, parts: string[], value: any) {\n let current: any = rootInstance;\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n\n if (i === parts.length - 1) {\n if (value == '$delete') {\n if (isSignal(current)) {\n current = current();\n }\n Reflect.deleteProperty(current, part);\n }\n else if (current[part]?._subject) {\n current[part].set(value);\n }\n } else {\n if (isSignal(current)) {\n current = current();\n }\n const currentValue = current[part];\n if (currentValue === undefined) {\n const parentInstance = getByPath(\n rootInstance,\n parts.slice(0, i).join(\".\")\n );\n const classType = parentInstance?.options?.classType;\n if (classType) {\n current[part] = !isClass(classType) ? classType(part) : new classType();\n setMetadata(current[part], 'id', part)\n } else {\n current[part] = {};\n }\n }\n current = current[part];\n }\n }\n}\n\n/**\n * Retrieves a value from the root instance by a path.\n * \n * @param {object} root - The root instance.\n * @param {string} path - The path to the value.\n * @returns {any} - The value at the specified path.\n * @example\n * const value = getByPath(instance, 'position.x');\n */\nexport function getByPath(root: any, path: string) {\n const parts = path.split(\".\");\n let current = root;\n for (const part of parts) {\n if (isSignal(current)) {\n current = current();\n }\n if (current[part]) {\n current = current[part];\n } else {\n return undefined;\n }\n }\n return current;\n}\n","import { dset } from \"dset\";\n\n/**\n * Checks if a value is a Promise.\n *\n * @param {unknown} value - The value to check.\n * @returns {boolean} - Returns true if the value is a Promise, otherwise false.\n *\n * @example\n * isPromise(Promise.resolve()); // true\n * isPromise(42); // false\n */\nexport function isPromise(value: unknown): value is Promise<any> {\n return value instanceof Promise;\n}\n\n/**\n * Awaits the given value if it is a Promise, otherwise returns the value directly.\n *\n * @param {unknown} val - The value to await or return.\n * @returns {Promise<any>} - Returns a Promise that resolves to the value.\n *\n * @example\n * awaitReturn(Promise.resolve(42)); // 42\n * awaitReturn(42); // 42\n */\nexport async function awaitReturn(val: unknown): Promise<any> {\n return isPromise(val) ? await val : val;\n}\n\n/**\n * Checks if a value is a class.\n *\n * @param {unknown} obj - The value to check.\n * @returns {boolean} - Returns true if the value is a class, otherwise false.\n *\n * @example\n * class MyClass {}\n * isClass(MyClass); // true\n * isClass(() => {}); // false\n */\nexport function isClass(obj: unknown): boolean {\n return (\n typeof obj === \"function\" &&\n obj.prototype &&\n obj.prototype.constructor === obj\n );\n}\n\n\n/**\n * Creates a throttled function that only invokes the provided function at most once per every wait milliseconds.\n *\n * The throttled function comes with a cancel method to cancel delayed invocations.\n * If the throttled function is invoked more than once during the wait timeout,\n * it will call the provided function with the latest arguments.\n *\n * @template F - The type of the function to throttle.\n * @param {F} func - The function to throttle.\n * @param {number} wait - The number of milliseconds to throttle invocations to.\n * @returns {(...args: Parameters<F>) => void} - Returns the new throttled function.\n *\n * @example\n * const log = throttle((message) => console.log(message), 1000);\n * log(\"Hello\"); // Will log \"Hello\" immediately\n * log(\"World\"); // Will log \"World\" after 1 second, if no other calls to log() are made within the 1 second.\n */\nexport function throttle<F extends (...args: any[]) => any>(\n func: F,\n wait: number\n): (...args: Parameters<F>) => void {\n let timeout: ReturnType<typeof setTimeout> | null = null;\n let lastArgs: Parameters<F> | null = null;\n\n return function (...args: Parameters<F>) {\n if (!timeout) {\n func(...args);\n timeout = setTimeout(() => {\n if (lastArgs) {\n func(...lastArgs);\n lastArgs = null;\n }\n timeout = null;\n }, wait);\n } else {\n lastArgs = args;\n }\n };\n}\n\n/**\n * Extracts parameters from a given string based on a specified pattern.\n *\n * The pattern can include placeholders in the form of {paramName}, which will be\n * extracted from the input string if they match.\n *\n * @param {string} pattern - The pattern containing placeholders.\n * @param {string} str - The string to extract parameters from.\n * @returns {{ [key: string]: string } | null} - An object containing the extracted parameters,\n * or null if the string does not match the pattern.\n *\n * @example\n * // returns { id: '123' }\n * extractParams('game-{id}', 'game-123');\n *\n * @example\n * // returns { foo: 'abc', bar: 'xyz' }\n * extractParams('test-{foo}-{bar}', 'test-abc-xyz');\n *\n */\nexport function extractParams(\n pattern: string,\n str: string\n): { [key: string]: string } | null {\n // Replace placeholders in the pattern with named capture groups\n const regexPattern = pattern.replace(/{(\\w+)}/g, \"(?<$1>[\\\\w-]+)\");\n\n // Create a strict regular expression from the pattern\n const regex = new RegExp(`^${regexPattern}$`);\n const match = regex.exec(str);\n\n // If a match is found and groups are present, return the captured groups\n if (match && match.groups) {\n return match.groups;\n } else if (pattern === str) {\n // If the pattern exactly matches the string, return an empty object\n return {};\n } else {\n // Otherwise, return null\n return null;\n }\n}\n\n/**\n * Removes a property from an object based on a dot-separated key string or an array of keys.\n *\n * The function modifies the original object by deleting the specified property.\n * It safely handles dangerous keys like __proto__, constructor, and prototype.\n *\n * @param {Record<string, any>} obj - The object from which to remove the property.\n * @param {string | string[]} keys - The key(s) specifying the property to remove. Can be a dot-separated string or an array of strings.\n *\n * @example\n * const obj = { a: { b: { c: 3 } } };\n * dremove(obj, 'a.b.c');\n * // obj is now { a: { b: {} } }\n *\n * @example\n * const obj = { a: 1, b: 2 };\n * dremove(obj, 'a');\n * // obj is now { b: 2 }\n *\n * @example\n * const obj = { a: { b: { c: 3 } } };\n * dremove(obj, ['a', 'b', 'c']);\n * // obj is now { a: { b: {} } }\n */\nexport function dremove(\n obj: Record<string, any>,\n keys: string | string[]\n): void {\n // If keys is a string, convert it to an array using the \".\" separator\n if (typeof keys === \"string\") {\n keys = keys.split(\".\");\n }\n\n let i = 0;\n const l = keys.length;\n let t = obj;\n let k;\n\n while (i < l - 1) {\n k = keys[i++];\n if (k === \"__proto__\" || k === \"constructor\" || k === \"prototype\") return; // Avoid dangerous keys\n if (typeof t[k] !== \"object\" || t[k] === null) return; // If the object doesn't exist, stop\n t = t[k];\n }\n\n k = keys[i];\n if (\n t &&\n typeof t === \"object\" &&\n !(k === \"__proto__\" || k === \"constructor\" || k === \"prototype\")\n ) {\n delete t[k];\n }\n}\n\n/**\n * Builds an object from a map of values and updates the provided memory object.\n *\n * For each key-value pair in the map, this function sets the value at the given path in the `memoryObj`.\n * If the value is \"$delete\", it removes the corresponding path from `allMemory`.\n *\n * @param {Map<string, any>} valuesMap - A map where the keys are paths and the values are the values to set at those paths.\n * @param {Record<string, any>} allMemory - The object to update based on the values in the map.\n * @returns {Record<string, any>} - The built memory object with the applied values from the map.\n *\n * @example\n * const valuesMap = new Map();\n * valuesMap.set('a.b.c', 1);\n * valuesMap.set('x.y.z', '$delete');\n * const allMemory = { x: { y: { z: 2 } } };\n * const result = buildObject(valuesMap, allMemory);\n * // result is { a: { b: { c: 1 } }, x: { y: { z: '$delete' } } }\n * // allMemory is { a: { b: { c: 1 } }, x: { y: {} } }\n */\nexport function buildObject(valuesMap: Map<string, any>, allMemory: Record<string, any>): Record<string, any> {\n let memoryObj = {};\n for (let path of valuesMap.keys()) {\n const value = valuesMap.get(path);\n dset(memoryObj, path, value);\n if (value === \"$delete\") {\n dremove(allMemory, path);\n } else {\n dset(allMemory, path, value);\n }\n }\n return memoryObj;\n}"],"mappings":";AAAO,SAAS,OAAO,MAAc,gBAAiB;AACpD,SAAO,SAAU,QAAa,aAAqB;AACjD,QAAI,CAAC,OAAO,YAAY,iBAAiB;AACvC,aAAO,YAAY,kBAAkB,oBAAI,IAAI;AAAA,IAC/C;AACA,WAAO,YAAY,gBAAgB,IAAI,MAAM;AAAA,MAC3C,KAAK;AAAA,MACL;AAAA,IACF,CAAC;AAAA,EACH;AACF;AAUO,SAAS,KAAK,SAAsB;AACzC,SAAO,SAAU,QAAa;AAC5B,WAAO,OAAO,QAAQ;AACtB,WAAO,WAAW,QAAQ;AAC1B,WAAO,kBAAkB,QAAQ;AACjC,WAAO,eAAe,QAAQ;AAAA,EAChC;AACF;;;ACHO,SAAS,QAAQ,KAAmB;AACzC,SACE,OAAO,QAAQ,cACf,IAAI,aACJ,IAAI,UAAU,gBAAgB;AAElC;AAYO,IAAM,WAAW,CAAC,SACvB,QAAQ,OAAO,SAAS,YAAY,CAAC,MAAM,QAAQ,IAAI,KAAK,SAAS;AAyBhE,SAAS,oBAA4B;AAC1C,QAAM,QAAQ;AACd,MAAI,OAAO;AACX,WAAS,IAAI,GAAG,IAAI,GAAG,KAAK;AACxB,UAAM,cAAc,KAAK,MAAM,KAAK,OAAO,IAAI,MAAM,MAAM;AAC3D,YAAQ,MAAM,WAAW;AAAA,EAC7B;AACA,SAAO;AACT;;;AC1EA,IAAM,kBAAN,MAAsB;AAAA,EAAtB;AACI,SAAQ,SAAgC,oBAAI,IAAI;AAChD,cAAK,kBAAkB;AAAA;AAAA,EAEvB,iBAAiB,OA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;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,MAAM,QAAQ,MAAwB;AACpC,UAAM,UAAU,MAAM,KAAK,WAAW;AACtC,UAAM,SAAS,KAAK,iBAAiB,OAAO;AAC5C,UAAM,EAAE,SAAS,IAAI,KAAK;AAC1B,UAAM,OAAO,SAAS,EAAE,QAAQ;AAEhC,UAAM,YAAY,QAAQ,SAAS,IAAI,MAAM,IAAI,CAAC;AAClD,QAAI,QAAQ;AAEV,aAAO,OAAO,EAAE,QAAQ;AAAA,IAC1B;AAAA,EACF;AACF;","names":["dset","isSignal","isSignal","isClass","dset","isClass"]}
@@ -0,0 +1,11 @@
1
+ {
2
+ "configurations": [
3
+ {
4
+ "type": "node",
5
+ "request": "attach",
6
+ "name": "PartyKit debugger",
7
+ "address": "localhost",
8
+ "port": 9229
9
+ }
10
+ ]
11
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "files.associations": {
3
+ "partykit.json": "jsonc"
4
+ },
5
+ "json.schemas": [
6
+ {
7
+ "fileMatch": ["partykit.json"],
8
+ "url": "https://www.partykit.io/schema.json"
9
+ }
10
+ ]
11
+ }
@@ -0,0 +1,40 @@
1
+ # 🎈 game
2
+
3
+ Welcome to the party, pal!
4
+
5
+ This is a [Partykit](https://partykit.io) project, which lets you create real-time collaborative applications with minimal coding effort.
6
+
7
+ This is the **React starter** which pairs a PartyKit server with a React client.
8
+
9
+ Refer to our docs for more information: https://github.com/partykit/partykit/blob/main/README.md. For more help, reach out to us on [Discord](https://discord.gg/g5uqHQJc3z), [GitHub](https://github.com/partykit/partykit), or [Twitter](https://twitter.com/partykit_io).
10
+
11
+ ## Usage
12
+
13
+ You can start developing by running `npm run dev` and opening [http://localhost:1999](http://localhost:1999) in your browser. When you're ready, you can deploy your application on to the PartyKit cloud with `npm run deploy`.
14
+
15
+ ## Finding your way around
16
+
17
+ [`party/server.ts`](./party/server.ts) is the server-side code, which is responsible for handling WebSocket events and HTTP requests.
18
+
19
+ It implements a simple counter that can be incremented by any connected client. The latest state is broadcast to all connected clients.
20
+
21
+ > [!NOTE]
22
+ > The full Server API is available at [Party.Server in the PartyKit docs](https://docs.partykit.io/reference/partyserver-api/)
23
+
24
+ [`app/client.tsx`](./src/client.ts) is the entrypoint to client-side code.
25
+
26
+ [`app/components/Counter.tsx`](./src/components/Counter.tsx) connects to the server, sends `increment` events on the WebSocket, and listens for updates.
27
+
28
+ > [!NOTE]
29
+ > The client-side reference can be found at [PartySocket in the PartyKit docs](https://docs.partykit.io/reference/partysocket-api/)
30
+
31
+ As a client-side React app, the app could be hosted every. During development, for convenience, the server serves the client-side code as well.
32
+
33
+ This is achieved with the optional `serve` property in the [`partykit.json`](./partykit.json) config file.
34
+
35
+ > [!NOTE]
36
+ > Learn about PartyKit config under [Configuration in the PartyKit docs](https://docs.partykit.io/reference/partykit-configuration/)
37
+
38
+ ## Next Steps
39
+
40
+ Learn about deploying PartyKit applications in the [Deployment guide of the PartyKit docs](https://docs.partykit.io/guides/deploying-your-partykit-server/).
@@ -0,0 +1,40 @@
1
+ import { createRoot } from "react-dom/client";
2
+ import Counter from "./components/Counter";
3
+ import "./styles.css";
4
+
5
+
6
+ function App() {
7
+ return (
8
+ <main>
9
+ <h1>🎈 Welcome to PartyKit!</h1>
10
+ <p>
11
+ This is the React starter. (
12
+ <a href="https://github.com/partykit/templates/tree/main/templates/react">
13
+ README on GitHub.
14
+ </a>
15
+ )
16
+ </p>
17
+ <p>Find your way around:</p>
18
+ <ul>
19
+ <li>
20
+ PartyKit server: <code>party/server.ts</code>
21
+ </li>
22
+ <li>
23
+ Client entrypoint: <code>app/client.tsx</code>
24
+ </li>
25
+ <li>
26
+ The Counter component: <code>app/components/Counter.tsx</code>
27
+ </li>
28
+ </ul>
29
+ <p>
30
+ Read more: <a href="https://docs.partykit.io">PartyKit docs</a>
31
+ </p>
32
+ <p>
33
+ <i>This counter is multiplayer. Try it with multiple browser tabs.</i>
34
+ </p>
35
+ <Counter />
36
+ </main>
37
+ );
38
+ }
39
+
40
+ createRoot(document.getElementById("app")!).render(<App />);
@@ -0,0 +1,44 @@
1
+ import { useEffect, useRef, useState } from "react";
2
+ import { effect } from '../../../../../reactive';
3
+ import { connection } from '../../../../../sync/src/client';
4
+ import { RoomSchema } from "../../shared/room.schema";
5
+
6
+ export default function Counter() {
7
+ const [count, setCount] = useState<number | null>(null);
8
+ let socket = useRef<any>(null);
9
+ let room = useRef<any>(null);
10
+
11
+ useEffect(() => {
12
+ room.current = new RoomSchema();
13
+ socket.current = connection({
14
+ host: location.hostname == 'localhost' ? 'localhost:1999' : 'https://signe.rsamaium.partykit.dev',
15
+ room: 'game'
16
+ }, room.current)
17
+
18
+ effect(() => {
19
+ setCount(room.current.count())
20
+ })
21
+ }, []);
22
+
23
+ const increment = () => {
24
+ room.current.count.update((count: number) => count + 1);
25
+ socket.current.emit('increment')
26
+ };
27
+
28
+ const styles = {
29
+ backgroundColor: "#ff0f0f",
30
+ borderRadius: "9999px",
31
+ border: "none",
32
+ color: "white",
33
+ fontSize: "0.95rem",
34
+ cursor: "pointer",
35
+ padding: "1rem 3rem",
36
+ margin: "1rem 0rem",
37
+ };
38
+
39
+ return (
40
+ <button style={styles} onClick={increment}>
41
+ Increment me! {count !== null && <>Count: {count}</>}
42
+ </button>
43
+ );
44
+ }
@@ -0,0 +1,31 @@
1
+ /*
2
+ We've already included normalize.css.
3
+
4
+ But we'd like a modern looking boilerplate.
5
+ Clean type, sans-serif, and a nice color palette.
6
+
7
+ */
8
+
9
+ body {
10
+ font-family: sans-serif;
11
+ font-size: 16px;
12
+ line-height: 1.5;
13
+ color: #333;
14
+ }
15
+
16
+ h1,
17
+ h2,
18
+ h3,
19
+ h4,
20
+ h5,
21
+ h6 {
22
+ font-family: sans-serif;
23
+ font-weight: 600;
24
+ line-height: 1.25;
25
+ margin-top: 0;
26
+ margin-bottom: 0.5rem;
27
+ }
28
+
29
+ #app {
30
+ padding: 1rem;
31
+ }
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "game",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "scripts": {
6
+ "dev": "partykit dev --live",
7
+ "deploy": "partykit deploy"
8
+ },
9
+ "dependencies": {
10
+ "partysocket": "^1.0.1",
11
+ "react": "^18.2.0",
12
+ "react-dom": "^18.2.0"
13
+ },
14
+ "devDependencies": {
15
+ "@types/react": "^18.2.66",
16
+ "@types/react-dom": "^18.2.22",
17
+ "partykit": "^0.0.100",
18
+ "typescript": "^5.4.2"
19
+ }
20
+ }
@@ -0,0 +1,12 @@
1
+ import { Action, Room } from "../../../src";
2
+ import { RoomSchema } from "../shared/room.schema";
3
+
4
+ @Room({
5
+ path: 'game'
6
+ })
7
+ export class GameRoom extends RoomSchema {
8
+ @Action('increment')
9
+ increment() {
10
+ this.count.update((count) => count + 1);
11
+ }
12
+ }
@@ -0,0 +1,12 @@
1
+ import { Server } from '../../../src';
2
+ import type * as Party from "../../../src/types/party";
3
+ import { GameRoom } from "./game.room";
4
+
5
+ export default class MainServer extends Server {
6
+ options: Party.ServerOptions = {
7
+ hibernate: true
8
+ }
9
+ rooms = [
10
+ GameRoom
11
+ ]
12
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "$schema": "https://www.partykit.io/schema.json",
3
+ "name": "signe",
4
+ "main": "party/server.ts",
5
+ "compatibilityDate": "2024-06-09",
6
+ "serve": {
7
+ "path": "public",
8
+ "build": "app/client.tsx"
9
+ }
10
+ }
Binary file
@@ -0,0 +1,27 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta
6
+ name="viewport"
7
+ content="width=device-width, initial-scale=1.0, shrink-to-fit=no"
8
+ />
9
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
10
+ <title>PartyKit: Everything's better with friends!</title>
11
+ <!-- Favicon -->
12
+ <link rel="icon" href="/favicon.ico" sizes="any" />
13
+ <!-- Primary Meta Tags -->
14
+ <meta name="title" content="PartyKit" />
15
+ <meta name="description" content="Everything's better with friends!" />
16
+ <meta name="author" content="PartyKit" />
17
+ <!-- Theme Colour -->
18
+ <meta name="theme-color" content="#ffffff" />
19
+
20
+ <link rel="stylesheet" href="/normalize.css" />
21
+ <link rel="stylesheet" href="/dist/client.css" />
22
+ </head>
23
+ <body>
24
+ <div id="app"></div>
25
+ <script type="module" src="/dist/client.js"></script>
26
+ </body>
27
+ </html>