@puzzmo/sdk 1.0.59 → 1.0.61
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/bootstrapPayload.d.ts +8 -0
- package/dist/bootstrapPayload.d.ts.map +1 -0
- package/dist/contracts.d.ts +1 -1
- package/dist/{createSimulator-Dory7qUL.js → createSimulator-CdInpCHG.js} +220 -202
- package/dist/{createSimulator-Dory7qUL.js.map → createSimulator-CdInpCHG.js.map} +1 -1
- package/dist/{createSimulator-kGIstLy9.cjs → createSimulator-PNeBoNux.cjs} +22 -22
- package/dist/{createSimulator-kGIstLy9.cjs.map → createSimulator-PNeBoNux.cjs.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +229 -179
- package/dist/index.js.map +1 -1
- package/dist/inputs/index.cjs +1 -1
- package/dist/inputs/index.js +1 -1
- package/dist/pico8/index.cjs +1 -1
- package/dist/pico8/index.cjs.map +1 -1
- package/dist/pico8/index.d.ts +6 -10
- package/dist/pico8/index.d.ts.map +1 -1
- package/dist/pico8/index.js +8 -12
- package/dist/pico8/index.js.map +1 -1
- package/dist/sdk.d.ts.map +1 -1
- package/dist/simulator/createSimulator.d.ts.map +1 -1
- package/dist/simulator/index.cjs +1 -1
- package/dist/simulator/index.js +1 -1
- package/dist/simulator/standalone.cjs +1 -1
- package/dist/simulator/standalone.js +1 -1
- package/dist/types.d.ts +99 -50
- package/dist/types.d.ts.map +1 -1
- package/dist/vite.cjs +3 -3
- package/dist/vite.js +26 -26
- package/package.json +1 -1
- /package/dist/{asyncToGenerator-Dn36a-ch.js → asyncToGenerator-BotOOyB7.js} +0 -0
- /package/dist/{asyncToGenerator-DANjdFmB.cjs → asyncToGenerator-DIL7svO7.cjs} +0 -0
- /package/dist/{objectSpread2-C8x7fbpH.js → objectSpread2-BQwrzeNG.js} +0 -0
- /package/dist/{objectSpread2-DLgRiGrq.cjs → objectSpread2-CCAs_T0X.cjs} +0 -0
- /package/dist/{objectWithoutProperties-BVU0RRck.js → objectWithoutProperties-Bjd1IAMi.js} +0 -0
- /package/dist/{objectWithoutProperties-ChRmjIUS.cjs → objectWithoutProperties-Ee8z5QMa.cjs} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/gameTracker.ts","../src/analytics.ts","../src/sdk.ts","../src/keyboard.ts","../src/editor.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) {\n if (!state.tracked.gameplayActive) {\n sendGameAnalyticsEvent(state.context, \"gameplay_active\")\n state.tracked.gameplayActive = true\n }\n if (!state.tracked.active30s) {\n sendGameAnalyticsEvent(state.context, \"active_30s\")\n state.tracked.active30s = true\n }\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 AvailableHaptics,\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/** Device haptics. The host owns the player's setting and the device bridge; a game only asks. */\nexport interface SDKHaptics {\n /**\n * Ask the host to fire a haptic. Fire-and-forget: it is never awaited, never reports back, and\n * is a no-op wherever the host can't deliver one, so a game can call it freely.\n *\n * Where it actually fires:\n *\n * - **Puzzmo's iOS app** — real UIKit haptics, via the native bridge.\n * - **puzzmo.com on Android/desktop** — approximated with `navigator.vibrate` by the page, which is why this goes to the host rather than\n * vibrating from the game. Chrome blocks `navigator.vibrate` outright in cross-origin iframes (since Chrome 55), and games run in one,\n * so a game calling it directly is silently ignored with no way to opt in — there is no Permissions-Policy feature for it.\n * - **Embeds** — no haptic. Our frame is cross-origin to the host page, so the block above applies to the host too, and there is no native\n * bridge. The cue is still forwarded to the host page on the private message stream, so a partner can action it themselves.\n *\n * Haptics are also off entirely when the player has turned them off, and the OS may drop them\n * in silent/DND or on hardware without a motor.\n *\n * @param haptic Which feel to ask for. Named after the iOS generators; other hosts approximate.\n * @param options `id` names the cue this haptic belongs to, for host logs and the simulator.\n */\n play: (haptic: AvailableHaptics, options?: { id?: string }) => 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 /** Device haptics, where the host can deliver them. See `SDKHaptics.play` for where that is. */\n haptics: SDKHaptics\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 | \"SENSORY_EVENT\"\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 /** Set the total penalty time in milliseconds, for games which derive it from their state */\n setPenalty: (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 setPenalty: (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 setPenalty: (ms: number) => internalTimer.setPenalty(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 haptics: {\n play: (haptic, options) => {\n hostAPI.sendMessage(\"SENSORY_EVENT\", { id: options?.id ?? haptic, haptic })\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, KeyStyleRule, KeyStyles } 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\n/**\n * Expands per-key-set styling rules into the `individualKeyStyles` map a `KeyboardConfig` carries,\n * so a game can style a group of keys in one go. Later rules win where two name the same key.\n *\n * @example\n * sdk.keyboard.show({\n * ...defaultKeyboardConfig,\n * individualKeyStyles: keyStylesFromRules([{ keys: usedLetters, text: { opacity: \"0.4\" } }]),\n * })\n */\nexport const keyStylesFromRules = (rules: KeyStyleRule[]): Record<string, KeyStyles> => {\n const styles: Record<string, KeyStyles> = {}\n for (const rule of rules) {\n for (const key of rule.keys) {\n const merged: KeyStyles = {}\n const text = { ...styles[key]?.text, ...rule.text }\n const background = { ...styles[key]?.background, ...rule.background }\n // Only the groups a rule actually set, so a text-only rule doesn't carry an empty background\n // for every key it names.\n if (Object.keys(text).length) merged.text = text\n if (Object.keys(background).length) merged.background = background\n styles[key] = merged\n }\n }\n return styles\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"],"mappings":";;;AAkCA,IAAM,IAAA,WAAA;sBACJ,GACA,GACA,GACA,GACG;AACH,MAAI;GACF,IAAM,IAAA,EAAA,EAAA,EAAA,EACD,EAAA,EAAA,EAAA,EAAA;IACH;IACA;IACA;KACD,EAEK,IAAW,MAAM,MAAM,GAAG,EAAQ,QAAQ,SAAS;IACvD,QAAQ;IACR,SAAS,EACP,gBAAgB,oBACjB;IACD,MAAM,KAAK,UAAU,EAAK;IAE1B,WAAW;IACZ,CAAC;AAEF,GAAK,EAAS,MACZ,QAAQ,KAAK,2BAA2B,EAAU,KAAK,EAAS,OAAO,GAAG,EAAS,aAAa;WAE3F,GAAO;AACd,WAAQ,KAAK,0BAA0B,KAAa,EAAM;;;iBA3B5D,GACA,GACA,GACA,GAAA;;;;AA4BF,MAAa,KAA8B,MAAkC;CAC3E,IAAM,IAA4B;EAChC;EACA,aAAa;EACb,2BAAW,IAAI,MAAM;EAC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,KAAsB,MAAqD;CACtF,IAAM,IAAoC,EAAE;AAC5C,MAAK,IAAM,KAAQ,EACjB,MAAK,IAAM,KAAO,EAAK,MAAM;;EAC3B,IAAM,IAAoB,EAAE,EACtB,IAAA,EAAA,EAAA,EAAA,GAAA,IAAY,EAAO,OAAA,OAAA,KAAA,IAAA,EAAM,KAAA,EAAS,EAAK,KAAM,EAC7C,IAAA,EAAA,EAAA,EAAA,GAAA,IAAkB,EAAO,OAAA,OAAA,KAAA,IAAA,EAAM,WAAA,EAAe,EAAK,WAAY;AAKrE,EAFI,OAAO,KAAK,EAAK,CAAC,WAAQ,EAAO,OAAO,IACxC,OAAO,KAAK,EAAW,CAAC,WAAQ,EAAO,aAAa,IACxD,EAAO,KAAO;;AAGlB,QAAO;;;ACbT,IAAa,IAAb,cAAuC,MAAM;CAC3C,YACE,GACA,GACA,GACA;AAEA,EADA,MAAM,EAAQ,EAJP,KAAA,OAAA,GAEA,KAAA,gBAAA,GAGP,KAAK,OAAO"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/bootstrapPayload.ts","../src/gameTracker.ts","../src/analytics.ts","../src/sdk.ts","../src/keyboard.ts","../src/editor.ts"],"sourcesContent":["import type { BootstrapGame, BootstrapGameData, BootstrapSession } from \"./types\"\n\n/**\n * READY_DATA as hosts from before the payload split send it: the gameplay with the puzzle nested\n * inside it, and a flattened game inside that. Deliberately not part of the SDK's public types.\n */\ntype LegacyReadyData = Omit<BootstrapGameData, \"game\" | \"session\"> & {\n game?: BootstrapGame\n session?: BootstrapSession\n startOrFindGameplay?: {\n gamePlayed?: BootstrapSession[\"gameplay\"] & { puzzle: BootstrapSession[\"puzzle\"] & { game?: any; viewerMetadata?: unknown } }\n }\n}\n\n/**\n * Fills in `game` and `session` when READY_DATA comes from a host which only sends the older\n * `startOrFindGameplay` nesting, so the SDK and games only ever see the new shape. A copy of\n * upgradeBootstrapGameData in @puzzmo-com/shared, which the SDK can't depend on.\n */\nexport const normalizeReadyData = (received: unknown): BootstrapGameData => {\n const { startOrFindGameplay, ...data } = received as LegacyReadyData\n if (data.game) return data as BootstrapGameData\n\n const gamePlayed = startOrFindGameplay?.gamePlayed\n const game = gameFromLegacy(gamePlayed?.puzzle?.game ?? {})\n if (!gamePlayed) return { ...data, game }\n\n const { puzzle, ...gameplay } = gamePlayed\n const { game: _game, viewerMetadata, ...puzzleFields } = puzzle\n return { ...data, game, session: { gameplay, puzzle: puzzleFields }, viewerMetadata: data.viewerMetadata ?? viewerMetadata }\n}\n\n/** Builds the game from the flattened fields older hosts put on `puzzle.game`, with no version IDs */\nconst gameFromLegacy = (game: any): BootstrapGame => {\n const flags = game.flagsArr\n return {\n id: game.id ?? \"\",\n slug: game.slug ?? \"\",\n stableSlug: game.stableSlug ?? game.slug ?? \"\",\n displayName: game.displayName ?? \"\",\n version: {\n id: \"\",\n label: null,\n featuresArr: game.featuresArr ?? [0],\n flagsArr: Array.isArray(flags) ? flags : typeof flags === \"number\" ? [flags] : [0],\n runtime: {\n id: \"\",\n version:\n game.assetsSha || game.assetsBaseURL\n ? { id: \"\", assetsSha: game.assetsSha ?? \"\", assetsBaseURL: game.assetsBaseURL ?? \"\" }\n : null,\n },\n },\n }\n}\n","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) {\n if (!state.tracked.gameplayActive) {\n sendGameAnalyticsEvent(state.context, \"gameplay_active\")\n state.tracked.gameplayActive = true\n }\n if (!state.tracked.active30s) {\n sendGameAnalyticsEvent(state.context, \"active_30s\")\n state.tracked.active30s = true\n }\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 session = readyData?.session\n if (!session) return null\n\n const gameplay = session.gameplay\n const puzzle: any = session.puzzle\n const hostContext: any[] = (readyData?.hostContext as any[]) ?? []\n\n return {\n gameSlug: readyData?.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 flagValue = readyData?.game?.version.flagsArr[0] ?? 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 { normalizeReadyData } from \"./bootstrapPayload\"\nimport { 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 AvailableHaptics,\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/** Device haptics. The host owns the player's setting and the device bridge; a game only asks. */\nexport interface SDKHaptics {\n /**\n * Ask the host to fire a haptic. Fire-and-forget: it is never awaited, never reports back, and\n * is a no-op wherever the host can't deliver one, so a game can call it freely.\n *\n * Where it actually fires:\n *\n * - **Puzzmo's iOS app** — real UIKit haptics, via the native bridge.\n * - **puzzmo.com on Android/desktop** — approximated with `navigator.vibrate` by the page, which is why this goes to the host rather than\n * vibrating from the game. Chrome blocks `navigator.vibrate` outright in cross-origin iframes (since Chrome 55), and games run in one,\n * so a game calling it directly is silently ignored with no way to opt in — there is no Permissions-Policy feature for it.\n * - **Embeds** — no haptic. Our frame is cross-origin to the host page, so the block above applies to the host too, and there is no native\n * bridge. The cue is still forwarded to the host page on the private message stream, so a partner can action it themselves.\n *\n * Haptics are also off entirely when the player has turned them off, and the OS may drop them\n * in silent/DND or on hardware without a motor.\n *\n * @param haptic Which feel to ask for. Named after the iOS generators; other hosts approximate.\n * @param options `id` names the cue this haptic belongs to, for host logs and the simulator.\n */\n play: (haptic: AvailableHaptics, options?: { id?: string }) => 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 /** Device haptics, where the host can deliver them. See `SDKHaptics.play` for where that is. */\n haptics: SDKHaptics\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 | \"SENSORY_EVENT\"\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 /** Set the total penalty time in milliseconds, for games which derive it from their state */\n setPenalty: (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 setPenalty: (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\n/**\n * The host<->game contract this SDK is built against, declared in READY and READY_GAME_LOADED.\n * Stays \"1.0\" until every host supporting \"1.1\" is deployed: an older puzzmo.com reloads when it\n * sees a contract it doesn't know.\n */\nconst sdkRuntimeContract = \"1.0\"\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?.session?.gameplay\n const getGameplayID = () => getGameplay()?.id ?? null\n const getPuzzleString = () => readyData?.session?.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 = normalizeReadyData(data as MessagesReceived[\"READY_DATA\"])\n readyData = bootstrapData\n\n const gamePlayed = bootstrapData.session?.gameplay\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 = bootstrapData.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 setPenalty: (ms: number) => internalTimer.setPenalty(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\", { runtimeContract: sdkRuntimeContract })\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: sdkRuntimeContract,\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 haptics: {\n play: (haptic, options) => {\n hostAPI.sendMessage(\"SENSORY_EVENT\", { id: options?.id ?? haptic, haptic })\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, KeyStyleRule, KeyStyles } 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\n/**\n * Expands per-key-set styling rules into the `individualKeyStyles` map a `KeyboardConfig` carries,\n * so a game can style a group of keys in one go. Later rules win where two name the same key.\n *\n * @example\n * sdk.keyboard.show({\n * ...defaultKeyboardConfig,\n * individualKeyStyles: keyStylesFromRules([{ keys: usedLetters, text: { opacity: \"0.4\" } }]),\n * })\n */\nexport const keyStylesFromRules = (rules: KeyStyleRule[]): Record<string, KeyStyles> => {\n const styles: Record<string, KeyStyles> = {}\n for (const rule of rules) {\n for (const key of rule.keys) {\n const merged: KeyStyles = {}\n const text = { ...styles[key]?.text, ...rule.text }\n const background = { ...styles[key]?.background, ...rule.background }\n // Only the groups a rule actually set, so a text-only rule doesn't carry an empty background\n // for every key it names.\n if (Object.keys(text).length) merged.text = text\n if (Object.keys(background).length) merged.background = background\n styles[key] = merged\n }\n }\n return styles\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"],"mappings":";;;SAoBU,sBAAA,EAAA,IAAA,CAOA,SAAA,EAAA,IAAA,CACA,QAAa,iBAAA;;;;;;AATvB,MAAa,KAAsB,MAAyC;;CAC1E,IA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,EACtB,CAAI,EAAU,SAAS,UAAS,OAAO,OAAO,GAAU,EAA+B,EAAU,QAAQ,CAAC,GACjG,UAAU,MAAW,EAAS,EAAU,QAAQ,EAAU;AAErE,QAAO;;;;;;;;;;;;;;AC5uBT,MAAa,IAAwC;CACnD,QAAQ;EAAC;EAAc;EAAa;EAAa,KAAA;EAAU;CAC3D,SAAS;EAAE,KAAK;EAAS,KAAK;EAAO;CACrC,WAAW,CAAC,KAAK,IAAI;CACrB,UAAU,EAAE;CACZ,IAAI,EAAE;CACN,GAAG,CAAC,KAAK,IAAI;CACb,oBAAoB;CACrB,EAYY,KAAsB,MAAqD;CACtF,IAAM,IAAoC,EAAE;AAC5C,MAAK,IAAM,KAAQ,EACjB,MAAK,IAAM,KAAO,EAAK,MAAM;;EAC3B,IAAM,IAAoB,EAAE,EACtB,IAAA,EAAA,EAAA,EAAA,GAAA,IAAY,EAAO,OAAA,OAAA,KAAA,IAAA,EAAM,KAAA,EAAS,EAAK,KAAM,EAC7C,IAAA,EAAA,EAAA,EAAA,GAAA,IAAkB,EAAO,OAAA,OAAA,KAAA,IAAA,EAAM,WAAA,EAAe,EAAK,WAAY;AAKrE,EAFI,OAAO,KAAK,EAAK,CAAC,WAAQ,EAAO,OAAO,IACxC,OAAO,KAAK,EAAW,CAAC,WAAQ,EAAO,aAAa,IACxD,EAAO,KAAO;;AAGlB,QAAO;;;ACbT,IAAa,IAAb,cAAuC,MAAM;CAC3C,YACE,GACA,GACA,GACA;AAEA,EADA,MAAM,EAAQ,EAJP,KAAA,OAAA,GAEA,KAAA,gBAAA,GAGP,KAAK,OAAO"}
|
package/dist/inputs/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../objectSpread2-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../objectSpread2-CCAs_T0X.cjs`);require(`../vite.cjs`);let t=require(`lz-string`);function n(e){if(e.length===0)return`0`;let t=``;for(let n=0;n<e.length;n+=4){let r=0;for(let t=0;t<4&&n+t<e.length;t++)e[n+t]&&(r|=1<<t);t+=r.toString(16)}return t||`0`}function r(e,t){let n=[];for(let r=0;r<t;r++){let t=Math.floor(r/4),i=r%4,a=parseInt(e[t]||`0`,16);n.push((a&1<<i)!=0)}return n}function i(e){if(e.length===0)return``;let t=e.map((e,t)=>({val:e,idx:t})).filter(e=>e.val!==0);return t.length===0?``:t.length>e.length/2?e.join(`,`):t.map(e=>`${e.idx}=${e.val}`).join(`,`)}function a(e,t){if(!e)return t?Array.from({length:t},()=>0):[];if(e.includes(`=`)){let n=t?Array.from({length:t},()=>0):[],r=e.split(`,`);for(let e of r){let[t,r]=e.split(`=`),i=Number(t),a=Number(r);!isNaN(i)&&!isNaN(a)&&(n[i]=a)}return n}return e.split(`,`).map(e=>Number(e))}function o(e,t=`,`){return e.join(t)}function s(e,t=`,`){return e?e.split(t):[]}function c(e){return(0,t.compressToEncodedURIComponent)(JSON.stringify(e))}function l(e){if(!e)return;let n=(0,t.decompressFromEncodedURIComponent)(e);return n?JSON.parse(n):void 0}function u(e,t,n){let r=Object.entries(e).filter(([e,t])=>t!=null);return n?r.map(([e,r])=>{let i=n.indexOf(e);return i===-1?null:`${i}=${t(r)}`}).filter(e=>e!==null).join(`,`):r.map(([e,n])=>`${e}=${t(n)}`).join(`;`)}function d(e,t,n){if(!e)return{};let r={};if(n){let i=e.split(`,`);for(let e of i){if(!e)continue;let[i,a]=e.split(`=`),o=Number(i);!isNaN(o)&&a&&n[o]&&(r[n[o]]=t(a))}}else{let n=e.split(`;`);for(let e of n){if(!e)continue;let[n,i]=e.split(`=`);n&&i&&(r[n]=t(i))}}return r}function f(e,t,r){switch(t.type){case`bitArray`:return n(e);case`intArray`:return i(e);case`int`:return String(e);case`string`:return String(e);case`stringArray`:return o(e,t.delimiter);case`sparseMap`:return u(e,t.valueEncoder,r==null?void 0:r.keys);case`json`:return c(e);default:throw Error(`Unknown field type: ${t.type}`)}}function p(e,t,n){let r=e.delimiter||`:`,i=Object.keys(e.fields).map(r=>{let i=e.fields[r],a=t[r];return f(a,i,n==null?void 0:n[r])});return`v${e.version}${r}${i.join(r)}`}function m(e,t,n){switch(t.type){case`bitArray`:if(!(n!=null&&n.length))throw Error(`bitArray requires length in context`);return r(e,n.length);case`intArray`:return a(e,n==null?void 0:n.length);case`int`:return Number(e);case`string`:return e;case`stringArray`:return s(e,t.delimiter);case`sparseMap`:return d(e,t.valueDecoder,n==null?void 0:n.keys);case`json`:return l(e);default:throw Error(`Unknown field type: ${t.type}`)}}function h(e,t,n){let r=e.delimiter||`:`,i=t.split(r),a=i[0],o=a.match(/^v(\d+)$/);if(!o)throw Error(`Invalid input string format: ${a}`);let s=Number(o[1]);if(s!==e.version)throw Error(`Version mismatch: expected v${e.version}, got v${s}. Make sure to run migrations first.`);let c=Object.keys(e.fields),l={};for(let t=0;t<c.length;t++){let r=c[t],a=e.fields[r];l[r]=m(i[t+1]||``,a,n==null?void 0:n[r])}return l}function g(t){return function(n,r){let i=n.match(/^v(\d+)/);if(!i)throw Error(`Invalid input string: no version found`);let a=Number(i[1]);if(a===t.version)return n;if(!t.migrations)throw Error(`No migrations defined for schema. Cannot migrate from v${a} to v${t.version}`);let o=h(e.t(e.t({},t),{},{version:a}),n,r);for(let e=a;e<t.version;e++){let n=t.migrations[e];n&&(o=n(o))}return p(t,o,r)}}function _(e){return e}function v(e,t){let n=g(e);return{encode:n=>p(e,n,t),decode:n=>h(e,n,t),migrate:e=>n(e,t)}}exports.createEncoder=v,exports.defineSchema=_;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/inputs/index.js
CHANGED
package/dist/pico8/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../objectSpread2-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../objectSpread2-CCAs_T0X.cjs`),t=require(`../asyncToGenerator-DIL7svO7.cjs`),n=require(`../lua-D5xtGGen.cjs`),r={HELLO:1,PALETTE:2,READY:3,START:4,PAUSE:5,RETRY:6,PUZZLE_PART:7,PROGRESS_PART:8},i={BOOT:1,LOADED:2,FINISHED:3,SAVE_PART:4,SAVE:5,DEED:6,COMPLETE:7};var a=e=>Math.max(0,Math.min(255,Math.round(e)||0)),o=class{constructor(t,n,r,i=20){e.n(this,`inSeq`,0),e.n(this,`outSeq`,0),e.n(this,`pending`,null),e.n(this,`wait`,0),e.n(this,`queue`,[]),this.mem=t,this.myBase=n,this.peerBase=r,this.resendAfter=i}send(e,t=[]){if(t.length>60)throw Error(`PICO-8 payloads are at most 60 bytes, op ${e} has ${t.length}`);this.queue.push({op:a(e),payload:Array.from(t,a)})}get backlog(){return this.queue.length+(this.pending?1:0)}tick(){var e;let t=[],n=this.read(this.peerBase);if(this.inSeq!==0&&this.write(this.myBase+3,this.inSeq),n!==0&&n!==this.inSeq){this.inSeq=n,this.write(this.myBase+3,n);let e=Math.min(this.read(this.peerBase+2),60),r=[];for(let t=0;t<e;t++)r.push(this.read(this.peerBase+4+t));t.push({op:this.read(this.peerBase+1),payload:r})}this.pending&&this.read(this.peerBase+3)===this.outSeq&&(this.pending=null);let r=this.pending;if(r){if(++this.wait<this.resendAfter)return t}else{var i;if(r=(i=this.queue.shift())==null?null:i,!r)return t;this.outSeq=this.outSeq%255+1}for(let t=0;t<60;t++)this.write(this.myBase+4+t,(e=r.payload[t])==null?0:e);return this.write(this.myBase+1,r.op),this.write(this.myBase+2,r.payload.length),this.write(this.myBase,this.outSeq),this.pending=r,this.wait=0,t}read(e){let t=this.mem[e];return typeof t==`number`&&t>=0?t&255:0}write(e,t){this.mem[e]=a(t)}};const s=[[0,0,0,0],[29,43,83,1],[126,37,83,2],[0,135,81,3],[171,82,54,4],[95,87,79,5],[194,195,199,6],[255,241,232,7],[255,0,77,8],[255,163,0,9],[255,236,39,10],[0,228,54,11],[41,173,255,12],[131,118,156,13],[255,119,168,14],[255,204,170,15],[41,24,20,128],[17,29,53,129],[66,33,54,130],[18,83,89,131],[116,47,41,132],[73,51,59,133],[162,136,121,134],[243,239,125,135],[190,18,80,136],[255,108,36,137],[168,231,46,138],[0,181,67,139],[6,90,181,140],[117,70,101,141],[255,110,89,142],[255,157,129,143]];var c=e=>{let t=e.replace(`#`,``);return/^[0-9a-f]{6}/i.test(t)?[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]:null};function l(e,t){let n=c(e);if(!n)return null;let r=null,i=1/0;for(let[e,a,o,c]of s){if(t!=null&&t.has(c))continue;let s=2*Math.pow(e-n[0],2)+4*Math.pow(a-n[1],2)+3*Math.pow(o-n[2],2);s<i&&(i=s,r=c)}return r}function u(e){let t=new Set,n=[];for(let i=0;i<16;i++){let a=e[i];if(typeof a==`number`)n.push(a);else if(typeof a==`string`){var r;let e=(r=l(a,t))==null?i:r;t.add(e),n.push(e)}else n.push(i)}return n}var d=()=>{let e=globalThis,t=e.pico8_gpio&&e.pico8_gpio.length>=128?e.pico8_gpio:e.pico8_gpio=Array(128);for(let e=0;e<128;e++)typeof t[e]!=`number`&&(t[e]=0);return t},f=e=>Array.from(e,e=>{let t=e.charCodeAt(0);return t<256?t:63}),p=e=>String.fromCharCode(...e),m=e=>{let t=[];for(let n=0;n<e.length;n+=60)t.push(e.slice(n,n+60));return t};function h(e){return g.apply(this,arguments)}function g(){return g=t.t(function*(t,n={}){let{puzzleString:r,inputString:i,completed:a}=yield t.gameReady();return _(e.t(e.t({},n),{},{sdk:t,completed:a,puzzleString:r,inputString:i}))}),g.apply(this,arguments)}function _(t){var n,a;let{sdk:s,debug:c=!1}=t,l=new o((n=t.memory)==null?d():n,0,64),h=t.palette?u(t.palette):null,g={started:!1,paused:!1,loaded:!1,reopened:!!t.completed,completed:!!t.completed,progress:(a=t.inputString)==null?``:a,saving:[],deeds:[]},_=(e,t,n)=>{c&&console.log(`[pico8] ${e} op ${t}`,Array.from(n))},v=(e,t=[])=>{_(`page -> cart`,e,t),l.send(e,t)},y=(e,t)=>{if(e<16)throw Error(`PICO-8 ops below 16 belong to the bridge, got ${e}`);v(e,t)},b=(n,a)=>{if(_(`cart -> page`,n,a),n===i.BOOT){var o;if(v(r.HELLO,[g.completed?1:0]),h&&v(r.PALETTE,h),t.puzzleString)for(let e of m(f(t.puzzleString)))v(r.PUZZLE_PART,e);if(g.progress)for(let e of m(f(g.progress)))v(r.PROGRESS_PART,e);(o=t.onBoot)==null||o.call(t,y),v(r.READY),g.started&&v(r.START),g.paused&&v(r.PAUSE,[1])}else if(n===i.LOADED)g.loaded||s.gameLoaded(),g.loaded=!0;else if(n===i.FINISHED){if(g.reopened)return;t.onFinished?t.onFinished():s.showCompletionScreen([])}else if(n===i.SAVE_PART)g.saving.push(...a);else if(n===i.SAVE){let e=p([...g.saving,...a]);if(g.saving=[],e===g.progress)return;g.progress=e,s.updateGameState(e)}else if(n===i.DEED){let[t=0,n=0,r=0,...i]=a,o={id:p(i),value:t*256+n};g.deeds=g.deeds.filter(e=>e.id!==o.id),g.deeds.push(r?e.t(e.t({},o),{},{persist:!0}):o)}else if(n===i.COMPLETE){if(g.completed)return;let[e=0,t=0]=a;s.gameCompleted({inputString:g.progress,pointsAwarded:e*256+t,completed:!0},{deeds:g.deeds}),g.completed=!0,g.deeds=[]}else if(n>=16){var c;(c=t.onMessage)==null||c.call(t,n,a,y)}};s.on(`start`,()=>{g.started=!0,v(r.START)}),s.on(`pause`,()=>{g.paused=!0,v(r.PAUSE,[1])}),s.on(`resume`,()=>{g.paused=!1,v(r.PAUSE,[0])}),s.on(`retry`,()=>{var e;g.reopened=!1,g.completed=!1,g.progress=``,g.deeds=[],(e=t.onRetry)==null||e.call(t),v(r.RETRY)});let x=()=>{for(let{op:e,payload:t}of l.tick())b(e,t)},S=null,C=()=>{x(),S=requestAnimationFrame(C)};return t.autoTick!==!1&&typeof requestAnimationFrame==`function`&&(S=requestAnimationFrame(C)),{send:y,tick:x,stop:()=>{S!==null&&cancelAnimationFrame(S),S=null},get backlog(){return l.backlog}}}exports.CartOp=i,exports.PageOp=r,exports.Pico8Channel=o,exports.createPico8Bridge=_,exports.createPico8Game=h,exports.firstGameOp=16,exports.maxPayload=60,exports.nearestPico8Colour=l,exports.pico8HardwareColours=s,exports.puzzmoLua=n.t,exports.resolvePico8Palette=u;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/pico8/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/pico8/protocol.ts","../../src/pico8/channel.ts","../../src/pico8/palette.ts","../../src/pico8/index.ts"],"sourcesContent":["/**\n * The PICO-8 bridge's wire format. PICO-8 mirrors the 128 bytes at 0x5f80 into a JavaScript array called\n * `pico8_gpio` once a frame, in both directions, and this splits them into two mailboxes. Each side only ever writes\n * to its own half: a byte written by both ends can lose one of the writes when the frame syncs.\n *\n * 0x00..0x3f page -> cart (only JavaScript writes)\n * 0x40..0x7f cart -> page (only Lua writes)\n *\n * Each mailbox holds one message:\n *\n * +0 seq 0 = nothing sent yet, else 1..255 wrapping back to 1\n * +1 op opcode\n * +2 len payload length, 0..60\n * +3 ack the last seq this side has read from the other side\n * +4..+63 payload\n *\n * Ops below 16 belong to the bridge, a game uses 16 and up. The Lua half is in ./lua.ts.\n */\n\nexport const gpioSize = 128\nexport const pageBase = 0\nexport const cartBase = 64\nexport const maxPayload = 60\n\n/** The first op a game can use for its own messages. */\nexport const firstGameOp = 16\n\n/** Page -> cart */\nexport const PageOp = {\n /** `[flags]`, bit 0: this play was already completed. First thing sent after every BOOT. */\n HELLO: 1,\n /** 16 bytes: the PICO-8 hardware colour for each draw colour, applied with `pal(i, c, 1)` */\n PALETTE: 2,\n /** Everything is sent: the cart sets `pz.puzzle`, `pz.progress` and `pz.ready`, calls `pz_on_ready()`, and answers LOADED */\n READY: 3,\n /** The host started the game */\n START: 4,\n /** `[0 or 1]` */\n PAUSE: 5,\n /** The player restarted the puzzle */\n RETRY: 6,\n /** Up to 60 characters of the puzzle string. It arrives in pieces after HELLO, and READY marks the end. */\n PUZZLE_PART: 7,\n /** Up to 60 characters of the player's saved progress, the same way. */\n PROGRESS_PART: 8,\n} as const\n\n/** Cart -> page */\nexport const CartOp = {\n /** Sent from `pz_init()`, so again whenever the cart restarts */\n BOOT: 1,\n /** The cart has everything it needs to draw */\n LOADED: 2,\n /** The cart finished its victory animation, from `pz_finished()` */\n FINISHED: 3,\n /** 60 characters of progress from `pz_save()`, with more to come */\n SAVE_PART: 4,\n /** The last (or only) piece of progress from `pz_save()` */\n SAVE: 5,\n /** `[value hi, value lo, persist, ...id]` from `pz_deed()` */\n DEED: 6,\n /** `[points hi, points lo]` from `pz_complete()`, which saves the final progress just before */\n COMPLETE: 7,\n} as const\n","import { maxPayload } from \"./protocol\"\n\n/** One message on the wire. */\nexport type Pico8Message = { op: number; payload: number[] }\n\n/** Anything indexable as bytes, in practice the `pico8_gpio` array. */\nexport type Pico8Memory = { [index: number]: number | undefined; length: number }\n\nconst clampByte = (n: number) => Math.max(0, Math.min(255, Math.round(n) || 0))\n\n/**\n * One end of a GPIO mailbox pair. The cart runs the same algorithm in Lua (`pz_update` in ./lua.ts).\n *\n * A message is written payload first and `seq` last, so a half-synced message is never read as a whole one. The\n * sender holds it until the other side's `ack` matches, and writes it again (under the same `seq`) if no ack arrives,\n * so a repeat is ignored by a side that already has it. The `ack` is restated every tick, because an ack lost to a\n * sync race would otherwise leave the other side waiting forever on a message which was delivered.\n */\nexport class Pico8Channel {\n private inSeq = 0\n private outSeq = 0\n private pending: Pico8Message | null = null\n private wait = 0\n private queue: Pico8Message[] = []\n\n /**\n * @param mem The shared 128 bytes\n * @param myBase Offset of the half this end writes\n * @param peerBase Offset of the half this end reads\n * @param resendAfter Ticks to wait for an ack before writing a message again\n */\n constructor(\n private mem: Pico8Memory,\n private myBase: number,\n private peerBase: number,\n private resendAfter = 20,\n ) {}\n\n /** Queues a message. They go out one per tick, in order. */\n send(op: number, payload: ArrayLike<number> = []) {\n if (payload.length > maxPayload) throw new Error(`PICO-8 payloads are at most ${maxPayload} bytes, op ${op} has ${payload.length}`)\n this.queue.push({ op: clampByte(op), payload: Array.from(payload, clampByte) })\n }\n\n /** Messages still to be delivered, including one waiting on an ack. */\n get backlog() {\n return this.queue.length + (this.pending ? 1 : 0)\n }\n\n /** Reads at most one message and writes at most one. Call once per frame. */\n tick(): Pico8Message[] {\n const received: Pico8Message[] = []\n\n const seq = this.read(this.peerBase)\n if (this.inSeq !== 0) this.write(this.myBase + 3, this.inSeq)\n if (seq !== 0 && seq !== this.inSeq) {\n this.inSeq = seq\n this.write(this.myBase + 3, seq)\n const len = Math.min(this.read(this.peerBase + 2), maxPayload)\n const payload: number[] = []\n for (let i = 0; i < len; i++) payload.push(this.read(this.peerBase + 4 + i))\n received.push({ op: this.read(this.peerBase + 1), payload })\n }\n\n if (this.pending && this.read(this.peerBase + 3) === this.outSeq) this.pending = null\n\n let message = this.pending\n if (message) {\n if (++this.wait < this.resendAfter) return received\n } else {\n message = this.queue.shift() ?? null\n if (!message) return received\n this.outSeq = (this.outSeq % 255) + 1\n }\n\n for (let i = 0; i < maxPayload; i++) this.write(this.myBase + 4 + i, message.payload[i] ?? 0)\n this.write(this.myBase + 1, message.op)\n this.write(this.myBase + 2, message.payload.length)\n this.write(this.myBase, this.outSeq) // seq last: it commits the message\n this.pending = message\n this.wait = 0\n return received\n }\n\n private read(i: number) {\n const v = this.mem[i]\n return typeof v === \"number\" && v >= 0 ? v & 0xff : 0\n }\n\n private write(i: number, v: number) {\n this.mem[i] = clampByte(v)\n }\n}\n","/** A colour for one of the cart's 16 draw colours: a hex string, a PICO-8 hardware colour id, or null to leave it alone. */\nexport type Pico8Colour = string | number | null | undefined\n\n/** PICO-8's 32 hardware colours as `[r, g, b, id]`: the 16 standard ones, then the 16 extras at 128..143. */\nexport const pico8HardwareColours: readonly (readonly [number, number, number, number])[] = [\n [0x00, 0x00, 0x00, 0],\n [0x1d, 0x2b, 0x53, 1],\n [0x7e, 0x25, 0x53, 2],\n [0x00, 0x87, 0x51, 3],\n [0xab, 0x52, 0x36, 4],\n [0x5f, 0x57, 0x4f, 5],\n [0xc2, 0xc3, 0xc7, 6],\n [0xff, 0xf1, 0xe8, 7],\n [0xff, 0x00, 0x4d, 8],\n [0xff, 0xa3, 0x00, 9],\n [0xff, 0xec, 0x27, 10],\n [0x00, 0xe4, 0x36, 11],\n [0x29, 0xad, 0xff, 12],\n [0x83, 0x76, 0x9c, 13],\n [0xff, 0x77, 0xa8, 14],\n [0xff, 0xcc, 0xaa, 15],\n [0x29, 0x18, 0x14, 128],\n [0x11, 0x1d, 0x35, 129],\n [0x42, 0x21, 0x36, 130],\n [0x12, 0x53, 0x59, 131],\n [0x74, 0x2f, 0x29, 132],\n [0x49, 0x33, 0x3b, 133],\n [0xa2, 0x88, 0x79, 134],\n [0xf3, 0xef, 0x7d, 135],\n [0xbe, 0x12, 0x50, 136],\n [0xff, 0x6c, 0x24, 137],\n [0xa8, 0xe7, 0x2e, 138],\n [0x00, 0xb5, 0x43, 139],\n [0x06, 0x5a, 0xb5, 140],\n [0x75, 0x46, 0x65, 141],\n [0xff, 0x6e, 0x59, 142],\n [0xff, 0x9d, 0x81, 143],\n]\n\nconst parseHex = (hex: string): [number, number, number] | null => {\n const s = hex.replace(\"#\", \"\")\n if (!/^[0-9a-f]{6}/i.test(s)) return null\n return [parseInt(s.slice(0, 2), 16), parseInt(s.slice(2, 4), 16), parseInt(s.slice(4, 6), 16)]\n}\n\n/**\n * The hardware colour closest to `hex`, weighted towards green the way eyes are. `exclude` skips colours which are\n * already taken. Returns null for anything which isn't a hex colour.\n */\nexport function nearestPico8Colour(hex: string, exclude?: ReadonlySet<number>): number | null {\n const rgb = parseHex(hex)\n if (!rgb) return null\n let best: number | null = null\n let bestDistance = Infinity\n for (const [r, g, b, id] of pico8HardwareColours) {\n if (exclude?.has(id)) continue\n const distance = 2 * (r - rgb[0]) ** 2 + 4 * (g - rgb[1]) ** 2 + 3 * (b - rgb[2]) ** 2\n if (distance < bestDistance) {\n bestDistance = distance\n best = id\n }\n }\n return best\n}\n\n/**\n * Resolves up to 16 colours into the 16 hardware ids the cart feeds to `pal()`. Hex colours are matched to the\n * nearest hardware colour which an earlier hex colour hasn't already claimed, because two theme colours landing on\n * the same PICO-8 colour usually means something drawn on top of the other one disappears. Numbers are used as-is,\n * and a missing entry keeps PICO-8's default for that slot.\n */\nexport function resolvePico8Palette(colours: readonly Pico8Colour[]): number[] {\n const taken = new Set<number>()\n const out: number[] = []\n for (let i = 0; i < 16; i++) {\n const c = colours[i]\n if (typeof c === \"number\") out.push(c)\n else if (typeof c === \"string\") {\n const id = nearestPico8Colour(c, taken) ?? i\n taken.add(id)\n out.push(id)\n } else out.push(i)\n }\n return out\n}\n","import type { PuzzmoSDK } from \"../sdk\"\nimport type { Deed } from \"../types\"\nimport { Pico8Channel, type Pico8Memory } from \"./channel\"\nimport { resolvePico8Palette, type Pico8Colour } from \"./palette\"\nimport { cartBase, CartOp, firstGameOp, gpioSize, maxPayload, pageBase, PageOp } from \"./protocol\"\n\nexport { Pico8Channel, type Pico8Message, type Pico8Memory } from \"./channel\"\nexport { nearestPico8Colour, resolvePico8Palette, pico8HardwareColours, type Pico8Colour } from \"./palette\"\nexport { CartOp, PageOp, firstGameOp, maxPayload } from \"./protocol\"\nexport { puzzmoLua } from \"./lua\"\n\n/** Sends one of your game's messages to the cart. `op` must be 16 or above, and a payload is at most 60 bytes. */\nexport type Pico8Send = (op: number, payload?: ArrayLike<number>) => void\n\n/** The parts of the SDK the bridge uses. */\nexport type Pico8BridgeSDK = Pick<PuzzmoSDK, \"gameLoaded\" | \"on\" | \"showCompletionScreen\" | \"updateGameState\" | \"gameCompleted\">\n\nexport type Pico8BridgeOptions = {\n /** The SDK, after `gameReady()` has resolved. */\n sdk: Pico8BridgeSDK\n /** `completed` from `gameReady()`. A finished play opens with `pz.completed` set, and won't ask for the completion screen again. */\n completed?: boolean\n /** `puzzleString` from `gameReady()`, which the cart gets as `pz.puzzle`. Keep puzzles to plain ASCII. */\n puzzleString?: string\n /** `inputString` from `gameReady()`: the progress the cart last saved with `pz_save()`, which it gets as `pz.progress`. */\n inputString?: string | null\n /**\n * Colours for the cart's 16 draw colours, as hex strings (matched to the nearest PICO-8 hardware colour), hardware\n * colour ids, or null to keep PICO-8's default for that slot. Leave it out to keep the default palette entirely.\n */\n palette?: readonly Pico8Colour[]\n /**\n * The cart has booted (or rebooted) and wants the board. Send whatever it needs to draw with `send`, the bridge\n * follows it with READY, and the cart's `pz_on_ready()` runs once it has all arrived.\n */\n onBoot?: (send: Pico8Send) => void\n /** One of your game's messages (op 16 and up) arrived from the cart. */\n onMessage?: (op: number, payload: number[], send: Pico8Send) => void\n /** The player restarted. Reset your state here, the cart's `pz_on_retry()` runs afterwards. */\n onRetry?: () => void\n /** The cart called `pz_finished()`. Defaults to `sdk.showCompletionScreen([])`. */\n onFinished?: () => void\n /** Log every message, both ways, to the console. Handy while you're getting started. */\n debug?: boolean\n /** The shared bytes. Defaults to the page's `pico8_gpio` array, creating it if needed. */\n memory?: Pico8Memory\n /** Tick on every animation frame. Turn it off to call `tick()` yourself. Defaults to true. */\n autoTick?: boolean\n}\n\nexport type Pico8Bridge = {\n /** Sends one of your game's messages to the cart. */\n send: Pico8Send\n /** Moves the conversation along by one frame, if you turned `autoTick` off. */\n tick: () => void\n /** Stops ticking. */\n stop: () => void\n /** Messages which haven't been acknowledged yet. */\n readonly backlog: number\n}\n\n/** The page's `pico8_gpio` array, with every slot a number. PICO-8's exported page declares it, older ones may not. */\nconst gpioMemory = (): Pico8Memory => {\n const g = globalThis as { pico8_gpio?: Pico8Memory }\n const mem = g.pico8_gpio && g.pico8_gpio.length >= gpioSize ? g.pico8_gpio : (g.pico8_gpio = new Array(gpioSize))\n for (let i = 0; i < gpioSize; i++) if (typeof mem[i] !== \"number\") mem[i] = 0\n return mem\n}\n\n/** Strings travel as one character per byte. PICO-8's characters match ASCII from 32 to 126, so keep to those. */\nconst textToBytes = (text: string) =>\n Array.from(text, (ch) => {\n const code = ch.charCodeAt(0)\n return code < 256 ? code : 63 // \"?\"\n })\nconst bytesToText = (bytes: number[]) => String.fromCharCode(...bytes)\n\n/** Splits bytes into message-sized pieces. An empty string is still one (empty) piece. */\nconst chunks = (bytes: number[]) => {\n const out: number[][] = []\n for (let i = 0; i < bytes.length; i += maxPayload) out.push(bytes.slice(i, i + maxPayload))\n return out\n}\n\n/**\n * Runs a PICO-8 cart as a Puzzmo game, with the whole game written in Lua. It waits for the puzzle, hands it to the\n * cart as `pz.puzzle` (and the player's saved progress as `pz.progress`), and turns the cart's `pz_save()`,\n * `pz_deed()` and `pz_complete()` into the SDK calls Puzzmo needs.\n *\n * ```ts\n * import { createPuzzmoSDK } from \"@puzzmo/sdk\"\n * import { createPico8Game } from \"@puzzmo/sdk/pico8\"\n *\n * createPico8Game(createPuzzmoSDK())\n * ```\n */\nexport async function createPico8Game(\n sdk: Pico8BridgeSDK & Pick<PuzzmoSDK, \"gameReady\">,\n options: Omit<Pico8BridgeOptions, \"sdk\" | \"completed\" | \"puzzleString\" | \"inputString\"> = {},\n): Promise<Pico8Bridge> {\n const { puzzleString, inputString, completed } = await sdk.gameReady()\n return createPico8Bridge({ ...options, sdk, completed, puzzleString, inputString })\n}\n\n/**\n * Connects a PICO-8 cart to the Puzzmo SDK over PICO-8's GPIO bytes. Most games want `createPico8Game`, which calls\n * this for you. The cart's half is `puzzmo.lua`, which the\n * `puzzmoPico8()` vite plugin writes next to your cart.\n *\n * The bridge runs the SDK lifecycle for you: it answers the cart's boot with the board (via `onBoot`), calls\n * `gameLoaded()` once the cart has it, and passes start, pause, resume and retry through to the cart. What's left for\n * your code is the game: what the board looks like in bytes, and what the cart's messages mean.\n *\n * ```ts\n * const sdk = createPuzzmoSDK()\n * const { puzzleString, inputString, completed } = await sdk.gameReady()\n *\n * const bridge = createPico8Bridge({\n * sdk,\n * completed,\n * onBoot: (send) => send(SETUP, [remaining]),\n * onMessage: (op, payload, send) => { ... },\n * })\n * ```\n */\nexport function createPico8Bridge(options: Pico8BridgeOptions): Pico8Bridge {\n const { sdk, debug = false } = options\n const channel = new Pico8Channel(options.memory ?? gpioMemory(), pageBase, cartBase)\n const palette = options.palette ? resolvePico8Palette(options.palette) : null\n\n const state = {\n started: false,\n paused: false,\n loaded: false,\n // A play which was already finished must not ask for its completion screen again: the host re-opens a finished\n // play to show that screen, and asking for it from inside it would loop. A retry makes the play live again.\n reopened: Boolean(options.completed),\n completed: Boolean(options.completed),\n // The latest progress the cart saved, so a cart which restarts part way through picks up where it was.\n progress: options.inputString ?? \"\",\n saving: [] as number[],\n deeds: [] as Deed[],\n }\n\n const log = (direction: string, op: number, payload: ArrayLike<number>) => {\n if (debug) console.log(`[pico8] ${direction} op ${op}`, Array.from(payload))\n }\n\n const sendRaw = (op: number, payload: ArrayLike<number> = []) => {\n log(\"page -> cart\", op, payload)\n channel.send(op, payload)\n }\n\n const send: Pico8Send = (op, payload) => {\n if (op < firstGameOp) throw new Error(`PICO-8 ops below ${firstGameOp} belong to the bridge, got ${op}`)\n sendRaw(op, payload)\n }\n\n const onCartMessage = (op: number, payload: number[]) => {\n log(\"cart -> page\", op, payload)\n if (op === CartOp.BOOT) {\n // The first boot, or the cart restarted part way through: send it the whole world again.\n sendRaw(PageOp.HELLO, [state.completed ? 1 : 0])\n if (palette) sendRaw(PageOp.PALETTE, palette)\n if (options.puzzleString) for (const part of chunks(textToBytes(options.puzzleString))) sendRaw(PageOp.PUZZLE_PART, part)\n if (state.progress) for (const part of chunks(textToBytes(state.progress))) sendRaw(PageOp.PROGRESS_PART, part)\n options.onBoot?.(send)\n sendRaw(PageOp.READY)\n if (state.started) sendRaw(PageOp.START)\n if (state.paused) sendRaw(PageOp.PAUSE, [1])\n } else if (op === CartOp.LOADED) {\n if (!state.loaded) sdk.gameLoaded()\n state.loaded = true\n } else if (op === CartOp.FINISHED) {\n if (state.reopened) return\n if (options.onFinished) options.onFinished()\n else sdk.showCompletionScreen([])\n } else if (op === CartOp.SAVE_PART) {\n state.saving.push(...payload)\n } else if (op === CartOp.SAVE) {\n const progress = bytesToText([...state.saving, ...payload])\n state.saving = []\n // pz_complete() saves the final progress, which the cart has often just saved already\n if (progress === state.progress) return\n state.progress = progress\n sdk.updateGameState(progress)\n } else if (op === CartOp.DEED) {\n const [hi = 0, lo = 0, persist = 0, ...id] = payload\n const deed = { id: bytesToText(id), value: hi * 256 + lo }\n state.deeds = state.deeds.filter((d) => d.id !== deed.id)\n state.deeds.push(persist ? { ...deed, persist: true } : deed)\n } else if (op === CartOp.COMPLETE) {\n if (state.completed) return\n const [hi = 0, lo = 0] = payload\n // The SDK adds the time and points deeds itself, from its own timer\n sdk.gameCompleted({ inputString: state.progress, pointsAwarded: hi * 256 + lo, completed: true }, { deeds: state.deeds })\n state.completed = true\n state.deeds = []\n } else if (op >= firstGameOp) {\n options.onMessage?.(op, payload, send)\n }\n }\n\n sdk.on(\"start\", () => {\n state.started = true\n sendRaw(PageOp.START)\n })\n sdk.on(\"pause\", () => {\n state.paused = true\n sendRaw(PageOp.PAUSE, [1])\n })\n sdk.on(\"resume\", () => {\n state.paused = false\n sendRaw(PageOp.PAUSE, [0])\n })\n sdk.on(\"retry\", () => {\n state.reopened = false\n state.completed = false\n state.progress = \"\"\n state.deeds = []\n options.onRetry?.()\n sendRaw(PageOp.RETRY)\n })\n\n const tick = () => {\n for (const { op, payload } of channel.tick()) onCartMessage(op, payload)\n }\n\n let frame: number | null = null\n const loop = () => {\n tick()\n frame = requestAnimationFrame(loop)\n }\n if (options.autoTick !== false && typeof requestAnimationFrame === \"function\") frame = requestAnimationFrame(loop)\n\n return {\n send,\n tick,\n stop: () => {\n if (frame !== null) cancelAnimationFrame(frame)\n frame = null\n },\n get backlog() {\n return channel.backlog\n },\n }\n}\n"],"mappings":"mMA4Ba,EAAS,CAEpB,MAAO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CAAC,CACzH,EAAM,UAAY,GAClB,EAAM,MAAQ,EAAE,SACP,GAAA,GAAmB,QAC5B,EAAA,EAAQ,YAAA,MAAA,EAAA,KAAA,EAAY,EAAI,EAAS,EAAK,GAI1C,EAAI,GAAG,YAAe,CACpB,EAAM,QAAU,GAChB,EAAQ,EAAO,MAAM,EACrB,CACF,EAAI,GAAG,YAAe,CACpB,EAAM,OAAS,GACf,EAAQ,EAAO,MAAO,CAAC,EAAE,CAAC,EAC1B,CACF,EAAI,GAAG,aAAgB,CACrB,EAAM,OAAS,GACf,EAAQ,EAAO,MAAO,CAAC,EAAE,CAAC,EAC1B,CACF,EAAI,GAAG,YAAe,OACpB,EAAM,SAAW,GACjB,EAAM,UAAY,GAClB,EAAM,SAAW,GACjB,EAAM,MAAQ,EAAE,EAChB,EAAA,EAAQ,UAAA,MAAA,EAAA,KAAA,EAAW,CACnB,EAAQ,EAAO,MAAM,EACrB,CAEF,IAAM,MAAa,CACjB,IAAK,GAAM,CAAE,KAAI,aAAa,EAAQ,MAAM,CAAE,EAAc,EAAI,EAAQ,EAGtE,EAAuB,KACrB,MAAa,CACjB,GAAM,CACN,EAAQ,sBAAsB,EAAK,EAIrC,OAFI,EAAQ,WAAa,IAAS,OAAO,uBAA0B,aAAY,EAAQ,sBAAsB,EAAK,EAE3G,CACL,OACA,OACA,SAAY,CACN,IAAU,MAAM,qBAAqB,EAAM,CAC/C,EAAQ,MAEV,IAAI,SAAU,CACZ,OAAO,EAAQ,SAElB"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../../src/pico8/protocol.ts","../../src/pico8/channel.ts","../../src/pico8/palette.ts","../../src/pico8/index.ts"],"sourcesContent":["/**\n * The PICO-8 bridge's wire format. PICO-8 mirrors the 128 bytes at 0x5f80 into a JavaScript array called\n * `pico8_gpio` once a frame, in both directions, and this splits them into two mailboxes. Each side only ever writes\n * to its own half: a byte written by both ends can lose one of the writes when the frame syncs.\n *\n * 0x00..0x3f page -> cart (only JavaScript writes)\n * 0x40..0x7f cart -> page (only Lua writes)\n *\n * Each mailbox holds one message:\n *\n * +0 seq 0 = nothing sent yet, else 1..255 wrapping back to 1\n * +1 op opcode\n * +2 len payload length, 0..60\n * +3 ack the last seq this side has read from the other side\n * +4..+63 payload\n *\n * Ops below 16 belong to the bridge, a game uses 16 and up. The Lua half is in ./lua.ts.\n */\n\nexport const gpioSize = 128\nexport const pageBase = 0\nexport const cartBase = 64\nexport const maxPayload = 60\n\n/** The first op a game can use for its own messages. */\nexport const firstGameOp = 16\n\n/** Page -> cart */\nexport const PageOp = {\n /** `[flags]`, bit 0: this play was already completed. First thing sent after every BOOT. */\n HELLO: 1,\n /** 16 bytes: the PICO-8 hardware colour for each draw colour, applied with `pal(i, c, 1)` */\n PALETTE: 2,\n /** Everything is sent: the cart sets `pz.puzzle`, `pz.progress` and `pz.ready`, calls `pz_on_ready()`, and answers LOADED */\n READY: 3,\n /** The host started the game */\n START: 4,\n /** `[0 or 1]` */\n PAUSE: 5,\n /** The player restarted the puzzle */\n RETRY: 6,\n /** Up to 60 characters of the puzzle string. It arrives in pieces after HELLO, and READY marks the end. */\n PUZZLE_PART: 7,\n /** Up to 60 characters of the player's saved progress, the same way. */\n PROGRESS_PART: 8,\n} as const\n\n/** Cart -> page */\nexport const CartOp = {\n /** Sent from `pz_init()`, so again whenever the cart restarts */\n BOOT: 1,\n /** The cart has everything it needs to draw */\n LOADED: 2,\n /** The cart finished its victory animation, from `pz_finished()` */\n FINISHED: 3,\n /** 60 characters of progress from `pz_save()`, with more to come */\n SAVE_PART: 4,\n /** The last (or only) piece of progress from `pz_save()` */\n SAVE: 5,\n /** `[value hi, value lo, persist, ...id]` from `pz_deed()` */\n DEED: 6,\n /** `[points hi, points lo]` from `pz_complete()`, which saves the final progress just before */\n COMPLETE: 7,\n} as const\n","import { maxPayload } from \"./protocol\"\n\n/** One message on the wire. */\nexport type Pico8Message = { op: number; payload: number[] }\n\n/** Anything indexable as bytes, in practice the `pico8_gpio` array. */\nexport type Pico8Memory = { [index: number]: number | undefined; length: number }\n\nconst clampByte = (n: number) => Math.max(0, Math.min(255, Math.round(n) || 0))\n\n/**\n * One end of a GPIO mailbox pair. The cart runs the same algorithm in Lua (`pz_update` in ./lua.ts).\n *\n * A message is written payload first and `seq` last, so a half-synced message is never read as a whole one. The\n * sender holds it until the other side's `ack` matches, and writes it again (under the same `seq`) if no ack arrives,\n * so a repeat is ignored by a side that already has it. The `ack` is restated every tick, because an ack lost to a\n * sync race would otherwise leave the other side waiting forever on a message which was delivered.\n */\nexport class Pico8Channel {\n private inSeq = 0\n private outSeq = 0\n private pending: Pico8Message | null = null\n private wait = 0\n private queue: Pico8Message[] = []\n\n /**\n * @param mem The shared 128 bytes\n * @param myBase Offset of the half this end writes\n * @param peerBase Offset of the half this end reads\n * @param resendAfter Ticks to wait for an ack before writing a message again\n */\n constructor(\n private mem: Pico8Memory,\n private myBase: number,\n private peerBase: number,\n private resendAfter = 20,\n ) {}\n\n /** Queues a message. They go out one per tick, in order. */\n send(op: number, payload: ArrayLike<number> = []) {\n if (payload.length > maxPayload) throw new Error(`PICO-8 payloads are at most ${maxPayload} bytes, op ${op} has ${payload.length}`)\n this.queue.push({ op: clampByte(op), payload: Array.from(payload, clampByte) })\n }\n\n /** Messages still to be delivered, including one waiting on an ack. */\n get backlog() {\n return this.queue.length + (this.pending ? 1 : 0)\n }\n\n /** Reads at most one message and writes at most one. Call once per frame. */\n tick(): Pico8Message[] {\n const received: Pico8Message[] = []\n\n const seq = this.read(this.peerBase)\n if (this.inSeq !== 0) this.write(this.myBase + 3, this.inSeq)\n if (seq !== 0 && seq !== this.inSeq) {\n this.inSeq = seq\n this.write(this.myBase + 3, seq)\n const len = Math.min(this.read(this.peerBase + 2), maxPayload)\n const payload: number[] = []\n for (let i = 0; i < len; i++) payload.push(this.read(this.peerBase + 4 + i))\n received.push({ op: this.read(this.peerBase + 1), payload })\n }\n\n if (this.pending && this.read(this.peerBase + 3) === this.outSeq) this.pending = null\n\n let message = this.pending\n if (message) {\n if (++this.wait < this.resendAfter) return received\n } else {\n message = this.queue.shift() ?? null\n if (!message) return received\n this.outSeq = (this.outSeq % 255) + 1\n }\n\n for (let i = 0; i < maxPayload; i++) this.write(this.myBase + 4 + i, message.payload[i] ?? 0)\n this.write(this.myBase + 1, message.op)\n this.write(this.myBase + 2, message.payload.length)\n this.write(this.myBase, this.outSeq) // seq last: it commits the message\n this.pending = message\n this.wait = 0\n return received\n }\n\n private read(i: number) {\n const v = this.mem[i]\n return typeof v === \"number\" && v >= 0 ? v & 0xff : 0\n }\n\n private write(i: number, v: number) {\n this.mem[i] = clampByte(v)\n }\n}\n","/** A colour for one of the cart's 16 draw colours: a hex string, a PICO-8 hardware colour id, or null to leave it alone. */\nexport type Pico8Colour = string | number | null | undefined\n\n/** PICO-8's 32 hardware colours as `[r, g, b, id]`: the 16 standard ones, then the 16 extras at 128..143. */\nexport const pico8HardwareColours: readonly (readonly [number, number, number, number])[] = [\n [0x00, 0x00, 0x00, 0],\n [0x1d, 0x2b, 0x53, 1],\n [0x7e, 0x25, 0x53, 2],\n [0x00, 0x87, 0x51, 3],\n [0xab, 0x52, 0x36, 4],\n [0x5f, 0x57, 0x4f, 5],\n [0xc2, 0xc3, 0xc7, 6],\n [0xff, 0xf1, 0xe8, 7],\n [0xff, 0x00, 0x4d, 8],\n [0xff, 0xa3, 0x00, 9],\n [0xff, 0xec, 0x27, 10],\n [0x00, 0xe4, 0x36, 11],\n [0x29, 0xad, 0xff, 12],\n [0x83, 0x76, 0x9c, 13],\n [0xff, 0x77, 0xa8, 14],\n [0xff, 0xcc, 0xaa, 15],\n [0x29, 0x18, 0x14, 128],\n [0x11, 0x1d, 0x35, 129],\n [0x42, 0x21, 0x36, 130],\n [0x12, 0x53, 0x59, 131],\n [0x74, 0x2f, 0x29, 132],\n [0x49, 0x33, 0x3b, 133],\n [0xa2, 0x88, 0x79, 134],\n [0xf3, 0xef, 0x7d, 135],\n [0xbe, 0x12, 0x50, 136],\n [0xff, 0x6c, 0x24, 137],\n [0xa8, 0xe7, 0x2e, 138],\n [0x00, 0xb5, 0x43, 139],\n [0x06, 0x5a, 0xb5, 140],\n [0x75, 0x46, 0x65, 141],\n [0xff, 0x6e, 0x59, 142],\n [0xff, 0x9d, 0x81, 143],\n]\n\nconst parseHex = (hex: string): [number, number, number] | null => {\n const s = hex.replace(\"#\", \"\")\n if (!/^[0-9a-f]{6}/i.test(s)) return null\n return [parseInt(s.slice(0, 2), 16), parseInt(s.slice(2, 4), 16), parseInt(s.slice(4, 6), 16)]\n}\n\n/**\n * The hardware colour closest to `hex`, weighted towards green the way eyes are. `exclude` skips colours which are\n * already taken. Returns null for anything which isn't a hex colour.\n */\nexport function nearestPico8Colour(hex: string, exclude?: ReadonlySet<number>): number | null {\n const rgb = parseHex(hex)\n if (!rgb) return null\n let best: number | null = null\n let bestDistance = Infinity\n for (const [r, g, b, id] of pico8HardwareColours) {\n if (exclude?.has(id)) continue\n const distance = 2 * (r - rgb[0]) ** 2 + 4 * (g - rgb[1]) ** 2 + 3 * (b - rgb[2]) ** 2\n if (distance < bestDistance) {\n bestDistance = distance\n best = id\n }\n }\n return best\n}\n\n/**\n * Resolves up to 16 colours into the 16 hardware ids the cart feeds to `pal()`. Hex colours are matched to the\n * nearest hardware colour which an earlier hex colour hasn't already claimed, because two theme colours landing on\n * the same PICO-8 colour usually means something drawn on top of the other one disappears. Numbers are used as-is,\n * and a missing entry keeps PICO-8's default for that slot.\n */\nexport function resolvePico8Palette(colours: readonly Pico8Colour[]): number[] {\n const taken = new Set<number>()\n const out: number[] = []\n for (let i = 0; i < 16; i++) {\n const c = colours[i]\n if (typeof c === \"number\") out.push(c)\n else if (typeof c === \"string\") {\n const id = nearestPico8Colour(c, taken) ?? i\n taken.add(id)\n out.push(id)\n } else out.push(i)\n }\n return out\n}\n","import type { PuzzmoSDK } from \"../sdk\"\nimport type { Deed } from \"../types\"\nimport { Pico8Channel, type Pico8Memory } from \"./channel\"\nimport { resolvePico8Palette, type Pico8Colour } from \"./palette\"\nimport { cartBase, CartOp, firstGameOp, gpioSize, maxPayload, pageBase, PageOp } from \"./protocol\"\n\nexport { Pico8Channel, type Pico8Message, type Pico8Memory } from \"./channel\"\nexport { nearestPico8Colour, resolvePico8Palette, pico8HardwareColours, type Pico8Colour } from \"./palette\"\nexport { CartOp, PageOp, firstGameOp, maxPayload } from \"./protocol\"\nexport { puzzmoLua } from \"./lua\"\n\n/** Sends one of your game's messages to the cart. `op` must be 16 or above, and a payload is at most 60 bytes. */\nexport type Pico8Send = (op: number, payload?: ArrayLike<number>) => void\n\n/** The parts of the SDK the bridge uses. */\nexport type Pico8BridgeSDK = Pick<PuzzmoSDK, \"gameLoaded\" | \"on\" | \"showCompletionScreen\" | \"updateGameState\" | \"gameCompleted\">\n\nexport type Pico8BridgeOptions = {\n /** The SDK, after `gameReady()` has resolved. */\n sdk: Pico8BridgeSDK\n /** `completed` from `gameReady()`. A finished play opens with `pz.completed` set, and won't ask for the completion screen again. */\n completed?: boolean\n /** `puzzleString` from `gameReady()`, which the cart gets as `pz.puzzle`. Keep puzzles to plain ASCII. */\n puzzleString?: string\n /** `inputString` from `gameReady()`: the progress the cart last saved with `pz_save()`, which it gets as `pz.progress`. */\n inputString?: string | null\n /**\n * Colours for the cart's 16 draw colours, as hex strings (matched to the nearest PICO-8 hardware colour), hardware\n * colour ids, or null to keep PICO-8's default for that slot. Leave it out to keep the default palette entirely.\n */\n palette?: readonly Pico8Colour[]\n /**\n * The cart has booted (or rebooted) and wants the board. Send whatever it needs to draw with `send`, the bridge\n * follows it with READY, and the cart's `pz_on_ready()` runs once it has all arrived.\n */\n onBoot?: (send: Pico8Send) => void\n /** One of your game's messages (op 16 and up) arrived from the cart. */\n onMessage?: (op: number, payload: number[], send: Pico8Send) => void\n /** The player restarted. Reset your state here, the cart's `pz_on_retry()` runs afterwards. */\n onRetry?: () => void\n /** The cart called `pz_finished()`. Defaults to `sdk.showCompletionScreen([])`. */\n onFinished?: () => void\n /** Log every message, both ways, to the console. Handy while you're getting started. */\n debug?: boolean\n /** The shared bytes. Defaults to the page's `pico8_gpio` array, creating it if needed. */\n memory?: Pico8Memory\n /** Tick on every animation frame. Turn it off to call `tick()` yourself. Defaults to true. */\n autoTick?: boolean\n}\n\nexport type Pico8Bridge = {\n /** Sends one of your game's messages to the cart. */\n send: Pico8Send\n /** Moves the conversation along by one frame, if you turned `autoTick` off. */\n tick: () => void\n /** Stops ticking. */\n stop: () => void\n /** Messages which haven't been acknowledged yet. */\n readonly backlog: number\n}\n\n/** The page's `pico8_gpio` array, with every slot a number. PICO-8's exported page declares it, older ones may not. */\nconst gpioMemory = (): Pico8Memory => {\n const g = globalThis as { pico8_gpio?: Pico8Memory }\n const mem = g.pico8_gpio && g.pico8_gpio.length >= gpioSize ? g.pico8_gpio : (g.pico8_gpio = new Array(gpioSize))\n for (let i = 0; i < gpioSize; i++) if (typeof mem[i] !== \"number\") mem[i] = 0\n return mem\n}\n\n/** Strings travel as one character per byte. PICO-8's characters match ASCII from 32 to 126, so keep to those. */\nconst textToBytes = (text: string) =>\n Array.from(text, (ch) => {\n const code = ch.charCodeAt(0)\n return code < 256 ? code : 63 // \"?\"\n })\nconst bytesToText = (bytes: number[]) => String.fromCharCode(...bytes)\n\n/** Splits bytes into message-sized pieces. An empty string is still one (empty) piece. */\nconst chunks = (bytes: number[]) => {\n const out: number[][] = []\n for (let i = 0; i < bytes.length; i += maxPayload) out.push(bytes.slice(i, i + maxPayload))\n return out\n}\n\n/**\n * Runs a PICO-8 cart as a Puzzmo game, with the whole game written in Lua. It waits for the puzzle, hands it to the\n * cart as `pz.puzzle` (and the player's saved progress as `pz.progress`), and turns the cart's `pz_save()`,\n * `pz_deed()` and `pz_complete()` into the SDK calls Puzzmo needs.\n *\n * ```ts\n * import { createPuzzmoSDK } from \"@puzzmo/sdk\"\n * import { createPico8Game } from \"@puzzmo/sdk/pico8\"\n *\n * createPico8Game(createPuzzmoSDK())\n * ```\n */\nexport async function createPico8Game(\n sdk: Pico8BridgeSDK & Pick<PuzzmoSDK, \"gameReady\">,\n options: Omit<Pico8BridgeOptions, \"sdk\" | \"completed\" | \"puzzleString\" | \"inputString\"> = {},\n): Promise<Pico8Bridge> {\n const { puzzleString, inputString, completed } = await sdk.gameReady()\n return createPico8Bridge({ ...options, sdk, completed, puzzleString, inputString })\n}\n\n/**\n * Connects a PICO-8 cart to the Puzzmo SDK over PICO-8's GPIO bytes. Most games want `createPico8Game`, which calls\n * this for you. The cart's half is `puzzmo.lua`, which the\n * `puzzmoPico8()` vite plugin writes next to your cart.\n *\n * The bridge runs the SDK lifecycle for you: it answers the cart's boot with the puzzle and progress, calls\n * `gameLoaded()` once the cart has them, passes start, pause, resume and retry through to the cart, and turns the\n * cart's `pz_save()`, `pz_deed()` and `pz_complete()` into SDK calls. Reach for it over `createPico8Game` when you\n * need something from `gameReady()` first, like the theme.\n *\n * ```ts\n * const sdk = createPuzzmoSDK()\n * const { puzzleString, inputString, completed, theme } = await sdk.gameReady()\n *\n * createPico8Bridge({ sdk, puzzleString, inputString, completed, palette: [theme.g_bg, theme.g_bgAlt] })\n * ```\n */\nexport function createPico8Bridge(options: Pico8BridgeOptions): Pico8Bridge {\n const { sdk, debug = false } = options\n const channel = new Pico8Channel(options.memory ?? gpioMemory(), pageBase, cartBase)\n const palette = options.palette ? resolvePico8Palette(options.palette) : null\n\n const state = {\n started: false,\n paused: false,\n loaded: false,\n // A play which was already finished must not ask for its completion screen again: the host re-opens a finished\n // play to show that screen, and asking for it from inside it would loop. A retry makes the play live again.\n reopened: Boolean(options.completed),\n completed: Boolean(options.completed),\n // The latest progress the cart saved, so a cart which restarts part way through picks up where it was.\n progress: options.inputString ?? \"\",\n saving: [] as number[],\n deeds: [] as Deed[],\n }\n\n const log = (direction: string, op: number, payload: ArrayLike<number>) => {\n if (debug) console.log(`[pico8] ${direction} op ${op}`, Array.from(payload))\n }\n\n const sendRaw = (op: number, payload: ArrayLike<number> = []) => {\n log(\"page -> cart\", op, payload)\n channel.send(op, payload)\n }\n\n const send: Pico8Send = (op, payload) => {\n if (op < firstGameOp) throw new Error(`PICO-8 ops below ${firstGameOp} belong to the bridge, got ${op}`)\n sendRaw(op, payload)\n }\n\n const onCartMessage = (op: number, payload: number[]) => {\n log(\"cart -> page\", op, payload)\n if (op === CartOp.BOOT) {\n // The first boot, or the cart restarted part way through: send it the whole world again.\n sendRaw(PageOp.HELLO, [state.completed ? 1 : 0])\n if (palette) sendRaw(PageOp.PALETTE, palette)\n if (options.puzzleString) for (const part of chunks(textToBytes(options.puzzleString))) sendRaw(PageOp.PUZZLE_PART, part)\n if (state.progress) for (const part of chunks(textToBytes(state.progress))) sendRaw(PageOp.PROGRESS_PART, part)\n options.onBoot?.(send)\n sendRaw(PageOp.READY)\n if (state.started) sendRaw(PageOp.START)\n if (state.paused) sendRaw(PageOp.PAUSE, [1])\n } else if (op === CartOp.LOADED) {\n if (!state.loaded) sdk.gameLoaded()\n state.loaded = true\n } else if (op === CartOp.FINISHED) {\n if (state.reopened) return\n if (options.onFinished) options.onFinished()\n else sdk.showCompletionScreen([])\n } else if (op === CartOp.SAVE_PART) {\n state.saving.push(...payload)\n } else if (op === CartOp.SAVE) {\n const progress = bytesToText([...state.saving, ...payload])\n state.saving = []\n // pz_complete() saves the final progress, which the cart has often just saved already\n if (progress === state.progress) return\n state.progress = progress\n sdk.updateGameState(progress)\n } else if (op === CartOp.DEED) {\n const [hi = 0, lo = 0, persist = 0, ...id] = payload\n const deed = { id: bytesToText(id), value: hi * 256 + lo }\n state.deeds = state.deeds.filter((d) => d.id !== deed.id)\n state.deeds.push(persist ? { ...deed, persist: true } : deed)\n } else if (op === CartOp.COMPLETE) {\n if (state.completed) return\n const [hi = 0, lo = 0] = payload\n // The SDK adds the time and points deeds itself, from its own timer\n sdk.gameCompleted({ inputString: state.progress, pointsAwarded: hi * 256 + lo, completed: true }, { deeds: state.deeds })\n state.completed = true\n state.deeds = []\n } else if (op >= firstGameOp) {\n options.onMessage?.(op, payload, send)\n }\n }\n\n sdk.on(\"start\", () => {\n state.started = true\n sendRaw(PageOp.START)\n })\n sdk.on(\"pause\", () => {\n state.paused = true\n sendRaw(PageOp.PAUSE, [1])\n })\n sdk.on(\"resume\", () => {\n state.paused = false\n sendRaw(PageOp.PAUSE, [0])\n })\n sdk.on(\"retry\", () => {\n state.reopened = false\n state.completed = false\n state.progress = \"\"\n state.deeds = []\n options.onRetry?.()\n sendRaw(PageOp.RETRY)\n })\n\n const tick = () => {\n for (const { op, payload } of channel.tick()) onCartMessage(op, payload)\n }\n\n let frame: number | null = null\n const loop = () => {\n tick()\n frame = requestAnimationFrame(loop)\n }\n if (options.autoTick !== false && typeof requestAnimationFrame === \"function\") frame = requestAnimationFrame(loop)\n\n return {\n send,\n tick,\n stop: () => {\n if (frame !== null) cancelAnimationFrame(frame)\n frame = null\n },\n get backlog() {\n return channel.backlog\n },\n }\n}\n"],"mappings":"mMA4Ba,EAAS,CAEpB,MAAO,EAEP,QAAS,EAET,MAAO,EAEP,MAAO,EAEP,MAAO,EAEP,MAAO,EAEP,YAAa,EAEb,cAAe,EAChB,CAGY,EAAS,CAEpB,KAAM,EAEN,OAAQ,EAER,SAAU,EAEV,UAAW,EAEX,KAAM,EAEN,KAAM,EAEN,SAAU,EACX,CCvDD,IAAM,EAAa,GAAc,KAAK,IAAI,EAAG,KAAK,IAAI,IAAK,KAAK,MAAM,EAAE,EAAI,EAAE,CAAC,CAUlE,EAAb,KAA0B,CAaxB,YACE,EACA,EACA,EACA,EAAsB,GACtB,UAjBF,QAAgB,EAAA,UAChB,SAAiB,EAAA,UACjB,UAAuC,KAAA,UACvC,OAAe,EAAA,UACf,QAAgC,EAAE,CAAA,CASxB,KAAA,IAAA,EACA,KAAA,OAAA,EACA,KAAA,SAAA,EACA,KAAA,YAAA,EAIV,KAAK,EAAY,EAA6B,EAAE,CAAE,CAChD,GAAI,EAAQ,OAAA,GAAqB,MAAU,MAAM,4CAAuD,EAAG,OAAO,EAAQ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,EAAQ,MAAM,CAAE,EAAc,EAAI,EAAQ,EAGtE,EAAuB,KACrB,MAAa,CACjB,GAAM,CACN,EAAQ,sBAAsB,EAAK,EAIrC,OAFI,EAAQ,WAAa,IAAS,OAAO,uBAA0B,aAAY,EAAQ,sBAAsB,EAAK,EAE3G,CACL,OACA,OACA,SAAY,CACN,IAAU,MAAM,qBAAqB,EAAM,CAC/C,EAAQ,MAEV,IAAI,SAAU,CACZ,OAAO,EAAQ,SAElB"}
|
package/dist/pico8/index.d.ts
CHANGED
|
@@ -69,20 +69,16 @@ export declare function createPico8Game(sdk: Pico8BridgeSDK & Pick<PuzzmoSDK, "g
|
|
|
69
69
|
* this for you. The cart's half is `puzzmo.lua`, which the
|
|
70
70
|
* `puzzmoPico8()` vite plugin writes next to your cart.
|
|
71
71
|
*
|
|
72
|
-
* The bridge runs the SDK lifecycle for you: it answers the cart's boot with the
|
|
73
|
-
* `gameLoaded()` once the cart has
|
|
74
|
-
*
|
|
72
|
+
* The bridge runs the SDK lifecycle for you: it answers the cart's boot with the puzzle and progress, calls
|
|
73
|
+
* `gameLoaded()` once the cart has them, passes start, pause, resume and retry through to the cart, and turns the
|
|
74
|
+
* cart's `pz_save()`, `pz_deed()` and `pz_complete()` into SDK calls. Reach for it over `createPico8Game` when you
|
|
75
|
+
* need something from `gameReady()` first, like the theme.
|
|
75
76
|
*
|
|
76
77
|
* ```ts
|
|
77
78
|
* const sdk = createPuzzmoSDK()
|
|
78
|
-
* const { puzzleString, inputString, completed } = await sdk.gameReady()
|
|
79
|
+
* const { puzzleString, inputString, completed, theme } = await sdk.gameReady()
|
|
79
80
|
*
|
|
80
|
-
*
|
|
81
|
-
* sdk,
|
|
82
|
-
* completed,
|
|
83
|
-
* onBoot: (send) => send(SETUP, [remaining]),
|
|
84
|
-
* onMessage: (op, payload, send) => { ... },
|
|
85
|
-
* })
|
|
81
|
+
* createPico8Bridge({ sdk, puzzleString, inputString, completed, palette: [theme.g_bg, theme.g_bgAlt] })
|
|
86
82
|
* ```
|
|
87
83
|
*/
|
|
88
84
|
export declare function createPico8Bridge(options: Pico8BridgeOptions): Pico8Bridge;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/pico8/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAA;AAEvC,OAAO,EAAgB,KAAK,WAAW,EAAE,MAAM,WAAW,CAAA;AAC1D,OAAO,EAAuB,KAAK,WAAW,EAAE,MAAM,WAAW,CAAA;AAGjE,OAAO,EAAE,YAAY,EAAE,KAAK,YAAY,EAAE,KAAK,WAAW,EAAE,MAAM,WAAW,CAAA;AAC7E,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,KAAK,WAAW,EAAE,MAAM,WAAW,CAAA;AAC3G,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AACpE,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAA;AAEjC,kHAAkH;AAClH,MAAM,MAAM,SAAS,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS,CAAC,MAAM,CAAC,KAAK,IAAI,CAAA;AAEzE,4CAA4C;AAC5C,MAAM,MAAM,cAAc,GAAG,IAAI,CAAC,SAAS,EAAE,YAAY,GAAG,IAAI,GAAG,sBAAsB,GAAG,iBAAiB,GAAG,eAAe,CAAC,CAAA;AAEhI,MAAM,MAAM,kBAAkB,GAAG;IAC/B,iDAAiD;IACjD,GAAG,EAAE,cAAc,CAAA;IACnB,oIAAoI;IACpI,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,0GAA0G;IAC1G,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,2HAA2H;IAC3H,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC3B;;;OAGG;IACH,OAAO,CAAC,EAAE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,EAAE,MAAM,IAAI,CAAA;IACvB,wFAAwF;IACxF,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,0FAA0F;IAC1F,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,8FAA8F;IAC9F,QAAQ,CAAC,EAAE,OAAO,CAAA;CACnB,CAAA;AAED,MAAM,MAAM,WAAW,GAAG;IACxB,qDAAqD;IACrD,IAAI,EAAE,SAAS,CAAA;IACf,+EAA+E;IAC/E,IAAI,EAAE,MAAM,IAAI,CAAA;IAChB,qBAAqB;IACrB,IAAI,EAAE,MAAM,IAAI,CAAA;IAChB,oDAAoD;IACpD,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CACzB,CAAA;AAyBD;;;;;;;;;;;GAWG;AACH,wBAAsB,eAAe,CACnC,GAAG,EAAE,cAAc,GAAG,IAAI,CAAC,SAAS,EAAE,WAAW,CAAC,EAClD,OAAO,GAAE,IAAI,CAAC,kBAAkB,EAAE,KAAK,GAAG,WAAW,GAAG,cAAc,GAAG,aAAa,CAAM,GAC3F,OAAO,CAAC,WAAW,CAAC,CAGtB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,kBAAkB,GAAG,WAAW,CAyH1E"}
|
package/dist/pico8/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as e, t } from "../objectSpread2-
|
|
2
|
-
import { t as n } from "../asyncToGenerator-
|
|
1
|
+
import { n as e, t } from "../objectSpread2-BQwrzeNG.js";
|
|
2
|
+
import { t as n } from "../asyncToGenerator-BotOOyB7.js";
|
|
3
3
|
import { t as r } from "../lua-C3M-mB0u.js";
|
|
4
4
|
const i = 60, a = 16, o = {
|
|
5
5
|
HELLO: 1,
|
|
@@ -355,20 +355,16 @@ function y() {
|
|
|
355
355
|
* this for you. The cart's half is `puzzmo.lua`, which the
|
|
356
356
|
* `puzzmoPico8()` vite plugin writes next to your cart.
|
|
357
357
|
*
|
|
358
|
-
* The bridge runs the SDK lifecycle for you: it answers the cart's boot with the
|
|
359
|
-
* `gameLoaded()` once the cart has
|
|
360
|
-
*
|
|
358
|
+
* The bridge runs the SDK lifecycle for you: it answers the cart's boot with the puzzle and progress, calls
|
|
359
|
+
* `gameLoaded()` once the cart has them, passes start, pause, resume and retry through to the cart, and turns the
|
|
360
|
+
* cart's `pz_save()`, `pz_deed()` and `pz_complete()` into SDK calls. Reach for it over `createPico8Game` when you
|
|
361
|
+
* need something from `gameReady()` first, like the theme.
|
|
361
362
|
*
|
|
362
363
|
* ```ts
|
|
363
364
|
* const sdk = createPuzzmoSDK()
|
|
364
|
-
* const { puzzleString, inputString, completed } = await sdk.gameReady()
|
|
365
|
+
* const { puzzleString, inputString, completed, theme } = await sdk.gameReady()
|
|
365
366
|
*
|
|
366
|
-
*
|
|
367
|
-
* sdk,
|
|
368
|
-
* completed,
|
|
369
|
-
* onBoot: (send) => send(SETUP, [remaining]),
|
|
370
|
-
* onMessage: (op, payload, send) => { ... },
|
|
371
|
-
* })
|
|
367
|
+
* createPico8Bridge({ sdk, puzzleString, inputString, completed, palette: [theme.g_bg, theme.g_bgAlt] })
|
|
372
368
|
* ```
|
|
373
369
|
*/
|
|
374
370
|
function b(e) {
|