checkpoint

This commit is contained in:
Rizky 2024-05-08 21:24:05 +07:00
parent fbc3c864eb
commit acc85512c5
16 changed files with 137 additions and 246 deletions

File diff suppressed because one or more lines are too long

View File

@ -119,8 +119,6 @@ export const SyncActions = {
| { type: "startup-check" }
| { type: "startup-run" }
| { type: "startup-stop" }
// | { type: "push-typings"; body: Uint8Array; hash: number }
| { type: "check-typings"; hash: number }
))
| { type: "flush-page-cache"; page_id: string }
) =>
@ -137,10 +135,6 @@ export const SyncActions = {
| {
type: "startup-stop";
status: "running" | "stopped";
}
| {
type: "check-typings";
hash: boolean;
},
},
};

View File

@ -1,14 +1,10 @@
import { Subprocess, spawn } from "bun";
import { waitUntil } from "web-utils";
import { SAction } from "../actions";
import { code } from "../code/code";
import { docs } from "../entity/docs";
import { snapshot } from "../entity/snapshot";
import { SyncConnection } from "../type";
import { dirAsync } from "fs-jetpack";
import path from "path";
import { gunzipAsync } from "../entity/zlib";
import { prismaExtendType } from "../../../../web/src/utils/script/prisma-extend";
import { code } from "../code/code";
const decoder = new TextDecoder();
const code_startup = {
@ -73,53 +69,5 @@ export const code_action: SAction["code"]["action"] = async function (
delete docs.page[page_id];
break;
}
case "check-typings": {
const dir = code.path(arg.site_id, "site", "src", "typings");
try {
if (
(await Bun.file(path.join(dir, "hash")).text()) ===
arg.hash.toString()
) {
return { type: "check-typings", hash: true };
}
} catch (e) {}
return { type: "check-typings", hash: false };
}
// case "push-typings": {
// const dir = code.path(arg.site_id, "site", "src", "typings");
// await dirAsync(dir);
// await dirAsync(path.join(dir, "runtime"));
// Bun.write(Bun.file(path.join(dir, "hash")), arg.hash.toString());
// const res = JSON.parse(decoder.decode(await gunzipAsync(arg.body)));
// await Bun.write(Bun.file(path.join(dir, "api.d.ts")), res.api);
// await Bun.write(
// Bun.file(path.join(dir, "prisma.d.ts")),
// res.prisma["prisma.d.ts"]
// );
// await Bun.write(
// Bun.file(path.join(dir, "runtime/index.d.ts")),
// res.prisma["runtime/index.d.ts"]
// );
// await Bun.write(
// Bun.file(path.join(dir, "runtime/library.d.ts")),
// res.prisma["runtime/library.d.ts"]
// );
// await Bun.write(
// Bun.file(path.join(dir, "global.d.ts")),
// codeGlobalTypings.replace(
// `declare global {`,
// `declare global {
// const db: prisma.PrismaClient & ${prismaExtendType};
// `
// )
// );
// Bun.spawn({
// cmd: ["chmod", "-R", "777", "."],
// cwd: code.path(arg.site_id, "site", "src"),
// });
// break;
// }
}
};

View File

@ -2,6 +2,7 @@
import type * as SRVAPI from "gen/srv/api/srv";
import { Server, WebSocketHandler } from "bun";
import prisma from "./prisma";
import { PrismaExtend } from "./prisma.ext";
declare global {
type Api = typeof SRVAPI;
@ -9,48 +10,7 @@ declare global {
const api: { [k in ApiName]: Awaited<Api[k]["handler"]>["_"]["api"] } & {
_raw: any;
};
const db: prisma.PrismaClient & {
_batch: {
update: (
batch: {
table: string;
data: any;
where: any;
}[]
) => Promise<void>;
};
_schema: {
tables: () => Promise<string[]>;
columns: (table: string) => Promise<
Record<
string,
{
is_pk: boolean;
type: string;
optional: boolean;
db_type: string;
default?: any;
}
>
>;
rels: (table: string) => Promise<
Record<
string,
{
type: "has-many" | "has-one";
to: {
table: string;
fields: string[];
};
from: {
table: string;
fields: string[];
};
}
>
>;
};
};
const db: prisma.PrismaClient & PrismaExtend;
type PrasiServer = {
ws?: WebSocketHandler<{ url: string }>;

View File

@ -0,0 +1,61 @@
import { Prisma, PrismaClient } from "./prisma";
export type PrismaExtend = {
_batch: {
update: <T extends Prisma.ModelName>(
batch: {
table: T;
data: Exclude<
Parameters<PrismaClient["location"]["update"]>[0],
undefined
>["data"];
where: Exclude<
Parameters<PrismaClient["location"]["findMany"]>[0],
undefined
>["where"];
}[]
) => Promise<void>;
upsert: <T extends Prisma.ModelName>(arg: {
table: T;
where: Exclude<
Parameters<PrismaClient["location"]["findMany"]>[0],
undefined
>["where"];
data: Exclude<
Parameters<PrismaClient["location"]["create"]>[0],
undefined
>["data"][];
}) => Promise<void>;
};
_schema: {
tables: () => Promise<Prisma.ModelName[]>;
columns: (table: Prisma.ModelName) => Promise<
Record<
string,
{
is_pk: boolean;
type: string;
optional: boolean;
db_type: string;
default?: any;
}
>
>;
rels: (table: Prisma.ModelName) => Promise<
Record<
string,
{
type: "has-many" | "has-one";
to: {
table: Prisma.ModelName;
fields: string[];
};
from: {
table: Prisma.ModelName;
fields: string[];
};
}
>
>;
};
};

View File

@ -1,6 +1,8 @@
import { $ } from "bun";
import { dir } from "dir";
import { exists, dirAsync } from "fs-jetpack";
import { removeAsync } from "fs-jetpack";
import { g } from "utils/global";
export const ensureLib = async (src_dir: string, id_site: string) => {
if (!exists(dir.data(src_dir))) {
@ -8,8 +10,38 @@ export const ensureLib = async (src_dir: string, id_site: string) => {
}
if (!exists(dir.data(`${src_dir}/lib`))) {
console.log(`${src_dir}/lib not found.`);
const _ = $.cwd(dir.data(src_dir));
await _`git clone https://github.com/avolut/prasi-lib lib`;
}
if (true || !exists(dir.data(`${src_dir}/typings`))) {
try {
const site = await _db.site.findFirst({
where: { id: id_site },
select: {
config: true,
},
});
if (site) {
const config = site.config as any;
if (config.api_url) {
new URL(config.api_url);
const url = `${config.api_url}/_prasi/load.js?dev=1`;
const res = await fetch(url);
const apires = await res.text();
const fn = new Function("window", "location", apires);
const w = {} as any;
fn(w, { href: "http://127.0.0.1" });
const { prismaTypes } = w.prasiApi["http://127.0.0.1/"];
for (const [k, v] of Object.entries(prismaTypes)) {
await Bun.write(dir.data(`${src_dir}/typings/${k}`), v as any);
}
}
}
} catch (e) {
console.error(e);
}
}
};

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -144,6 +144,11 @@ declare global {
where: any
}[]
) => Promise<void>;
upsert: (arg: {
table: string;
where: any;
data: any[];
}) => Promise<void>;
};
_schema: {
tables: () => Promise<string[]>;
@ -318,4 +323,4 @@ ${e}`,c.pop(),`[${t}]`}let I=Object.keys(s),h=I.length;if(0===h)return"{}";if(g<
${d}`,p="",f="",u=Math.min(h,l);a(s)&&(p+=B(s,E,l),I=I.slice(s.length),u-=s.length,f=E),r&&(I=n(I)),c.push(s);for(let e=0;e<u;e++){let t=I[e],i=A(t,s[t],c,C,d);void 0!==i&&(p+=`${f}${o(t)}: ${i}`,f=E)}return h>l&&(p+=`${f}"...": "${Q(h-l)} not stringified"`,f=E),""!==f&&(p=`
${d}${p}
${e}`),c.pop(),`{${p}}`}case"number":return isFinite(s)?String(s):e?e(s):"null";case"boolean":return!0===s?"true":"false";case"undefined":return;case"bigint":if(I)return String(s);default:return e?e(s):void 0}}("",A,[],c,"")}return function A(i,s,c){switch(typeof s){case"string":return o(s);case"object":{if(null===s)return"null";if("function"==typeof s.toJSON){if("object"!=typeof(s=s.toJSON(i)))return A(i,s,c);if(null===s)return"null"}if(-1!==c.indexOf(s))return t;let e="";if(Array.isArray(s)){if(0===s.length)return"[]";if(g<c.length+1)return'"[Array]"';c.push(s);let t=Math.min(s.length,l),i=0;for(;i<t-1;i++){let t=A(String(i),s[i],c);e+=(void 0!==t?t:"null")+","}let I=A(String(i),s[i],c);if(e+=void 0!==I?I:"null",s.length-1>l){let A=s.length-l-1;e+=`,"... ${Q(A)} not stringified"`}return c.pop(),`[${e}]`}let I=Object.keys(s),C=I.length;if(0===C)return"{}";if(g<c.length+1)return'"[Object]"';let d="",h=Math.min(C,l);a(s)&&(e+=B(s,",",l),I=I.slice(s.length),h-=s.length,d=","),r&&(I=n(I)),c.push(s);for(let t=0;t<h;t++){let i=I[t],r=A(i,s[i],c);void 0!==r&&(e+=`${d}${o(i)}:${r}`,d=",")}return C>l&&(e+=`${d}"...":"${Q(C-l)} not stringified"`),c.pop(),`{${e}}`}case"number":return isFinite(s)?String(s):e?e(s):"null";case"boolean":return!0===s?"true":"false";case"undefined":return;case"bigint":if(I)return String(s);default:return e?e(s):void 0}}("",A,[])}}},{}],"6Bu6A":[function(A,e,t){var i=A("@parcel/transformer-js/src/esmodule-helpers.js");i.defineInteropFlag(t),i.export(t,"SyncActionDefinition",()=>I),i.export(t,"SyncActionPaths",()=>r);let I={site:{list:"0",group:"1",load:"2",update:"3"},comp:{new:"4",list:"5",group:"6",load:"7"},page:{list:"8",load:"9",cache:"10"},yjs:{um:"11",sv_local:"12",diff_local:"13",sv_remote:"14"},client:{info:"15"},code:{load:"16",edit:"17",action:"18"}},r={0:"site.list",1:"site.group",2:"site.load",3:"site.update",4:"comp.new",5:"comp.list",6:"comp.group",7:"comp.load",8:"page.list",9:"page.load",10:"page.cache",11:"yjs.um",12:"yjs.sv_local",13:"yjs.diff_local",14:"yjs.sv_remote",15:"client.info",16:"code.load",17:"code.edit",18:"code.action"}},{"@parcel/transformer-js/src/esmodule-helpers.js":"4uUBn"}],eZNf9:[function(A,e,t){var i,I,r=A("@parcel/transformer-js/src/esmodule-helpers.js");r.defineInteropFlag(t),r.export(t,"SyncType",()=>I),(i=I||(I={}))[i.ClientID=0]="ClientID",i[i.UserID=1]="UserID",i[i.Event=2]="Event",i[i.Action=3]="Action",i[i.ActionResult=4]="ActionResult"},{"@parcel/transformer-js/src/esmodule-helpers.js":"4uUBn"}],bZFhN:[function(A,e,t){var i=A("@parcel/transformer-js/src/esmodule-helpers.js");i.defineInteropFlag(t),i.export(t,"initIDB",()=>r);var I=A("idb-keyval");let r=A=>(0,I.createStore)(`prasi-user-${A}`,"default")},{"idb-keyval":"8Atof","@parcel/transformer-js/src/esmodule-helpers.js":"4uUBn"}]},[],0,"parcelRequire2d1f");
//# sourceMappingURL=ed.55787c67.js.map
//# sourceMappingURL=ed.22759bde.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,119 +0,0 @@
import hash_sum from "hash-sum";
import { fetchViaProxy } from "../proxy";
import pako from "pako";
export const dbClient = (name: string, dburl: string) => {
return new Proxy(
{},
{
get(_, table: string) {
if (table === "_tables") {
return () => {
return fetchSendDb(
name,
{
name,
action: "definition",
table: "*",
},
dburl
);
};
}
if (table === "_definition") {
return (table: string) => {
return fetchSendDb(
name,
{
name,
action: "definition",
table,
},
dburl
);
};
}
if (table.startsWith("$")) {
return (...params: any[]) => {
const bytes = pako.gzip(JSON.stringify(params));
return fetchSendDb(
name,
{
name,
action: "query",
table,
params: btoa(
bytes.reduce(
(acc, current) => acc + String.fromCharCode(current),
""
)
),
},
dburl
);
};
}
return new Proxy(
{},
{
get(_, action: string) {
return (...params: any[]) => {
if (table === "query") {
table = action;
action = "query";
}
return fetchSendDb(
name,
{
name,
action,
table,
params,
},
dburl
);
};
},
}
);
},
}
);
};
const cachedQueryResult: Record<
string,
{ timestamp: number; result: any; promise: Promise<any> }
> = {};
export const fetchSendDb = async (name: string, params: any, dburl: string) => {
const base = new URL(dburl);
base.pathname = `/_dbs/${name}`;
if (params.table) {
base.pathname += `/${params.table}`;
}
const url = base.toString();
const hsum = hash_sum(params);
const cached = cachedQueryResult[hsum];
if (!cached || (cached && Date.now() - cached.timestamp > 1000)) {
cachedQueryResult[hsum] = {
timestamp: Date.now(),
promise: fetchViaProxy(url, params, {
"content-type": "application/json",
}),
result: null,
};
const result = await cachedQueryResult[hsum].promise;
cachedQueryResult[hsum].result = result;
return result;
}
return await cached.promise;
};

View File

@ -1,6 +1,6 @@
import hash_sum from "hash-sum";
import { fetchViaProxy } from "../proxy";
import pako from "pako";
import { fetchViaProxy } from "../proxy";
export const dbProxy = (dburl: string) => {
const name = "";
@ -10,7 +10,6 @@ export const dbProxy = (dburl: string) => {
get(_, table: string) {
if (table === "_batch") {
return {
// pancingan ini table batch
update: async (batch: any) => {
return fetchSendDb(
{
@ -22,6 +21,17 @@ export const dbProxy = (dburl: string) => {
dburl
);
},
upsert: async (arg: any) => {
return fetchSendDb(
{
name,
action: "batch_upsert",
table: "",
params: { arg },
},
dburl
);
},
};
}
if (table === "_schema") {

View File

@ -8,6 +8,11 @@ export const prismaExtendType = `\
where: any
}[]
) => Promise<void>;
upsert: (arg: {
table: string;
where: any;
data: any[];
}) => Promise<void>;
};
_schema: {
tables: () => Promise<string[]>;
@ -36,8 +41,3 @@ export const prismaExtendType = `\
}>>;
}
}`;
const rel_types = `\
{
}`;