[feat] charajs apis
This commit is contained in:
137
src/etc/example-char.js
Normal file
137
src/etc/example-char.js
Normal file
@@ -0,0 +1,137 @@
|
||||
//@use editInput
|
||||
//@use editOutput
|
||||
//@use editProcess
|
||||
//@use editDisplay
|
||||
//@use onButtonClick
|
||||
|
||||
async function editInput(text){
|
||||
return text;
|
||||
}
|
||||
|
||||
async function editOutput(text){
|
||||
return text;
|
||||
}
|
||||
|
||||
async function editProcess(text){
|
||||
return text;
|
||||
}
|
||||
|
||||
async function onButtonClick(code){
|
||||
let fm = await getCharacterFirstMessage()
|
||||
|
||||
if(code === 'calculate'){
|
||||
fm = calculateString(fm)
|
||||
}
|
||||
else if(code === 'clearResult'){
|
||||
fm = '0';
|
||||
}
|
||||
else if(code.startsWith("click")){
|
||||
fm += code.substring(5);
|
||||
}
|
||||
else{
|
||||
fm += code;
|
||||
}
|
||||
setCharacterFirstMessage(fm);
|
||||
|
||||
}
|
||||
|
||||
|
||||
function calculateString(input) {
|
||||
let numbers = input.split(/\+|\-|\*|\//).map(Number);
|
||||
let operators = input.split(/[0-9]+/).filter(Boolean);
|
||||
|
||||
let result = numbers[0];
|
||||
|
||||
for (let i = 0; i < operators.length; i++) {
|
||||
switch (operators[i]) {
|
||||
case '+':
|
||||
result += numbers[i + 1];
|
||||
break;
|
||||
case '-':
|
||||
result -= numbers[i + 1];
|
||||
break;
|
||||
case '*':
|
||||
result *= numbers[i + 1];
|
||||
break;
|
||||
case '/':
|
||||
result /= numbers[i + 1];
|
||||
break;
|
||||
default:
|
||||
return "Error: Invalid operator";
|
||||
}
|
||||
}
|
||||
return result.toFixed(1);
|
||||
}
|
||||
|
||||
async function editDisplay(text){
|
||||
return `
|
||||
<div class="calculator">
|
||||
<div class="result" id="result">${text}</div>
|
||||
<button class="btn" risu-btn="click7">7</button>
|
||||
<button class="btn" risu-btn="click8">8</button>
|
||||
<button class="btn" risu-btn="click9">9</button>
|
||||
<button class="btn operator" risu-btn="+">+</button>
|
||||
<button class="btn" risu-btn="click4">4</button>
|
||||
<button class="btn" risu-btn="click5">5</button>
|
||||
<button class="btn" risu-btn="click6">6</button>
|
||||
<button class="btn operator" risu-btn="-">-</button>
|
||||
<button class="btn" risu-btn="click1">1</button>
|
||||
<button class="btn" risu-btn="click2">2</button>
|
||||
<button class="btn" risu-btn="click3">3</button>
|
||||
<button class="btn operator" risu-btn="*">*</button>
|
||||
<button class="btn" risu-btn="click0">0</button>
|
||||
<button class="btn" onclick="clearResult">C</button>
|
||||
<button class="btn operator" risu-btn="calculate">=</button>
|
||||
<button class="btn operator" risu-btn="/">/</button>
|
||||
</div>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
}
|
||||
|
||||
.calculator {
|
||||
max-width: 300px;
|
||||
margin: 0 auto;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 5px;
|
||||
padding: 10px;
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
|
||||
.result {
|
||||
font-size: 24px;
|
||||
text-align: right;
|
||||
margin-bottom: 10px;
|
||||
padding: 5px;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 5px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.btn {
|
||||
font-size: 18px;
|
||||
padding: 10px;
|
||||
margin: 5px;
|
||||
width: 45px;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
color:black;
|
||||
}
|
||||
|
||||
.btn:hover {
|
||||
background-color: #ddd;
|
||||
}
|
||||
|
||||
.btn.operator {
|
||||
background-color: #ff9800;
|
||||
color: #fff;
|
||||
}
|
||||
</style>
|
||||
`;
|
||||
}
|
||||
|
||||
async function edit(text){
|
||||
return text;
|
||||
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import App from "./App.svelte";
|
||||
import { loadData } from "./ts/storage/globalApi";
|
||||
import { initHotkey } from "./ts/hotkey";
|
||||
import { polyfill } from "./ts/polyfill";
|
||||
import { watchParamButton } from "./ts/plugins/embedscript";
|
||||
|
||||
polyfill()
|
||||
|
||||
@@ -13,4 +14,5 @@ const app = new App({
|
||||
|
||||
loadData()
|
||||
initHotkey()
|
||||
watchParamButton()
|
||||
export default app;
|
||||
@@ -45,13 +45,17 @@ DOMPurify.addHook("uponSanitizeElement", (node: HTMLElement, data) => {
|
||||
});
|
||||
|
||||
DOMPurify.addHook("uponSanitizeAttribute", (node, data) => {
|
||||
if(data.attrName === 'style'){
|
||||
data.attrValue = data.attrValue.replace(/(absolute)|(z-index)|(fixed)/g, '')
|
||||
}
|
||||
if(data.attrName === 'class'){
|
||||
data.attrValue = data.attrValue.split(' ').map((v) => {
|
||||
return "x-risu-" + v
|
||||
}).join(' ')
|
||||
switch(data.attrName){
|
||||
case 'style':{
|
||||
data.attrValue = data.attrValue.replace(/(absolute)|(z-index)|(fixed)/g, '')
|
||||
break
|
||||
}
|
||||
case 'class':{
|
||||
data.attrValue = data.attrValue.split(' ').map((v) => {
|
||||
return "x-risu-" + v
|
||||
}).join(' ')
|
||||
break
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -123,7 +127,7 @@ export async function ParseMarkdown(data:string, charArg:(simpleCharacterArgumen
|
||||
}
|
||||
return decodeStyle(DOMPurify.sanitize(mconverted.parse(encodeStyle(data)), {
|
||||
ADD_TAGS: ["iframe", "style", "risu-style"],
|
||||
ADD_ATTR: ["allow", "allowfullscreen", "frameborder", "scrolling"],
|
||||
ADD_ATTR: ["allow", "allowfullscreen", "frameborder", "scrolling", "risu-btn"],
|
||||
FORBID_ATTR: ["href"]
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { get } from 'svelte/store'
|
||||
import type { ScriptMode } from '../process/scripts'
|
||||
import myWorkerUrl from './embedworker?worker&url'
|
||||
import { DataBase } from '../storage/database'
|
||||
import { DataBase, type Chat, type character, type Message } from '../storage/database'
|
||||
import { selectedCharID } from '../stores'
|
||||
import { cloneDeep } from 'lodash'
|
||||
import { add, cloneDeep } from 'lodash'
|
||||
import { sleep } from '../util'
|
||||
import { characterFormatUpdate } from '../characters'
|
||||
import { setDatabase } from '../storage/database'
|
||||
|
||||
let worker = new Worker(new URL(myWorkerUrl), {type: 'module'})
|
||||
let worker = new Worker(myWorkerUrl, {type: 'module'})
|
||||
|
||||
let results:{
|
||||
id: string,
|
||||
@@ -49,7 +52,6 @@ function runVirtualJS(code:string){
|
||||
return new Promise((resolve,reject)=>{
|
||||
const interval = setInterval(()=>{
|
||||
const result = results.find(r=>r.id === id)
|
||||
console.log(performance.now() - startTime )
|
||||
if(result){
|
||||
clearInterval(interval)
|
||||
resolve(result.result)
|
||||
@@ -61,30 +63,184 @@ function runVirtualJS(code:string){
|
||||
worker = new Worker(new URL('./worker.ts', import.meta.url), {type: 'module'})
|
||||
reject('timeout')
|
||||
}
|
||||
},100)
|
||||
},10)
|
||||
})
|
||||
}
|
||||
|
||||
addWorkerFunction('getCharacter', async () => {
|
||||
addWorkerFunction('getChat', async () => {
|
||||
const db = get(DataBase)
|
||||
const selectedChar = get(selectedCharID)
|
||||
return cloneDeep(db.characters[selectedChar])
|
||||
const char = db.characters[selectedChar]
|
||||
return cloneDeep(char.chats[char.chatPage].message)
|
||||
})
|
||||
|
||||
addWorkerFunction('setChat', async (data:Message[]) => {
|
||||
const db = get(DataBase)
|
||||
const selectedChar = get(selectedCharID)
|
||||
let newChat:Message[] = []
|
||||
for(const dat of data){
|
||||
if(dat.role !== 'char' && dat.role !== 'user'){
|
||||
return false
|
||||
}
|
||||
if(typeof dat.data !== 'string'){
|
||||
return false
|
||||
}
|
||||
if(typeof dat.saying !== 'string'){
|
||||
return false
|
||||
}
|
||||
if(typeof dat.time !== 'number'){
|
||||
return false
|
||||
}
|
||||
if(typeof dat.chatId !== 'string'){
|
||||
return false
|
||||
}
|
||||
newChat.push({
|
||||
role: dat.role,
|
||||
data: dat.data,
|
||||
saying: dat.saying,
|
||||
time: dat.time,
|
||||
chatId: dat.chatId
|
||||
})
|
||||
}
|
||||
db.characters[selectedChar].chats[db.characters[selectedChar].chatPage].message = newChat
|
||||
setDatabase(db)
|
||||
return true
|
||||
})
|
||||
|
||||
addWorkerFunction('getName', async () => {
|
||||
const db = get(DataBase)
|
||||
const selectedChar = get(selectedCharID)
|
||||
const char = db.characters[selectedChar]
|
||||
return char.name
|
||||
})
|
||||
|
||||
addWorkerFunction('setName', async (data:string) => {
|
||||
const db = get(DataBase)
|
||||
const selectedChar = get(selectedCharID)
|
||||
if(typeof data !== 'string'){
|
||||
return false
|
||||
}
|
||||
db.characters[selectedChar].name = data
|
||||
setDatabase(db)
|
||||
return true
|
||||
})
|
||||
|
||||
addWorkerFunction('getDescription', async () => {
|
||||
const db = get(DataBase)
|
||||
const selectedChar = get(selectedCharID)
|
||||
const char = db.characters[selectedChar]
|
||||
if(char.type === 'group'){
|
||||
return ''
|
||||
}
|
||||
return char.desc
|
||||
})
|
||||
|
||||
addWorkerFunction('setDescription', async (data:string) => {
|
||||
const db = get(DataBase)
|
||||
const selectedChar = get(selectedCharID)
|
||||
const char =db.characters[selectedChar]
|
||||
if(typeof data !== 'string'){
|
||||
return false
|
||||
}
|
||||
if(char.type === 'group'){
|
||||
return false
|
||||
}
|
||||
char.desc = data
|
||||
db.characters[selectedChar] = char
|
||||
setDatabase(db)
|
||||
return true
|
||||
})
|
||||
|
||||
addWorkerFunction('getCharacterFirstMessage', async () => {
|
||||
const db = get(DataBase)
|
||||
const selectedChar = get(selectedCharID)
|
||||
const char = db.characters[selectedChar]
|
||||
return char.firstMessage
|
||||
})
|
||||
|
||||
addWorkerFunction('setCharacterFirstMessage', async (data:string) => {
|
||||
const db = get(DataBase)
|
||||
const selectedChar = get(selectedCharID)
|
||||
const char = db.characters[selectedChar]
|
||||
if(typeof data !== 'string'){
|
||||
return false
|
||||
}
|
||||
char.firstMessage = data
|
||||
db.characters[selectedChar] = char
|
||||
setDatabase(db)
|
||||
return true
|
||||
})
|
||||
|
||||
addWorkerFunction('getState', async (statename) => {
|
||||
const db = get(DataBase)
|
||||
const selectedChar = get(selectedCharID)
|
||||
const char = db.characters[selectedChar]
|
||||
const chat = char.chats[char.chatPage]
|
||||
return (chat.scriptstate ?? {})[statename]
|
||||
})
|
||||
|
||||
addWorkerFunction('setState', async (statename, data) => {
|
||||
const db = get(DataBase)
|
||||
const selectedChar = get(selectedCharID)
|
||||
const char = db.characters[selectedChar]
|
||||
const chat = char.chats[char.chatPage]
|
||||
if(typeof statename !== 'string'){
|
||||
return false
|
||||
}
|
||||
if(typeof data !== 'string' && typeof data !== 'number' && typeof data !== 'boolean'){
|
||||
return false
|
||||
}
|
||||
if(!chat.scriptstate){
|
||||
chat.scriptstate = {}
|
||||
}
|
||||
chat.scriptstate[statename] = data
|
||||
char.chats[char.chatPage] = chat
|
||||
db.characters[selectedChar] = char
|
||||
setDatabase(db)
|
||||
return true
|
||||
})
|
||||
|
||||
|
||||
|
||||
let lastCode = ''
|
||||
let lastModeList:string[] = []
|
||||
|
||||
export async function runCharacterJS(arg:{
|
||||
code: string,
|
||||
mode: ScriptMode
|
||||
code: string|null,
|
||||
mode: ScriptMode|'onButtonClick'
|
||||
data: string
|
||||
}):Promise<string>{
|
||||
try {
|
||||
if(arg.code === null){
|
||||
const db = get(DataBase)
|
||||
const selectedChar = get(selectedCharID)
|
||||
arg.code = db.characters[selectedChar].virtualscript
|
||||
}
|
||||
const codes = {
|
||||
"editinput": 'editInput',
|
||||
"editoutput": 'editOutput',
|
||||
"editprocess": 'editProcess',
|
||||
"editdisplay": 'editDisplay',
|
||||
'onButtonClick': "onButtonClick"
|
||||
} as const
|
||||
|
||||
if(lastCode !== arg.code){
|
||||
lastModeList = []
|
||||
const codesplit = arg.code.split('\n')
|
||||
for(let i = 0; i < codesplit.length; i++){
|
||||
const line = codesplit[i]
|
||||
if(line.startsWith('//@use')){
|
||||
lastModeList.push(line.replace('//@use','').trim())
|
||||
}
|
||||
}
|
||||
lastCode = arg.code
|
||||
}
|
||||
|
||||
const runCode = codes[arg.mode]
|
||||
|
||||
if(!lastModeList.includes(runCode)){
|
||||
return arg.data
|
||||
}
|
||||
const result = await runVirtualJS(`${arg.code}\n${runCode}(${JSON.stringify(arg.data)})`)
|
||||
|
||||
if(!result){
|
||||
@@ -99,4 +255,23 @@ export async function runCharacterJS(arg:{
|
||||
return arg.data
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export async function watchParamButton() {
|
||||
while(true){
|
||||
const qs = document.querySelectorAll('*[risu-btn]:not([risu-btn-run="true"])')
|
||||
for(let i = 0; i < qs.length; i++){
|
||||
const q = qs[i]
|
||||
const code = q.getAttribute('risu-btn')
|
||||
q.setAttribute('risu-btn-run','true')
|
||||
q.addEventListener('click',async ()=>{
|
||||
await runCharacterJS({
|
||||
code: null,
|
||||
mode: 'onButtonClick',
|
||||
data: code
|
||||
})
|
||||
})
|
||||
}
|
||||
await sleep(100)
|
||||
}
|
||||
}
|
||||
@@ -71,20 +71,27 @@ const whitelist = [
|
||||
"Request",
|
||||
"Response",
|
||||
"Blob",
|
||||
"postMessage"
|
||||
"postMessage",
|
||||
"Node",
|
||||
"Element",
|
||||
"Text",
|
||||
"Comment",
|
||||
]
|
||||
|
||||
const evaluation = global.eval
|
||||
const evaluation = globaly.eval
|
||||
|
||||
Object.getOwnPropertyNames( global ).forEach( function( prop ) {
|
||||
if( !whitelist.includes(prop) ) {
|
||||
Object.defineProperty( global, prop, {
|
||||
get : function() {
|
||||
throw "Security Exception: cannot access "+prop;
|
||||
return 1;
|
||||
},
|
||||
configurable : false
|
||||
});
|
||||
Object.getOwnPropertyNames( globaly ).forEach( function( prop ) {
|
||||
if( (!whitelist.includes(prop)) && (!prop.startsWith('HTML')) && (!prop.startsWith('XML')) ) {
|
||||
try {
|
||||
Object.defineProperty( globaly, prop, {
|
||||
get : function() {
|
||||
throw "Security Exception: cannot access "+prop;
|
||||
return 1;
|
||||
},
|
||||
configurable : false
|
||||
});
|
||||
} catch (error) {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -93,6 +100,7 @@ let workerResults:{
|
||||
result: any
|
||||
}[] = []
|
||||
|
||||
|
||||
self.onmessage = async (event) => {
|
||||
const da = event.data
|
||||
if(da.type === 'result'){
|
||||
@@ -101,7 +109,7 @@ self.onmessage = async (event) => {
|
||||
}
|
||||
if(da.type === 'api'){
|
||||
//add api
|
||||
Object.defineProperty( global, da.name, {
|
||||
Object.defineProperty( globaly, da.name, {
|
||||
get : function() {
|
||||
return function (...args:any[]) {
|
||||
return new Promise((resolve)=>{
|
||||
@@ -118,7 +126,7 @@ self.onmessage = async (event) => {
|
||||
clearInterval(interval)
|
||||
resolve(result.result)
|
||||
}
|
||||
},100)
|
||||
},10)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -578,6 +578,7 @@ export interface character{
|
||||
additionalText:string
|
||||
oaiVoice?:string
|
||||
virtualscript?:string
|
||||
scriptstate?:{[key:string]:string|number|boolean}
|
||||
}
|
||||
|
||||
|
||||
@@ -699,6 +700,7 @@ export interface Chat{
|
||||
lastMemory?:string
|
||||
suggestMessages?:string[]
|
||||
isStreaming?:boolean
|
||||
scriptstate?:{[key:string]:string|number|boolean}
|
||||
}
|
||||
|
||||
export interface Message{
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
* of JS in `.svelte` files.
|
||||
*/
|
||||
"allowJs": true,
|
||||
"checkJs": true,
|
||||
"checkJs": false,
|
||||
"isolatedModules": true
|
||||
},
|
||||
"include": ["src/**/*.d.ts", "src/**/*.ts", "src/**/*.js", "src/**/*.svelte", "public/sw.js"],
|
||||
|
||||
Reference in New Issue
Block a user