@adminide-stack/yantra-mobile 12.0.175-alpha.2 → 12.0.176-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/features/agent-chat/NativeAgentChat.js +1 -1
- package/lib/features/agent-chat/NativeAgentChat.js.map +1 -1
- package/lib/features/chat/ChatTranscript.js +22 -9
- package/lib/features/chat/ChatTranscript.js.map +1 -1
- package/lib/features/chat/MessageActionBar.js +1 -1
- package/lib/features/chat/MessageActionBar.js.map +1 -1
- package/lib/features/games/cubeforge3D.js +39 -14
- package/lib/features/games/cubeforge3D.js.map +1 -1
- package/lib/features/games/cubeforgeFriends.js +17 -1
- package/lib/features/games/cubeforgeFriends.js.map +1 -1
- package/lib/features/games/cubeforgeHelper.js +3 -2
- package/lib/features/games/cubeforgeHelper.js.map +1 -1
- package/lib/features/games/gameInvite.js +6 -1
- package/lib/features/games/gameInvite.js.map +1 -1
- package/lib/features/games/gameNotifications.js +9 -0
- package/lib/features/games/gameNotifications.js.map +1 -0
- package/lib/features/games/gameOrientation.js +10 -0
- package/lib/features/games/gameOrientation.js.map +1 -0
- package/lib/features/games/useCubeforgeFriends.js +86 -38
- package/lib/features/games/useCubeforgeFriends.js.map +1 -1
- package/lib/features/games/vendored/core/cubeforge/openingMemory.js +31 -0
- package/lib/features/games/vendored/core/cubeforge/openingMemory.js.map +1 -0
- package/lib/features/games/vendored/core/cubeforge/sharedWorlds.js +66 -2
- package/lib/features/games/vendored/core/cubeforge/sharedWorlds.js.map +1 -1
- package/lib/features/games/vendored/ui/GamesRoot.js +62 -6
- package/lib/features/games/vendored/ui/GamesRoot.js.map +1 -1
- package/lib/features/games/vendored/ui/components/primitives.js +1 -1
- package/lib/features/games/vendored/ui/screens/Cubeforge3DHomeScreen.js +128 -16
- package/lib/features/games/vendored/ui/screens/Cubeforge3DHomeScreen.js.map +1 -1
- package/lib/features/games/vendored/ui/screens/HowToPlayScreen.js +474 -0
- package/lib/features/games/vendored/ui/screens/HowToPlayScreen.js.map +1 -0
- package/lib/features/reporting/ReportAiContentButton.js +13 -0
- package/lib/features/reporting/ReportAiContentButton.js.map +1 -0
- package/lib/features/reporting/reportAiContent.js +55 -0
- package/lib/features/reporting/reportAiContent.js.map +1 -0
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/lib/screens/Account/index.js +6 -1
- package/lib/screens/Account/index.js.map +1 -1
- package/lib/screens/GamesNative/index.js +4 -3
- package/lib/screens/GamesNative/index.js.map +1 -1
- package/package.json +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {jsxs,jsx}from'react/jsx-runtime';import*as React from'react';import {StyleSheet,Platform,Modal,KeyboardAvoidingView,Pressable,Text,
|
|
1
|
+
import {jsxs,jsx}from'react/jsx-runtime';import*as React from'react';import {MaterialCommunityIcons}from'@expo/vector-icons';import {StyleSheet,Platform,Modal,KeyboardAvoidingView,Pressable,View,Text,TextInput}from'react-native';import {requireNativeViewManager,requireOptionalNativeModule}from'expo-modules-core';import {SafeAreaView}from'react-native-safe-area-context';import {getApolloContext}from'@apollo/client/index.js';import AsyncStorage from'@react-native-async-storage/async-storage';import {reportAiContent}from'../reporting/reportAiContent.js';import {letGameTurnWithPhone}from'./gameOrientation.js';import {helperConsentGiven,askAndPreview,rememberHelperConsent}from'./cubeforgeHelper.js';const MAX_CHAT_CHARS = 200;
|
|
2
2
|
const SUPPORTED_PLATFORMS = /* @__PURE__ */ new Set(["ios", "android"]);
|
|
3
3
|
function nativeModule() {
|
|
4
4
|
if (!SUPPORTED_PLATFORMS.has(Platform.OS)) return null;
|
|
@@ -22,7 +22,7 @@ function HelperConsent({
|
|
|
22
22
|
onAgree,
|
|
23
23
|
onClose
|
|
24
24
|
}) {
|
|
25
|
-
return /* @__PURE__ */ jsx(Modal, { transparent: true, visible: true, animationType: "fade", onRequestClose: onClose, children: /* @__PURE__ */ jsx(View, { style: styles.consentBackdrop, children: /* @__PURE__ */ jsxs(View, { style: styles.consentCard, children: [
|
|
25
|
+
return /* @__PURE__ */ jsx(Modal, { transparent: true, visible: true, animationType: "fade", supportedOrientations: GAME_ORIENTATIONS, onRequestClose: onClose, children: /* @__PURE__ */ jsx(View, { style: styles.consentBackdrop, children: /* @__PURE__ */ jsxs(View, { style: styles.consentCard, children: [
|
|
26
26
|
/* @__PURE__ */ jsx(Text, { style: styles.consentTitle, children: "Your build helper" }),
|
|
27
27
|
/* @__PURE__ */ jsx(Text, { style: styles.consentBody, children: "To suggest ideas, your helper sends Yantra's AI the blocks around you and what you type. Your name, your friends and your chats are not sent." }),
|
|
28
28
|
/* @__PURE__ */ jsxs(View, { style: styles.consentRow, children: [
|
|
@@ -31,11 +31,13 @@ function HelperConsent({
|
|
|
31
31
|
] })
|
|
32
32
|
] }) }) });
|
|
33
33
|
}
|
|
34
|
+
const GAME_ORIENTATIONS = ["portrait", "landscape"];
|
|
34
35
|
function ChatBar({
|
|
35
36
|
onSend,
|
|
36
37
|
onClose,
|
|
37
38
|
placeholder = "Message everyone here",
|
|
38
|
-
quickAsk
|
|
39
|
+
quickAsk,
|
|
40
|
+
quickReport
|
|
39
41
|
}) {
|
|
40
42
|
const [draft, setDraft] = React.useState("");
|
|
41
43
|
const send = () => {
|
|
@@ -43,12 +45,15 @@ function ChatBar({
|
|
|
43
45
|
if (text) onSend(text);
|
|
44
46
|
onClose();
|
|
45
47
|
};
|
|
46
|
-
return /* @__PURE__ */ jsx(Modal, { transparent: true, visible: true, animationType: "fade", onRequestClose: onClose, children: /* @__PURE__ */ jsxs(KeyboardAvoidingView, { behavior: Platform.OS === "ios" ? "padding" : void 0, style: styles.fillClear, children: [
|
|
48
|
+
return /* @__PURE__ */ jsx(Modal, { transparent: true, visible: true, animationType: "fade", supportedOrientations: GAME_ORIENTATIONS, onRequestClose: onClose, children: /* @__PURE__ */ jsxs(KeyboardAvoidingView, { behavior: Platform.OS === "ios" ? "padding" : void 0, style: styles.fillClear, children: [
|
|
47
49
|
/* @__PURE__ */ jsx(Pressable, { accessibilityLabel: "Close chat", style: styles.fillClear, onPress: onClose }),
|
|
48
|
-
quickAsk ? /* @__PURE__ */
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
50
|
+
quickAsk || quickReport ? /* @__PURE__ */ jsxs(View, { style: styles.quickRow, children: [
|
|
51
|
+
quickAsk ? /* @__PURE__ */ jsx(Pressable, { accessibilityRole: "button", onPress: () => {
|
|
52
|
+
onSend(quickAsk.message);
|
|
53
|
+
onClose();
|
|
54
|
+
}, style: styles.quickAsk, children: /* @__PURE__ */ jsx(Text, { style: styles.chatSendLabel, children: quickAsk.label }) }) : null,
|
|
55
|
+
quickReport ? /* @__PURE__ */ jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: "Report last reply", onPress: quickReport, style: styles.quickReport, children: /* @__PURE__ */ jsx(MaterialCommunityIcons, { name: "flag-outline", size: 20, color: "#ffffff" }) }) : null
|
|
56
|
+
] }) : null,
|
|
52
57
|
/* @__PURE__ */ jsxs(View, { style: styles.chatBar, children: [
|
|
53
58
|
/* @__PURE__ */ jsx(TextInput, { autoFocus: true, value: draft, onChangeText: setDraft, onSubmitEditing: send, maxLength: MAX_CHAT_CHARS, placeholder, placeholderTextColor: "#94a3b8", returnKeyType: "send", style: styles.chatInput }),
|
|
54
59
|
/* @__PURE__ */ jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: "Send", onPress: send, style: styles.chatSend, children: /* @__PURE__ */ jsx(Text, { style: styles.chatSendLabel, children: "Send" }) })
|
|
@@ -73,6 +78,7 @@ function cubeforge3DComponent() {
|
|
|
73
78
|
helper
|
|
74
79
|
}) {
|
|
75
80
|
const engine = React.useRef(null);
|
|
81
|
+
React.useEffect(letGameTurnWithPhone, []);
|
|
76
82
|
const [chatting, setChatting] = React.useState(false);
|
|
77
83
|
const [asking, setAsking] = React.useState(false);
|
|
78
84
|
const [askingConsent, setAskingConsent] = React.useState(false);
|
|
@@ -80,14 +86,18 @@ function cubeforge3DComponent() {
|
|
|
80
86
|
if (await helperConsentGiven(AsyncStorage)) setAsking(true);
|
|
81
87
|
else setAskingConsent(true);
|
|
82
88
|
};
|
|
89
|
+
const apollo = React.useContext(getApolloContext()).client;
|
|
90
|
+
const [lastReply, setLastReply] = React.useState("");
|
|
83
91
|
const askHelper = async (message) => {
|
|
84
|
-
if (engine.current
|
|
92
|
+
if (!engine.current || !helper) return;
|
|
93
|
+
const said = await askAndPreview(engine.current, helper, message);
|
|
94
|
+
if (said) setLastReply(said);
|
|
85
95
|
};
|
|
86
96
|
return /* @__PURE__ */ jsxs(SafeAreaView, { edges: ["bottom", "left", "right"], style: styles.fill, children: [
|
|
87
97
|
/* @__PURE__ */ jsx(NativeCubeforge, { ref: engine, style: styles.fill, seed, worldKey, room, skin, onExit: (event) => {
|
|
88
98
|
var _a;
|
|
89
99
|
return onExit(((_a = event.nativeEvent) == null ? void 0 : _a.summary) || void 0);
|
|
90
|
-
}, helperEnabled: Boolean(helper), onOpenHelper: () =>
|
|
100
|
+
}, helperEnabled: Boolean(helper), onOpenHelper: () => openHelper().catch(() => void 0), onOpenChat: () => setChatting(true), onRoomClosed: () => onRoomClosed == null ? void 0 : onRoomClosed(), onTokenExpired: () => onTokenExpired == null ? void 0 : onTokenExpired() }),
|
|
91
101
|
chatting ? /* @__PURE__ */ jsx(ChatBar, { onSend: (text) => {
|
|
92
102
|
var _a;
|
|
93
103
|
(_a = engine.current) == null ? void 0 : _a.sendChat(text).catch(() => void 0);
|
|
@@ -95,7 +105,10 @@ function cubeforge3DComponent() {
|
|
|
95
105
|
asking ? /* @__PURE__ */ jsx(ChatBar, { placeholder: "Ask your helper", quickAsk: {
|
|
96
106
|
label: "Beautify what I built",
|
|
97
107
|
message: BEAUTIFY_MESSAGE
|
|
98
|
-
},
|
|
108
|
+
}, quickReport: apollo && lastReply ? () => reportAiContent(apollo, {
|
|
109
|
+
surface: "cubeforge-helper",
|
|
110
|
+
content: lastReply
|
|
111
|
+
}) : void 0, onSend: (text) => askHelper(text).catch(() => void 0), onClose: () => setAsking(false) }) : null,
|
|
99
112
|
askingConsent ? /* @__PURE__ */ jsx(HelperConsent, { onClose: () => setAskingConsent(false), onAgree: () => {
|
|
100
113
|
setAskingConsent(false);
|
|
101
114
|
setAsking(true);
|
|
@@ -145,16 +158,28 @@ const styles = StyleSheet.create({
|
|
|
145
158
|
fontSize: 15,
|
|
146
159
|
fontWeight: "600"
|
|
147
160
|
},
|
|
148
|
-
|
|
149
|
-
|
|
161
|
+
quickRow: {
|
|
162
|
+
flexDirection: "row",
|
|
163
|
+
alignItems: "center",
|
|
164
|
+
gap: 8,
|
|
150
165
|
marginLeft: 10,
|
|
151
|
-
marginBottom: 8
|
|
166
|
+
marginBottom: 8
|
|
167
|
+
},
|
|
168
|
+
quickAsk: {
|
|
152
169
|
minHeight: 40,
|
|
153
170
|
paddingHorizontal: 14,
|
|
154
171
|
borderRadius: 20,
|
|
155
172
|
justifyContent: "center",
|
|
156
173
|
backgroundColor: "#3f7fbf"
|
|
157
174
|
},
|
|
175
|
+
quickReport: {
|
|
176
|
+
width: 40,
|
|
177
|
+
height: 40,
|
|
178
|
+
borderRadius: 20,
|
|
179
|
+
alignItems: "center",
|
|
180
|
+
justifyContent: "center",
|
|
181
|
+
backgroundColor: "#475569"
|
|
182
|
+
},
|
|
158
183
|
consentBackdrop: {
|
|
159
184
|
flex: 1,
|
|
160
185
|
alignItems: "center",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cubeforge3D.js","sources":["../../../src/features/games/cubeforge3D.tsx"],"sourcesContent":["/**\n * Cubeforge 3D: the native Rust engine (portable-devices/mobile/modules/\n * yantra-cubeforge, Metal on iOS, Vulkan or GL on Android) as the `cubeforge3D`\n * component Yantra Games shows behind \"Play in 3D\".\n *\n * Optional on purpose: an over-the-air JS update can reach a binary built\n * before the module existed, and 32-bit Android phones have no engine. Both\n * read as \"no module\", and Yantra Games then simply hides \"Play in 3D\".\n */\nimport * as React from 'react';\nimport {\n KeyboardAvoidingView,\n Modal,\n Platform,\n Pressable,\n StyleSheet,\n Text,\n TextInput,\n View,\n type ViewProps,\n} from 'react-native';\nimport { requireNativeViewManager, requireOptionalNativeModule } from 'expo-modules-core';\nimport { SafeAreaView } from 'react-native-safe-area-context';\nimport AsyncStorage from '@react-native-async-storage/async-storage';\nimport { askAndPreview, helperConsentGiven, rememberHelperConsent } from './cubeforgeHelper';\nimport type { Cubeforge3DProps } from './vendored';\n\ninterface NativeCubeforgeProps extends ViewProps {\n seed: number;\n worldKey: string;\n room?: Cubeforge3DProps['room'];\n skin?: string;\n onExit: (event: { nativeEvent?: { summary?: string } }) => void;\n onOpenChat: () => void;\n onOpenHelper: () => void;\n helperEnabled: boolean;\n onRoomClosed: () => void;\n onTokenExpired: () => void;\n}\n\ninterface NativeCubeforgeHandle {\n sendChat: (text: string) => Promise<boolean>;\n helperSnapshot: () => Promise<string | null>;\n helperPropose: (plan: string) => Promise<number>;\n helperSay: (text: string) => Promise<boolean>;\n}\n\ntype NativeCubeforgeView = React.ComponentType<NativeCubeforgeProps & React.RefAttributes<NativeCubeforgeHandle>>;\n\ninterface NativeCubeforgeModule {\n deleteWorld?: (worldKey: string) => void;\n /** Address of the world's saved picture; absent on older binaries. */\n picturePath?: (worldKey: string) => string | null;\n /** Android only: false on a CPU the engine is not built for. */\n engineAvailable?: boolean;\n}\n\nconst MAX_CHAT_CHARS = 200;\n\nconst SUPPORTED_PLATFORMS = new Set(['ios', 'android']);\n\nfunction nativeModule(): NativeCubeforgeModule | null {\n if (!SUPPORTED_PLATFORMS.has(Platform.OS)) return null;\n const module = requireOptionalNativeModule<NativeCubeforgeModule>('YantraCubeforge');\n return module?.engineAvailable === false ? null : module;\n}\n\n/** Whether this binary's engine can join shared worlds. Older ones cannot. */\nexport function cubeforgeFriendsSupported(): boolean {\n return typeof nativeModule()?.deleteWorld === 'function';\n}\n\n/** Remove a 3D world's save from this device. */\nexport function deleteCubeforgeSave(worldKey: string): void {\n nativeModule()?.deleteWorld?.(worldKey);\n}\n\n/** Address of a 3D world's saved picture, or null when it has none. */\nexport function cubeforgePicture(worldKey: string): string | null {\n return nativeModule()?.picturePath?.(worldKey) ?? null;\n}\n\nconst BEAUTIFY_MESSAGE = 'Make what I built look better';\n\nfunction HelperConsent({ onAgree, onClose }: { onAgree: () => void; onClose: () => void }) {\n return (\n <Modal transparent visible animationType=\"fade\" onRequestClose={onClose}>\n <View style={styles.consentBackdrop}>\n <View style={styles.consentCard}>\n <Text style={styles.consentTitle}>Your build helper</Text>\n <Text style={styles.consentBody}>\n To suggest ideas, your helper sends Yantra's AI the blocks around you and what you type.\n Your name, your friends and your chats are not sent.\n </Text>\n <View style={styles.consentRow}>\n <Pressable accessibilityRole=\"button\" onPress={onClose} style={styles.consentSecondary}>\n <Text style={styles.consentSecondaryLabel}>Not now</Text>\n </Pressable>\n <Pressable accessibilityRole=\"button\" onPress={onAgree} style={styles.chatSend}>\n <Text style={styles.chatSendLabel}>OK</Text>\n </Pressable>\n </View>\n </View>\n </View>\n </Modal>\n );\n}\n\nfunction ChatBar({\n onSend,\n onClose,\n placeholder = 'Message everyone here',\n quickAsk,\n}: {\n onSend: (text: string) => void;\n onClose: () => void;\n placeholder?: string;\n quickAsk?: { label: string; message: string };\n}) {\n const [draft, setDraft] = React.useState('');\n const send = () => {\n const text = draft.trim();\n if (text) onSend(text);\n onClose();\n };\n return (\n <Modal transparent visible animationType=\"fade\" onRequestClose={onClose}>\n <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={styles.fillClear}>\n <Pressable accessibilityLabel=\"Close chat\" style={styles.fillClear} onPress={onClose} />\n {quickAsk ? (\n <Pressable\n accessibilityRole=\"button\"\n onPress={() => {\n onSend(quickAsk.message);\n onClose();\n }}\n style={styles.quickAsk}\n >\n <Text style={styles.chatSendLabel}>{quickAsk.label}</Text>\n </Pressable>\n ) : null}\n <View style={styles.chatBar}>\n <TextInput\n autoFocus\n value={draft}\n onChangeText={setDraft}\n onSubmitEditing={send}\n maxLength={MAX_CHAT_CHARS}\n placeholder={placeholder}\n placeholderTextColor=\"#94a3b8\"\n returnKeyType=\"send\"\n style={styles.chatInput}\n />\n <Pressable\n accessibilityRole=\"button\"\n accessibilityLabel=\"Send\"\n onPress={send}\n style={styles.chatSend}\n >\n <Text style={styles.chatSendLabel}>Send</Text>\n </Pressable>\n </View>\n </KeyboardAvoidingView>\n </Modal>\n );\n}\n\nlet cached: React.ComponentType<Cubeforge3DProps> | null | undefined;\n\n/** The 3D component when this binary ships the engine, otherwise null. */\nexport function cubeforge3DComponent(): React.ComponentType<Cubeforge3DProps> | null {\n if (cached !== undefined) return cached;\n cached = null;\n try {\n if (!nativeModule()) return cached;\n const NativeCubeforge = requireNativeViewManager<NativeCubeforgeProps>(\n 'YantraCubeforge',\n ) as unknown as NativeCubeforgeView;\n cached = function Cubeforge3D({\n seed,\n worldKey,\n room,\n skin,\n onExit,\n onRoomClosed,\n onTokenExpired,\n helper,\n }: Cubeforge3DProps) {\n const engine = React.useRef<NativeCubeforgeHandle>(null);\n const [chatting, setChatting] = React.useState(false);\n const [asking, setAsking] = React.useState(false);\n const [askingConsent, setAskingConsent] = React.useState(false);\n\n const openHelper = async () => {\n if (await helperConsentGiven(AsyncStorage)) setAsking(true);\n else setAskingConsent(true);\n };\n\n const askHelper = async (message: string) => {\n if (engine.current && helper) await askAndPreview(engine.current, helper, message);\n };\n\n // The engine draws edge to edge; keep its HUD clear of the home indicator.\n return (\n <SafeAreaView edges={['bottom', 'left', 'right']} style={styles.fill}>\n <NativeCubeforge\n ref={engine}\n style={styles.fill}\n seed={seed}\n worldKey={worldKey}\n room={room}\n skin={skin}\n onExit={(event) => onExit(event.nativeEvent?.summary || undefined)}\n helperEnabled={Boolean(helper)}\n onOpenHelper={() => void openHelper().catch(() => undefined)}\n onOpenChat={() => setChatting(true)}\n onRoomClosed={() => onRoomClosed?.()}\n onTokenExpired={() => onTokenExpired?.()}\n />\n {chatting ? (\n <ChatBar\n onSend={(text) => {\n engine.current?.sendChat(text).catch(() => undefined);\n }}\n onClose={() => setChatting(false)}\n />\n ) : null}\n {asking ? (\n <ChatBar\n placeholder=\"Ask your helper\"\n quickAsk={{ label: 'Beautify what I built', message: BEAUTIFY_MESSAGE }}\n onSend={(text) => void askHelper(text).catch(() => undefined)}\n onClose={() => setAsking(false)}\n />\n ) : null}\n {askingConsent ? (\n <HelperConsent\n onClose={() => setAskingConsent(false)}\n onAgree={() => {\n setAskingConsent(false);\n setAsking(true);\n void rememberHelperConsent(AsyncStorage).catch(() => undefined);\n }}\n />\n ) : null}\n </SafeAreaView>\n );\n };\n } catch {\n cached = null;\n }\n return cached;\n}\n\nconst styles = StyleSheet.create({\n fill: { flex: 1, backgroundColor: '#000' },\n fillClear: { flex: 1 },\n chatBar: { flexDirection: 'row', alignItems: 'center', gap: 8, padding: 10, backgroundColor: '#12161b' },\n chatInput: {\n flex: 1,\n minHeight: 44,\n borderRadius: 10,\n paddingHorizontal: 12,\n color: '#f1f5f9',\n backgroundColor: '#242b33',\n fontSize: 16,\n },\n chatSend: {\n minHeight: 44,\n minWidth: 64,\n borderRadius: 10,\n alignItems: 'center',\n justifyContent: 'center',\n backgroundColor: '#3f7fbf',\n },\n chatSendLabel: { color: '#ffffff', fontSize: 15, fontWeight: '600' },\n quickAsk: {\n alignSelf: 'flex-start',\n marginLeft: 10,\n marginBottom: 8,\n minHeight: 40,\n paddingHorizontal: 14,\n borderRadius: 20,\n justifyContent: 'center',\n backgroundColor: '#3f7fbf',\n },\n consentBackdrop: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: 24, backgroundColor: 'rgba(0,0,0,0.55)' },\n consentCard: { maxWidth: 420, width: '100%', gap: 12, padding: 20, borderRadius: 14, backgroundColor: '#12161b' },\n consentTitle: { color: '#f1f5f9', fontSize: 18, fontWeight: '700' },\n consentBody: { color: '#cbd5e1', fontSize: 15, lineHeight: 21 },\n consentRow: { flexDirection: 'row', justifyContent: 'flex-end', gap: 8 },\n consentSecondary: { min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AAA;AAAA,IACT,YAAc,EAAA,EAAA;AAAA,IACd,eAAiB,EAAA;AAAA,GACnB;AAAA,EACA,YAAc,EAAA;AAAA,IACZ,KAAO,EAAA,SAAA;AAAA,IACP,QAAU,EAAA,EAAA;AAAA,IACV,UAAY,EAAA;AAAA,GACd;AAAA,EACA,WAAa,EAAA;AAAA,IACX,KAAO,EAAA,SAAA;AAAA,IACP,QAAU,EAAA,EAAA;AAAA,IACV,UAAY,EAAA;AAAA,GACd;AAAA,EACA,UAAY,EAAA;AAAA,IACV,aAAe,EAAA,KAAA;AAAA,IACf,cAAgB,EAAA,UAAA;AAAA,IAChB,GAAK,EAAA;AAAA,GACP;AAAA,EACA,gBAAkB,EAAA;AAAA,IAChB,SAAW,EAAA,EAAA;AAAA,IACX,QAAU,EAAA,EAAA;AAAA,IACV,UAAY,EAAA,QAAA;AAAA,IACZ,cAAgB,EAAA;AAAA,GAClB;AAAA,EACA,qBAAuB,EAAA;AAAA,IACrB,KAAO,EAAA,SAAA;AAAA,IACP,QAAU,EAAA,EAAA;AAAA,IACV,UAAY,EAAA;AAAA;AAEhB,CAAC,CAAA"}
|
|
1
|
+
{"version":3,"file":"cubeforge3D.js","sources":["../../../src/features/games/cubeforge3D.tsx"],"sourcesContent":["/**\n * Cubeforge 3D: the native Rust engine (portable-devices/mobile/modules/\n * yantra-cubeforge, Metal on iOS, Vulkan or GL on Android) as the `cubeforge3D`\n * component Yantra Games shows behind \"Play in 3D\".\n *\n * Optional on purpose: an over-the-air JS update can reach a binary built\n * before the module existed, and 32-bit Android phones have no engine. Both\n * read as \"no module\", and Yantra Games then simply hides \"Play in 3D\".\n */\nimport * as React from 'react';\nimport { MaterialCommunityIcons } from '@expo/vector-icons';\nimport {\n KeyboardAvoidingView,\n Modal,\n Platform,\n Pressable,\n StyleSheet,\n Text,\n TextInput,\n View,\n type ViewProps,\n} from 'react-native';\nimport { requireNativeViewManager, requireOptionalNativeModule } from 'expo-modules-core';\nimport { SafeAreaView } from 'react-native-safe-area-context';\nimport { getApolloContext } from '@apollo/client';\nimport AsyncStorage from '@react-native-async-storage/async-storage';\nimport { reportAiContent } from '../reporting/reportAiContent';\nimport { letGameTurnWithPhone } from './gameOrientation';\nimport { askAndPreview, helperConsentGiven, rememberHelperConsent } from './cubeforgeHelper';\nimport type { Cubeforge3DProps } from './vendored';\n\ninterface NativeCubeforgeProps extends ViewProps {\n seed: number;\n worldKey: string;\n room?: Cubeforge3DProps['room'];\n skin?: string;\n onExit: (event: { nativeEvent?: { summary?: string } }) => void;\n onOpenChat: () => void;\n onOpenHelper: () => void;\n helperEnabled: boolean;\n onRoomClosed: () => void;\n onTokenExpired: () => void;\n}\n\ninterface NativeCubeforgeHandle {\n sendChat: (text: string) => Promise<boolean>;\n helperSnapshot: () => Promise<string | null>;\n helperPropose: (plan: string) => Promise<number>;\n helperSay: (text: string) => Promise<boolean>;\n}\n\ntype NativeCubeforgeView = React.ComponentType<NativeCubeforgeProps & React.RefAttributes<NativeCubeforgeHandle>>;\n\ninterface NativeCubeforgeModule {\n deleteWorld?: (worldKey: string) => void;\n /** Address of the world's saved picture; absent on older binaries. */\n picturePath?: (worldKey: string) => string | null;\n /** Android only: false on a CPU the engine is not built for. */\n engineAvailable?: boolean;\n}\n\nconst MAX_CHAT_CHARS = 200;\n\nconst SUPPORTED_PLATFORMS = new Set(['ios', 'android']);\n\nfunction nativeModule(): NativeCubeforgeModule | null {\n if (!SUPPORTED_PLATFORMS.has(Platform.OS)) return null;\n const module = requireOptionalNativeModule<NativeCubeforgeModule>('YantraCubeforge');\n return module?.engineAvailable === false ? null : module;\n}\n\n/** Whether this binary's engine can join shared worlds. Older ones cannot. */\nexport function cubeforgeFriendsSupported(): boolean {\n return typeof nativeModule()?.deleteWorld === 'function';\n}\n\n/** Remove a 3D world's save from this device. */\nexport function deleteCubeforgeSave(worldKey: string): void {\n nativeModule()?.deleteWorld?.(worldKey);\n}\n\n/** Address of a 3D world's saved picture, or null when it has none. */\nexport function cubeforgePicture(worldKey: string): string | null {\n return nativeModule()?.picturePath?.(worldKey) ?? null;\n}\n\nconst BEAUTIFY_MESSAGE = 'Make what I built look better';\n\nfunction HelperConsent({ onAgree, onClose }: { onAgree: () => void; onClose: () => void }) {\n return (\n <Modal\n transparent\n visible\n animationType=\"fade\"\n supportedOrientations={GAME_ORIENTATIONS}\n onRequestClose={onClose}\n >\n <View style={styles.consentBackdrop}>\n <View style={styles.consentCard}>\n <Text style={styles.consentTitle}>Your build helper</Text>\n <Text style={styles.consentBody}>\n To suggest ideas, your helper sends Yantra's AI the blocks around you and what you type.\n Your name, your friends and your chats are not sent.\n </Text>\n <View style={styles.consentRow}>\n <Pressable accessibilityRole=\"button\" onPress={onClose} style={styles.consentSecondary}>\n <Text style={styles.consentSecondaryLabel}>Not now</Text>\n </Pressable>\n <Pressable accessibilityRole=\"button\" onPress={onAgree} style={styles.chatSend}>\n <Text style={styles.chatSendLabel}>OK</Text>\n </Pressable>\n </View>\n </View>\n </View>\n </Modal>\n );\n}\n\n/** Without this, opening a box over the game on iOS forces it back upright. */\nconst GAME_ORIENTATIONS: ('portrait' | 'landscape')[] = ['portrait', 'landscape'];\n\nfunction ChatBar({\n onSend,\n onClose,\n placeholder = 'Message everyone here',\n quickAsk,\n quickReport,\n}: {\n onSend: (text: string) => void;\n onClose: () => void;\n placeholder?: string;\n quickAsk?: { label: string; message: string };\n quickReport?: () => void;\n}) {\n const [draft, setDraft] = React.useState('');\n const send = () => {\n const text = draft.trim();\n if (text) onSend(text);\n onClose();\n };\n return (\n <Modal\n transparent\n visible\n animationType=\"fade\"\n supportedOrientations={GAME_ORIENTATIONS}\n onRequestClose={onClose}\n >\n <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={styles.fillClear}>\n <Pressable accessibilityLabel=\"Close chat\" style={styles.fillClear} onPress={onClose} />\n {quickAsk || quickReport ? (\n <View style={styles.quickRow}>\n {quickAsk ? (\n <Pressable\n accessibilityRole=\"button\"\n onPress={() => {\n onSend(quickAsk.message);\n onClose();\n }}\n style={styles.quickAsk}\n >\n <Text style={styles.chatSendLabel}>{quickAsk.label}</Text>\n </Pressable>\n ) : null}\n {quickReport ? (\n <Pressable\n accessibilityRole=\"button\"\n accessibilityLabel=\"Report last reply\"\n onPress={quickReport}\n style={styles.quickReport}\n >\n <MaterialCommunityIcons name=\"flag-outline\" size={20} color=\"#ffffff\" />\n </Pressable>\n ) : null}\n </View>\n ) : null}\n <View style={styles.chatBar}>\n <TextInput\n autoFocus\n value={draft}\n onChangeText={setDraft}\n onSubmitEditing={send}\n maxLength={MAX_CHAT_CHARS}\n placeholder={placeholder}\n placeholderTextColor=\"#94a3b8\"\n returnKeyType=\"send\"\n style={styles.chatInput}\n />\n <Pressable\n accessibilityRole=\"button\"\n accessibilityLabel=\"Send\"\n onPress={send}\n style={styles.chatSend}\n >\n <Text style={styles.chatSendLabel}>Send</Text>\n </Pressable>\n </View>\n </KeyboardAvoidingView>\n </Modal>\n );\n}\n\nlet cached: React.ComponentType<Cubeforge3DProps> | null | undefined;\n\n/** The 3D component when this binary ships the engine, otherwise null. */\nexport function cubeforge3DComponent(): React.ComponentType<Cubeforge3DProps> | null {\n if (cached !== undefined) return cached;\n cached = null;\n try {\n if (!nativeModule()) return cached;\n const NativeCubeforge = requireNativeViewManager<NativeCubeforgeProps>(\n 'YantraCubeforge',\n ) as unknown as NativeCubeforgeView;\n cached = function Cubeforge3D({\n seed,\n worldKey,\n room,\n skin,\n onExit,\n onRoomClosed,\n onTokenExpired,\n helper,\n }: Cubeforge3DProps) {\n const engine = React.useRef<NativeCubeforgeHandle>(null);\n React.useEffect(letGameTurnWithPhone, []);\n const [chatting, setChatting] = React.useState(false);\n const [asking, setAsking] = React.useState(false);\n const [askingConsent, setAskingConsent] = React.useState(false);\n\n const openHelper = async () => {\n if (await helperConsentGiven(AsyncStorage)) setAsking(true);\n else setAskingConsent(true);\n };\n\n const apollo = React.useContext(getApolloContext()).client;\n const [lastReply, setLastReply] = React.useState('');\n\n const askHelper = async (message: string) => {\n if (!engine.current || !helper) return;\n const said = await askAndPreview(engine.current, helper, message);\n if (said) setLastReply(said);\n };\n\n // The engine draws edge to edge; keep its HUD clear of the home indicator.\n return (\n <SafeAreaView edges={['bottom', 'left', 'right']} style={styles.fill}>\n <NativeCubeforge\n ref={engine}\n style={styles.fill}\n seed={seed}\n worldKey={worldKey}\n room={room}\n skin={skin}\n onExit={(event) => onExit(event.nativeEvent?.summary || undefined)}\n helperEnabled={Boolean(helper)}\n onOpenHelper={() => openHelper().catch(() => undefined)}\n onOpenChat={() => setChatting(true)}\n onRoomClosed={() => onRoomClosed?.()}\n onTokenExpired={() => onTokenExpired?.()}\n />\n {chatting ? (\n <ChatBar\n onSend={(text) => {\n engine.current?.sendChat(text).catch(() => undefined);\n }}\n onClose={() => setChatting(false)}\n />\n ) : null}\n {asking ? (\n <ChatBar\n placeholder=\"Ask your helper\"\n quickAsk={{ label: 'Beautify what I built', message: BEAUTIFY_MESSAGE }}\n quickReport={\n apollo && lastReply\n ? () => reportAiContent(apollo, { surface: 'cubeforge-helper', content: lastReply })\n : undefined\n }\n onSend={(text) => askHelper(text).catch(() => undefined)}\n onClose={() => setAsking(false)}\n />\n ) : null}\n {askingConsent ? (\n <HelperConsent\n onClose={() => setAskingConsent(false)}\n onAgree={() => {\n setAskingConsent(false);\n setAsking(true);\n void rememberHelperConsent(AsyncStorage).catch(() => undefined);\n }}\n />\n ) : null}\n </SafeAreaView>\n );\n };\n } catch {\n cached = null;\n }\n return cached;\n}\n\nconst styles = StyleSheet.create({\n fill: { flex: 1, backgroundColor: '#000' },\n fillClear: { flex: 1 },\n chatBar: { flexDirection: 'row', alignItems: 'center', gap: 8, padding: 10, backgroundColor: '#12161b' },\n chatInput: {\n flex: 1,\n minHeight: 44,\n borderRadius: 10,\n paddingHorizontal: 12,\n color: '#f1f5f9',\n backgroundColor: '#242b33',\n fontSize: 16,\n },\n chatSend: {\n minHeight: 44,\n minWidth: 64,\n borderRadius: 10,\n alignItems: 'center',\n justifyContent: 'center',\n backgroundColor: '#3f7fbf',\n },\n chatSendLabel: { color: '#ffffff', fontSize: 15, fontWeight: '600' },\n quickRow: { flexDirection: 'row', alignItems: 'center', gap: 8, marginLeft: 10, marginBottom: 8 },\n quickAsk: {\n minHeight: 40,\n paddingHorizontal: 14,\n borderRadius: 20,\n justifyContent: 'center',\n backgroundColor: '#3f7fbf',\n },\n quickReport: {\n width: 40,\n height: 40,\n borderRadius: 20,\n alignItems: 'center',\n justifyContent: 'center',\n backgroundColor: '#475569',\n },\n consentBackdrop: {\n flex: 1,\n alignItems: 'center',\n justifyContent: 'center',\n padding: 24,\n backgroundColor: 'rgba(0,0,0,0.55)',\n },\n consentCard: { maxWidth: 420, width: '100%', gap: 12, padding: 20, borderRadius: 14, backgroundColor: '#12161b' },\n consentTitle: { color: '#f1f5f9', fontSize: 18, fontWeight: '700' },\n consentBody: { color: '#cbd5e1', fontSize: 15, lineHeight: 21 },\n consentRow: { flexDirection: 'row', justifyContent: 'flex-end', gap: 8 },\n consentSecondary: { minHeight: 44, minWidth: 80, alignItems: 'center', justifyContent: 'center' },\n consentSecondaryLabel: { color: '#cbd5e1', fontSize: 15, fontWeight: '600' },\n});\n"],"names":[],"mappings":"+rBAkDA,MAAM,cAAiB,GAAA,GAAA;AACvB,MAAM,sCAA0B,IAAA,GAAA,CAAI,CAAC,KAAA,EAAO,SAAS,CAAC,CAAA;AACtD,SAAS,YAA6C,GAAA;AACpD,EAAA,IAAI,CAAC,mBAAoB,CAAA,GAAA,CAAI,QAAS,CAAA,EAAE,GAAU,OAAA,IAAA;AAClD,EAAM,MAAA,MAAA,GAAS,4BAAmD,iBAAiB,CAAA;AACnF,EAAO,OAAA,CAAA,MAAA,IAAA,IAAA,GAAA,MAAA,GAAA,MAAA,CAAQ,eAAoB,MAAA,KAAA,GAAQ,IAAO,GAAA,MAAA;AACpD;AAGO,SAAS,yBAAqC,GAAA;AA3DrD,EAAA,IAAA,EAAA;AA4DE,EAA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,IACX,QAAU,EAAA,EAAA;AAAA,IACV,UAAY,EAAA,QAAA;AAAA,IACZ,cAAgB,EAAA;AAAA,GAClB;AAAA,EACA,qBAAuB,EAAA;AAAA,IACrB,KAAO,EAAA,SAAA;AAAA,IACP,QAAU,EAAA,EAAA;AAAA,IACV,UAAY,EAAA;AAAA;AAEhB,CAAC,CAAA"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {inviteMessage}from'./gameInvite.js';const TERRAIN_GENERATION = 2;
|
|
1
|
+
import {inviteMessage,parseInviteMessage}from'./gameInvite.js';const TERRAIN_GENERATION = 2;
|
|
2
2
|
const WORLD_FIELDS = "id name seed memberIds inviteCode viewerIsOwner";
|
|
3
3
|
const UNREACHABLE = "Could not reach the game server. Check your connection and try again.";
|
|
4
4
|
const SIGN_IN = "Please sign in again.";
|
|
@@ -30,6 +30,7 @@ function createCubeforgeFriends(deps) {
|
|
|
30
30
|
playerName,
|
|
31
31
|
listChats,
|
|
32
32
|
sendToChat,
|
|
33
|
+
recentChatMessages,
|
|
33
34
|
fetchImpl = fetch
|
|
34
35
|
} = deps;
|
|
35
36
|
const post = async (query, variables, token) => {
|
|
@@ -115,6 +116,21 @@ function createCubeforgeFriends(deps) {
|
|
|
115
116
|
});
|
|
116
117
|
},
|
|
117
118
|
listChats,
|
|
119
|
+
listInvites: async () => (await recentChatMessages()).flatMap(({
|
|
120
|
+
body,
|
|
121
|
+
from,
|
|
122
|
+
chatTitle,
|
|
123
|
+
sentAt
|
|
124
|
+
}) => {
|
|
125
|
+
const invite = parseInviteMessage(body);
|
|
126
|
+
return invite ? [{
|
|
127
|
+
code: invite.code,
|
|
128
|
+
worldName: invite.worldName,
|
|
129
|
+
from,
|
|
130
|
+
chatTitle,
|
|
131
|
+
sentAt
|
|
132
|
+
}] : [];
|
|
133
|
+
}),
|
|
118
134
|
inviteToChat: async (world, chatId) => {
|
|
119
135
|
if (!world.inviteCode) throw new Error("This world has no invite code.");
|
|
120
136
|
await sendToChat(chatId, inviteMessage(world.name, world.inviteCode));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cubeforgeFriends.js","sources":["../../../src/features/games/cubeforgeFriends.ts"],"sourcesContent":["/**\n * Shared Cubeforge worlds over the games subgraph, and invites over chat.\n * Everything that touches the app (tokens, chat) comes in through `FriendsDeps`,\n * so this file can be tested without a running app.\n */\nimport type { CubeforgeFriends, InviteChat, SharedWorld } from './vendored';\nimport { inviteMessage } from './gameInvite';\n\n/**\n * The terrain new shared worlds are made with. Only raise this in the same change\n * that vendors an engine able to draw it: the server refuses older engines from such\n * a world, so a mismatch would lock this app out of the worlds it creates.\n */\nconst TERRAIN_GENERATION = 2;\n\nexport interface FriendsDeps {\n /** `https://host/graphql`. */\n graphqlUrl: string;\n /** A bearer token; `renew` asks for a new one. Null when signed out. */\n getToken: (renew: boolean) => Promise<string | null>;\n playerName: () => string;\n listChats: () => Promise<InviteChat[]>;\n sendToChat: (chatId: string, text: string) => Promise<void>;\n fetchImpl?: typeof fetch;\n}\n\ninterface WireWorld {\n id: string;\n name: string;\n seed: number;\n memberIds: string[];\n inviteCode: string | null;\n viewerIsOwner: boolean;\n}\n\ninterface GraphQLResponse<T> {\n data?: T | null;\n errors?: { message?: string; extensions?: { code?: string } }[];\n}\n\nconst WORLD_FIELDS = 'id name seed memberIds inviteCode viewerIsOwner';\nconst UNREACHABLE = 'Could not reach the game server. Check your connection and try again.';\nconst SIGN_IN = 'Please sign in again.';\n/** Longer than the session's own two quick retries, 3s then 10s after a failed mint. */\nconst TOKEN_WAIT_MS = 15_000;\nconst TOKEN_POLL_MS = 250;\n\nconst toWorld = (w: WireWorld): SharedWorld => ({\n id: w.id,\n name: w.name,\n seed: w.seed,\n memberCount: w.memberIds.length,\n inviteCode: w.inviteCode,\n ownedByMe: w.viewerIsOwner,\n});\n\n/**\n * Waits for a token that is still on its way. The app opens Games from a chat\n * card as soon as it is tapped, which can be before the signed-in session exists.\n */\nexport async function waitForToken(\n read: () => string | null,\n timeoutMs = TOKEN_WAIT_MS,\n intervalMs = TOKEN_POLL_MS,\n): Promise<string | null> {\n const deadline = Date.now() + timeoutMs;\n let token = read();\n while (!token && Date.now() < deadline) {\n // eslint-disable-next-line no-await-in-loop\n await new Promise((resolve) => {\n setTimeout(resolve, intervalMs);\n });\n token = read();\n }\n return token;\n}\n\nexport function createCubeforgeFriends(deps: FriendsDeps): CubeforgeFriends {\n const { graphqlUrl, getToken, playerName, listChats, sendToChat, fetchImpl = fetch } = deps;\n\n const post = async <T>(query: string, variables: object, token: string): Promise<GraphQLResponse<T> | 401> => {\n let response: Response;\n try {\n response = await fetchImpl(graphqlUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },\n body: JSON.stringify({ query, variables }),\n });\n } catch {\n throw new Error(UNREACHABLE);\n }\n if (response.status === 401) return 401;\n try {\n return (await response.json()) as GraphQLResponse<T>;\n } catch {\n throw new Error(UNREACHABLE);\n }\n };\n\n const isUnauthenticated = <T>(result: GraphQLResponse<T> | 401): boolean =>\n result === 401 || Boolean(result.errors?.some((e) => e.extensions?.code === 'UNAUTHENTICATED'));\n\n const request = async <T>(query: string, variables: object = {}): Promise<T> => {\n const token = await getToken(false);\n if (!token) throw new Error(SIGN_IN);\n let result = await post<T>(query, variables, token);\n if (isUnauthenticated(result)) {\n const fresh = await getToken(true);\n if (!fresh) throw new Error(SIGN_IN);\n result = await post<T>(query, variables, fresh);\n }\n if (result === 401 || isUnauthenticated(result)) throw new Error(SIGN_IN);\n const message = result.errors?.[0]?.message;\n if (message) throw new Error(message);\n if (!result.data) throw new Error(UNREACHABLE);\n return result.data;\n };\n\n return {\n listWorlds: async () => {\n const data = await request<{ myGameWorlds: WireWorld[] }>(`query { myGameWorlds { ${WORLD_FIELDS} } }`);\n return data.myGameWorlds.map(toWorld);\n },\n createWorld: async (name, chatId) => {\n const data = await request<{ createGameWorld: WireWorld }>(\n `mutation($name: String!, $channelId: String, $gen: Int) { createGameWorld(name: $name, channelId: $channelId, gen: $gen) { ${WORLD_FIELDS} } }`,\n { name, channelId: chatId, gen: TERRAIN_GENERATION },\n );\n return toWorld(data.createGameWorld);\n },\n joinWorld: async (inviteCode) => {\n const data = await request<{ joinGameWorld: WireWorld }>(\n `mutation($inviteCode: String!) { joinGameWorld(inviteCode: $inviteCode) { ${WORLD_FIELDS} } }`,\n { inviteCode },\n );\n return toWorld(data.joinGameWorld);\n },\n leaveWorld: async (world) => {\n await request('mutation($id: ID!) { leaveGameWorld(id: $id) }', { id: world.id });\n },\n renameWorld: async (world, name) => {\n await request('mutation($id: ID!, $name: String!) { renameGameWorld(id: $id, name: $name) { id } }', {\n id: world.id,\n name,\n });\n },\n deleteWorld: async (world) => {\n await request('mutation($id: ID!) { deleteGameWorld(id: $id) }', { id: world.id });\n },\n listChats,\n inviteToChat: async (world, chatId) => {\n if (!world.inviteCode) throw new Error('This world has no invite code.');\n await sendToChat(chatId, inviteMessage(world.name, world.inviteCode));\n },\n roomAccess: async (world, options) => {\n const token = await getToken(Boolean(options?.renewToken));\n if (!token) throw new Error(SIGN_IN);\n const base = graphqlUrl.replace(/^http/, 'ws').replace(/\\/graphql\\/?$/, '');\n return { url: `${base}/rooms/${encodeURIComponent(world.id)}`, token, playerName: playerName() };\n },\n };\n}\n"],"names":["_a"],"mappings":"4CAaA,MAAM,kBAAqB,GAAA,CAAA;AA4B3B,MAAM,YAAe,GAAA,iDAAA;AACrB,MAAM,WAAc,GAAA,uEAAA;AACpB,MAAM,OAAU,GAAA,uBAAA;AAEhB,MAAM,aAAgB,GAAA,IAAA;AACtB,MAAM,aAAgB,GAAA,GAAA;AACtB,MAAM,OAAA,GAAU,CAAC,CAA+B,MAAA;AAAA,EAC9C,IAAI,CAAE,CAAA,EAAA;AAAA,EACN,MAAM,CAAE,CAAA,IAAA;AAAA,EACR,MAAM,CAAE,CAAA,IAAA;AAAA,EACR,WAAA,EAAa,EAAE,SAAU,CAAA,MAAA;AAAA,EACzB,YAAY,CAAE,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Friends.ts"],"sourcesContent":["/**\n * Shared Cubeforge worlds over the games subgraph, and invites over chat.\n * Everything that touches the app (tokens, chat) comes in through `FriendsDeps`,\n * so this file can be tested without a running app.\n */\nimport type { CubeforgeFriends, InviteChat, SharedWorld } from './vendored';\nimport { inviteMessage, parseInviteMessage } from './gameInvite';\n\n/**\n * The terrain new shared worlds are made with. Only raise this in the same change\n * that vendors an engine able to draw it: the server refuses older engines from such\n * a world, so a mismatch would lock this app out of the worlds it creates.\n */\nconst TERRAIN_GENERATION = 2;\n\n/** A chat message that may be an invite. */\nexport interface RecentChatMessage {\n body: string;\n /** Who sent it, or null when this player did. */\n from: string | null;\n chatTitle: string;\n sentAt: number;\n}\n\nexport interface FriendsDeps {\n /** `https://host/graphql`. */\n graphqlUrl: string;\n /** A bearer token; `renew` asks for a new one. Null when signed out. */\n getToken: (renew: boolean) => Promise<string | null>;\n playerName: () => string;\n listChats: () => Promise<InviteChat[]>;\n sendToChat: (chatId: string, text: string) => Promise<void>;\n recentChatMessages: () => Promise<RecentChatMessage[]>;\n fetchImpl?: typeof fetch;\n}\n\ninterface WireWorld {\n id: string;\n name: string;\n seed: number;\n memberIds: string[];\n inviteCode: string | null;\n viewerIsOwner: boolean;\n}\n\ninterface GraphQLResponse<T> {\n data?: T | null;\n errors?: { message?: string; extensions?: { code?: string } }[];\n}\n\nconst WORLD_FIELDS = 'id name seed memberIds inviteCode viewerIsOwner';\nconst UNREACHABLE = 'Could not reach the game server. Check your connection and try again.';\nconst SIGN_IN = 'Please sign in again.';\n/** Longer than the session's own two quick retries, 3s then 10s after a failed mint. */\nconst TOKEN_WAIT_MS = 15_000;\nconst TOKEN_POLL_MS = 250;\n\nconst toWorld = (w: WireWorld): SharedWorld => ({\n id: w.id,\n name: w.name,\n seed: w.seed,\n memberCount: w.memberIds.length,\n inviteCode: w.inviteCode,\n ownedByMe: w.viewerIsOwner,\n});\n\n/**\n * Waits for a token that is still on its way. The app opens Games from a chat\n * card as soon as it is tapped, which can be before the signed-in session exists.\n */\nexport async function waitForToken(\n read: () => string | null,\n timeoutMs = TOKEN_WAIT_MS,\n intervalMs = TOKEN_POLL_MS,\n): Promise<string | null> {\n const deadline = Date.now() + timeoutMs;\n let token = read();\n while (!token && Date.now() < deadline) {\n // eslint-disable-next-line no-await-in-loop\n await new Promise((resolve) => {\n setTimeout(resolve, intervalMs);\n });\n token = read();\n }\n return token;\n}\n\nexport function createCubeforgeFriends(deps: FriendsDeps): CubeforgeFriends {\n const { graphqlUrl, getToken, playerName, listChats, sendToChat, recentChatMessages, fetchImpl = fetch } = deps;\n\n const post = async <T>(query: string, variables: object, token: string): Promise<GraphQLResponse<T> | 401> => {\n let response: Response;\n try {\n response = await fetchImpl(graphqlUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },\n body: JSON.stringify({ query, variables }),\n });\n } catch {\n throw new Error(UNREACHABLE);\n }\n if (response.status === 401) return 401;\n try {\n return (await response.json()) as GraphQLResponse<T>;\n } catch {\n throw new Error(UNREACHABLE);\n }\n };\n\n const isUnauthenticated = <T>(result: GraphQLResponse<T> | 401): boolean =>\n result === 401 || Boolean(result.errors?.some((e) => e.extensions?.code === 'UNAUTHENTICATED'));\n\n const request = async <T>(query: string, variables: object = {}): Promise<T> => {\n const token = await getToken(false);\n if (!token) throw new Error(SIGN_IN);\n let result = await post<T>(query, variables, token);\n if (isUnauthenticated(result)) {\n const fresh = await getToken(true);\n if (!fresh) throw new Error(SIGN_IN);\n result = await post<T>(query, variables, fresh);\n }\n if (result === 401 || isUnauthenticated(result)) throw new Error(SIGN_IN);\n const message = result.errors?.[0]?.message;\n if (message) throw new Error(message);\n if (!result.data) throw new Error(UNREACHABLE);\n return result.data;\n };\n\n return {\n listWorlds: async () => {\n const data = await request<{ myGameWorlds: WireWorld[] }>(`query { myGameWorlds { ${WORLD_FIELDS} } }`);\n return data.myGameWorlds.map(toWorld);\n },\n createWorld: async (name, chatId) => {\n const data = await request<{ createGameWorld: WireWorld }>(\n `mutation($name: String!, $channelId: String, $gen: Int) { createGameWorld(name: $name, channelId: $channelId, gen: $gen) { ${WORLD_FIELDS} } }`,\n { name, channelId: chatId, gen: TERRAIN_GENERATION },\n );\n return toWorld(data.createGameWorld);\n },\n joinWorld: async (inviteCode) => {\n const data = await request<{ joinGameWorld: WireWorld }>(\n `mutation($inviteCode: String!) { joinGameWorld(inviteCode: $inviteCode) { ${WORLD_FIELDS} } }`,\n { inviteCode },\n );\n return toWorld(data.joinGameWorld);\n },\n leaveWorld: async (world) => {\n await request('mutation($id: ID!) { leaveGameWorld(id: $id) }', { id: world.id });\n },\n renameWorld: async (world, name) => {\n await request('mutation($id: ID!, $name: String!) { renameGameWorld(id: $id, name: $name) { id } }', {\n id: world.id,\n name,\n });\n },\n deleteWorld: async (world) => {\n await request('mutation($id: ID!) { deleteGameWorld(id: $id) }', { id: world.id });\n },\n listChats,\n listInvites: async () =>\n (await recentChatMessages()).flatMap(({ body, from, chatTitle, sentAt }) => {\n const invite = parseInviteMessage(body);\n return invite ? [{ code: invite.code, worldName: invite.worldName, from, chatTitle, sentAt }] : [];\n }),\n inviteToChat: async (world, chatId) => {\n if (!world.inviteCode) throw new Error('This world has no invite code.');\n await sendToChat(chatId, inviteMessage(world.name, world.inviteCode));\n },\n roomAccess: async (world, options) => {\n const token = await getToken(Boolean(options?.renewToken));\n if (!token) throw new Error(SIGN_IN);\n const base = graphqlUrl.replace(/^http/, 'ws').replace(/\\/graphql\\/?$/, '');\n return { url: `${base}/rooms/${encodeURIComponent(world.id)}`, token, playerName: playerName() };\n },\n };\n}\n"],"names":["_a"],"mappings":"+DAaA,MAAM,kBAAqB,GAAA,CAAA;AAsC3B,MAAM,YAAe,GAAA,iDAAA;AACrB,MAAM,WAAc,GAAA,uEAAA;AACpB,MAAM,OAAU,GAAA,uBAAA;AAEhB,MAAM,aAAgB,GAAA,IAAA;AACtB,MAAM,aAAgB,GAAA,GAAA;AACtB,MAAM,OAAA,GAAU,CAAC,CAA+B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AAY,OAAO,KAAA,EAAO,OAAY,KAAA;AACpC,MAAA,MAAM,QAAQ,MAAM,QAAA,CAAS,OAAQ,CAAA,OAAA,IAAA,IAAA,GAAA,MAAA,GAAA,OAAA,CAAS,UAAU,CAAC,CAAA;AACzD,MAAA,IAAI,CAAC,KAAA,EAAa,MAAA,IAAI,MAAM,OAAO,CAAA;AACnC,MAAM,MAAA,IAAA,GAAO,WAAW,OAAQ,CAAA,OAAA,EAAS,IAAI,CAAE,CAAA,OAAA,CAAQ,iBAAiB,EAAE,CAAA;AAC1E,MAAO,OAAA;AAAA,QACL,KAAK,CAAG,EAAA,IAAI,UAAU,kBAAmB,CAAA,KAAA,CAAM,EAAE,CAAC,CAAA,CAAA;AAAA,QAClD,KAAA;AAAA,QACA,YAAY,UAAW;AAAA,OACzB;AAAA;AACF,GACF;AACF"}
|
|
@@ -46,7 +46,7 @@ async function rememberHelperConsent(storage) {
|
|
|
46
46
|
}
|
|
47
47
|
async function askAndPreview(game, helper, message) {
|
|
48
48
|
const snapshot = await game.helperSnapshot();
|
|
49
|
-
if (!snapshot) return;
|
|
49
|
+
if (!snapshot) return null;
|
|
50
50
|
await game.helperSay("Let me take a look...");
|
|
51
51
|
const shown = async (answer2) => answer2.plan !== null && await game.helperPropose(JSON.stringify(answer2.plan)) > 0;
|
|
52
52
|
let answer = await helper.ask(message, snapshot);
|
|
@@ -58,10 +58,11 @@ async function askAndPreview(game, helper, message) {
|
|
|
58
58
|
};
|
|
59
59
|
if (!await shown(answer)) {
|
|
60
60
|
await game.helperSay(TOO_TIGHT_REPLY);
|
|
61
|
-
return;
|
|
61
|
+
return null;
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
64
|
if (answer.reply) await game.helperSay(answer.reply);
|
|
65
|
+
return answer.reply || null;
|
|
65
66
|
}
|
|
66
67
|
function createCubeforgeHelper(deps) {
|
|
67
68
|
var _a;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cubeforgeHelper.js","sources":["../../../src/features/games/cubeforgeHelper.ts"],"sourcesContent":["/**\n * The game's build helper, reached through a connector the way Dictate reaches\n * its AI. What goes out is the blocks around the player and what they typed; no\n * name, chat or friend is ever part of it.\n */\nimport type { RemoteConnectorExec } from '../canvas/videoEditor/remoteMediaClient';\nimport type { CubeforgeHelper, HelperAnswer } from './vendored';\n\nexport const HELPER_CONNECTOR = 'yantra-games';\nexport const HELPER_ACTION = 'YANTRA_GAMES_HELPER';\nconst HELPER_TIMEOUT_MS = 90_000;\nconst NAME_TIMEOUT_MS = 30_000;\n/** A day's worth of asking, kept on this device. */\nexport const DAILY_HELPER_LIMIT = 20;\nconst MAX_NAME_CHARS = 24;\n\nexport const LIMIT_REPLY = 'That is all the help I can give today. Come back tomorrow!';\nexport const UNAVAILABLE_REPLY = 'I cannot reach my workshop right now. Please try again soon.';\n\nexport const TOO_TIGHT_REPLY = 'This spot is too tight. Walk somewhere more open and tap ASK again.';\n/** Goes first, because the connector keeps only so much of a message. */\nconst DID_NOT_FIT = 'Your last plan did not fit, so use only cells marked with a dot.';\n\nconst CONSENT_KEY = 'yantra.cubeforge.helperConsent.v1';\nconst USAGE_KEY = 'yantra.cubeforge.helperUsage.v1';\n\nexport interface HelperStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n}\n\ntype Json = Record<string, unknown>;\n\nfunction asRecord(value: unknown): Json | null {\n return value && typeof value === 'object' && !Array.isArray(value) ? (value as Json) : null;\n}\n\n/** The first layer of the reply (itself, its `data`, its `result`...) holding `key`. */\nfunction findLayer(raw: unknown, key: string): Json | null {\n let layer = asRecord(raw);\n for (let depth = 0; layer && depth < 6; depth += 1) {\n if (key in layer) return layer;\n layer = asRecord(layer.data) ?? asRecord(layer.result);\n }\n return null;\n}\n\nfunction dayOf(now: number): string {\n return new Date(now).toISOString().slice(0, 10);\n}\n\nasync function usedToday(storage: HelperStorage, now: number): Promise<number> {\n try {\n const saved = JSON.parse((await storage.getItem(USAGE_KEY)) ?? '{}') as { day?: string; used?: number };\n return saved.day === dayOf(now) ? Number(saved.used) || 0 : 0;\n } catch {\n return 0;\n }\n}\n\nexport async function helperConsentGiven(storage: HelperStorage): Promise<boolean> {\n try {\n return (await storage.getItem(CONSENT_KEY)) === '1';\n } catch {\n return false;\n }\n}\n\nexport async function rememberHelperConsent(storage: HelperStorage): Promise<void> {\n await storage.setItem(CONSENT_KEY, '1');\n}\n\n/** What the helper needs from the running game. */\nexport interface HelperGame {\n helperSnapshot(): Promise<string | null>;\n helperPropose(plan: string): Promise<number>;\n helperSay(text: string): Promise<boolean>;\n}\n\n/**\n * One request from the player, start to finish. A plan that does not fit gets\n * one more try before the player hears anything, and a reply is only shown once\n * what it describes is really on screen.\n */\nexport async function askAndPreview(game: HelperGame, helper: CubeforgeHelper, message: string): Promise<void> {\n const snapshot = await game.helperSnapshot();\n if (!snapshot) return;\n await game.helperSay('Let me take a look...');\n const shown = async (answer: HelperAnswer) =>\n answer.plan !== null && (await game.helperPropose(JSON.stringify(answer.plan))) > 0;\n\n let answer = await helper.ask(message, snapshot);\n if (answer.plan !== null && !(await shown(answer))) {\n const fresh = await game.helperSnapshot();\n answer = fresh ? await helper.ask(`${DID_NOT_FIT} ${message}`, fresh) : { reply: '', plan: null };\n if (!(await shown(answer))) {\n await game.helperSay(TOO_TIGHT_REPLY);\n return;\n }\n }\n if (answer.reply) await game.helperSay(answer.reply);\n}\n\nexport function createCubeforgeHelper(deps: {\n exec: RemoteConnectorExec;\n storage: HelperStorage;\n now?: () => number;\n}): CubeforgeHelper {\n const { exec, storage } = deps;\n const now = deps.now ?? Date.now;\n return {\n ask: async (message, snapshot): Promise<HelperAnswer> => {\n const today = await usedToday(storage, now());\n if (today >= DAILY_HELPER_LIMIT) return { reply: LIMIT_REPLY, plan: null };\n try {\n const raw = await exec(\n HELPER_CONNECTOR,\n HELPER_ACTION,\n { mode: 'build', message, snapshot: JSON.parse(snapshot) as unknown },\n { timeoutMs: HELPER_TIMEOUT_MS },\n );\n const layer = findLayer(raw, 'reply');\n if (!layer) return { reply: UNAVAILABLE_REPLY, plan: null };\n await storage\n .setItem(USAGE_KEY, JSON.stringify({ day: dayOf(now()), used: today + 1 }))\n .catch(() => undefined);\n return { reply: typeof layer.reply === 'string' ? layer.reply : '', plan: layer.plan ?? null };\n } catch {\n return { reply: UNAVAILABLE_REPLY, plan: null };\n }\n },\n nameWorld: async (summary) => {\n try {\n const raw = await exec(\n HELPER_CONNECTOR,\n HELPER_ACTION,\n { mode: 'name', summary: JSON.parse(summary) as unknown },\n { timeoutMs: NAME_TIMEOUT_MS },\n );\n const name = findLayer(raw, 'name')?.name;\n const clean = typeof name === 'string' ? name.trim().slice(0, MAX_NAME_CHARS) : '';\n return clean || null;\n } catch {\n return null;\n }\n },\n };\n}\n"],"names":["answer","_a"],"mappings":"AAOO,MAAM,gBAAmB,GAAA;AACzB,MAAM,aAAgB,GAAA;AAC7B,MAAM,iBAAoB,GAAA,GAAA;AAC1B,MAAM,eAAkB,GAAA,GAAA;AAEjB,MAAM,kBAAqB,GAAA;AAClC,MAAM,cAAiB,GAAA,EAAA;AAChB,MAAM,WAAc,GAAA;AACpB,MAAM,iBAAoB,GAAA;AAC1B,MAAM,eAAkB,GAAA;AAE/B,MAAM,WAAc,GAAA,kEAAA;AACpB,MAAM,WAAc,GAAA,mCAAA;AACpB,MAAM,SAAY,GAAA,iCAAA;AAMlB,SAAS,SAAS,KAA6B,EAAA;AAC7C,EAAO,OAAA,KAAA,IAAS,OAAO,KAAU,KAAA,QAAA,IAAY,CAAC,KAAM,CAAA,OAAA,CAAQ,KAAK,CAAA,GAAI,KAAgB,GAAA,IAAA;AACvF;AAGA,SAAS,SAAA,CAAU,KAAc,GAA0B,EAAA;AA/B3D,EAAA,IAAA,EAAA;AAgCE,EAAI,IAAA,KAAA,GAAQ,SAAS,GAAG,CAAA;AACxB,EAAA,KAAA,IAAS,QAAQ,CAAG,EAAA,KAAA,IAAS,KAAQ,GAAA,CAAA,EAAG,SAAS,CA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A5IhC,MAAAA,IAAAA,GAAAA;AA6IM,MAAI,IAAA;AACF,QAAA,MAAM,GAAM,GAAA,MAAM,IAAK,CAAA,gBAAA,EAAkB,aAAe,EAAA;AAAA,UACtD,IAAM,EAAA,MAAA;AAAA,UACN,OAAA,EAAS,IAAK,CAAA,KAAA,CAAM,OAAO;AAAA,SAC1B,EAAA;AAAA,UACD,SAAW,EAAA;AAAA,SACZ,CAAA;AACD,QAAA,MAAM,QAAOA,GAAA,GAAA,SAAA,CAAU,KAAK,MAAM,CAAA,KAArB,gBAAAA,GAAwB,CAAA,IAAA;AACrC,QAAM,MAAA,KAAA,GAAQ,OAAO,IAAA,KAAS,QAAW,GAAA,IAAA,CAAK,MAAO,CAAA,KAAA,CAAM,CAAG,EAAA,cAAc,CAAI,GAAA,EAAA;AAChF,QAAA,OAAO,KAAS,IAAA,IAAA;AAAA,OACV,CAAA,OAAA,CAAA,EAAA;AACN,QAAO,OAAA,IAAA;AAAA;AACT;AACF,GACF;AACF"}
|
|
1
|
+
{"version":3,"file":"cubeforgeHelper.js","sources":["../../../src/features/games/cubeforgeHelper.ts"],"sourcesContent":["/**\n * The game's build helper, reached through a connector the way Dictate reaches\n * its AI. What goes out is the blocks around the player and what they typed; no\n * name, chat or friend is ever part of it.\n */\nimport type { RemoteConnectorExec } from '../canvas/videoEditor/remoteMediaClient';\nimport type { CubeforgeHelper, HelperAnswer } from './vendored';\n\nexport const HELPER_CONNECTOR = 'yantra-games';\nexport const HELPER_ACTION = 'YANTRA_GAMES_HELPER';\nconst HELPER_TIMEOUT_MS = 90_000;\nconst NAME_TIMEOUT_MS = 30_000;\n/** A day's worth of asking, kept on this device. */\nexport const DAILY_HELPER_LIMIT = 20;\nconst MAX_NAME_CHARS = 24;\n\nexport const LIMIT_REPLY = 'That is all the help I can give today. Come back tomorrow!';\nexport const UNAVAILABLE_REPLY = 'I cannot reach my workshop right now. Please try again soon.';\n\nexport const TOO_TIGHT_REPLY = 'This spot is too tight. Walk somewhere more open and tap ASK again.';\n/** Goes first, because the connector keeps only so much of a message. */\nconst DID_NOT_FIT = 'Your last plan did not fit, so use only cells marked with a dot.';\n\nconst CONSENT_KEY = 'yantra.cubeforge.helperConsent.v1';\nconst USAGE_KEY = 'yantra.cubeforge.helperUsage.v1';\n\nexport interface HelperStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n}\n\ntype Json = Record<string, unknown>;\n\nfunction asRecord(value: unknown): Json | null {\n return value && typeof value === 'object' && !Array.isArray(value) ? (value as Json) : null;\n}\n\n/** The first layer of the reply (itself, its `data`, its `result`...) holding `key`. */\nfunction findLayer(raw: unknown, key: string): Json | null {\n let layer = asRecord(raw);\n for (let depth = 0; layer && depth < 6; depth += 1) {\n if (key in layer) return layer;\n layer = asRecord(layer.data) ?? asRecord(layer.result);\n }\n return null;\n}\n\nfunction dayOf(now: number): string {\n return new Date(now).toISOString().slice(0, 10);\n}\n\nasync function usedToday(storage: HelperStorage, now: number): Promise<number> {\n try {\n const saved = JSON.parse((await storage.getItem(USAGE_KEY)) ?? '{}') as { day?: string; used?: number };\n return saved.day === dayOf(now) ? Number(saved.used) || 0 : 0;\n } catch {\n return 0;\n }\n}\n\nexport async function helperConsentGiven(storage: HelperStorage): Promise<boolean> {\n try {\n return (await storage.getItem(CONSENT_KEY)) === '1';\n } catch {\n return false;\n }\n}\n\nexport async function rememberHelperConsent(storage: HelperStorage): Promise<void> {\n await storage.setItem(CONSENT_KEY, '1');\n}\n\n/** What the helper needs from the running game. */\nexport interface HelperGame {\n helperSnapshot(): Promise<string | null>;\n helperPropose(plan: string): Promise<number>;\n helperSay(text: string): Promise<boolean>;\n}\n\n/**\n * One request from the player, start to finish. A plan that does not fit gets\n * one more try before the player hears anything, and a reply is only shown once\n * what it describes is really on screen.\n */\nexport async function askAndPreview(\n game: HelperGame,\n helper: CubeforgeHelper,\n message: string,\n): Promise<string | null> {\n const snapshot = await game.helperSnapshot();\n if (!snapshot) return null;\n await game.helperSay('Let me take a look...');\n const shown = async (answer: HelperAnswer) =>\n answer.plan !== null && (await game.helperPropose(JSON.stringify(answer.plan))) > 0;\n\n let answer = await helper.ask(message, snapshot);\n if (answer.plan !== null && !(await shown(answer))) {\n const fresh = await game.helperSnapshot();\n answer = fresh ? await helper.ask(`${DID_NOT_FIT} ${message}`, fresh) : { reply: '', plan: null };\n if (!(await shown(answer))) {\n await game.helperSay(TOO_TIGHT_REPLY);\n return null;\n }\n }\n if (answer.reply) await game.helperSay(answer.reply);\n return answer.reply || null;\n}\n\nexport function createCubeforgeHelper(deps: {\n exec: RemoteConnectorExec;\n storage: HelperStorage;\n now?: () => number;\n}): CubeforgeHelper {\n const { exec, storage } = deps;\n const now = deps.now ?? Date.now;\n return {\n ask: async (message, snapshot): Promise<HelperAnswer> => {\n const today = await usedToday(storage, now());\n if (today >= DAILY_HELPER_LIMIT) return { reply: LIMIT_REPLY, plan: null };\n try {\n const raw = await exec(\n HELPER_CONNECTOR,\n HELPER_ACTION,\n { mode: 'build', message, snapshot: JSON.parse(snapshot) as unknown },\n { timeoutMs: HELPER_TIMEOUT_MS },\n );\n const layer = findLayer(raw, 'reply');\n if (!layer) return { reply: UNAVAILABLE_REPLY, plan: null };\n await storage\n .setItem(USAGE_KEY, JSON.stringify({ day: dayOf(now()), used: today + 1 }))\n .catch(() => undefined);\n return { reply: typeof layer.reply === 'string' ? layer.reply : '', plan: layer.plan ?? null };\n } catch {\n return { reply: UNAVAILABLE_REPLY, plan: null };\n }\n },\n nameWorld: async (summary) => {\n try {\n const raw = await exec(\n HELPER_CONNECTOR,\n HELPER_ACTION,\n { mode: 'name', summary: JSON.parse(summary) as unknown },\n { timeoutMs: NAME_TIMEOUT_MS },\n );\n const name = findLayer(raw, 'name')?.name;\n const clean = typeof name === 'string' ? name.trim().slice(0, MAX_NAME_CHARS) : '';\n return clean || null;\n } catch {\n return null;\n }\n },\n };\n}\n"],"names":["answer","_a"],"mappings":"AAOO,MAAM,gBAAmB,GAAA;AACzB,M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,CAAI,GAAA,EAAA;AAChF,QAAA,OAAO,KAAS,IAAA,IAAA;AAAA,OACV,CAAA,OAAA,CAAA,EAAA;AACN,QAAO,OAAA,IAAA;AAAA;AACT;AACF,GACF;AACF"}
|
|
@@ -4,10 +4,15 @@ function inviteMessage(worldName, code) {
|
|
|
4
4
|
return `Join my Cubeforge world "${worldName}"
|
|
5
5
|
${INVITE_LINK}${code}`;
|
|
6
6
|
}
|
|
7
|
+
const INVITE_CODE_IN_TEXT = /yantra\.app\/games\/cubeforge\/join\/([2-9A-HJKMNP-Z]{8,})/;
|
|
8
|
+
function inviteCodeInPush(text) {
|
|
9
|
+
var _a, _b;
|
|
10
|
+
return (_b = (_a = INVITE_CODE_IN_TEXT.exec(text != null ? text : "")) == null ? void 0 : _a[1]) != null ? _b : null;
|
|
11
|
+
}
|
|
7
12
|
function parseInviteMessage(body) {
|
|
8
13
|
const match = INVITE_MESSAGE.exec(body.trim());
|
|
9
14
|
return match ? {
|
|
10
15
|
worldName: match[1],
|
|
11
16
|
code: match[2]
|
|
12
17
|
} : null;
|
|
13
|
-
}export{inviteMessage,parseInviteMessage};//# sourceMappingURL=gameInvite.js.map
|
|
18
|
+
}export{inviteCodeInPush,inviteMessage,parseInviteMessage};//# sourceMappingURL=gameInvite.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gameInvite.js","sources":["../../../src/features/games/gameInvite.ts"],"sourcesContent":["/**\n * The Cubeforge invite as chat text. Chat keeps only plain text on direct and\n * group messages, so the text itself carries the invite, and anyone on an older\n * app or on the web still sees a readable message with a link.\n */\nconst INVITE_LINK = 'https://yantra.app/games/cubeforge/join/';\nconst INVITE_MESSAGE =\n /^Join my Cubeforge world \"(.{1,40})\"\\nhttps:\\/\\/yantra\\.app\\/games\\/cubeforge\\/join\\/([2-9A-HJKMNP-Z]{8,})$/;\n\nexport interface GameInvite {\n worldName: string;\n code: string;\n}\n\nexport function inviteMessage(worldName: string, code: string): string {\n return `Join my Cubeforge world \"${worldName}\"\\n${INVITE_LINK}${code}`;\n}\n\n/** The invite in a message, or null for any other text. */\nexport function parseInviteMessage(body: string): GameInvite | null {\n const match = INVITE_MESSAGE.exec(body.trim());\n return match ? { worldName: match[1], code: match[2] } : null;\n}\n"],"names":[],"mappings":"AAKA,MAAM,WAAc,GAAA,0CAAA;AACpB,MAAM,cAAiB,GAAA,6GAAA;AAKP,SAAA,aAAA,CAAc,WAAmB,IAAsB,EAAA;AACrE,EAAA,OAAO,4BAA4B,SAAS,CAAA;AAAA,EAAM,WAAW,GAAG,IAAI,CAAA,CAAA;AACtE;AAGO,SAAS,mBAAmB,IAAiC,EAAA;AAClE,EAAA,MAAM,KAAQ,GAAA,cAAA,CAAe,IAAK,CAAA,IAAA,CAAK,MAAM,CAAA;AAC7C,EAAA,OAAO,KAAQ,GAAA;AAAA,IACb,SAAA,EAAW,MAAM,CAAC,CAAA;AAAA,IAClB,IAAA,EAAM,MAAM,CAAC;AAAA,GACX,GAAA,IAAA;AACN"}
|
|
1
|
+
{"version":3,"file":"gameInvite.js","sources":["../../../src/features/games/gameInvite.ts"],"sourcesContent":["/**\n * The Cubeforge invite as chat text. Chat keeps only plain text on direct and\n * group messages, so the text itself carries the invite, and anyone on an older\n * app or on the web still sees a readable message with a link.\n */\nconst INVITE_LINK = 'https://yantra.app/games/cubeforge/join/';\nconst INVITE_MESSAGE =\n /^Join my Cubeforge world \"(.{1,40})\"\\nhttps:\\/\\/yantra\\.app\\/games\\/cubeforge\\/join\\/([2-9A-HJKMNP-Z]{8,})$/;\n\nexport interface GameInvite {\n worldName: string;\n code: string;\n}\n\nexport function inviteMessage(worldName: string, code: string): string {\n return `Join my Cubeforge world \"${worldName}\"\\n${INVITE_LINK}${code}`;\n}\n\nconst INVITE_CODE_IN_TEXT = /yantra\\.app\\/games\\/cubeforge\\/join\\/([2-9A-HJKMNP-Z]{8,})/;\n\n/**\n * The invite code anywhere in a notification's text. A chat push carries the message\n * flattened onto one line, after the sender's name in a group, so it is not the exact\n * message `parseInviteMessage` reads.\n */\nexport function inviteCodeInPush(text: string | null | undefined): string | null {\n return INVITE_CODE_IN_TEXT.exec(text ?? '')?.[1] ?? null;\n}\n\n/** The invite in a message, or null for any other text. */\nexport function parseInviteMessage(body: string): GameInvite | null {\n const match = INVITE_MESSAGE.exec(body.trim());\n return match ? { worldName: match[1], code: match[2] } : null;\n}\n"],"names":[],"mappings":"AAKA,MAAM,WAAc,GAAA,0CAAA;AACpB,MAAM,cAAiB,GAAA,6GAAA;AAKP,SAAA,aAAA,CAAc,WAAmB,IAAsB,EAAA;AACrE,EAAA,OAAO,4BAA4B,SAAS,CAAA;AAAA,EAAM,WAAW,GAAG,IAAI,CAAA,CAAA;AACtE;AACA,MAAM,mBAAsB,GAAA,4DAAA;AAOrB,SAAS,iBAAiB,IAAgD,EAAA;AArBjF,EAAA,IAAA,EAAA,EAAA,EAAA;AAsBE,EAAA,OAAA,CAAO,+BAAoB,IAAK,CAAA,IAAA,IAAA,IAAA,GAAA,IAAA,GAAQ,EAAE,CAAnC,KAAA,IAAA,GAAA,MAAA,GAAA,EAAA,CAAuC,OAAvC,IAA6C,GAAA,EAAA,GAAA,IAAA;AACtD;AAGO,SAAS,mBAAmB,IAAiC,EAAA;AAClE,EAAA,MAAM,KAAQ,GAAA,cAAA,CAAe,IAAK,CAAA,IAAA,CAAK,MAAM,CAAA;AAC7C,EAAA,OAAO,KAAQ,GAAA;AAAA,IACb,SAAA,EAAW,MAAM,CAAC,CAAA;AAAA,IAClB,IAAA,EAAM,MAAM,CAAC;AAAA,GACX,GAAA,IAAA;AACN"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
let registered = null;
|
|
2
|
+
const useNoNotifications = () => null;
|
|
3
|
+
function registerGameNotifications(usePushSeam) {
|
|
4
|
+
registered = usePushSeam;
|
|
5
|
+
}
|
|
6
|
+
function useGameNotifications() {
|
|
7
|
+
const useSeam = registered != null ? registered : useNoNotifications;
|
|
8
|
+
return useSeam();
|
|
9
|
+
}export{registerGameNotifications,useGameNotifications};//# sourceMappingURL=gameNotifications.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gameNotifications.js","sources":["../../../src/features/games/gameNotifications.ts"],"sourcesContent":["/**\n * The phone's notification switch, for Cubeforge. A friend's invite is a chat\n * message, so it arrives as a chat push: Games only needs the same switch the chat\n * list offers. The app registers its chat push seam at startup, like the chat\n * experience, and Games reads it back. Exported from the package index so rollup\n * keeps the registration.\n */\nimport type { ChatPushSeam } from '../messaging/chatHost';\n\ntype UsePushSeam = () => ChatPushSeam;\n\nlet registered: UsePushSeam | null = null;\n\nconst useNoNotifications = (): ChatPushSeam | null => null;\n\nexport function registerGameNotifications(usePushSeam: UsePushSeam): void {\n registered = usePushSeam;\n}\n\n/** Null in a build whose host never registered one. Registration happens before any render. */\nexport function useGameNotifications(): ChatPushSeam | null {\n const useSeam: () => ChatPushSeam | null = registered ?? useNoNotifications;\n return useSeam();\n}\n"],"names":[],"mappings":"AASA,IAAI,UAAiC,GAAA,IAAA;AACrC,MAAM,qBAAqB,MAA2B,IAAA;AAC/C,SAAS,0BAA0B,WAAgC,EAAA;AACxE,EAAa,UAAA,GAAA,WAAA;AACf;AAGO,SAAS,oBAA4C,GAAA;AAC1D,EAAA,MAAM,UAAqC,UAAc,IAAA,IAAA,GAAA,UAAA,GAAA,kBAAA;AACzD,EAAA,OAAO,OAAQ,EAAA;AACjB"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import {requireOptionalNativeModule}from'expo-modules-core';const FOLLOW_THE_PHONE = 0;
|
|
2
|
+
const UPRIGHT = 3;
|
|
3
|
+
function letGameTurnWithPhone() {
|
|
4
|
+
const orientation = requireOptionalNativeModule("ExpoScreenOrientation");
|
|
5
|
+
if (!orientation) return () => void 0;
|
|
6
|
+
orientation.lockAsync(FOLLOW_THE_PHONE).catch(() => void 0);
|
|
7
|
+
return () => {
|
|
8
|
+
orientation.lockAsync(UPRIGHT).catch(() => void 0);
|
|
9
|
+
};
|
|
10
|
+
}export{letGameTurnWithPhone};//# sourceMappingURL=gameOrientation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gameOrientation.js","sources":["../../../src/features/games/gameOrientation.ts"],"sourcesContent":["/**\n * The game turns with the phone; the rest of the app stays upright. The native\n * module is absent on a binary built before this shipped, which an over-the-air\n * update can reach, and then the game simply stays upright too.\n */\nimport { requireOptionalNativeModule } from 'expo-modules-core';\n\n/** `OrientationLock.DEFAULT` and `.PORTRAIT_UP` in expo-screen-orientation. */\nconst FOLLOW_THE_PHONE = 0;\nconst UPRIGHT = 3;\n\ninterface NativeOrientation {\n lockAsync(lock: number): Promise<void>;\n}\n\n/** Lets the screen turn, and returns the function that puts it back upright. */\nexport function letGameTurnWithPhone(): () => void {\n const orientation = requireOptionalNativeModule<NativeOrientation>('ExpoScreenOrientation');\n if (!orientation) return () => undefined;\n orientation.lockAsync(FOLLOW_THE_PHONE).catch(() => undefined);\n return () => {\n orientation.lockAsync(UPRIGHT).catch(() => undefined);\n };\n}\n"],"names":[],"mappings":"4DAQA,MAAM,gBAAmB,GAAA,CAAA;AACzB,MAAM,OAAU,GAAA,CAAA;AAMT,SAAS,oBAAmC,GAAA;AACjD,EAAM,MAAA,WAAA,GAAc,4BAA+C,uBAAuB,CAAA;AAC1F,EAAI,IAAA,CAAC,WAAa,EAAA,OAAO,MAAM,MAAA;AAC/B,EAAA,WAAA,CAAY,SAAU,CAAA,gBAAgB,CAAE,CAAA,KAAA,CAAM,MAAM,MAAS,CAAA;AAC7D,EAAA,OAAO,MAAM;AACX,IAAA,WAAA,CAAY,SAAU,CAAA,OAAO,CAAE,CAAA,KAAA,CAAM,MAAM,MAAS,CAAA;AAAA,GACtD;AACF"}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {useRef,useMemo}from'react';import {useApolloClient,gql}from'@apollo/client/index.js';import {config}from'../../config/env-config.js';import {useCanvasSession}from'../canvas/useCanvasSession.js';import {toConversation}from'../messaging/chatModel.js';import {SEND_MESSAGE_MUTATION,CHANNELS_QUERY}from'../messaging/chatOperations.js';import {NATIVE_CHAT_CHANNELS_QUERY_VARS,isNativeMessengerChannel}from'../messaging/nativeChatChannelQuery.js';import {useChatViewer}from'../messaging/useChatViewer.js';import {createCubeforgeFriends,waitForToken}from'./cubeforgeFriends.js';const FALLBACK_PLAYER_NAME = "Player";
|
|
1
|
+
import {useRef,useMemo}from'react';import {useApolloClient,gql}from'@apollo/client/index.js';import {config}from'../../config/env-config.js';import {useCanvasSession}from'../canvas/useCanvasSession.js';import {pickAuthor,displayNameOf,toEpoch,toConversation}from'../messaging/chatModel.js';import {SEND_MESSAGE_MUTATION,MESSAGES_QUERY,CHANNELS_QUERY}from'../messaging/chatOperations.js';import {NATIVE_CHAT_CHANNELS_QUERY_VARS,isNativeMessengerChannel}from'../messaging/nativeChatChannelQuery.js';import {useChatViewer}from'../messaging/useChatViewer.js';import {createCubeforgeFriends,waitForToken}from'./cubeforgeFriends.js';const FALLBACK_PLAYER_NAME = "Player";
|
|
2
|
+
const INVITE_CHATS_SCANNED = 10;
|
|
3
|
+
const INVITE_MESSAGES_SCANNED = 30;
|
|
2
4
|
function useCubeforgeFriends() {
|
|
3
5
|
const client = useApolloClient();
|
|
4
6
|
const {
|
|
@@ -18,26 +20,9 @@ function useCubeforgeFriends() {
|
|
|
18
20
|
token,
|
|
19
21
|
renew
|
|
20
22
|
};
|
|
21
|
-
return useMemo(() =>
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
const {
|
|
25
|
-
token: current,
|
|
26
|
-
renew: mint
|
|
27
|
-
} = latest.current;
|
|
28
|
-
if (current && !forceNew) return current;
|
|
29
|
-
const minted = await mint();
|
|
30
|
-
if (minted || forceNew) return minted;
|
|
31
|
-
return waitForToken(() => latest.current.token);
|
|
32
|
-
},
|
|
33
|
-
playerName: () => {
|
|
34
|
-
var _a, _b;
|
|
35
|
-
return ((_b = (_a = latest.current.viewer) == null ? void 0 : _a.displayName) == null ? void 0 : _b.trim()) || FALLBACK_PLAYER_NAME;
|
|
36
|
-
},
|
|
37
|
-
listChats: async () => {
|
|
38
|
-
var _a, _b;
|
|
39
|
-
const viewerId = (_a = latest.current.viewer) == null ? void 0 : _a.userId;
|
|
40
|
-
if (!viewerId) return [];
|
|
23
|
+
return useMemo(() => {
|
|
24
|
+
const loadChats = async (viewerId) => {
|
|
25
|
+
var _a;
|
|
41
26
|
const {
|
|
42
27
|
data
|
|
43
28
|
} = await client.query({
|
|
@@ -45,22 +30,85 @@ function useCubeforgeFriends() {
|
|
|
45
30
|
variables: NATIVE_CHAT_CHANNELS_QUERY_VARS,
|
|
46
31
|
fetchPolicy: "network-only"
|
|
47
32
|
});
|
|
48
|
-
return ((
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
33
|
+
return ((_a = data.channelsByUser) != null ? _a : []).filter((c) => isNativeMessengerChannel(c)).map((c) => toConversation(c, viewerId));
|
|
34
|
+
};
|
|
35
|
+
return createCubeforgeFriends({
|
|
36
|
+
graphqlUrl: config.GAMES_SUBGRAPH_URL,
|
|
37
|
+
getToken: async (forceNew) => {
|
|
38
|
+
const {
|
|
39
|
+
token: current,
|
|
40
|
+
renew: mint
|
|
41
|
+
} = latest.current;
|
|
42
|
+
if (current && !forceNew) return current;
|
|
43
|
+
const minted = await mint();
|
|
44
|
+
if (minted || forceNew) return minted;
|
|
45
|
+
return waitForToken(() => latest.current.token);
|
|
46
|
+
},
|
|
47
|
+
playerName: () => {
|
|
48
|
+
var _a, _b;
|
|
49
|
+
return ((_b = (_a = latest.current.viewer) == null ? void 0 : _a.displayName) == null ? void 0 : _b.trim()) || FALLBACK_PLAYER_NAME;
|
|
50
|
+
},
|
|
51
|
+
listChats: async () => {
|
|
52
|
+
var _a;
|
|
53
|
+
const viewerId = (_a = latest.current.viewer) == null ? void 0 : _a.userId;
|
|
54
|
+
if (!viewerId) return [];
|
|
55
|
+
return (await loadChats(viewerId)).map((c) => ({
|
|
56
|
+
id: c.id,
|
|
57
|
+
title: c.title,
|
|
58
|
+
detail: c.isDirect ? "Person" : `Group, ${c.members.length} members`
|
|
59
|
+
}));
|
|
60
|
+
},
|
|
61
|
+
recentChatMessages: async () => {
|
|
62
|
+
const viewerId = await waitForToken(() => {
|
|
63
|
+
var _a, _b;
|
|
64
|
+
return (_b = (_a = latest.current.viewer) == null ? void 0 : _a.userId) != null ? _b : null;
|
|
65
|
+
});
|
|
66
|
+
if (!viewerId) return [];
|
|
67
|
+
const chats = (await loadChats(viewerId)).slice(0, INVITE_CHATS_SCANNED);
|
|
68
|
+
const pages = await Promise.all(chats.map(async (chat) => {
|
|
69
|
+
var _a, _b;
|
|
70
|
+
try {
|
|
71
|
+
const {
|
|
72
|
+
data
|
|
73
|
+
} = await client.query({
|
|
74
|
+
query: gql(MESSAGES_QUERY),
|
|
75
|
+
variables: {
|
|
76
|
+
channelId: chat.id,
|
|
77
|
+
limit: INVITE_MESSAGES_SCANNED,
|
|
78
|
+
skip: 0
|
|
79
|
+
},
|
|
80
|
+
// Reading for invites must not disturb the chat screen's own copy.
|
|
81
|
+
fetchPolicy: "no-cache"
|
|
82
|
+
});
|
|
83
|
+
return ((_b = (_a = data.messages) == null ? void 0 : _a.data) != null ? _b : []).filter((post) => Boolean(post) && !(post == null ? void 0 : post.deletedAt)).map((post) => {
|
|
84
|
+
var _a2;
|
|
85
|
+
const author = pickAuthor(post);
|
|
86
|
+
const mine = Boolean(author == null ? void 0 : author.id) && String(author == null ? void 0 : author.id) === viewerId;
|
|
87
|
+
const sender = chat.isDirect ? chat.title : displayNameOf(author);
|
|
88
|
+
return {
|
|
89
|
+
body: (_a2 = post.message) != null ? _a2 : "",
|
|
90
|
+
from: mine ? null : sender,
|
|
91
|
+
chatTitle: chat.title,
|
|
92
|
+
sentAt: toEpoch(post.createdAt)
|
|
93
|
+
};
|
|
94
|
+
});
|
|
95
|
+
} catch (e) {
|
|
96
|
+
return [];
|
|
61
97
|
}
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
98
|
+
}));
|
|
99
|
+
return pages.flat();
|
|
100
|
+
},
|
|
101
|
+
sendToChat: async (chatId, text) => {
|
|
102
|
+
await client.mutate({
|
|
103
|
+
mutation: gql(SEND_MESSAGE_MUTATION),
|
|
104
|
+
variables: {
|
|
105
|
+
channelId: chatId,
|
|
106
|
+
messageInput: {
|
|
107
|
+
content: text
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
}, [client]);
|
|
66
114
|
}export{useCubeforgeFriends};//# sourceMappingURL=useCubeforgeFriends.js.map
|