@adminide-stack/yantra-mobile 12.0.174-alpha.1 → 12.0.174
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/config/env-config.js +4 -0
- package/lib/config/env-config.js.map +1 -1
- package/lib/features/channels/ChannelIcon.js +11 -0
- package/lib/features/channels/ChannelIcon.js.map +1 -1
- package/lib/features/channels/ComputerPanel.js +538 -0
- package/lib/features/channels/ComputerPanel.js.map +1 -0
- package/lib/features/channels/ConnectAppsSheet.js +3 -2
- package/lib/features/channels/ConnectAppsSheet.js.map +1 -1
- package/lib/features/channels/channelLinks.js +6 -0
- package/lib/features/channels/channelLinks.js.map +1 -1
- package/lib/features/channels/computerLink.js +80 -0
- package/lib/features/channels/computerLink.js.map +1 -0
- package/lib/features/games/cubeforge3D.js +114 -7
- package/lib/features/games/cubeforge3D.js.map +1 -1
- package/lib/features/games/cubeforgeFriends.js +11 -3
- package/lib/features/games/cubeforgeFriends.js.map +1 -1
- package/lib/features/games/cubeforgeHelper.js +105 -0
- package/lib/features/games/cubeforgeHelper.js.map +1 -0
- package/lib/features/games/useCubeforgeHelper.js +25 -0
- package/lib/features/games/useCubeforgeHelper.js.map +1 -0
- package/lib/features/games/vendored/core/cubeforge/helper.js +13 -0
- package/lib/features/games/vendored/core/cubeforge/helper.js.map +1 -0
- package/lib/features/games/vendored/core/cubeforge/nativeWorlds.js +36 -1
- package/lib/features/games/vendored/core/cubeforge/nativeWorlds.js.map +1 -1
- package/lib/features/games/vendored/core/cubeforge/sharedWorlds.js.map +1 -1
- package/lib/features/games/vendored/core/cubeforge/skin.js +2 -2
- package/lib/features/games/vendored/core/cubeforge/skin.js.map +1 -1
- package/lib/features/games/vendored/ui/GamesRoot.js +25 -5
- package/lib/features/games/vendored/ui/GamesRoot.js.map +1 -1
- package/lib/features/games/vendored/ui/screens/Cubeforge3DHomeScreen.js +21 -9
- package/lib/features/games/vendored/ui/screens/Cubeforge3DHomeScreen.js.map +1 -1
- package/lib/screens/GamesNative/index.js +5 -3
- package/lib/screens/GamesNative/index.js.map +1 -1
- package/package.json +5 -4
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {jsxs,jsx}from'react/jsx-runtime';import*as React from'react';import {StyleSheet,Platform,Modal,KeyboardAvoidingView,Pressable,View,TextInput
|
|
1
|
+
import {jsxs,jsx}from'react/jsx-runtime';import*as React from'react';import {StyleSheet,Platform,Modal,KeyboardAvoidingView,Pressable,Text,View,TextInput}from'react-native';import {requireNativeViewManager,requireOptionalNativeModule}from'expo-modules-core';import {SafeAreaView}from'react-native-safe-area-context';import AsyncStorage from'@react-native-async-storage/async-storage';import {helperConsentGiven,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;
|
|
@@ -13,9 +13,29 @@ function deleteCubeforgeSave(worldKey) {
|
|
|
13
13
|
var _a, _b;
|
|
14
14
|
(_b = (_a = nativeModule()) == null ? void 0 : _a.deleteWorld) == null ? void 0 : _b.call(_a, worldKey);
|
|
15
15
|
}
|
|
16
|
+
function cubeforgePicture(worldKey) {
|
|
17
|
+
var _a, _b, _c;
|
|
18
|
+
return (_c = (_b = (_a = nativeModule()) == null ? void 0 : _a.picturePath) == null ? void 0 : _b.call(_a, worldKey)) != null ? _c : null;
|
|
19
|
+
}
|
|
20
|
+
const BEAUTIFY_MESSAGE = "Make what I built look better";
|
|
21
|
+
function HelperConsent({
|
|
22
|
+
onAgree,
|
|
23
|
+
onClose
|
|
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: [
|
|
26
|
+
/* @__PURE__ */ jsx(Text, { style: styles.consentTitle, children: "Your build helper" }),
|
|
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
|
+
/* @__PURE__ */ jsxs(View, { style: styles.consentRow, children: [
|
|
29
|
+
/* @__PURE__ */ jsx(Pressable, { accessibilityRole: "button", onPress: onClose, style: styles.consentSecondary, children: /* @__PURE__ */ jsx(Text, { style: styles.consentSecondaryLabel, children: "Not now" }) }),
|
|
30
|
+
/* @__PURE__ */ jsx(Pressable, { accessibilityRole: "button", onPress: onAgree, style: styles.chatSend, children: /* @__PURE__ */ jsx(Text, { style: styles.chatSendLabel, children: "OK" }) })
|
|
31
|
+
] })
|
|
32
|
+
] }) }) });
|
|
33
|
+
}
|
|
16
34
|
function ChatBar({
|
|
17
35
|
onSend,
|
|
18
|
-
onClose
|
|
36
|
+
onClose,
|
|
37
|
+
placeholder = "Message everyone here",
|
|
38
|
+
quickAsk
|
|
19
39
|
}) {
|
|
20
40
|
const [draft, setDraft] = React.useState("");
|
|
21
41
|
const send = () => {
|
|
@@ -25,8 +45,12 @@ function ChatBar({
|
|
|
25
45
|
};
|
|
26
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: [
|
|
27
47
|
/* @__PURE__ */ jsx(Pressable, { accessibilityLabel: "Close chat", style: styles.fillClear, onPress: onClose }),
|
|
48
|
+
quickAsk ? /* @__PURE__ */ jsx(Pressable, { accessibilityRole: "button", onPress: () => {
|
|
49
|
+
onSend(quickAsk.message);
|
|
50
|
+
onClose();
|
|
51
|
+
}, style: styles.quickAsk, children: /* @__PURE__ */ jsx(Text, { style: styles.chatSendLabel, children: quickAsk.label }) }) : null,
|
|
28
52
|
/* @__PURE__ */ jsxs(View, { style: styles.chatBar, children: [
|
|
29
|
-
/* @__PURE__ */ jsx(TextInput, { autoFocus: true, value: draft, onChangeText: setDraft, onSubmitEditing: send, maxLength: MAX_CHAT_CHARS, placeholder
|
|
53
|
+
/* @__PURE__ */ jsx(TextInput, { autoFocus: true, value: draft, onChangeText: setDraft, onSubmitEditing: send, maxLength: MAX_CHAT_CHARS, placeholder, placeholderTextColor: "#94a3b8", returnKeyType: "send", style: styles.chatInput }),
|
|
30
54
|
/* @__PURE__ */ jsx(Pressable, { accessibilityRole: "button", accessibilityLabel: "Send", onPress: send, style: styles.chatSend, children: /* @__PURE__ */ jsx(Text, { style: styles.chatSendLabel, children: "Send" }) })
|
|
31
55
|
] })
|
|
32
56
|
] }) });
|
|
@@ -45,16 +69,48 @@ function cubeforge3DComponent() {
|
|
|
45
69
|
skin,
|
|
46
70
|
onExit,
|
|
47
71
|
onRoomClosed,
|
|
48
|
-
onTokenExpired
|
|
72
|
+
onTokenExpired,
|
|
73
|
+
helper
|
|
49
74
|
}) {
|
|
50
75
|
const engine = React.useRef(null);
|
|
51
76
|
const [chatting, setChatting] = React.useState(false);
|
|
77
|
+
const [asking, setAsking] = React.useState(false);
|
|
78
|
+
const [askingConsent, setAskingConsent] = React.useState(false);
|
|
79
|
+
const openHelper = async () => {
|
|
80
|
+
if (await helperConsentGiven(AsyncStorage)) setAsking(true);
|
|
81
|
+
else setAskingConsent(true);
|
|
82
|
+
};
|
|
83
|
+
const askHelper = async (message) => {
|
|
84
|
+
const handle = engine.current;
|
|
85
|
+
if (!handle || !helper) return;
|
|
86
|
+
const snapshot = await handle.helperSnapshot();
|
|
87
|
+
if (!snapshot) return;
|
|
88
|
+
await handle.helperSay("Let me take a look...");
|
|
89
|
+
const answer = await helper.ask(message, snapshot);
|
|
90
|
+
if (answer.reply) await handle.helperSay(answer.reply);
|
|
91
|
+
if (answer.plan) {
|
|
92
|
+
const blocks = await handle.helperPropose(JSON.stringify(answer.plan));
|
|
93
|
+
if (blocks <= 0) await handle.helperSay("I could not find a good spot for that here.");
|
|
94
|
+
}
|
|
95
|
+
};
|
|
52
96
|
return /* @__PURE__ */ jsxs(SafeAreaView, { edges: ["bottom", "left", "right"], style: styles.fill, children: [
|
|
53
|
-
/* @__PURE__ */ jsx(NativeCubeforge, { ref: engine, style: styles.fill, seed, worldKey, room, skin, onExit
|
|
97
|
+
/* @__PURE__ */ jsx(NativeCubeforge, { ref: engine, style: styles.fill, seed, worldKey, room, skin, onExit: (event) => {
|
|
98
|
+
var _a;
|
|
99
|
+
return onExit(((_a = event.nativeEvent) == null ? void 0 : _a.summary) || void 0);
|
|
100
|
+
}, helperEnabled: Boolean(helper), onOpenHelper: () => void openHelper().catch(() => void 0), onOpenChat: () => setChatting(true), onRoomClosed: () => onRoomClosed == null ? void 0 : onRoomClosed(), onTokenExpired: () => onTokenExpired == null ? void 0 : onTokenExpired() }),
|
|
54
101
|
chatting ? /* @__PURE__ */ jsx(ChatBar, { onSend: (text) => {
|
|
55
102
|
var _a;
|
|
56
103
|
(_a = engine.current) == null ? void 0 : _a.sendChat(text).catch(() => void 0);
|
|
57
|
-
}, onClose: () => setChatting(false) }) : null
|
|
104
|
+
}, onClose: () => setChatting(false) }) : null,
|
|
105
|
+
asking ? /* @__PURE__ */ jsx(ChatBar, { placeholder: "Ask your helper", quickAsk: {
|
|
106
|
+
label: "Beautify what I built",
|
|
107
|
+
message: BEAUTIFY_MESSAGE
|
|
108
|
+
}, onSend: (text) => void askHelper(text).catch(() => void 0), onClose: () => setAsking(false) }) : null,
|
|
109
|
+
askingConsent ? /* @__PURE__ */ jsx(HelperConsent, { onClose: () => setAskingConsent(false), onAgree: () => {
|
|
110
|
+
setAskingConsent(false);
|
|
111
|
+
setAsking(true);
|
|
112
|
+
void rememberHelperConsent(AsyncStorage).catch(() => void 0);
|
|
113
|
+
} }) : null
|
|
58
114
|
] });
|
|
59
115
|
};
|
|
60
116
|
} catch (e) {
|
|
@@ -98,5 +154,56 @@ const styles = StyleSheet.create({
|
|
|
98
154
|
color: "#ffffff",
|
|
99
155
|
fontSize: 15,
|
|
100
156
|
fontWeight: "600"
|
|
157
|
+
},
|
|
158
|
+
quickAsk: {
|
|
159
|
+
alignSelf: "flex-start",
|
|
160
|
+
marginLeft: 10,
|
|
161
|
+
marginBottom: 8,
|
|
162
|
+
minHeight: 40,
|
|
163
|
+
paddingHorizontal: 14,
|
|
164
|
+
borderRadius: 20,
|
|
165
|
+
justifyContent: "center",
|
|
166
|
+
backgroundColor: "#3f7fbf"
|
|
167
|
+
},
|
|
168
|
+
consentBackdrop: {
|
|
169
|
+
flex: 1,
|
|
170
|
+
alignItems: "center",
|
|
171
|
+
justifyContent: "center",
|
|
172
|
+
padding: 24,
|
|
173
|
+
backgroundColor: "rgba(0,0,0,0.55)"
|
|
174
|
+
},
|
|
175
|
+
consentCard: {
|
|
176
|
+
maxWidth: 420,
|
|
177
|
+
width: "100%",
|
|
178
|
+
gap: 12,
|
|
179
|
+
padding: 20,
|
|
180
|
+
borderRadius: 14,
|
|
181
|
+
backgroundColor: "#12161b"
|
|
182
|
+
},
|
|
183
|
+
consentTitle: {
|
|
184
|
+
color: "#f1f5f9",
|
|
185
|
+
fontSize: 18,
|
|
186
|
+
fontWeight: "700"
|
|
187
|
+
},
|
|
188
|
+
consentBody: {
|
|
189
|
+
color: "#cbd5e1",
|
|
190
|
+
fontSize: 15,
|
|
191
|
+
lineHeight: 21
|
|
192
|
+
},
|
|
193
|
+
consentRow: {
|
|
194
|
+
flexDirection: "row",
|
|
195
|
+
justifyContent: "flex-end",
|
|
196
|
+
gap: 8
|
|
197
|
+
},
|
|
198
|
+
consentSecondary: {
|
|
199
|
+
minHeight: 44,
|
|
200
|
+
minWidth: 80,
|
|
201
|
+
alignItems: "center",
|
|
202
|
+
justifyContent: "center"
|
|
203
|
+
},
|
|
204
|
+
consentSecondaryLabel: {
|
|
205
|
+
color: "#cbd5e1",
|
|
206
|
+
fontSize: 15,
|
|
207
|
+
fontWeight: "600"
|
|
101
208
|
}
|
|
102
|
-
});export{cubeforge3DComponent,cubeforgeFriendsSupported,deleteCubeforgeSave};//# sourceMappingURL=cubeforge3D.js.map
|
|
209
|
+
});export{cubeforge3DComponent,cubeforgeFriendsSupported,cubeforgePicture,deleteCubeforgeSave};//# sourceMappingURL=cubeforge3D.js.map
|
|
@@ -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 type { Cubeforge3DProps } from './vendored';\n\ninterface NativeCubeforgeProps extends ViewProps {\n seed: number;\n worldKey: string;\n room?: Cubeforge3DProps['room'];\n skin?: string;\n onExit: () => void;\n onOpenChat: () => void;\n onRoomClosed: () => void;\n onTokenExpired: () => void;\n}\n\ninterface NativeCubeforgeHandle {\n sendChat: (text: string) => Promise<boolean>;\n}\n\ntype NativeCubeforgeView = React.ComponentType<NativeCubeforgeProps & React.RefAttributes<NativeCubeforgeHandle>>;\n\ninterface NativeCubeforgeModule {\n deleteWorld?: (worldKey: string) => void;\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\nfunction ChatBar({ onSend, onClose }: { onSend: (text: string) => void; onClose: () => void }) {\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 <View style={styles.chatBar}>\n <TextInput\n autoFocus\n value={draft}\n onChangeText={setDraft}\n onSubmitEditing={send}\n maxLength={MAX_CHAT_CHARS}\n placeholder=\"Message everyone here\"\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 }: Cubeforge3DProps) {\n const engine = React.useRef<NativeCubeforgeHandle>(null);\n const [chatting, setChatting] = React.useState(false);\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={onExit}\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 </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});\n"],"names":[],"mappings":"4TAiCA,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,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AS,EAAA,EAAA;AAAA,IACT,eAAiB,EAAA;AAAA,GACnB;AAAA,EACA,SAAW,EAAA;AAAA,IACT,IAAM,EAAA,CAAA;AAAA,IACN,SAAW,EAAA,EAAA;AAAA,IACX,YAAc,EAAA,EAAA;AAAA,IACd,iBAAmB,EAAA,EAAA;AAAA,IACnB,KAAO,EAAA,SAAA;AAAA,IACP,eAAiB,EAAA,SAAA;AAAA,IACjB,QAAU,EAAA;AAAA,GACZ;AAAA,EACA,QAAU,EAAA;AAAA,IACR,SAAW,EAAA,EAAA;AAAA,IACX,QAAU,EAAA,EAAA;AAAA,IACV,YAAc,EAAA,EAAA;AAAA,IACd,UAAY,EAAA,QAAA;AAAA,IACZ,cAAgB,EAAA,QAAA;AAAA,IAChB,eAAiB,EAAA;AAAA,GACnB;AAAA,EACA,aAAe,EAAA;AAAA,IACb,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 {\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 { 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 const handle = engine.current;\n if (!handle || !helper) return;\n const snapshot = await handle.helperSnapshot();\n if (!snapshot) return;\n await handle.helperSay('Let me take a look...');\n const answer = await helper.ask(message, snapshot);\n if (answer.reply) await handle.helperSay(answer.reply);\n if (answer.plan) {\n const blocks = await handle.helperPropose(JSON.stringify(answer.plan));\n if (blocks <= 0) await handle.helperSay('I could not find a good spot for that here.');\n }\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: { minHeight: 44, minWidth: 80, alignItems: 'center', justifyContent: 'center' },\n consentSecondaryLabel: { color: '#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';const
|
|
1
|
+
import {inviteMessage}from'./gameInvite.js';const TERRAIN_GENERATION = 2;
|
|
2
|
+
const WORLD_FIELDS = "id name seed memberIds inviteCode viewerIsOwner";
|
|
2
3
|
const UNREACHABLE = "Could not reach the game server. Check your connection and try again.";
|
|
3
4
|
const SIGN_IN = "Please sign in again.";
|
|
4
5
|
const TOKEN_WAIT_MS = 15e3;
|
|
@@ -84,9 +85,10 @@ function createCubeforgeFriends(deps) {
|
|
|
84
85
|
return data.myGameWorlds.map(toWorld);
|
|
85
86
|
},
|
|
86
87
|
createWorld: async (name, chatId) => {
|
|
87
|
-
const data = await request(`mutation($name: String!, $channelId: String) { createGameWorld(name: $name, channelId: $channelId) { ${WORLD_FIELDS} } }`, {
|
|
88
|
+
const data = await request(`mutation($name: String!, $channelId: String, $gen: Int) { createGameWorld(name: $name, channelId: $channelId, gen: $gen) { ${WORLD_FIELDS} } }`, {
|
|
88
89
|
name,
|
|
89
|
-
channelId: chatId
|
|
90
|
+
channelId: chatId,
|
|
91
|
+
gen: TERRAIN_GENERATION
|
|
90
92
|
});
|
|
91
93
|
return toWorld(data.createGameWorld);
|
|
92
94
|
},
|
|
@@ -101,6 +103,12 @@ function createCubeforgeFriends(deps) {
|
|
|
101
103
|
id: world.id
|
|
102
104
|
});
|
|
103
105
|
},
|
|
106
|
+
renameWorld: async (world, name) => {
|
|
107
|
+
await request("mutation($id: ID!, $name: String!) { renameGameWorld(id: $id, name: $name) { id } }", {
|
|
108
|
+
id: world.id,
|
|
109
|
+
name
|
|
110
|
+
});
|
|
111
|
+
},
|
|
104
112
|
deleteWorld: async (world) => {
|
|
105
113
|
await request("mutation($id: ID!) { deleteGameWorld(id: $id) }", {
|
|
106
114
|
id: world.id
|
|
@@ -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\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) { createGameWorld(name: $name, channelId: $channelId) { ${WORLD_FIELDS} } }`,\n { name, channelId: chatId },\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 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":"4CAkCA,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,CAAA,UAAA;AAAA,EACd,WAAW,CAAE,CAAA;AACf,CAAA,CAAA;AAMA,eAAsB,YAAa,CAAA,IAAA,EAA2B,SAAY,GAAA,aAAA,EAAe,aAAa,aAAuC,EAAA;AAC3I,EAAM,MAAA,QAAA,GAAW,IAAK,CAAA,GAAA,EAAQ,GAAA,SAAA;AAC9B,EAAA,IAAI,QAAQ,IAAK,EAAA;AACjB,EAAA,OAAO,CAAC,KAAA,IAAS,IAAK,CAAA,GAAA,KAAQ,QAAU,EAAA;AAEtC,IAAM,MAAA,IAAI,QAAQ,CAAW,OAAA,KAAA;AAC3B,MAAA,UAAA,CAAW,SAAS,UAAU,CAAA;AAAA,KAC/B,CAAA;AACD,IAAA,KAAA,GAAQ,IAAK,EAAA;AAAA;AAEf,EAAO,O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ACpC,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"}
|
|
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}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AC,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"}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
const HELPER_CONNECTOR = "yantra-games";
|
|
2
|
+
const HELPER_ACTION = "YANTRA_GAMES_HELPER";
|
|
3
|
+
const HELPER_TIMEOUT_MS = 9e4;
|
|
4
|
+
const NAME_TIMEOUT_MS = 3e4;
|
|
5
|
+
const DAILY_HELPER_LIMIT = 20;
|
|
6
|
+
const MAX_NAME_CHARS = 24;
|
|
7
|
+
const LIMIT_REPLY = "That is all the help I can give today. Come back tomorrow!";
|
|
8
|
+
const UNAVAILABLE_REPLY = "I cannot reach my workshop right now. Please try again soon.";
|
|
9
|
+
const CONSENT_KEY = "yantra.cubeforge.helperConsent.v1";
|
|
10
|
+
const USAGE_KEY = "yantra.cubeforge.helperUsage.v1";
|
|
11
|
+
function asRecord(value) {
|
|
12
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
13
|
+
}
|
|
14
|
+
function findLayer(raw, key) {
|
|
15
|
+
var _a;
|
|
16
|
+
let layer = asRecord(raw);
|
|
17
|
+
for (let depth = 0; layer && depth < 6; depth += 1) {
|
|
18
|
+
if (key in layer) return layer;
|
|
19
|
+
layer = (_a = asRecord(layer.data)) != null ? _a : asRecord(layer.result);
|
|
20
|
+
}
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
function dayOf(now) {
|
|
24
|
+
return new Date(now).toISOString().slice(0, 10);
|
|
25
|
+
}
|
|
26
|
+
async function usedToday(storage, now) {
|
|
27
|
+
var _a;
|
|
28
|
+
try {
|
|
29
|
+
const saved = JSON.parse((_a = await storage.getItem(USAGE_KEY)) != null ? _a : "{}");
|
|
30
|
+
return saved.day === dayOf(now) ? Number(saved.used) || 0 : 0;
|
|
31
|
+
} catch (e) {
|
|
32
|
+
return 0;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
async function helperConsentGiven(storage) {
|
|
36
|
+
try {
|
|
37
|
+
return await storage.getItem(CONSENT_KEY) === "1";
|
|
38
|
+
} catch (e) {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
async function rememberHelperConsent(storage) {
|
|
43
|
+
await storage.setItem(CONSENT_KEY, "1");
|
|
44
|
+
}
|
|
45
|
+
function createCubeforgeHelper(deps) {
|
|
46
|
+
var _a;
|
|
47
|
+
const {
|
|
48
|
+
exec,
|
|
49
|
+
storage
|
|
50
|
+
} = deps;
|
|
51
|
+
const now = (_a = deps.now) != null ? _a : Date.now;
|
|
52
|
+
return {
|
|
53
|
+
ask: async (message, snapshot) => {
|
|
54
|
+
var _a2;
|
|
55
|
+
const today = await usedToday(storage, now());
|
|
56
|
+
if (today >= DAILY_HELPER_LIMIT) return {
|
|
57
|
+
reply: LIMIT_REPLY,
|
|
58
|
+
plan: null
|
|
59
|
+
};
|
|
60
|
+
try {
|
|
61
|
+
const raw = await exec(HELPER_CONNECTOR, HELPER_ACTION, {
|
|
62
|
+
mode: "build",
|
|
63
|
+
message,
|
|
64
|
+
snapshot: JSON.parse(snapshot)
|
|
65
|
+
}, {
|
|
66
|
+
timeoutMs: HELPER_TIMEOUT_MS
|
|
67
|
+
});
|
|
68
|
+
const layer = findLayer(raw, "reply");
|
|
69
|
+
if (!layer) return {
|
|
70
|
+
reply: UNAVAILABLE_REPLY,
|
|
71
|
+
plan: null
|
|
72
|
+
};
|
|
73
|
+
await storage.setItem(USAGE_KEY, JSON.stringify({
|
|
74
|
+
day: dayOf(now()),
|
|
75
|
+
used: today + 1
|
|
76
|
+
})).catch(() => void 0);
|
|
77
|
+
return {
|
|
78
|
+
reply: typeof layer.reply === "string" ? layer.reply : "",
|
|
79
|
+
plan: (_a2 = layer.plan) != null ? _a2 : null
|
|
80
|
+
};
|
|
81
|
+
} catch (e) {
|
|
82
|
+
return {
|
|
83
|
+
reply: UNAVAILABLE_REPLY,
|
|
84
|
+
plan: null
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
nameWorld: async (summary) => {
|
|
89
|
+
var _a2;
|
|
90
|
+
try {
|
|
91
|
+
const raw = await exec(HELPER_CONNECTOR, HELPER_ACTION, {
|
|
92
|
+
mode: "name",
|
|
93
|
+
summary: JSON.parse(summary)
|
|
94
|
+
}, {
|
|
95
|
+
timeoutMs: NAME_TIMEOUT_MS
|
|
96
|
+
});
|
|
97
|
+
const name = (_a2 = findLayer(raw, "name")) == null ? void 0 : _a2.name;
|
|
98
|
+
const clean = typeof name === "string" ? name.trim().slice(0, MAX_NAME_CHARS) : "";
|
|
99
|
+
return clean || null;
|
|
100
|
+
} catch (e) {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
}export{DAILY_HELPER_LIMIT,HELPER_ACTION,HELPER_CONNECTOR,LIMIT_REPLY,UNAVAILABLE_REPLY,createCubeforgeHelper,helperConsentGiven,rememberHelperConsent};//# sourceMappingURL=cubeforgeHelper.js.map
|
|
@@ -0,0 +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\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\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":["_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;AACjC,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,S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,QAAO,OAAA;AAAA,UACL,OAAO,OAAO,KAAA,CAAM,KAAU,KAAA,QAAA,GAAW,MAAM,KAAQ,GAAA,EAAA;AAAA,UACvD,IAAMA,EAAAA,CAAAA,GAAAA,GAAA,KAAM,CAAA,IAAA,KAAN,OAAAA,GAAc,GAAA;AAAA,SACtB;AAAA,OACM,CAAA,OAAA,CAAA,EAAA;AACN,QAAO,OAAA;AAAA,UACL,KAAO,EAAA,iBAAA;AAAA,UACP,IAAM,EAAA;AAAA,SACR;AAAA;AACF,KACF;AAAA,IACA,SAAA,EAAW,OAAM,OAAW,KAAA;AAzGhC,MAAAA,IAAAA,GAAAA;AA0GM,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"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import {useRef,useMemo}from'react';import AsyncStorage from'@react-native-async-storage/async-storage';import {createRemoteConnectorExec}from'../canvas/videoEditor/remoteMediaClient.js';import {useCanvasSession}from'../canvas/useCanvasSession.js';import {createCubeforgeHelper}from'./cubeforgeHelper.js';function useCubeforgeHelper() {
|
|
2
|
+
const {
|
|
3
|
+
token,
|
|
4
|
+
indexUrl
|
|
5
|
+
} = useCanvasSession();
|
|
6
|
+
const latest = useRef({
|
|
7
|
+
token,
|
|
8
|
+
indexUrl
|
|
9
|
+
});
|
|
10
|
+
latest.current = {
|
|
11
|
+
token,
|
|
12
|
+
indexUrl
|
|
13
|
+
};
|
|
14
|
+
return useMemo(() => createCubeforgeHelper({
|
|
15
|
+
storage: AsyncStorage,
|
|
16
|
+
exec: (connector, action, params, options) => {
|
|
17
|
+
const {
|
|
18
|
+
token: current,
|
|
19
|
+
indexUrl: url
|
|
20
|
+
} = latest.current;
|
|
21
|
+
if (!current) return Promise.reject(new Error("not signed in yet"));
|
|
22
|
+
return createRemoteConnectorExec(current, url)(connector, action, params, options);
|
|
23
|
+
}
|
|
24
|
+
}), []);
|
|
25
|
+
}export{useCubeforgeHelper};//# sourceMappingURL=useCubeforgeHelper.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useCubeforgeHelper.js","sources":["../../../src/features/games/useCubeforgeHelper.ts"],"sourcesContent":["/** The build helper for the signed-in person. */\nimport { useMemo, useRef } from 'react';\nimport AsyncStorage from '@react-native-async-storage/async-storage';\nimport { createRemoteConnectorExec } from '../canvas/videoEditor/remoteMediaClient';\nimport { useCanvasSession } from '../canvas/useCanvasSession';\nimport { createCubeforgeHelper } from './cubeforgeHelper';\nimport type { CubeforgeHelper } from './vendored';\n\nexport function useCubeforgeHelper(): CubeforgeHelper {\n const { token, indexUrl } = useCanvasSession();\n const latest = useRef({ token, indexUrl });\n latest.current = { token, indexUrl };\n return useMemo(\n () =>\n createCubeforgeHelper({\n storage: AsyncStorage,\n exec: (connector, action, params, options) => {\n const { token: current, indexUrl: url } = latest.current;\n if (!current) return Promise.reject(new Error('not signed in yet'));\n return createRemoteConnectorExec(current, url)(connector, action, params, options);\n },\n }),\n [],\n );\n}\n"],"names":[],"mappings":"gTAOO,SAAS,kBAAsC,GAAA;AACpD,EAAM,MAAA;AAAA,IACJ,KAAA;AAAA,IACA;AAAA,MACE,gBAAiB,EAAA;AACrB,EAAA,MAAM,SAAS,MAAO,CAAA;AAAA,IACpB,KAAA;AAAA,IACA;AAAA,GACD,CAAA;AACD,EAAA,MAAA,CAAO,OAAU,GAAA;AAAA,IACf,KAAA;AAAA,IACA;AAAA,GACF;AACA,EAAO,OAAA,OAAA,CAAQ,MAAM,qBAAsB,CAAA;AAAA,IACzC,OAAS,EAAA,YAAA;AAAA,IACT,IAAM,EAAA,CAAC,SAAW,EAAA,MAAA,EAAQ,QAAQ,OAAY,KAAA;AAC5C,MAAM,MAAA;AAAA,QACJ,KAAO,EAAA,OAAA;AAAA,QACP,QAAU,EAAA;AAAA,UACR,MAAO,CAAA,OAAA;AACX,MAAI,IAAA,CAAC,SAAgB,OAAA,OAAA,CAAQ,OAAO,IAAI,KAAA,CAAM,mBAAmB,CAAC,CAAA;AAClE,MAAA,OAAO,0BAA0B,OAAS,EAAA,GAAG,EAAE,SAAW,EAAA,MAAA,EAAQ,QAAQ,OAAO,CAAA;AAAA;AACnF,GACD,CAAG,EAAA,EAAE,CAAA;AACR"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
const DEFAULT_NAMES = /* @__PURE__ */ new Set(["our world", "my world", "new world"]);
|
|
2
|
+
const MIN_BLOCKS_TO_NAME = 8;
|
|
3
|
+
function hasDefaultName(name) {
|
|
4
|
+
return DEFAULT_NAMES.has(name.trim().toLowerCase());
|
|
5
|
+
}
|
|
6
|
+
function worthNaming(summary) {
|
|
7
|
+
try {
|
|
8
|
+
const placed = JSON.parse(summary).blocks_placed;
|
|
9
|
+
return typeof placed === "number" && placed >= MIN_BLOCKS_TO_NAME;
|
|
10
|
+
} catch (e) {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
}export{hasDefaultName,worthNaming};//# sourceMappingURL=helper.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"helper.js","sources":["../../../../../../src/features/games/vendored/core/cubeforge/helper.ts"],"sourcesContent":["/**\n * The build helper's connection to the host. The engine knows the world; the\n * host knows how to reach an AI. Neither needs to know about the other.\n */\n\n/** What the helper said, and a plan for the engine to preview if it has one. */\nexport interface HelperAnswer {\n reply: string;\n plan: unknown | null;\n}\n\nexport interface CubeforgeHelper {\n /** Answer the player, given what is around them. */\n ask(message: string, snapshot: string): Promise<HelperAnswer>;\n /** A fitting name for a world from its summary, or null. */\n nameWorld(summary: string): Promise<string | null>;\n}\n\nconst DEFAULT_NAMES = new Set(['our world', 'my world', 'new world']);\n/** Too little built to say what a world is like. */\nconst MIN_BLOCKS_TO_NAME = 8;\n\n/** Whether nobody has chosen this name, so the helper may replace it. */\nexport function hasDefaultName(name: string): boolean {\n return DEFAULT_NAMES.has(name.trim().toLowerCase());\n}\n\n/** Whether a world's summary shows enough building to name it from. */\nexport function worthNaming(summary: string): boolean {\n try {\n const placed = (JSON.parse(summary) as { blocks_placed?: unknown }).blocks_placed;\n return typeof placed === 'number' && placed >= MIN_BLOCKS_TO_NAME;\n } catch {\n return false;\n }\n}\n"],"names":[],"mappings":"AAgBA,MAAM,gCAAoB,IAAA,GAAA,CAAI,CAAC,WAAa,EAAA,UAAA,EAAY,WAAW,CAAC,CAAA;AAEpE,MAAM,kBAAqB,GAAA,CAAA;AAGpB,SAAS,eAAe,IAAuB,EAAA;AACpD,EAAA,OAAO,cAAc,GAAI,CAAA,IAAA,CAAK,IAAK,EAAA,CAAE,aAAa,CAAA;AACpD;AAGO,SAAS,YAAY,OAA0B,EAAA;AACpD,EAAI,IAAA;AACF,IAAA,MAAM,MAAU,GAAA,IAAA,CAAK,KAAM,CAAA,OAAO,CAE/B,CAAA,aAAA;AACH,IAAO,OAAA,OAAO,MAAW,KAAA,QAAA,IAAY,MAAU,IAAA,kBAAA;AAAA,GACzC,CAAA,OAAA,CAAA,EAAA;AACN,IAAO,OAAA,KAAA;AAAA;AAEX"}
|
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
import {nativeWorldKey}from'./nativeWorld.js';import {seedFromString}from'./worldgen.js';var __defProp = Object.defineProperty;
|
|
2
|
+
var __defProps = Object.defineProperties;
|
|
3
|
+
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
4
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
2
7
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
8
|
+
var __spreadValues = (a, b) => {
|
|
9
|
+
for (var prop in b || (b = {}))
|
|
10
|
+
if (__hasOwnProp.call(b, prop))
|
|
11
|
+
__defNormalProp(a, prop, b[prop]);
|
|
12
|
+
if (__getOwnPropSymbols)
|
|
13
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
14
|
+
if (__propIsEnum.call(b, prop))
|
|
15
|
+
__defNormalProp(a, prop, b[prop]);
|
|
16
|
+
}
|
|
17
|
+
return a;
|
|
18
|
+
};
|
|
19
|
+
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
3
20
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
4
21
|
const MAX_NAME_CHARS = 40;
|
|
5
22
|
const FIRST_WORLD_NAME = "My world";
|
|
@@ -40,7 +57,10 @@ class NativeWorldRepository {
|
|
|
40
57
|
}
|
|
41
58
|
/** The org's first world, then the others, newest first. */
|
|
42
59
|
async list() {
|
|
43
|
-
|
|
60
|
+
var _a;
|
|
61
|
+
const stored = await this.read();
|
|
62
|
+
const first = (_a = stored.find((w) => w.key === this.first.key)) != null ? _a : this.first;
|
|
63
|
+
return [first, ...stored.filter((w) => w.key !== this.first.key)];
|
|
44
64
|
}
|
|
45
65
|
async create(name) {
|
|
46
66
|
const worlds = await this.read();
|
|
@@ -56,6 +76,21 @@ class NativeWorldRepository {
|
|
|
56
76
|
await this.write([world, ...worlds]);
|
|
57
77
|
return world;
|
|
58
78
|
}
|
|
79
|
+
/** Give a world a new name. Returns false if there is no such world. */
|
|
80
|
+
async rename(key, name) {
|
|
81
|
+
const trimmed = name.trim().slice(0, MAX_NAME_CHARS);
|
|
82
|
+
if (!trimmed) return false;
|
|
83
|
+
const worlds = await this.read();
|
|
84
|
+
const known = worlds.some((w) => w.key === key);
|
|
85
|
+
if (!known && key !== this.first.key) return false;
|
|
86
|
+
const next = known ? worlds.map((w) => w.key === key ? __spreadProps(__spreadValues({}, w), {
|
|
87
|
+
name: trimmed
|
|
88
|
+
}) : w) : [...worlds, __spreadProps(__spreadValues({}, this.first), {
|
|
89
|
+
name: trimmed
|
|
90
|
+
})];
|
|
91
|
+
await this.write(next);
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
59
94
|
/** Forget a world. The org's first world cannot be removed. */
|
|
60
95
|
async remove(key) {
|
|
61
96
|
if (key === this.first.key) return false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nativeWorlds.js","sources":["../../../../../../src/features/games/vendored/core/cubeforge/nativeWorlds.ts"],"sourcesContent":["/**\n * The list of solo 3D worlds on this device. Each world's terrain and progress\n * live in the engine's own save file, named by `key`; this is just the index.\n * The org's first world always exists and keeps the key older builds used.\n */\nimport type { KeyValueStorage } from '../storage/storage';\nimport { nativeWorldKey } from './nativeWorld';\nimport { seedFromString } from './worldgen';\n\nexport interface NativeWorld {\n key: string;\n name: string;\n seed: number;\n}\n\nconst MAX_NAME_CHARS = 40;\nconst FIRST_WORLD_NAME = 'My world';\nconst NEW_WORLD_NAME = 'New world';\n\ninterface StoredList {\n worlds: NativeWorld[];\n}\n\nfunction isNativeWorld(v: unknown): v is NativeWorld {\n const w = v as NativeWorld;\n return !!w && typeof w.key === 'string' && !!w.key && typeof w.name === 'string' && Number.isFinite(w.seed);\n}\n\nexport class NativeWorldRepository {\n private readonly storageKey: string;\n private readonly first: NativeWorld;\n\n constructor(\n private readonly storage: KeyValueStorage,\n orgName: string,\n /** Injected so tests are repeatable. */\n private readonly now: () => number = Date.now,\n ) {\n const org = orgName || 'default';\n this.storageKey = `yantra-games:cubeforge3d-worlds:${org}`;\n this.first = { key: nativeWorldKey(org), name: FIRST_WORLD_NAME, seed: seedFromString(org) };\n }\n\n private async read(): Promise<NativeWorld[]> {\n const raw = await this.storage.getItem(this.storageKey);\n if (!raw) return [];\n try {\n const parsed = JSON.parse(raw) as StoredList;\n return Array.isArray(parsed.worlds) ? parsed.worlds.filter(isNativeWorld) : [];\n } catch {\n return [];\n }\n }\n\n private async write(worlds: NativeWorld[]): Promise<void> {\n const payload: StoredList = { worlds };\n await this.storage.setItem(this.storageKey, JSON.stringify(payload));\n }\n\n /** The org's first world, then the others, newest first. */\n async list(): Promise<NativeWorld[]> {\n
|
|
1
|
+
{"version":3,"file":"nativeWorlds.js","sources":["../../../../../../src/features/games/vendored/core/cubeforge/nativeWorlds.ts"],"sourcesContent":["/**\n * The list of solo 3D worlds on this device. Each world's terrain and progress\n * live in the engine's own save file, named by `key`; this is just the index.\n * The org's first world always exists and keeps the key older builds used.\n */\nimport type { KeyValueStorage } from '../storage/storage';\nimport { nativeWorldKey } from './nativeWorld';\nimport { seedFromString } from './worldgen';\n\nexport interface NativeWorld {\n key: string;\n name: string;\n seed: number;\n}\n\nconst MAX_NAME_CHARS = 40;\nconst FIRST_WORLD_NAME = 'My world';\nconst NEW_WORLD_NAME = 'New world';\n\ninterface StoredList {\n worlds: NativeWorld[];\n}\n\nfunction isNativeWorld(v: unknown): v is NativeWorld {\n const w = v as NativeWorld;\n return !!w && typeof w.key === 'string' && !!w.key && typeof w.name === 'string' && Number.isFinite(w.seed);\n}\n\nexport class NativeWorldRepository {\n private readonly storageKey: string;\n private readonly first: NativeWorld;\n\n constructor(\n private readonly storage: KeyValueStorage,\n orgName: string,\n /** Injected so tests are repeatable. */\n private readonly now: () => number = Date.now,\n ) {\n const org = orgName || 'default';\n this.storageKey = `yantra-games:cubeforge3d-worlds:${org}`;\n this.first = { key: nativeWorldKey(org), name: FIRST_WORLD_NAME, seed: seedFromString(org) };\n }\n\n private async read(): Promise<NativeWorld[]> {\n const raw = await this.storage.getItem(this.storageKey);\n if (!raw) return [];\n try {\n const parsed = JSON.parse(raw) as StoredList;\n return Array.isArray(parsed.worlds) ? parsed.worlds.filter(isNativeWorld) : [];\n } catch {\n return [];\n }\n }\n\n private async write(worlds: NativeWorld[]): Promise<void> {\n const payload: StoredList = { worlds };\n await this.storage.setItem(this.storageKey, JSON.stringify(payload));\n }\n\n /** The org's first world, then the others, newest first. */\n async list(): Promise<NativeWorld[]> {\n const stored = await this.read();\n // The first world is implied, so a saved copy only exists once it is renamed.\n const first = stored.find((w) => w.key === this.first.key) ?? this.first;\n return [first, ...stored.filter((w) => w.key !== this.first.key)];\n }\n\n async create(name: string): Promise<NativeWorld> {\n const worlds = await this.read();\n const stamp = this.now().toString(36);\n let key = `${this.first.key}-${stamp}`;\n for (let n = 2; worlds.some((w) => w.key === key); n += 1) key = `${this.first.key}-${stamp}-${n}`;\n const trimmed = name.trim().slice(0, MAX_NAME_CHARS) || NEW_WORLD_NAME;\n const world: NativeWorld = { key, name: trimmed, seed: seedFromString(key) };\n await this.write([world, ...worlds]);\n return world;\n }\n\n /** Give a world a new name. Returns false if there is no such world. */\n async rename(key: string, name: string): Promise<boolean> {\n const trimmed = name.trim().slice(0, MAX_NAME_CHARS);\n if (!trimmed) return false;\n const worlds = await this.read();\n const known = worlds.some((w) => w.key === key);\n if (!known && key !== this.first.key) return false;\n const next = known\n ? worlds.map((w) => (w.key === key ? { ...w, name: trimmed } : w))\n : [...worlds, { ...this.first, name: trimmed }];\n await this.write(next);\n return true;\n }\n\n /** Forget a world. The org's first world cannot be removed. */\n async remove(key: string): Promise<boolean> {\n if (key === this.first.key) return false;\n const worlds = await this.read();\n const next = worlds.filter((w) => w.key !== key);\n if (next.length === worlds.length) return false;\n await this.write(next);\n return true;\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MAEnB,IAAM,EAAA;AAAA,KACP,CAAA,CAAA;AACD,IAAM,MAAA,IAAA,CAAK,MAAM,IAAI,CAAA;AACrB,IAAO,OAAA,IAAA;AAAA;AACT;AAAA,EAGA,MAAM,OAAO,GAA+B,EAAA;AAC1C,IAAA,IAAI,GAAQ,KAAA,IAAA,CAAK,KAAM,CAAA,GAAA,EAAY,OAAA,KAAA;AACnC,IAAM,MAAA,MAAA,GAAS,MAAM,IAAA,CAAK,IAAK,EAAA;AAC/B,IAAA,MAAM,OAAO,MAAO,CAAA,MAAA,CAAO,CAAK,CAAA,KAAA,CAAA,CAAE,QAAQ,GAAG,CAAA;AAC7C,IAAA,IAAI,IAAK,CAAA,MAAA,KAAW,MAAO,CAAA,MAAA,EAAe,OAAA,KAAA;AAC1C,IAAM,MAAA,IAAA,CAAK,MAAM,IAAI,CAAA;AACrB,IAAO,OAAA,IAAA;AAAA;AAEX"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sharedWorlds.js","sources":["../../../../../../src/features/games/vendored/core/cubeforge/sharedWorlds.ts"],"sourcesContent":["/**\n * Playing Cubeforge 3D with friends. The host app implements `CubeforgeFriends`\n * over its own backend and chat, so this package stays free of both.\n */\n\nexport interface SharedWorld {\n id: string;\n name: string;\n /** World seed; the server is the authority once connected. */\n seed: number;\n memberCount: number;\n inviteCode: string | null;\n ownedByMe: boolean;\n}\n\n/** A chat group or person who can receive an invite. */\nexport interface InviteChat {\n id: string;\n title: string;\n detail: string;\n}\n\n/** What the engine needs to enter a shared world. */\nexport interface RoomAccess {\n /** `wss://host/rooms/<worldId>`. */\n url: string;\n token: string;\n playerName: string;\n}\n\nexport interface CubeforgeFriends {\n listWorlds(): Promise<SharedWorld[]>;\n createWorld(name: string, chatId: string): Promise<SharedWorld>;\n joinWorld(inviteCode: string): Promise<SharedWorld>;\n leaveWorld(world: SharedWorld): Promise<void>;\n deleteWorld(world: SharedWorld): Promise<void>;\n listChats(): Promise<InviteChat[]>;\n /** Post a join card for `world` into the chat. */\n inviteToChat(world: SharedWorld, chatId: string): Promise<void>;\n /** `renewToken` asks for new credentials after the old token expired. */\n roomAccess(world: SharedWorld, options?: { renewToken?: boolean }): Promise<RoomAccess>;\n}\n\nconst CODE = /^[2-9A-HJKMNP-Z]{8,}$/;\n\n/**\n * The invite code in what someone typed or pasted: a bare code in any case, or\n * a link ending in one. Returns null when there is no valid code.\n */\nexport function parseInviteCode(input: string): string | null {\n const last =\n input\n .trim()\n .split(/[/?#=]/)\n .filter(Boolean)\n .pop() ?? '';\n const code = last.replace(/[\\s-]/g, '').toUpperCase();\n return CODE.test(code) ? code : null;\n}\n\n/** The save file name for a shared world on this device. */\nexport function sharedWorldKey(worldId: string): string {\n return `room-${worldId.toLowerCase().replace(/[^a-z0-9_-]+/g, '-')}`;\n}\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"sharedWorlds.js","sources":["../../../../../../src/features/games/vendored/core/cubeforge/sharedWorlds.ts"],"sourcesContent":["/**\n * Playing Cubeforge 3D with friends. The host app implements `CubeforgeFriends`\n * over its own backend and chat, so this package stays free of both.\n */\n\nexport interface SharedWorld {\n id: string;\n name: string;\n /** World seed; the server is the authority once connected. */\n seed: number;\n memberCount: number;\n inviteCode: string | null;\n ownedByMe: boolean;\n}\n\n/** A chat group or person who can receive an invite. */\nexport interface InviteChat {\n id: string;\n title: string;\n detail: string;\n}\n\n/** What the engine needs to enter a shared world. */\nexport interface RoomAccess {\n /** `wss://host/rooms/<worldId>`. */\n url: string;\n token: string;\n playerName: string;\n}\n\nexport interface CubeforgeFriends {\n listWorlds(): Promise<SharedWorld[]>;\n createWorld(name: string, chatId: string): Promise<SharedWorld>;\n joinWorld(inviteCode: string): Promise<SharedWorld>;\n leaveWorld(world: SharedWorld): Promise<void>;\n deleteWorld(world: SharedWorld): Promise<void>;\n /** Hosts that predate world names leave this out. */\n renameWorld?(world: SharedWorld, name: string): Promise<void>;\n listChats(): Promise<InviteChat[]>;\n /** Post a join card for `world` into the chat. */\n inviteToChat(world: SharedWorld, chatId: string): Promise<void>;\n /** `renewToken` asks for new credentials after the old token expired. */\n roomAccess(world: SharedWorld, options?: { renewToken?: boolean }): Promise<RoomAccess>;\n}\n\nconst CODE = /^[2-9A-HJKMNP-Z]{8,}$/;\n\n/**\n * The invite code in what someone typed or pasted: a bare code in any case, or\n * a link ending in one. Returns null when there is no valid code.\n */\nexport function parseInviteCode(input: string): string | null {\n const last =\n input\n .trim()\n .split(/[/?#=]/)\n .filter(Boolean)\n .pop() ?? '';\n const code = last.replace(/[\\s-]/g, '').toUpperCase();\n return CODE.test(code) ? code : null;\n}\n\n/** The save file name for a shared world on this device. */\nexport function sharedWorldKey(worldId: string): string {\n return `room-${worldId.toLowerCase().replace(/[^a-z0-9_-]+/g, '-')}`;\n}\n"],"names":[],"mappings":"AA6CA,MAAM,IAAO,GAAA,uBAAA;AAMN,SAAS,gBAAgB,KAA8B,EAAA;AAnD9D,EAAA,IAAA,EAAA;AAoDE,EAAA,MAAM,IAAO,GAAA,CAAA,EAAA,GAAA,KAAA,CAAM,IAAK,EAAA,CAAE,KAAM,CAAA,QAAQ,CAAE,CAAA,MAAA,CAAO,OAAO,CAAA,CAAE,GAAI,EAAA,KAAjD,IAAsD,GAAA,EAAA,GAAA,EAAA;AACnE,EAAA,MAAM,OAAO,IAAK,CAAA,OAAA,CAAQ,QAAU,EAAA,EAAE,EAAE,WAAY,EAAA;AACpD,EAAA,OAAO,IAAK,CAAA,IAAA,CAAK,IAAI,CAAA,GAAI,IAAO,GAAA,IAAA;AAClC;AAGO,SAAS,eAAe,OAAyB,EAAA;AACtD,EAAA,OAAO,QAAQ,OAAQ,CAAA,WAAA,GAAc,OAAQ,CAAA,eAAA,EAAiB,GAAG,CAAC,CAAA,CAAA;AACpE"}
|