@puzzmo/sdk 1.0.39 → 1.0.40

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.global.js","names":[],"sources":["../src/gameTracker.ts","../src/analytics.ts","../src/sdk.ts","../src/keyboard.ts","../src/editor.ts","../../../node_modules/lz-string/libs/lz-string.js","../src/inputs/encodings.ts","../src/inputs/encoder.ts","../src/inputs/decoder.ts","../src/inputs/migration.ts","../src/inputs/types.ts","../src/inputs/index.ts"],"sourcesContent":["import type { GameAnalyticsContext, LinkClickedInfo } from \"./analytics\"\n\n/**\n * Game analytics event-firing logic for the SDK.\n *\n * This mirrors the runtime's tracker (and the canonical copy in @puzzmo-com/clickhouse/gameTracker\n * used server-side): which host messages map to which events, the engagement thresholds, the\n * payload shape, and the /events endpoint. It is kept here, dependency-free, so the published SDK\n * pulls in none of the clickhouse package's server deps (kysely / @clickhouse/client) and so the\n * public OSS mirror can build it without the private workspace packages present.\n */\n\nexport type GameAnalyticsEventType = \"page_view\" | \"gameplay_active\" | \"active_30s\" | \"completed\" | \"link_click\"\n\ntype GameAnalyticsState = {\n context: GameAnalyticsContext\n updateCount: number\n startTime: Date\n tracked: {\n pageView: boolean\n gameplayActive: boolean\n active30s: boolean\n completed: boolean\n }\n}\n\ntype MessagesSent =\n | \"READY_GAME_LOADED\"\n | \"UPLOAD_NEW_GAME_STATE\"\n | \"GAME_COMPLETED\"\n | \"SHOW_GAME_COMPLETE_SCREEN\"\n | \"UPDATE_GAME_STATE\"\n | string\n\nconst sendGameAnalyticsEvent = async (\n context: GameAnalyticsContext,\n eventType: GameAnalyticsEventType,\n metadata?: Record<string, string | number | boolean>,\n elapsedTimeOnComplete?: number,\n) => {\n try {\n const body = {\n ...context,\n eventType,\n elapsedTimeOnComplete,\n metadata,\n }\n\n const response = await fetch(`${context.apiRoot}events`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n // Ensures the event still fires if the user navigates away (e.g. clicking a _blank link)\n keepalive: true,\n })\n\n if (!response.ok) {\n console.warn(`Analytics event failed: ${eventType} - ${response.status} ${response.statusText}`)\n }\n } catch (error) {\n console.warn(`Analytics event error: ${eventType}`, error)\n }\n}\n\nexport const createGameAnalyticsTracker = (context: GameAnalyticsContext) => {\n const state: GameAnalyticsState = {\n context,\n updateCount: 0,\n startTime: new Date(),\n tracked: {\n pageView: false,\n gameplayActive: false,\n active30s: false,\n completed: false,\n },\n }\n\n const trackEvent = (type: MessagesSent, json?: any) => {\n const now = new Date()\n const timeDiff = now.getTime() - state.startTime.getTime()\n const seconds = timeDiff / 1000\n\n switch (type) {\n case \"READY_GAME_LOADED\": {\n if (!state.tracked.pageView) {\n sendGameAnalyticsEvent(state.context, \"page_view\")\n state.tracked.pageView = true\n }\n break\n }\n\n case \"UPLOAD_NEW_GAME_STATE\": {\n state.updateCount++\n\n // Fire gameplay_active early (after 2 state changes) to indicate user engagement\n if (state.updateCount > 2 && !state.tracked.gameplayActive) {\n sendGameAnalyticsEvent(state.context, \"gameplay_active\")\n state.tracked.gameplayActive = true\n }\n\n // Fire active_30s for sustained engagement\n if (seconds > 30 && !state.tracked.active30s) {\n sendGameAnalyticsEvent(state.context, \"active_30s\")\n state.tracked.active30s = true\n }\n break\n }\n\n case \"GAME_COMPLETED\": {\n if (!state.tracked.completed && json?.input) {\n sendGameAnalyticsEvent(state.context, \"completed\", {}, json.input.elapsedTimeSecs)\n state.tracked.completed = true\n }\n break\n }\n }\n }\n\n const trackLinkClick = (info: LinkClickedInfo) => {\n sendGameAnalyticsEvent(state.context, \"link_click\", info)\n }\n\n return {\n trackEvent,\n trackLinkClick,\n }\n}\n","import { createGameAnalyticsTracker } from \"./gameTracker\"\n\nimport type { BootstrapGameData } from \"./types\"\n\n/**\n * Game analytics for the SDK.\n *\n * The event-firing logic — which host messages map to which ClickHouse events, the\n * engagement thresholds, the payload, and the /events endpoint — lives in ./gameTracker,\n * a self-contained mirror of the runtime's tracker. It is kept local (rather than imported\n * from @puzzmo-com/clickhouse) so the published SDK pulls in none of the clickhouse package's\n * server deps, and so the public OSS mirror can build the SDK without the private workspace\n * packages present.\n *\n * This file only adds the SDK-specific glue: deciding whether analytics should run,\n * building the context from bootstrap data, and watching for link clicks. Events are\n * never sent from localhost (dev + the SDK simulator).\n */\n\nexport type LinkClickedInfo = {\n href: string\n text: string\n target: string\n}\n\ntype UserType = \"anon\" | \"user\" | \"paid\"\ntype RuntimeType = \"puzzmo_com\" | \"iframe\" | \"simple_embed\" | \"app_embed\" | \"ios_native\"\n\n/** Everything the events endpoint needs to attribute an event, mirrors the runtime's context. */\nexport type GameAnalyticsContext = {\n gameSlug: string\n puzzleID: string\n gameplayOwnerID: string\n apiRoot: string\n userType: UserType\n runtimeType: RuntimeType\n userID?: string\n teamSlug?: string\n partnerSlug?: string\n dailyDateKey?: string\n embedID?: string\n}\n\nexport type GameAnalyticsTracker = {\n /** Map an outgoing host message to its analytics event(s), if any. */\n trackEvent: (type: string, json?: any) => void\n /** Report an anchor click inside the game. */\n trackLinkClick: (info: LinkClickedInfo) => void\n}\n\n/**\n * Build the analytics tracker for a game, or null when analytics shouldn't run\n * (the game doesn't bring its own runtime, no browser, running on localhost, or\n * missing bootstrap data).\n */\nexport const createGameAnalytics = (readyData: BootstrapGameData | null): GameAnalyticsTracker | null => {\n // Only games that bring their own runtime track via the SDK — see gameBringsOwnRuntime.\n if (!gameBringsOwnRuntime(readyData)) return null\n\n const endpoint = resolveAnalyticsEndpoint()\n if (!endpoint.enabled) return null\n\n const context = buildAnalyticsContext(readyData, endpoint.apiRoot)\n if (!context) return null\n\n return createGameAnalyticsTracker(context)\n}\n\n/** Delegates document clicks to report anchor navigations. Returns a cleanup function. */\nexport const setupLinkTracking = (onLinkClicked: (info: LinkClickedInfo) => void): (() => void) => {\n if (typeof document === \"undefined\") return () => {}\n\n const handler = (event: MouseEvent) => {\n const node = event.target\n if (!(node instanceof Element)) return\n const anchor = node.closest(\"a[href]\")\n if (!(anchor instanceof HTMLAnchorElement)) return\n\n onLinkClicked({\n href: anchor.href,\n text: anchor.textContent?.trim() ?? \"\",\n target: anchor.target,\n })\n }\n\n document.addEventListener(\"click\", handler)\n return () => document.removeEventListener(\"click\", handler)\n}\n\n/** Picks the events endpoint, and disables analytics entirely on localhost (dev + simulator). */\nconst resolveAnalyticsEndpoint = (): { apiRoot: string; enabled: boolean } => {\n if (typeof window === \"undefined\" || !window.location) return { apiRoot: \"\", enabled: false }\n\n const hostname = window.location.hostname\n const isLocalhost =\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"0.0.0.0\" ||\n hostname === \"[::1]\" ||\n hostname.endsWith(\".localhost\")\n\n if (isLocalhost) return { apiRoot: \"\", enabled: false }\n\n const isStaging = hostname.includes(\"staging\")\n return { apiRoot: isStaging ? \"https://api-staging.puzzmo.com/\" : \"https://api.puzzmo.com/\", enabled: true }\n}\n\n/** Derive the analytics context from the host's bootstrap data, or null if a game isn't present. */\nconst buildAnalyticsContext = (readyData: BootstrapGameData | null, apiRoot: string): GameAnalyticsContext | null => {\n const gameplay = readyData?.startOrFindGameplay?.gamePlayed\n if (!gameplay) return null\n\n const puzzle: any = gameplay.puzzle\n const hostContext: any[] = (readyData?.hostContext as any[]) ?? []\n\n return {\n gameSlug: puzzle.game?.slug ?? \"unknown\",\n puzzleID: puzzle.id,\n gameplayOwnerID: gameplay.ownerID || readyData?.userState?.id || \"unknown\",\n apiRoot,\n userType: mapUserType(readyData?.currentUser?.type),\n runtimeType: getRuntimeType(hostContext),\n userID: readyData?.currentUser?.id,\n teamSlug: puzzle.team?.slug || undefined,\n partnerSlug: hostContext.find((hc) => hc?.type === \"embed\")?.partner?.slug || undefined,\n dailyDateKey: puzzle.mostRecentDaily?.daily?.dateKey,\n embedID: hostContext.find((hc) => hc?.type === \"embed\")?.embedID || undefined,\n }\n}\n\n/** Map the user's subscription tier to the analytics user bucket. */\nconst mapUserType = (type: string | null | undefined): UserType => {\n if (!type || type === \"Unverified\") return \"anon\"\n if (type === \"Paid\") return \"paid\"\n return \"user\"\n}\n\n// GameFlags1.bringsOwnRuntime — see packages/shared/flags/gameFlags.ts. Inlined to keep the SDK\n// free of the @puzzmo-com/shared workspace dep (the OSS mirror doesn't have that package).\nconst bringsOwnRuntimeFlag = 1 << 9\n\n/**\n * Whether the bootstrapped game has the \"brings own runtime\" flag set. SDK analytics only\n * run for these games; the standard Puzzmo runtime tracks the same events itself, so gating\n * here avoids double-counting for games that don't bring their own runtime.\n */\nconst gameBringsOwnRuntime = (readyData: BootstrapGameData | null): boolean => {\n const game: any = readyData?.startOrFindGameplay?.gamePlayed?.puzzle?.game\n const flags = game?.flagsArr\n const flagValue = Array.isArray(flags) ? (flags[0] ?? 0) : typeof flags === \"number\" ? flags : 0\n return (flagValue & bringsOwnRuntimeFlag) === bringsOwnRuntimeFlag\n}\n\n/** Derive the runtime bucket from host context, mirroring the runtime's getRuntimeType. */\nconst getRuntimeType = (hostContext: any[]): RuntimeType => {\n if (hostContext.find((hc) => hc?.type === \"embed\")) return \"iframe\"\n\n const app = hostContext.find((hc) => hc?.type === \"app\")\n if (app?.host === \"__embed\") return \"simple_embed\"\n if (app?.host === \"app-embed\") return \"app_embed\"\n if (app?.host === \"ios-app\") return \"ios_native\"\n\n return \"puzzmo_com\"\n}\n","import { createGameAnalytics, setupLinkTracking, type GameAnalyticsTracker } from \"./analytics\"\nimport type { PluginAPIs, SDKPlugin, SDKPluginContext } from \"./plugins\"\nimport type {\n MessagesSentFromEmbed,\n MessagesReceived,\n GamePlay,\n GameCompletedPlay,\n AugmentationConfig,\n CheckpointConfig,\n Theme,\n Deed,\n GameOverMessageUIComponent,\n KeyboardConfig,\n GameSettingsUIComponents,\n} from \"./types\"\n\nexport type SDK = PuzzmoSDK\n\nexport interface PuzzmoSDKOptions<Plugins extends readonly SDKPlugin[] = []> {\n /** Optional timeout in ms to wait for READY_DATA (default: 5000) */\n timeout?: number\n /** Plugins to extend the SDK with; each contributes a namespaced API at `sdk.plugins[name]`. */\n plugins?: Plugins\n}\n\n/** The bootstrap info a game needs to set up its board, returned by `sdk.gameReady()`. */\nexport type GameReadyResult = {\n /** The serialized puzzle for this gameplay, in the game's own format. */\n puzzleString: string\n /** The player's saved in-progress board state from a previous session, or null when starting fresh. */\n inputString: string | null\n /** The host's current display theme, so the game can match the surrounding page. */\n theme: Theme | null\n /** True when the player has already finished this puzzle (e.g. re-opening a completed daily). */\n completed: boolean\n /** The raw bootstrap payload from the host: user state, the gameplay record, host context, etc. */\n readyData: MessagesReceived[\"READY_DATA\"] | null\n}\n\n/** Player-facing game settings, rendered by the host's settings panel and persisted per-user, per-game. */\nexport interface SDKSettings {\n /**\n * Register the game's settings UI with the host. Component `defaultValue`s are merged\n * underneath the player's saved values, the host shows the components in its settings panel,\n * and the resolved settings object is returned. Listen for the `settingsUpdate` event to\n * react to the player changing values. Call after `gameReady()`.\n */\n initialize: (components: GameSettingsUIComponents[]) => any\n /** Get the current resolved settings object. */\n get: () => any\n /** Merge changes into the current settings and persist them to the host. Returns the updated settings. */\n update: (changes: any) => any\n}\n\n/** The host-rendered on-screen keyboard, for games that take text or symbol input on touch devices. */\nexport interface SDKKeyboard {\n /** Show the on-screen keyboard with the given config. Call again to update state (e.g. to change disabled keys). */\n show: (config: KeyboardConfig) => void\n /** Hide the on-screen keyboard. */\n hide: () => void\n}\n\n/**\n * The SDK instance returned by `createPuzzmoSDK` — a game's API surface for talking to whichever\n * host is embedding it (puzzmo.com, a partner embed, or the native apps): bootstrapping the\n * puzzle, syncing progress, reporting completion, and driving host UI like settings and the\n * on-screen keyboard.\n *\n * The expected lifecycle is: `gameReady()` → build your board from the result → `gameLoaded()` →\n * play, persisting via `updateGameState()` → `gameCompleted()` → `showCompletionScreen()`.\n */\nexport interface PuzzmoSDK<Plugins extends readonly SDKPlugin[] = []> {\n /**\n * The play clock. The SDK manages it for you: it starts when the host starts the game, pauses\n * and resumes with the host UI, and its display is mirrored into the host chrome twice a\n * second. Most games only need `addPenalty()` for hint or mistake costs.\n */\n timer: SDKTimer\n\n /** APIs contributed by the plugins passed to `createPuzzmoSDK`, keyed by plugin name. */\n plugins: PluginAPIs<Plugins>\n\n /**\n * Announce that the game is ready to receive data. Sends `READY` to the host and resolves with\n * the bootstrap info once the host replies: the puzzle to load, any saved in-progress state,\n * and the host theme. Call this first — every other API assumes it has resolved. Rejects when\n * the host doesn't reply within `PuzzmoSDKOptions.timeout` (default 5s).\n */\n gameReady: () => Promise<GameReadyResult>\n\n /**\n * Tell the host the game has parsed the puzzle, rendered, and is ready to be revealed. The\n * host dismisses its loading UI and replies with a start signal — listen via `on(\"start\")` to\n * begin play; the timer starts then too.\n */\n gameLoaded: (state?: any) => void\n\n /**\n * Subscribe to a host lifecycle event: `start`, `pause`, `resume`, `retry`, `settingsUpdate`,\n * or the on-screen `keyboard*` events. Returns an unsubscribe function.\n */\n on: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void) => () => void\n\n /** Remove an event listener previously registered with `on`. */\n off: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void) => void\n\n /**\n * Save the player's in-progress state to the server so play can resume later, on any\n * device. `inputString` is the game's own serialized format — it comes back as `inputString`\n * from `gameReady()`. Call whenever the player makes a meaningful move; elapsed time is filled\n * in from the SDK timer unless provided in `play`.\n */\n updateGameState: (inputString: string, play?: Partial<GamePlay>) => void\n\n /**\n * Report the game as finished. Concludes the timer, fills in elapsed/penalty time when not\n * provided, and uploads the final play plus its deeds — the host uses these for scoring,\n * leaderboards, stats, and other augmentations. Pass progress as `inputString` (the same\n * string `updateGameState()` takes). Follow with `showCompletionScreen()`.\n */\n gameCompleted: (play: GameCompletedPlay, config?: AugmentationConfig) => void\n\n /**\n * Ask the host to show its post-game completion UI. `results` render in the completion\n * sidebar: markdown congratulations, the player's streak stats, and custom stat rows. Call\n * after `gameCompleted()`, typically once your own victory animation has finished.\n */\n showCompletionScreen: (results: GameOverMessageUIComponent[]) => void\n\n /**\n * Record a named mid-game checkpoint. Uploads the current board state and play time, and can\n * run parts of the completion pipeline early (e.g. posting to leaderboards) via\n * `checkpointConfig.process`. A checkpoint is also the host's opportunity to show an ad when\n * `checkpointConfig.interruptible` is true.\n */\n hitCheckpoint: (checkpointName: string, checkpointConfig: CheckpointConfig, config?: AugmentationConfig) => void\n\n /** Player-facing game settings, rendered in the host's settings panel and persisted per-user, per-game. */\n settings: SDKSettings\n\n /** The host-rendered on-screen keyboard, for games that take text or symbol input on touch devices. */\n keyboard: SDKKeyboard\n\n /**\n * The raw postMessage transport to the host — an escape hatch for protocol messages the SDK\n * doesn't wrap.\n *\n * @internal\n */\n _hostAPI: {\n sendMessage: <T extends keyof SupportedOutgoingMessages>(type: T, json: SupportedOutgoingMessages[T]) => void\n onMessage: <T extends keyof SupportedIncomingMessages>(type: T, handler: (data: SupportedIncomingMessages[T]) => void) => () => void\n }\n}\n\nexport type SupportedOutgoingMessages = Pick<\n MessagesSentFromEmbed,\n | \"READY\"\n | \"READY_GAME_LOADED\"\n | \"GAME_COMPLETED\"\n | \"SHOW_GAME_COMPLETE_SCREEN\"\n | \"TIMER_TICK\"\n | \"TIMER_SYNC\"\n | \"UPLOAD_NEW_GAME_STATE\"\n | \"HIT_CHECKPOINT\"\n | \"KEYBOARD_UPDATE_CONFIG\"\n | \"INITIALIZE_SETTINGS\"\n | \"UPDATE_SETTINGS_FROM_EMBED\"\n>\n\nexport type SupportedIncomingMessages = Pick<\n MessagesReceived,\n | \"READY_DATA\"\n | \"START_GAME\"\n | \"PAUSE_GAME\"\n | \"RESUME_GAME\"\n | \"SETTINGS_UPDATE\"\n | \"RETRY_PUZZLE\"\n | \"KEYBOARD_KEY_PRESS\"\n | \"KEYBOARD_CURSOR_CHANGE\"\n | \"KEYBOARD_CURSOR_END\"\n>\n\ntype MessageHandler<T extends keyof SupportedIncomingMessages> = (data: SupportedIncomingMessages[T]) => void\n\nexport type SDKEventMap = {\n start: void\n pause: void\n resume: void\n retry: void\n /** The player changed a setting in the host UI. The payload is the full resolved settings object. */\n settingsUpdate: any\n /** A key on the on-screen keyboard was tapped. */\n keyboardKeyPress: { key: string }\n /** The drag cursor moved across the keyboard. Only fires when `supportsDragCursor` is true. */\n keyboardCursorChange: { position: [number, number] }\n /** The drag cursor was released. Only fires when `supportsDragCursor` is true. */\n keyboardCursorEnd: void\n}\n\nexport type SDKEventType = keyof SDKEventMap\n\nexport interface SDKTimer {\n /** Get elapsed time in milliseconds */\n timeMs: () => number\n /** Get elapsed time in seconds */\n timeSecs: () => number\n /** Get added/penalty time in milliseconds */\n addedTimeMs: () => number\n /** Get added/penalty time in seconds */\n addedTimeSecs: () => number\n /** Get elapsed time without penalties in seconds */\n timeWithoutPenaltySecs: () => number\n /** Get formatted display strings [elapsed, added] */\n display: () => [string, string]\n /** Add penalty time in milliseconds */\n addPenalty: (ms: number) => void\n /** Check if timer is paused */\n isPaused: () => boolean\n /** Check if timer has been started */\n isRunning: () => boolean\n /** Pause the timer (same as a host-sent PAUSE_GAME); emits \"pause\" on an actual transition. */\n pause: () => void\n /** Resume the timer (same as a host-sent RESUME_GAME); emits \"resume\" on an actual transition. */\n resume: () => void\n}\n\nfunction formatTime(timeMs: number): string {\n const isAnHourOrMore = timeMs >= 60 * 60 * 1000\n return new Date(timeMs)\n .toISOString()\n .slice(isAnHourOrMore ? 11 : 14, -1)\n .split(\".\")[0]\n}\n\nfunction createTimer(\n initialTimeMs = 0,\n initialAddedTimeMs = 0,\n): Omit<SDKTimer, \"pause\" | \"resume\"> & {\n _init: () => void\n _pause: () => void\n _resume: () => void\n _reset: (initialTimeMs?: number, initialAddedTimeMs?: number) => void\n _conclude: () => void\n} {\n let baseTime = initialTimeMs\n let addedTime = initialAddedTimeMs\n let pausedTime = 0\n let concludeTime: number | undefined\n\n let startDate: number | undefined = undefined\n let pausedDate: number | undefined = undefined\n\n const getTime = (): number => {\n if (startDate === undefined) return baseTime + addedTime\n if (concludeTime !== undefined) return concludeTime\n const now = pausedDate ?? performance.now()\n const elapsed = now - startDate - pausedTime\n return baseTime + addedTime + elapsed\n }\n\n return {\n _init: () => {\n if (startDate === undefined) {\n startDate = performance.now()\n pausedDate = undefined\n }\n },\n _pause: () => {\n if (pausedDate !== undefined || startDate === undefined) return\n pausedDate = performance.now()\n },\n _resume: () => {\n if (pausedDate === undefined) return\n pausedTime += performance.now() - pausedDate\n pausedDate = undefined\n },\n _reset: (newInitialTimeMs = 0, newInitialAddedTimeMs = 0) => {\n baseTime = newInitialTimeMs\n addedTime = newInitialAddedTimeMs\n pausedTime = 0\n concludeTime = undefined\n startDate = undefined\n pausedDate = undefined\n },\n _conclude: () => {\n if (pausedDate !== undefined) {\n concludeTime = getTime()\n return\n }\n if (startDate === undefined) {\n concludeTime = baseTime + addedTime\n return\n }\n concludeTime = getTime()\n },\n timeMs: () => getTime(),\n timeSecs: () => getTime() / 1000,\n addedTimeMs: () => addedTime,\n addedTimeSecs: () => addedTime / 1000,\n timeWithoutPenaltySecs: () => (getTime() - addedTime) / 1000,\n addPenalty: (ms: number) => {\n addedTime += ms\n },\n isPaused: () => pausedDate !== undefined || startDate === undefined,\n isRunning: () => startDate !== undefined && pausedDate === undefined,\n display: () => {\n const elapsed = getTime() - addedTime\n const elapsedStr = formatTime(Math.max(0, elapsed))\n const addedStr = addedTime === 0 ? \"\" : formatTime(addedTime)\n return [elapsedStr, addedStr]\n },\n }\n}\n\nfunction createHostAPI() {\n const messageHandlers = new Map<string, Set<(data: any) => void>>()\n\n const sendMessage = <T extends keyof SupportedOutgoingMessages>(type: T, json: SupportedOutgoingMessages[T]) => {\n const message = { type, json, _: \"p\", __: \"mp\", private: true }\n\n if (\"parent\" in window && window.parent !== window) window.parent.postMessage(message, \"*\")\n\n window.postMessage(message, \"*\")\n\n if (\"webkit\" in window && (window as any).webkit?.messageHandlers?.app) (window as any).webkit.messageHandlers.app.postMessage(message)\n\n if (\"puzzmoMessageString\" in window) (window as any).puzzmoMessageString(JSON.stringify(message))\n\n if (\"ReactNativeWebView\" in window && (window as any).ReactNativeWebView?.postMessage)\n (window as any).ReactNativeWebView.postMessage(JSON.stringify(message))\n\n if (type !== \"TIMER_TICK\" && type !== \"TIMER_SYNC\") console.log(\"[Puzzmo SDK] sent:\", type, json)\n }\n\n const onMessage = <T extends keyof SupportedIncomingMessages>(type: T, handler: MessageHandler<T>) => {\n if (!messageHandlers.has(type)) messageHandlers.set(type, new Set())\n messageHandlers.get(type)!.add(handler)\n\n return () => {\n messageHandlers.get(type)?.delete(handler)\n }\n }\n\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"message\", (event) => {\n if (!event?.data?.type) return\n const msgType = event.data.type as string\n const handlers = messageHandlers.get(msgType)\n if (handlers) {\n const msgData = event.data.data ?? event.data.json ?? {}\n if (msgType !== \"TIMER_TICK\" && msgType !== \"TIMER_SYNC\") console.log(\"[Puzzmo SDK] received:\", msgType, msgData)\n handlers.forEach((handler) => handler(msgData))\n }\n })\n }\n\n return { sendMessage, onMessage }\n}\n\nconst hostAPI = createHostAPI()\n\n/** Creates a Puzzmo SDK instance for communicating with the Puzzmo host */\nexport const createPuzzmoSDK = <const Plugins extends readonly SDKPlugin[] = []>(\n options: PuzzmoSDKOptions<Plugins> = {},\n): PuzzmoSDK<Plugins> => {\n let readyData: MessagesReceived[\"READY_DATA\"] | null = null\n let readyDataResolve: ((data: MessagesReceived[\"READY_DATA\"]) => void) | null = null\n\n const getGameplay = () => readyData?.startOrFindGameplay?.gamePlayed\n const getGameplayID = () => getGameplay()?.id ?? null\n const getPuzzleString = () => getGameplay()?.puzzle.puzzle ?? null\n const getBoardState = () => getGameplay()?.boardState ?? null\n const getTheme = () => readyData?.theme ?? null\n const getCompleted = () => getGameplay()?.completed ?? false\n\n const eventListeners = new Map<SDKEventType, Set<(data?: any) => void>>()\n\n // The resolved settings object — seeded from READY_DATA's saved values, then component\n // defaults are merged underneath when the game calls settings.initialize\n let currentSettings: any | null = null\n\n // ClickHouse game analytics — sends the same lifecycle events the runtime tracks\n // (page_view, gameplay_active, active_30s, completed, link_click). Disabled on localhost.\n let analytics: GameAnalyticsTracker | null = null\n let analyticsCompletedAtStart = false\n\n const trackAnalyticsEvent = (type: string, json?: any) => {\n // Don't re-send progression events for a game that was already completed when loaded\n if (analyticsCompletedAtStart) return\n analytics?.trackEvent(type, json)\n }\n\n const internalTimer = createTimer()\n let timerTickInterval: ReturnType<typeof setInterval> | null = null\n let timerSyncInterval: ReturnType<typeof setInterval> | null = null\n\n const startTimerIntervals = () => {\n if (timerTickInterval) return\n\n timerTickInterval = setInterval(() => {\n if (internalTimer.isPaused()) return\n const [elapsed, added] = internalTimer.display()\n hostAPI.sendMessage(\"TIMER_TICK\", { display: [elapsed, added] })\n }, 500)\n\n timerSyncInterval = setInterval(() => {\n if (internalTimer.isPaused()) return\n hostAPI.sendMessage(\"TIMER_SYNC\", Math.floor(internalTimer.timeWithoutPenaltySecs()))\n }, 10000)\n }\n\n const stopTimerIntervals = () => {\n if (timerTickInterval) {\n clearInterval(timerTickInterval)\n timerTickInterval = null\n }\n if (timerSyncInterval) {\n clearInterval(timerSyncInterval)\n timerSyncInterval = null\n }\n }\n\n const emit = <T extends SDKEventType>(event: T, data?: SDKEventMap[T]) => {\n const listeners = eventListeners.get(event)\n if (listeners) listeners.forEach((listener) => listener(data))\n }\n\n hostAPI.onMessage(\"START_GAME\", () => {\n internalTimer._init()\n startTimerIntervals()\n emit(\"start\")\n })\n\n // Shared by the host-sent PAUSE_GAME/RESUME_GAME messages and the game-initiated\n // sdk.timer.pause()/resume() below, so both paths stop/start the same timer identically.\n const pauseTimer = () => {\n const wasPaused = internalTimer.isPaused()\n internalTimer._pause()\n if (internalTimer.isPaused() !== wasPaused) emit(\"pause\")\n }\n const resumeTimer = () => {\n const wasPaused = internalTimer.isPaused()\n internalTimer._resume()\n if (internalTimer.isPaused() !== wasPaused) emit(\"resume\")\n }\n\n hostAPI.onMessage(\"PAUSE_GAME\", pauseTimer)\n hostAPI.onMessage(\"RESUME_GAME\", resumeTimer)\n\n hostAPI.onMessage(\"SETTINGS_UPDATE\", (data) => {\n currentSettings = { ...currentSettings, ...data }\n emit(\"settingsUpdate\", currentSettings)\n })\n\n hostAPI.onMessage(\"KEYBOARD_KEY_PRESS\", (data) => emit(\"keyboardKeyPress\", data))\n hostAPI.onMessage(\"KEYBOARD_CURSOR_CHANGE\", (data) => emit(\"keyboardCursorChange\", data))\n hostAPI.onMessage(\"KEYBOARD_CURSOR_END\", () => emit(\"keyboardCursorEnd\"))\n\n hostAPI.onMessage(\"RETRY_PUZZLE\", () => {\n internalTimer._reset()\n stopTimerIntervals()\n emit(\"retry\")\n })\n\n hostAPI.onMessage(\"READY_DATA\", (data) => {\n const bootstrapData = data as MessagesReceived[\"READY_DATA\"]\n readyData = bootstrapData\n\n const gamePlayed = bootstrapData.startOrFindGameplay?.gamePlayed\n\n // userState.gameSettings is a map keyed by game slug; older records can hold the\n // value as a JSON string rather than an object\n if (currentSettings === null) {\n const gameSlug = gamePlayed?.puzzle?.game?.slug\n let saved = gameSlug ? bootstrapData.userState?.gameSettings?.[gameSlug] : null\n if (typeof saved === \"string\") {\n try {\n saved = JSON.parse(saved)\n } catch {\n saved = null\n }\n }\n currentSettings = saved ?? {}\n }\n if (gamePlayed) {\n const existingTime = (gamePlayed.elapsedTimeSecs ?? 0) * 1000\n const existingAddedTime = (gamePlayed.additionalTimeAddedSecs ?? 0) * 1000\n internalTimer._reset(existingTime, existingAddedTime)\n }\n\n // Wire up analytics once, from the first bootstrap payload\n if (!analytics) {\n analytics = createGameAnalytics(bootstrapData)\n analyticsCompletedAtStart = gamePlayed?.completed ?? false\n // Link clicks are tracked even for already-completed games, matching the runtime\n if (analytics) setupLinkTracking((info) => analytics!.trackLinkClick(info))\n }\n\n if (readyDataResolve) {\n readyDataResolve(bootstrapData)\n readyDataResolve = null\n }\n })\n\n const timer: SDKTimer = {\n timeMs: () => internalTimer.timeMs(),\n timeSecs: () => internalTimer.timeSecs(),\n addedTimeMs: () => internalTimer.addedTimeMs(),\n addedTimeSecs: () => internalTimer.addedTimeSecs(),\n timeWithoutPenaltySecs: () => internalTimer.timeWithoutPenaltySecs(),\n display: () => internalTimer.display(),\n addPenalty: (ms: number) => internalTimer.addPenalty(ms),\n isPaused: () => internalTimer.isPaused(),\n isRunning: () => internalTimer.isRunning(),\n pause: pauseTimer,\n resume: resumeTimer,\n }\n\n // Wire up plugins. Each gets the host transport (open to the full protocol), the timer, and\n // the bootstrap payload, and contributes a namespaced API onto `sdk.plugins[name]`.\n const pluginContext: SDKPluginContext = {\n send: (type, json) => hostAPI.sendMessage(type as keyof SupportedOutgoingMessages, json as never),\n on: (type, handler) => hostAPI.onMessage(type as keyof SupportedIncomingMessages, handler),\n timer,\n bootstrap: () => readyData,\n }\n const pluginAPIs: Record<string, unknown> = {}\n for (const plugin of options.plugins ?? []) pluginAPIs[plugin.name] = plugin.setup(pluginContext)\n\n return {\n timer,\n\n plugins: pluginAPIs as PluginAPIs<Plugins>,\n\n gameReady: async (): Promise<GameReadyResult> => {\n hostAPI.sendMessage(\"READY\", {})\n\n if (getPuzzleString()) {\n const inputString = getBoardState()\n return {\n puzzleString: getPuzzleString()!,\n inputString,\n // @ts-expect-error - this is backwards compat\n boardState: inputString,\n theme: getTheme(),\n completed: getCompleted(),\n readyData,\n }\n }\n\n const timeout = options.timeout ?? 5000\n const readyDataPromise = new Promise<MessagesReceived[\"READY_DATA\"]>((resolve, reject) => {\n readyDataResolve = resolve\n setTimeout(() => {\n if (readyDataResolve) {\n readyDataResolve = null\n reject(new Error(`Timeout waiting for READY_DATA after ${timeout}ms`))\n }\n }, timeout)\n })\n\n await readyDataPromise\n\n const puzzleString = getPuzzleString()\n if (!puzzleString) throw new Error(\"READY_DATA received but no puzzle data found\")\n\n const inputString = getBoardState()\n return {\n puzzleString,\n inputString,\n // @ts-expect-error - this is backwards compat\n boardState: inputString,\n theme: getTheme(),\n completed: getCompleted(),\n readyData,\n }\n },\n\n gameLoaded: (state: any = {}) => {\n hostAPI.sendMessage(\"READY_GAME_LOADED\", {\n state,\n gameRuntimeContract: \"1.0\",\n embedRuntimeContract: \"1.0\",\n })\n trackAnalyticsEvent(\"READY_GAME_LOADED\")\n },\n\n on: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void): (() => void) => {\n if (!eventListeners.has(event)) eventListeners.set(event, new Set())\n eventListeners.get(event)!.add(listener)\n return () => {\n eventListeners.get(event)?.delete(listener)\n }\n },\n\n off: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void) => {\n eventListeners.get(event)?.delete(listener)\n },\n\n updateGameState: (inputString: string, play?: Partial<GamePlay>) => {\n const gameplayID = getGameplayID()\n if (!gameplayID) return\n\n hostAPI.sendMessage(\"UPLOAD_NEW_GAME_STATE\", {\n id: gameplayID,\n input: {\n boardState: inputString,\n elapsedTimeSecs: play?.elapsedTimeSecs ?? internalTimer.timeWithoutPenaltySecs(),\n additionalTimeAddedSecs: play?.additionalTimeAddedSecs ?? internalTimer.addedTimeSecs(),\n collabUserReferences: [],\n },\n })\n trackAnalyticsEvent(\"UPLOAD_NEW_GAME_STATE\")\n },\n\n gameCompleted: (play: GameCompletedPlay, config?: AugmentationConfig) => {\n internalTimer._conclude()\n stopTimerIntervals()\n\n // Games say inputString; the wire and database say boardState. Untyped callers\n // may still send the old boardState spelling, so keep accepting it at runtime.\n const { inputString, ...rest } = play\n const finalPlay: Partial<GamePlay> = {\n ...rest,\n boardState: inputString ?? (play as { boardState?: string }).boardState,\n elapsedTimeSecs: play.elapsedTimeSecs ?? internalTimer.timeWithoutPenaltySecs(),\n additionalTimeAddedSecs: play.additionalTimeAddedSecs ?? internalTimer.addedTimeSecs(),\n }\n\n const deeds: Deed[] = (config?.deeds as any) ?? []\n deeds.push({ id: \"points\", value: play.pointsAwarded })\n deeds.push({\n id: \"time\",\n value: Math.round(finalPlay.elapsedTimeSecs ?? 0) + Math.round(finalPlay.additionalTimeAddedSecs ?? 0),\n })\n\n const gameplayID = getGameplayID()\n if (gameplayID) {\n hostAPI.sendMessage(\"GAME_COMPLETED\", {\n id: gameplayID,\n input: finalPlay,\n config,\n })\n trackAnalyticsEvent(\"GAME_COMPLETED\", { input: finalPlay })\n }\n },\n\n showCompletionScreen: (results: GameOverMessageUIComponent[]) => {\n // showRetry stays in the message contract for a future host play-again button; no host renders one yet\n hostAPI.sendMessage(\"SHOW_GAME_COMPLETE_SCREEN\", { results, showRetry: true })\n },\n\n hitCheckpoint: (checkpointName: string, checkpointConfig: CheckpointConfig, config?: AugmentationConfig) => {\n const gameplayID = getGameplayID()\n if (!gameplayID) return\n\n const inputStr = getBoardState() ?? \"\"\n const play: Partial<GamePlay> = {\n elapsedTimeSecs: internalTimer.timeWithoutPenaltySecs(),\n additionalTimeAddedSecs: internalTimer.addedTimeSecs(),\n }\n\n hostAPI.sendMessage(\"HIT_CHECKPOINT\", {\n checkpointName,\n gameplay: { inputStr, play },\n checkpointConfig,\n augConfig: config ?? {},\n })\n },\n\n settings: {\n initialize: (components: GameSettingsUIComponents[]) => {\n currentSettings = { ...settingsDefaultsFromComponents(components), ...currentSettings }\n hostAPI.sendMessage(\"INITIALIZE_SETTINGS\", { components, settings: currentSettings })\n return currentSettings\n },\n get: () => currentSettings ?? {},\n update: (changes: any) => {\n currentSettings = { ...currentSettings, ...changes }\n hostAPI.sendMessage(\"UPDATE_SETTINGS_FROM_EMBED\", { settings: currentSettings })\n return currentSettings\n },\n },\n\n keyboard: {\n show: (config: KeyboardConfig) => {\n hostAPI.sendMessage(\"KEYBOARD_UPDATE_CONFIG\", config)\n },\n hide: () => {\n hostAPI.sendMessage(\"KEYBOARD_UPDATE_CONFIG\", {\n layout: [],\n symbols: {},\n highlight: [],\n disabled: [],\n xl: [],\n l: [],\n supportsDragCursor: false,\n })\n },\n },\n\n _hostAPI: hostAPI,\n }\n}\n\n/** Walks settings UI components (recursing into split groups) collecting name → defaultValue pairs */\nfunction settingsDefaultsFromComponents(components: GameSettingsUIComponents[]): Record<string, unknown> {\n const defaults: Record<string, unknown> = {}\n for (const component of components) {\n if (component.type === \"split\") Object.assign(defaults, settingsDefaultsFromComponents(component.content))\n else if (\"name\" in component) defaults[component.name] = component.defaultValue\n }\n return defaults\n}\n","import type { KeyboardConfig } from \"./types\"\n\n/**\n * A standard QWERTY layout with Enter and Backspace — a reasonable default for\n * any game that needs text input. Customize from here by spreading and overriding.\n *\n * @example\n * // Use as-is\n * sdk.keyboard.show(defaultKeyboardConfig)\n *\n * @example\n * // Extend with dynamic disabled letters\n * sdk.keyboard.show({ ...defaultKeyboardConfig, disabled: usedLetters })\n */\nexport const defaultKeyboardConfig: KeyboardConfig = {\n layout: [\"qwertyuiop\", \"asdfghjkl\", \"↵zxcvbnm⌫\", undefined],\n symbols: { \"↵\": \"Enter\", \"⌫\": \"bsp\" },\n highlight: [\"↵\", \"⌫\"],\n disabled: [],\n xl: [],\n l: [\"↵\", \"⌫\"],\n supportsDragCursor: false,\n}\n","// For now, we will keep these types in here but not mark them as something which should appear in the public SDK docs\n\nimport type { Theme } from \"./types\"\n\n/**\n * The theme passed to an editor bundle. The host sends its full {@link Theme} so editors derive\n * their colors from it rather than making their own theme decisions. Use `theme.type` for\n * light/dark bucketing.\n *\n * The bare `\"light\" | \"dark\"` string form is deprecated and will be removed in a future SDK\n * release — editors should handle the full `Theme` object.\n */\nexport type EditorTheme = Theme | \"light\" | \"dark\"\n\n/** Severity level for validation issues */\nexport type ValidationLevel = \"error\" | \"warning\" | \"info\"\n\n/** Represents a single validation issue found during puzzle validation */\nexport interface ValidationIssue {\n level: ValidationLevel\n message: string\n line?: number\n col?: number\n length?: number\n}\n\n/** Complete validation report for a puzzle */\nexport interface ValidationReport {\n success: boolean\n issues: ValidationIssue[]\n}\n\nexport type ImportErrorType = \"invalid_format\" | \"parsing_error\" | \"unknown\"\n\n/** Custom error class for workshop import failures */\nexport class EditorImportError extends Error {\n constructor(\n public type: ImportErrorType,\n message: string,\n public originalError?: unknown,\n ) {\n super(message)\n this.name = \"EditorImportError\"\n }\n}\n\n/** Result of a successful puzzle import operation */\nexport interface ImportResult {\n data: string\n warnings?: ValidationIssue[]\n title?: string\n authors?: string[]\n editors?: string[]\n}\n\n/** Settings UI descriptor returned by an editor bundle */\nexport interface EditorBundleSettings<TComponent = unknown> {\n components: TComponent[]\n defaults: Record<string, unknown>\n}\n\n/** A preceding/following phrase for a word, returned by the getRelatedWords editor callback */\nexport interface RelatedWord {\n word: string\n frequency: number\n position: \"preceding\" | \"following\"\n}\n\n/** Result of fetching a URL from within the editor */\nexport interface EditorFetchURLResult {\n status: number\n body: string\n}\n\n/** Config passed to an editor bundle's mount() */\nexport interface EditorMountConfig {\n puzzleString: string\n onChange: (puzzleString: string) => void\n theme: EditorTheme\n width: number\n height: number\n /**\n * Optional function for making chat completions from the editor (e.g. for AI-assisted puzzle\n * editing). This needs to be enabled for a team explicitly.\n */\n chatCompletion?: (prompt: string) => Promise<string>\n /**\n * Optional function for fetching URLs from the editor (e.g. for fetching article content).\n * This needs to be enabled for a team explicitly.\n */\n fetchURL?: (url: string) => Promise<EditorFetchURLResult>\n /** Optional function for looking up a word's preceding/following phrases from wordvault. */\n getRelatedWords?: (word: string, limit?: number) => Promise<RelatedWord[]>\n /** Pre-configured editor settings values from the queue's editorSettings. */\n settings?: Record<string, unknown>\n}\n\n/** Handle returned by an editor bundle's mount() */\nexport interface EditorMountHandle {\n unmount: () => void\n /**\n * Called whenever the puzzle string is updated in the editor from the outside, or when the theme\n * or dimensions update. Workshop will rely on the validator to reject / accept updates.\n */\n update: (config: { puzzleString?: string; theme?: EditorTheme; width?: number; height?: number }) => void\n}\n\n/** Main interface for a Workshop editor bundle */\nexport interface EditorBundle<TSettingsComponent = unknown> {\n /** Required validator for puzzle data validation */\n validator: {\n validate(data: string): Promise<ValidationReport> | ValidationReport\n }\n /** Optional importer for converting external puzzle file formats */\n importer?: {\n onImport(filename: string, contents: string | ArrayBuffer): Promise<ImportResult> | ImportResult\n }\n /** Embed-level settings UI, populated from the bundle's declared settings */\n settings?: EditorBundleSettings<TSettingsComponent>\n /** Editor-level settings UI, populated from the bundle's declared editor settings */\n editorSettings?: EditorBundleSettings<TSettingsComponent>\n /** Custom puzzle editor, if provided by the bundle */\n editor?: {\n /** Called when first visiting a puzzle page. */\n mount(element: HTMLElement, config: EditorMountConfig): Promise<EditorMountHandle>\n }\n}\n","// Copyright (c) 2013 Pieroxy <pieroxy@pieroxy.net>\n// This work is free. You can redistribute it and/or modify it\n// under the terms of the WTFPL, Version 2\n// For more information see LICENSE.txt or http://www.wtfpl.net/\n//\n// For more information, the home page:\n// http://pieroxy.net/blog/pages/lz-string/testing.html\n//\n// LZ-based compression algorithm, version 1.4.5\nvar LZString = (function() {\n\n// private property\nvar f = String.fromCharCode;\nvar keyStrBase64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\nvar keyStrUriSafe = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$\";\nvar baseReverseDic = {};\n\nfunction getBaseValue(alphabet, character) {\n if (!baseReverseDic[alphabet]) {\n baseReverseDic[alphabet] = {};\n for (var i=0 ; i<alphabet.length ; i++) {\n baseReverseDic[alphabet][alphabet.charAt(i)] = i;\n }\n }\n return baseReverseDic[alphabet][character];\n}\n\nvar LZString = {\n compressToBase64 : function (input) {\n if (input == null) return \"\";\n var res = LZString._compress(input, 6, function(a){return keyStrBase64.charAt(a);});\n switch (res.length % 4) { // To produce valid Base64\n default: // When could this happen ?\n case 0 : return res;\n case 1 : return res+\"===\";\n case 2 : return res+\"==\";\n case 3 : return res+\"=\";\n }\n },\n\n decompressFromBase64 : function (input) {\n if (input == null) return \"\";\n if (input == \"\") return null;\n return LZString._decompress(input.length, 32, function(index) { return getBaseValue(keyStrBase64, input.charAt(index)); });\n },\n\n compressToUTF16 : function (input) {\n if (input == null) return \"\";\n return LZString._compress(input, 15, function(a){return f(a+32);}) + \" \";\n },\n\n decompressFromUTF16: function (compressed) {\n if (compressed == null) return \"\";\n if (compressed == \"\") return null;\n return LZString._decompress(compressed.length, 16384, function(index) { return compressed.charCodeAt(index) - 32; });\n },\n\n //compress into uint8array (UCS-2 big endian format)\n compressToUint8Array: function (uncompressed) {\n var compressed = LZString.compress(uncompressed);\n var buf=new Uint8Array(compressed.length*2); // 2 bytes per character\n\n for (var i=0, TotalLen=compressed.length; i<TotalLen; i++) {\n var current_value = compressed.charCodeAt(i);\n buf[i*2] = current_value >>> 8;\n buf[i*2+1] = current_value % 256;\n }\n return buf;\n },\n\n //decompress from uint8array (UCS-2 big endian format)\n decompressFromUint8Array:function (compressed) {\n if (compressed===null || compressed===undefined){\n return LZString.decompress(compressed);\n } else {\n var buf=new Array(compressed.length/2); // 2 bytes per character\n for (var i=0, TotalLen=buf.length; i<TotalLen; i++) {\n buf[i]=compressed[i*2]*256+compressed[i*2+1];\n }\n\n var result = [];\n buf.forEach(function (c) {\n result.push(f(c));\n });\n return LZString.decompress(result.join(''));\n\n }\n\n },\n\n\n //compress into a string that is already URI encoded\n compressToEncodedURIComponent: function (input) {\n if (input == null) return \"\";\n return LZString._compress(input, 6, function(a){return keyStrUriSafe.charAt(a);});\n },\n\n //decompress from an output of compressToEncodedURIComponent\n decompressFromEncodedURIComponent:function (input) {\n if (input == null) return \"\";\n if (input == \"\") return null;\n input = input.replace(/ /g, \"+\");\n return LZString._decompress(input.length, 32, function(index) { return getBaseValue(keyStrUriSafe, input.charAt(index)); });\n },\n\n compress: function (uncompressed) {\n return LZString._compress(uncompressed, 16, function(a){return f(a);});\n },\n _compress: function (uncompressed, bitsPerChar, getCharFromInt) {\n if (uncompressed == null) return \"\";\n var i, value,\n context_dictionary= {},\n context_dictionaryToCreate= {},\n context_c=\"\",\n context_wc=\"\",\n context_w=\"\",\n context_enlargeIn= 2, // Compensate for the first entry which should not count\n context_dictSize= 3,\n context_numBits= 2,\n context_data=[],\n context_data_val=0,\n context_data_position=0,\n ii;\n\n for (ii = 0; ii < uncompressed.length; ii += 1) {\n context_c = uncompressed.charAt(ii);\n if (!Object.prototype.hasOwnProperty.call(context_dictionary,context_c)) {\n context_dictionary[context_c] = context_dictSize++;\n context_dictionaryToCreate[context_c] = true;\n }\n\n context_wc = context_w + context_c;\n if (Object.prototype.hasOwnProperty.call(context_dictionary,context_wc)) {\n context_w = context_wc;\n } else {\n if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) {\n if (context_w.charCodeAt(0)<256) {\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n }\n value = context_w.charCodeAt(0);\n for (i=0 ; i<8 ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n } else {\n value = 1;\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1) | value;\n if (context_data_position ==bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = 0;\n }\n value = context_w.charCodeAt(0);\n for (i=0 ; i<16 ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n }\n context_enlargeIn--;\n if (context_enlargeIn == 0) {\n context_enlargeIn = Math.pow(2, context_numBits);\n context_numBits++;\n }\n delete context_dictionaryToCreate[context_w];\n } else {\n value = context_dictionary[context_w];\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n\n\n }\n context_enlargeIn--;\n if (context_enlargeIn == 0) {\n context_enlargeIn = Math.pow(2, context_numBits);\n context_numBits++;\n }\n // Add wc to the dictionary.\n context_dictionary[context_wc] = context_dictSize++;\n context_w = String(context_c);\n }\n }\n\n // Output the code for w.\n if (context_w !== \"\") {\n if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) {\n if (context_w.charCodeAt(0)<256) {\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n }\n value = context_w.charCodeAt(0);\n for (i=0 ; i<8 ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n } else {\n value = 1;\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1) | value;\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = 0;\n }\n value = context_w.charCodeAt(0);\n for (i=0 ; i<16 ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n }\n context_enlargeIn--;\n if (context_enlargeIn == 0) {\n context_enlargeIn = Math.pow(2, context_numBits);\n context_numBits++;\n }\n delete context_dictionaryToCreate[context_w];\n } else {\n value = context_dictionary[context_w];\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n\n\n }\n context_enlargeIn--;\n if (context_enlargeIn == 0) {\n context_enlargeIn = Math.pow(2, context_numBits);\n context_numBits++;\n }\n }\n\n // Mark the end of the stream\n value = 2;\n for (i=0 ; i<context_numBits ; i++) {\n context_data_val = (context_data_val << 1) | (value&1);\n if (context_data_position == bitsPerChar-1) {\n context_data_position = 0;\n context_data.push(getCharFromInt(context_data_val));\n context_data_val = 0;\n } else {\n context_data_position++;\n }\n value = value >> 1;\n }\n\n // Flush the last char\n while (true) {\n context_data_val = (context_data_val << 1);\n if (context_data_position == bitsPerChar-1) {\n context_data.push(getCharFromInt(context_data_val));\n break;\n }\n else context_data_position++;\n }\n return context_data.join('');\n },\n\n decompress: function (compressed) {\n if (compressed == null) return \"\";\n if (compressed == \"\") return null;\n return LZString._decompress(compressed.length, 32768, function(index) { return compressed.charCodeAt(index); });\n },\n\n _decompress: function (length, resetValue, getNextValue) {\n var dictionary = [],\n next,\n enlargeIn = 4,\n dictSize = 4,\n numBits = 3,\n entry = \"\",\n result = [],\n i,\n w,\n bits, resb, maxpower, power,\n c,\n data = {val:getNextValue(0), position:resetValue, index:1};\n\n for (i = 0; i < 3; i += 1) {\n dictionary[i] = i;\n }\n\n bits = 0;\n maxpower = Math.pow(2,2);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n\n switch (next = bits) {\n case 0:\n bits = 0;\n maxpower = Math.pow(2,8);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n c = f(bits);\n break;\n case 1:\n bits = 0;\n maxpower = Math.pow(2,16);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n c = f(bits);\n break;\n case 2:\n return \"\";\n }\n dictionary[3] = c;\n w = c;\n result.push(c);\n while (true) {\n if (data.index > length) {\n return \"\";\n }\n\n bits = 0;\n maxpower = Math.pow(2,numBits);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n\n switch (c = bits) {\n case 0:\n bits = 0;\n maxpower = Math.pow(2,8);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n\n dictionary[dictSize++] = f(bits);\n c = dictSize-1;\n enlargeIn--;\n break;\n case 1:\n bits = 0;\n maxpower = Math.pow(2,16);\n power=1;\n while (power!=maxpower) {\n resb = data.val & data.position;\n data.position >>= 1;\n if (data.position == 0) {\n data.position = resetValue;\n data.val = getNextValue(data.index++);\n }\n bits |= (resb>0 ? 1 : 0) * power;\n power <<= 1;\n }\n dictionary[dictSize++] = f(bits);\n c = dictSize-1;\n enlargeIn--;\n break;\n case 2:\n return result.join('');\n }\n\n if (enlargeIn == 0) {\n enlargeIn = Math.pow(2, numBits);\n numBits++;\n }\n\n if (dictionary[c]) {\n entry = dictionary[c];\n } else {\n if (c === dictSize) {\n entry = w + w.charAt(0);\n } else {\n return null;\n }\n }\n result.push(entry);\n\n // Add w+entry[0] to the dictionary.\n dictionary[dictSize++] = w + entry.charAt(0);\n enlargeIn--;\n\n w = entry;\n\n if (enlargeIn == 0) {\n enlargeIn = Math.pow(2, numBits);\n numBits++;\n }\n\n }\n }\n};\n return LZString;\n})();\n\nif (typeof define === 'function' && define.amd) {\n define(function () { return LZString; });\n} else if( typeof module !== 'undefined' && module != null ) {\n module.exports = LZString\n} else if( typeof angular !== 'undefined' && angular != null ) {\n angular.module('LZString', [])\n .factory('LZString', function () {\n return LZString;\n });\n}\n","import { compressToEncodedURIComponent, decompressFromEncodedURIComponent } from \"lz-string\"\n\nexport function encodeBitArrayToHex(bits: boolean[]): string {\n if (bits.length === 0) return \"0\"\n\n let hex = \"\"\n for (let i = 0; i < bits.length; i += 4) {\n let nibble = 0\n for (let j = 0; j < 4 && i + j < bits.length; j++) {\n if (bits[i + j]) {\n nibble |= 1 << j\n }\n }\n hex += nibble.toString(16)\n }\n\n return hex || \"0\"\n}\n\nexport function decodeBitArrayFromHex(hex: string, length: number): boolean[] {\n const bits: boolean[] = []\n\n for (let i = 0; i < length; i++) {\n const hexIndex = Math.floor(i / 4)\n const bitIndex = i % 4\n const nibble = parseInt(hex[hexIndex] || \"0\", 16)\n bits.push((nibble & (1 << bitIndex)) !== 0)\n }\n\n return bits\n}\n\nexport function encodeIntArray(arr: number[]): string {\n if (arr.length === 0) return \"\"\n\n const nonZero = arr.map((val, idx) => ({ val, idx })).filter((item) => item.val !== 0)\n\n if (nonZero.length === 0) return \"\"\n if (nonZero.length > arr.length / 2) {\n return arr.join(\",\")\n }\n\n return nonZero.map((item) => `${item.idx}=${item.val}`).join(\",\")\n}\n\nexport function decodeIntArray(str: string, defaultLength?: number): number[] {\n if (!str) return defaultLength ? Array.from({ length: defaultLength }, () => 0) : []\n\n if (str.includes(\"=\")) {\n const result = defaultLength ? Array.from({ length: defaultLength }, () => 0) : []\n const pairs = str.split(\",\")\n for (const pair of pairs) {\n const [idxStr, valStr] = pair.split(\"=\")\n const idx = Number(idxStr)\n const val = Number(valStr)\n if (!isNaN(idx) && !isNaN(val)) {\n result[idx] = val\n }\n }\n return result\n }\n\n return str.split(\",\").map((x) => Number(x))\n}\n\nexport function encodeStringArray(arr: string[], delimiter = \",\"): string {\n return arr.join(delimiter)\n}\n\nexport function decodeStringArray(str: string, delimiter = \",\"): string[] {\n if (!str) return []\n return str.split(delimiter)\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- JSON can encode any data\nexport function encodeJson(data: any): string {\n const json = JSON.stringify(data)\n return compressToEncodedURIComponent(json)\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- JSON can decode to any data\nexport function decodeJson(str: string): any {\n if (!str) return undefined\n const json = decompressFromEncodedURIComponent(str)\n return json ? JSON.parse(json) : undefined\n}\n\nexport function encodeSparseMap<T>(map: Record<string, T>, encodeValue: (val: T) => string, orderedKeys?: string[]): string {\n const entries = Object.entries(map).filter(([_, val]) => val !== null && val !== undefined)\n\n if (orderedKeys) {\n // Use numeric indices instead of string keys\n const indexedEntries = entries\n .map(([key, val]) => {\n const idx = orderedKeys.indexOf(key)\n if (idx === -1) return null\n return `${idx}=${encodeValue(val)}`\n })\n .filter((entry): entry is string => entry !== null)\n\n return indexedEntries.join(\",\")\n } else {\n // Fall back to string keys\n return entries.map(([key, val]) => `${key}=${encodeValue(val)}`).join(\";\")\n }\n}\n\nexport function decodeSparseMap<T>(str: string, decodeValue: (val: string) => T, orderedKeys?: string[]): Record<string, T> {\n if (!str) return {}\n\n const result: Record<string, T> = {}\n\n if (orderedKeys) {\n // Decode numeric indices\n const entries = str.split(\",\")\n for (const entry of entries) {\n if (!entry) continue\n const [idxStr, val] = entry.split(\"=\")\n const idx = Number(idxStr)\n if (!isNaN(idx) && val && orderedKeys[idx]) {\n result[orderedKeys[idx]] = decodeValue(val)\n }\n }\n } else {\n // Decode string keys\n const entries = str.split(\";\")\n for (const entry of entries) {\n if (!entry) continue\n const [key, val] = entry.split(\"=\")\n if (key && val) {\n result[key] = decodeValue(val)\n }\n }\n }\n\n return result\n}\n","import type { Schema, FieldType } from \"./types\"\nimport { encodeBitArrayToHex, encodeIntArray, encodeStringArray, encodeSparseMap, encodeJson } from \"./encodings\"\n\nexport function encodeField(value: any, fieldType: FieldType, context?: any): string {\n switch (fieldType.type) {\n case \"bitArray\":\n return encodeBitArrayToHex(value)\n\n case \"intArray\":\n return encodeIntArray(value)\n\n case \"int\":\n return String(value)\n\n case \"string\":\n return String(value)\n\n case \"stringArray\":\n return encodeStringArray(value, fieldType.delimiter)\n\n case \"sparseMap\":\n return encodeSparseMap(value, fieldType.valueEncoder, context?.keys)\n\n case \"json\":\n return encodeJson(value)\n\n default:\n throw new Error(`Unknown field type: ${(fieldType as any).type}`)\n }\n}\n\nexport function encode<TData>(schema: Schema<TData>, data: TData, context?: Record<string, any>): string {\n const delimiter = schema.delimiter || \":\"\n const fieldNames = Object.keys(schema.fields) as (keyof TData)[]\n\n const encodedFields = fieldNames.map((fieldName) => {\n const fieldType = schema.fields[fieldName]\n const value = data[fieldName]\n const fieldContext = context?.[fieldName as string]\n return encodeField(value, fieldType, fieldContext)\n })\n\n return `v${schema.version}${delimiter}${encodedFields.join(delimiter)}`\n}\n","import type { Schema, FieldType } from \"./types\"\nimport { decodeBitArrayFromHex, decodeIntArray, decodeStringArray, decodeSparseMap, decodeJson } from \"./encodings\"\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- context is dynamic and return type depends on fieldType\nexport function decodeField(value: string, fieldType: FieldType, context?: any): any {\n switch (fieldType.type) {\n case \"bitArray\":\n if (!context?.length) {\n throw new Error(\"bitArray requires length in context\")\n }\n return decodeBitArrayFromHex(value, context.length)\n\n case \"intArray\":\n return decodeIntArray(value, context?.length)\n\n case \"int\":\n return Number(value)\n\n case \"string\":\n return value\n\n case \"stringArray\":\n return decodeStringArray(value, fieldType.delimiter)\n\n case \"sparseMap\":\n return decodeSparseMap(value, fieldType.valueDecoder, context?.keys)\n\n case \"json\":\n return decodeJson(value)\n\n default:\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- used in error message for invalid type\n throw new Error(`Unknown field type: ${(fieldType as any).type}`)\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- context values are dynamic\nexport function decode<TData>(schema: Schema<TData>, inputString: string, context?: Record<string, any>): TData {\n const delimiter = schema.delimiter || \":\"\n const parts = inputString.split(delimiter)\n\n const versionPart = parts[0]\n const versionMatch = versionPart.match(/^v(\\d+)$/)\n if (!versionMatch) {\n throw new Error(`Invalid input string format: ${versionPart}`)\n }\n\n const version = Number(versionMatch[1])\n if (version !== schema.version) {\n throw new Error(`Version mismatch: expected v${schema.version}, got v${version}. ` + `Make sure to run migrations first.`)\n }\n\n const fieldNames = Object.keys(schema.fields) as (keyof TData)[]\n const data = {} as TData\n\n for (let i = 0; i < fieldNames.length; i++) {\n const fieldName = fieldNames[i]\n const fieldType = schema.fields[fieldName]\n const fieldValue = parts[i + 1] || \"\"\n\n const fieldContext = context?.[fieldName as string]\n data[fieldName] = decodeField(fieldValue, fieldType, fieldContext)\n }\n\n return data\n}\n","import type { Schema } from \"./types\"\nimport { encode } from \"./encoder\"\nimport { decode } from \"./decoder\"\n\nexport function createMigrator<TData>(schema: Schema<TData>) {\n return function migrate(inputString: string, context?: Record<string, any>): string {\n const versionMatch = inputString.match(/^v(\\d+)/)\n if (!versionMatch) {\n throw new Error(\"Invalid input string: no version found\")\n }\n\n const currentVersion = Number(versionMatch[1])\n\n if (currentVersion === schema.version) {\n return inputString\n }\n\n if (!schema.migrations) {\n throw new Error(`No migrations defined for schema. Cannot migrate from v${currentVersion} to v${schema.version}`)\n }\n\n // Data type changes at each migration step (v0 → v1 → v2, etc.)\n // TypeScript can't track these transformations statically, so we use `any`\n // Migrations are developer-written and tested to maintain type safety through the chain\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let data: any = decode(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n { ...schema, version: currentVersion } as Schema<any>,\n inputString,\n context,\n )\n\n for (let v = currentVersion; v < schema.version; v++) {\n const migration = schema.migrations[v]\n if (migration) {\n data = migration(data)\n }\n }\n\n return encode(schema, data, context)\n }\n}\n","/**\n * Encodes boolean arrays as compact hexadecimal strings.\n *\n * **When to use:**\n *\n * - Revealed/hidden state of game tiles\n * - Feature flags or settings\n * - Any boolean array where order matters\n *\n * **Encoding:**\n *\n * - Packs 4 bits per hex character (75% size reduction)\n * - Example: [true, false, false, false, false, true, false, false] → \"12\"\n *\n * **Decoding:**\n *\n * - Requires length in context: `{ fieldName: { length: 100 } }`\n */\nexport type BitArrayFieldType = {\n type: \"bitArray\"\n}\n\n/**\n * Encodes integer arrays with automatic sparse optimization.\n *\n * **When to use:**\n *\n * - Arrays of numeric values (scores, counts, experience)\n * - Sparse data (mostly zeros)\n * - Dense data (will auto-fallback to CSV)\n *\n * **Encoding:**\n *\n * - Uses decimal (base-10) numbers separated by commas\n * - Smart sparse: If >50% zeros, uses `index=value` pairs (e.g., \"2=5,4=3\")\n * - Dense fallback: If not beneficial, uses CSV (e.g., \"1,2,3,4\")\n * - Empty arrays encode as empty string\n *\n * **Decoding:**\n *\n * - Requires length in context for sparse format: `{ fieldName: { length: 100 } }`\n * - CSV format decodes without context\n */\nexport type IntArrayFieldType = {\n type: \"intArray\"\n}\n\n/**\n * Encodes single integer values.\n *\n * **When to use:**\n *\n * - Single numeric values (score, level, count)\n * - Non-negative integers only\n *\n * **Encoding:**\n *\n * - Uses decimal (base-10) representation\n * - Example: 42 → \"42\"\n */\nexport type IntFieldType = {\n type: \"int\"\n}\n\n/**\n * Encodes string values as-is.\n *\n * **When to use:**\n *\n * - Single string values (name, color, mode)\n * - Short identifiers\n *\n * **Warning:**\n *\n * - Strings containing the schema delimiter (default ':') will break parsing\n * - Consider using a custom delimiter or different encoding for such strings\n */\nexport type StringFieldType = {\n type: \"string\"\n}\n\n/**\n * Encodes arrays of strings.\n *\n * **When to use:**\n *\n * - Lists of tags, categories, or identifiers\n * - Ordered collections of strings\n *\n * **Encoding:**\n *\n * - Uses comma delimiter by default\n * - Custom delimiter can be specified to avoid conflicts\n *\n * **Warning:**\n *\n * - Strings containing the delimiter will break parsing\n * - Use custom delimiter to avoid conflicts\n */\nexport type StringArrayFieldType = {\n type: \"stringArray\"\n delimiter?: string\n}\n\n/**\n * Encodes sparse key-value maps with custom value encoding.\n *\n * **When to use:**\n *\n * - Tile annotations, cell metadata\n * - Any sparse mapping where most keys don't have values\n * - Custom object types that need specialized encoding\n *\n * **Encoding:**\n *\n * - With context keys: Uses numeric indices (e.g., `0=2.1,5=3.0`)\n * - Without context: Uses string keys (e.g., `key1=val1;key2=val2`)\n * - Only stores non-empty entries\n * - Keys are always strings in the data, converted to indices when context provides ordered keys\n * - ValueEncoder: Convert your object to a string\n * - ValueDecoder: Parse string back to your object\n *\n * **Optimization:**\n * Provide ordered keys in context to use numeric indices instead of string keys:\n *\n * ```typescript\n * const { encode, decode } = createEncoder(schema, {\n * annotations: { keys: tileIds }, // Ordered list of possible keys\n * })\n * ```\n *\n * **Example:**\n *\n * ```typescript\n * annotations: {\n * type: 'sparseMap',\n * valueEncoder: (ann) => `${ann.level}.${ann.color}`,\n * valueDecoder: (str) => {\n * const [level, color] = str.split('.').map(Number)\n * return { level, color }\n * }\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Generic type parameter for value type\nexport type SparseMapFieldType<TValue = any> = {\n type: \"sparseMap\"\n valueEncoder: (value: TValue) => string\n valueDecoder: (str: string) => TValue\n}\n\n/**\n * Encodes arbitrary data as JSON with automatic compression.\n *\n * **When to use:**\n *\n * - Complex nested structures\n * - Fallback for data that doesn't fit other types\n * - Temporary solution before implementing custom encoding\n *\n * **Encoding:**\n *\n * - Converts data to JSON string\n * - Automatically compresses with lz-string\n * - Helps reduce size of complex objects\n *\n * **Warning:**\n *\n * - Still larger than specialized encodings even with compression\n * - Use only when necessary\n * - Consider creating custom sparseMap encoding instead\n */\nexport type JsonFieldType = {\n type: \"json\"\n}\n\n/** Union of all available field types. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Generic type parameter for field values\nexport type FieldType<TValue = any> =\n | BitArrayFieldType\n | IntArrayFieldType\n | IntFieldType\n | StringFieldType\n | StringArrayFieldType\n | SparseMapFieldType<TValue>\n | JsonFieldType\n\n/**\n * Function that migrates data from one version to another.\n *\n * **When to use:**\n *\n * - Add new fields with default values\n * - Transform existing field values\n * - Rename or restructure fields\n *\n * **Important:**\n *\n * - Migrations operate on decoded data objects, not strings\n * - Each migration goes from version N to version N+1\n * - Migrations are applied sequentially\n *\n * **Example:**\n *\n * ```typescript\n * migrations: {\n * 0: (oldData) => ({\n * ...oldData,\n * newField: 'default value'\n * }),\n * 1: (oldData) => ({\n * ...oldData,\n * name: oldData.name.toUpperCase()\n * })\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Generic type parameters for migration input/output\nexport type DataMigration<TFrom = any, TTo = any> = (data: TFrom) => TTo\n\n/**\n * Map of version numbers to migration functions.\n *\n * Keys are the source version numbers (0, 1, 2, etc.)\n * Values are functions that migrate from that version to the next\n */\nexport type MigrationMap = {\n [fromVersion: number]: DataMigration\n}\n\n/**\n * Complete schema definition for encoding/decoding data.\n *\n * **Basic usage:**\n *\n * ```typescript\n * const schema = defineSchema({\n * version: 1,\n * fields: {\n * name: { type: \"string\" },\n * age: { type: \"int\" },\n * },\n * })\n * ```\n *\n * **With custom delimiter:**\n *\n * ```typescript\n * const schema = defineSchema({\n * version: 1,\n * delimiter: '|', // Use | instead of :\n * fields: { ... }\n * })\n * ```\n *\n * **With migrations:**\n *\n * ```typescript\n * const schema = defineSchema({\n * version: 2,\n * fields: {\n * name: { type: \"string\" },\n * value: { type: \"int\" },\n * },\n * migrations: {\n * 0: (old) => ({ ...old, value: 0 }),\n * 1: (old) => ({ ...old, name: old.name.toUpperCase() }),\n * },\n * })\n * ```\n *\n * @param version - Current schema version (increment when making breaking changes)\n * @param delimiter - Character to separate fields (default: ':')\n * @param fields - Map of field names to field type definitions\n * @param migrations - Optional map of version migrations\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Generic type parameter for schema data, and field values need 'any' for flexibility\nexport type Schema<TData = any> = {\n version: number\n delimiter?: string\n fields: {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Field values can be any type\n [K in keyof TData]: FieldType<any>\n }\n migrations?: MigrationMap\n}\n\n/**\n * Result of creating an encoder from a schema.\n *\n * **Usage:**\n *\n * ```typescript\n * const { encode, decode, migrate } = createEncoder(schema, context)\n *\n * // Encode data to string\n * const inputString = encode(data)\n *\n * // Decode string to data\n * const data = decode(inputString)\n *\n * // Migrate old version to current version\n * const currentVersion = migrate(oldInputString)\n * ```\n */\nexport type EncoderResult<TData> = {\n encode: (data: TData) => string\n decode: (str: string) => TData\n migrate: (str: string) => string\n}\n\n/**\n * Define a typed schema for encoding/decoding game state.\n *\n * **Purpose:**\n *\n * - Provides type inference for encode/decode functions\n * - Documents the structure of your input strings\n * - Enables version migrations\n *\n * **Example:**\n *\n * ```typescript\n * type GameData = {\n * revealed: boolean[]\n * score: number\n * annotations: Record<string, Annotation>\n * }\n *\n * export const schema = defineSchema<GameData>({\n * version: 1,\n * fields: {\n * revealed: { type: \"bitArray\" },\n * score: { type: \"int\" },\n * annotations: {\n * type: \"sparseMap\",\n * valueEncoder: (ann) => `${ann.level}.${ann.color}`,\n * valueDecoder: (str) => {\n * const [level, color] = str.split(\".\").map(Number)\n * return { level, color }\n * },\n * },\n * },\n * })\n * ```\n */\nexport function defineSchema<TData>(schema: Schema<TData>): Schema<TData> {\n return schema\n}\n","import type { Schema, EncoderResult } from \"./types\"\nimport { encode } from \"./encoder\"\nimport { decode } from \"./decoder\"\nimport { createMigrator } from \"./migration\"\n\nexport { defineSchema } from \"./types\"\nexport type {\n Schema,\n EncoderResult,\n FieldType,\n BitArrayFieldType,\n IntArrayFieldType,\n IntFieldType,\n StringFieldType,\n StringArrayFieldType,\n SparseMapFieldType,\n JsonFieldType,\n DataMigration,\n MigrationMap,\n} from \"./types\"\n\n/**\n * Create an encoder/decoder for a schema-defined data structure.\n *\n * **Basic usage:**\n *\n * ```typescript\n * import { defineSchema, createEncoder } from \"@puzzmo/sdk/inputs\"\n *\n * const schema = defineSchema({\n * version: 1,\n * fields: {\n * name: { type: \"string\" },\n * age: { type: \"int\" },\n * },\n * })\n *\n * const { encode, decode } = createEncoder(schema)\n *\n * const data = { name: \"Alice\", age: 30 }\n * const inputString = encode(data) // \"v1:Alice:30\"\n * const decoded = decode(inputString) // { name: 'Alice', age: 30 }\n * ```\n *\n * **With context (for length-dependent fields):**\n *\n * ```typescript\n * const schema = defineSchema({\n * version: 1,\n * fields: {\n * revealed: { type: \"bitArray\" },\n * scores: { type: \"intArray\" },\n * },\n * })\n *\n * const { encode, decode } = createEncoder(schema, {\n * revealed: { length: 100 }, // Required for bitArray decoding\n * scores: { length: 10 }, // Required for sparse intArray decoding\n * annotations: { keys: tileIds }, // Optional: optimize sparseMap with numeric indices\n * })\n * ```\n *\n * **With migrations:**\n *\n * ```typescript\n * const { encode, decode, migrate } = createEncoder(schema)\n *\n * const oldString = \"v0:Alice:30\"\n * const migrated = migrate(oldString) // \"v1:Alice:30:default\"\n * const data = decode(migrated)\n * ```\n *\n * @param schema - Schema definition created with defineSchema()\n * @param context - Optional context for decoding (lengths for bitArray/intArray)\n * @returns Object with encode, decode, and migrate functions\n */\nexport function createEncoder<TData>(\n schema: Schema<TData>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Context values can be any shape depending on field types\n context?: Record<string, any>,\n): EncoderResult<TData> {\n const migrator = createMigrator(schema)\n\n return {\n encode: (data: TData) => encode(schema, data, context),\n decode: (str: string) => decode(schema, str, context),\n migrate: (str: string) => migrator(str, context),\n }\n}\n"],"x_google_ignoreList":[5],"mappings":"w0DAkCA,IAAM,EAAA,UAAA,mBACJ,EACA,EACA,EACA,EACG,CACH,GAAI,CACF,IAAM,EAAA,EAAA,EAAA,EAAA,CACD,EAAA,CAAA,EAAA,CAAA,CACH,YACA,wBACA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