@supalive/core 1.1.0 → 1.2.1
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/README.md +28 -0
- package/dist/db-ClCicssQ.js +28 -0
- package/dist/db-ClCicssQ.js.map +1 -0
- package/dist/{index-DouKwYL6.d.ts → index-DJYvJYR4.d.ts} +214 -9
- package/dist/index-DJYvJYR4.d.ts.map +1 -0
- package/dist/{mysql-Bxurg_PH.d.ts → mysql-53W9lRh9.d.ts} +8 -3
- package/dist/mysql-53W9lRh9.d.ts.map +1 -0
- package/dist/{mysql-bvnjYWvZ.js → mysql-C0mysDQ_.js} +57 -25
- package/dist/mysql-C0mysDQ_.js.map +1 -0
- package/dist/{overlap-checker-Ct_HP_iB.js → overlap-checker-ClJC0nxW.js} +52 -4
- package/dist/overlap-checker-ClJC0nxW.js.map +1 -0
- package/dist/{postgres-Ck-xt72U.d.ts → postgres-7d6R9P7w.d.ts} +8 -3
- package/dist/postgres-7d6R9P7w.d.ts.map +1 -0
- package/dist/{postgres-B8u1YN8X.js → postgres-SvdXfb0w.js} +55 -22
- package/dist/postgres-SvdXfb0w.js.map +1 -0
- package/dist/{procedure-DX87tyef.js → procedure-Ze1GE-N9.js} +33 -2
- package/dist/procedure-Ze1GE-N9.js.map +1 -0
- package/dist/{query-Bh0RNxDz.js → query-CrbJ_W0W.js} +21 -1
- package/dist/query-CrbJ_W0W.js.map +1 -0
- package/dist/{realtime_db-DOCgqbwi.js → realtime_db-BtwBABDY.js} +76 -51
- package/dist/realtime_db-BtwBABDY.js.map +1 -0
- package/dist/{router-DlTYWpop.js → router-CiWYeWUR.js} +8 -2
- package/dist/router-CiWYeWUR.js.map +1 -0
- package/dist/src/client/index.d.ts +1 -1
- package/dist/src/client/index.js +44 -5
- package/dist/src/client/index.js.map +1 -1
- package/dist/src/exports/mysql.d.ts +1 -1
- package/dist/src/exports/mysql.js +1 -1
- package/dist/src/exports/postgres.d.ts +1 -1
- package/dist/src/exports/postgres.js +1 -1
- package/dist/src/exports/procedure.d.ts +2 -2
- package/dist/src/exports/procedure.js +4 -4
- package/dist/src/exports/schema-sql.d.ts +36 -2
- package/dist/src/exports/schema-sql.d.ts.map +1 -1
- package/dist/src/exports/schema-sql.js +74 -19
- package/dist/src/exports/schema-sql.js.map +1 -1
- package/dist/src/exports/server.d.ts +65 -17
- package/dist/src/exports/server.d.ts.map +1 -1
- package/dist/src/exports/server.js +724 -63
- package/dist/src/exports/server.js.map +1 -1
- package/dist/src/exports/subscription-manager-worker-entry.js +8 -5
- package/dist/src/exports/subscription-manager-worker-entry.js.map +1 -1
- package/dist/src/exports/types.d.ts +3 -3
- package/dist/src/exports/types.js +1 -1
- package/dist/{subscription-worker-CqoWp6zB.js → subscription-worker-B2XtjFWY.js} +307 -69
- package/dist/subscription-worker-B2XtjFWY.js.map +1 -0
- package/dist/{types_db-DXj_l9n-.js → types_db-CTRm_awX.js} +7 -2
- package/dist/types_db-CTRm_awX.js.map +1 -0
- package/dist/types_server-wW3ZgE7l.d.ts +420 -0
- package/dist/types_server-wW3ZgE7l.d.ts.map +1 -0
- package/package.json +5 -4
- package/dist/index-CaWMDqq0.d.ts +0 -1754
- package/dist/index-CaWMDqq0.d.ts.map +0 -1
- package/dist/index-DouKwYL6.d.ts.map +0 -1
- package/dist/mysql-Bxurg_PH.d.ts.map +0 -1
- package/dist/mysql-Cxd4Uq5p.d.ts +0 -104
- package/dist/mysql-Cxd4Uq5p.d.ts.map +0 -1
- package/dist/mysql-bvnjYWvZ.js.map +0 -1
- package/dist/overlap-checker-Ct_HP_iB.js.map +0 -1
- package/dist/postgres-B8u1YN8X.js.map +0 -1
- package/dist/postgres-CfT_aDx3.d.ts +0 -108
- package/dist/postgres-CfT_aDx3.d.ts.map +0 -1
- package/dist/postgres-Ck-xt72U.d.ts.map +0 -1
- package/dist/procedure-DX87tyef.js.map +0 -1
- package/dist/query-Bh0RNxDz.js.map +0 -1
- package/dist/realtime_db-DOCgqbwi.js.map +0 -1
- package/dist/router-DlTYWpop.js.map +0 -1
- package/dist/src/exports/codegen.d.ts +0 -38
- package/dist/src/exports/codegen.d.ts.map +0 -1
- package/dist/src/exports/codegen.js +0 -134
- package/dist/src/exports/codegen.js.map +0 -1
- package/dist/subscription-worker-CqoWp6zB.js.map +0 -1
- package/dist/subscription-worker-PtmJWEj1.js +0 -511
- package/dist/subscription-worker-PtmJWEj1.js.map +0 -1
- package/dist/subscription-worker-pahX0zxg.js +0 -511
- package/dist/subscription-worker-pahX0zxg.js.map +0 -1
- package/dist/types_db-DXj_l9n-.js.map +0 -1
- package/dist/types_server-BW1ys_SK.d.ts +0 -216
- package/dist/types_server-BW1ys_SK.d.ts.map +0 -1
- package/dist/types_server-Dpsi0wpG.d.ts +0 -216
- package/dist/types_server-Dpsi0wpG.d.ts.map +0 -1
- package/dist/types_server-DzrIccyO.d.ts +0 -216
- package/dist/types_server-DzrIccyO.d.ts.map +0 -1
- package/dist/types_server-TFo6SWDH.d.ts +0 -216
- package/dist/types_server-TFo6SWDH.d.ts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"realtime_db-BtwBABDY.js","names":["z"],"sources":["../src/db/context.ts","../src/db/realtime_db.ts"],"sourcesContent":["import { z, ZodRawShape } from \"zod\";\nimport { Database } from \"./db\";\nimport { ReadEntry, WriteEntry, } from \"./types_db\";\n\nimport { ColumnCodec, InferSchema, InsertData, Model, SchemaDefinition } from \"./schema\";\nimport { normalizeCodec, unwrapZodType } from \"./codec\";\nimport { QueryBuilder } from \"./query\";\n\n/**\n * Materialize a schema's runtime {@link Model}: column-name mapping, per-column\n * coarse type tags, and the codec used to (de)serialize each column.\n *\n * Codecs are resolved via {@link normalizeCodec}, which supplies a sensible\n * default per Zod type (e.g. a {@link dateCodec} for `z.date()`, so `Date`\n * columns round-trip automatically) while letting a user-supplied codec in\n * `schema.columnsOptions.codecs` override it — partially or fully.\n */\nexport function buildModel(schema: SchemaDefinition<string, ZodRawShape>): Model {\n const shape = schema.schema.shape;\n const customColumns = (schema as any).columns;\n const columns: Record<string, string> = {};\n const types: Record<string, string> = {};\n const codecs: Record<string, ColumnCodec<any, any>> = {};\n const schemaCodecs = schema.columnsOptions.codecs ?? {};\n\n for (const key of Object.keys(shape)) {\n columns[key] = customColumns?.[key] ?? key;\n const field = shape[key];\n const baseField = unwrapZodType(field);\n if (baseField instanceof z.ZodNumber) {\n types[key] = \"integer\";\n } else if (baseField instanceof z.ZodString) {\n types[key] = \"string\";\n } else if (baseField instanceof z.ZodBoolean) {\n types[key] = \"boolean\";\n } else if (baseField instanceof z.ZodDate) {\n types[key] = \"date\";\n } else if (baseField instanceof z.ZodArray) {\n types[key] = \"array\";\n } else {\n types[key] = \"json\";\n }\n codecs[key] = normalizeCodec(schemaCodecs[key], baseField);\n }\n\n return {\n table: schema.table,\n tableId: schema.tableId,\n columns,\n reverseColumns: Object.fromEntries(Object.entries(columns).map(([k, v]) => [v, k])),\n types,\n codecs,\n };\n}\n\nexport class TxContext {\n readonly beginTs: bigint;\n readonly db: Database;\n protected readSet: ReadEntry[] = [];\n protected writeSet: WriteEntry[] = [];\n private models: Map<string, Model> = new Map();\n\n protected getOrCreateModel(schema: SchemaDefinition<string, ZodRawShape>): Model {\n const existing = this.models.get(schema.table);\n if (existing) return existing;\n\n const model = buildModel(schema);\n this.models.set(schema.table, model);\n return model;\n }\n\n constructor(db: Database, beginTs: bigint) {\n this.db = db;\n this.beginTs = beginTs;\n }\n\n internalGetReadSet(): ReadEntry[] { return this.readSet; }\n internalGetWriteSet(): WriteEntry[] { return this.writeSet; }\n\n /**\n * Merge a parent procedure's reads into this context's readSet. Used when a\n * `runMutation` sub-transaction inherits the reads of the procedure that\n * invoked it, so the sub-tx's OCC validation also fences on those rows.\n * Entries are shallow-cloned so the two readSets don't alias.\n */\n appendInternalReadSet(parentEntries: ReadEntry[]) {\n this.readSet.push(...parentEntries.map((e) => ({...e})));\n }\n\n protected findPendingWrite(table: string, id: string): WriteEntry | undefined {\n return this.writeSet.find(w => w.table === table && w.id === id);\n }\n\n protected findPendingInsert(table: string, id: string): WriteEntry | undefined {\n return this.writeSet.find(w => w.table === table && w.id === id && w.op === \"insert\");\n }\n\n protected encodeWithCodec(model: Model, property: string, value: unknown): unknown {\n const codec = model.codecs[property];\n if (!codec?.encode || value === undefined || value === null) return value;\n return codec.encode(value);\n }\n}\n\nexport class DbReader extends TxContext {\n query<S extends SchemaDefinition<string, ZodRawShape>>(schema: S): QueryBuilder<S> {\n const model = this.getOrCreateModel(schema);\n return new QueryBuilder<S>(this, model);\n }\n}\n\nexport class DbWriter extends DbReader {\n async insert<S extends SchemaDefinition<string, ZodRawShape>, ID extends string>(\n schema: S,\n id: ID,\n data: InsertData<S>\n ): Promise<void> {\n const model = this.getOrCreateModel(schema);\n const mappedData: Record<string, unknown> = { id };\n const shape = schema.schema.shape;\n\n for (const key of Object.keys(shape)) {\n let value = data[key];\n\n if (value === undefined) {\n const field = shape[key];\n if (field instanceof z.ZodDefault) {\n const defaultVal = field.def.defaultValue;\n value = (typeof defaultVal === \"function\" ? defaultVal() : defaultVal)\n\n if (value !== undefined) {\n const columnName = model.columns[key] ?? key;\n mappedData[columnName] = this.encodeWithCodec(model, key, value);\n }\n }\n } else {\n const columnName = model.columns[key] ?? key;\n mappedData[columnName] = this.encodeWithCodec(model, key, value);\n }\n }\n // ensure id same\n mappedData[\"id\"] = id;\n\n // Check for existing pending write for the same ID\n const existing = this.findPendingWrite(schema.table, id);\n if (existing) {\n if (existing.op === \"delete\") {\n // If there's a pending delete, change it to an update with the new data\n existing.op = \"update\";\n existing.data = mappedData;\n } else {\n // If there's a pending update or same insert with the same ID , merge the new data\n existing.data = { ...existing.data, ...mappedData };\n }\n } else {\n this.writeSet.push({ table: schema.table, tableId: schema.tableId, id: id, op: \"insert\", data: mappedData });\n }\n }\n\n async update<S extends SchemaDefinition<string, ZodRawShape>, ID extends string>(\n schema: S,\n id: ID,\n data: Partial<Omit<InferSchema<S>, \"id\" | \"commitTs\">>,\n ): Promise<void> {\n const model = this.getOrCreateModel(schema);\n const mappedData: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(data)) {\n const columnName = model.columns[key] ?? key;\n mappedData[columnName] = this.encodeWithCodec(model, key, value);\n }\n\n const existing = this.findPendingWrite(schema.table, id);\n if (existing) {\n existing.op = existing.op === \"insert\" ? \"insert\" : \"update\";\n existing.data = { ...existing.data, ...mappedData };\n } else {\n // expectedTs will be filled by the committer via batch fetch if not known yet\n this.writeSet.push({ table: schema.table, tableId: schema.tableId, id, op: \"update\", data: mappedData });\n }\n }\n\n async delete<S extends SchemaDefinition<string, ZodRawShape>, ID extends string>(\n schema: S,\n id: ID,\n ): Promise<void> {\n // If there's a pending insert for the same ID, remove it instead of adding a delete\n const existingInsert = this.findPendingInsert(schema.table, id);\n if (existingInsert) {\n this.writeSet = this.writeSet.filter(w => w !== existingInsert);\n return;\n }\n\n // expectedTs will be filled by the committer via batch fetch if not known yet\n this.writeSet.push({ table: schema.table, tableId: schema.tableId, id, op: \"delete\" });\n }\n}\n","import { Database, LazyCommitTsParam, TxDatabase } from \"./db\";\nimport {\n OccConflictError, WriteEntry, CommitTs, LiveResult, MutationResult\n} from \"./types_db\";\nimport { DbReader, DbWriter } from \"./context\";\nimport { ExponentialBackoff, handleWhen, retry, RetryPolicy } from \"cockatiel\";\n\nexport const occRetryPolicy = retry(\n handleWhen((err) => OccConflictError.isOccConflictError(err)),\n {\n maxAttempts: 15,\n backoff: new ExponentialBackoff({\n initialDelay: 10,\n maxDelay: 7000,\n exponent: 2,\n }),\n },\n);\n\nexport const getDbclientRetryPolicy = retry(\n handleWhen((err) => err.message.includes('timeout exceeded')),\n {\n maxAttempts: 3,\n backoff: new ExponentialBackoff({\n initialDelay: 500,\n maxDelay: 2000,\n exponent: 2,\n }),\n },\n);\n\nexport class SupaliveDb {\n constructor(readonly impl: Database) { }\n\n static create(config: { db: Database }): SupaliveDb {\n return new SupaliveDb(config.db);\n }\n\n protected onAfterCommit?: (writeSet: WriteEntry[], commitTs: CommitTs) => void;\n\n /**\n * Register a hook fired once after every successful `mutation()` commit\n * (never on an OCC conflict/rollback), with the committed writeSet and its\n * commitTs. The server uses this to drive subscription invalidation for ALL\n * mutation sources — client WS calls, actions, jobs, and the internal caller —\n * so a server-side write pushes live updates just like a client write does.\n * Non-server consumers (migration tooling, tests) leave it unset (no-op).\n */\n setOnAfterCommit(cb: (writeSet: WriteEntry[], commitTs: CommitTs) => void): void {\n this.onAfterCommit = cb;\n }\n\n // ── Read-only query ──────────────────────────────────────────────\n\n async query<T>(fn: (ctx: DbReader) => Promise<T>): Promise<T> {\n const beginTs = await this.impl.getLatestSnapshotTimestamp();\n const ctx = new DbReader(this.impl, beginTs);\n return await fn(ctx);\n }\n\n /**\n * Compute a query once at the latest snapshot, returning the result together\n * with the snapshot `ts` and the tracked `readSet`. This is a plain one-shot\n * evaluation — it registers NO live subscription; the `readSet`/`ts` are\n * returned purely so the caller (e.g. the one-shot query cache) can store\n * freshness metadata. Use this for cached one-shot query calls (WS `call`,\n * HTTP RPC). `liveQuery` is the same computation under the subscription path's\n * name and simply delegates here.\n */\n async queryInternal<T>(fn: (ctx: DbReader) => Promise<T>): Promise<LiveResult<T>> {\n const beginTs = await this.impl.getLatestSnapshotTimestamp();\n const ctx = new DbReader(this.impl, beginTs);\n const data = await fn(ctx);\n\n return {\n ts: beginTs,\n data,\n readSet: ctx.internalGetReadSet(),\n };\n }\n\n async liveQuery<T>(fn: (ctx: DbReader) => Promise<T>): Promise<LiveResult<T>> {\n return this.queryInternal(fn);\n }\n\n // ── Mutation ───────────────────────────────────────────────────────\n\n async mutation<T>(\n fn: (ctx: DbWriter) => Promise<T>,\n retryPolicy: RetryPolicy = occRetryPolicy,\n ): Promise<MutationResult<T>> {\n return await retryPolicy.execute(async (p) => {\n let db: TxDatabase | undefined;\n try {\n // Step1: Get latest snapshot timestamp as beginTs\n const beginTs = await this.impl.getLatestSnapshotTimestamp() + 1n;\n\n const ctx = new DbWriter(this.impl, beginTs);\n const result = await fn(ctx);\n\n const readSet = ctx.internalGetReadSet();\n const writeSet = ctx.internalGetWriteSet();\n const commitTsLazy = new LazyCommitTsParam(undefined);\n\n // Step2: Capture prevData + expectedCommitTs per write. prevData\n // is consumed by the invalidator (range subs need it to detect\n // result-set transitions). expectedCommitTs becomes the CAS fence\n // for the apply step — preferring prior find()-captured ts so\n // read-then-update patterns get beginTs-level isolation.\n await this.impl.attachPrevDataToWriteSet(writeSet, readSet);\n\n // Step3: Prepare quieries before transaction\n const queries = await this.impl.prepareCommitWrites(\n readSet,\n writeSet,\n commitTsLazy,\n );\n\n // Step4: Starts new transaction\n db = await getDbclientRetryPolicy.execute(() => this.impl.getTransactionClient());\n await db.begin();\n\n // Step5: Get commitTs from DB sequence (bigger than all previous)\n const commitTs = await db.getNextTimestamp();\n commitTsLazy.value = commitTs;\n\n // Step6: Apply + validate. CAS UPDATE/DELETE catches concurrent\n // peer touches on the write set; the readSet is validated either\n // per-row (fast path, no range reads) or via commit-log scan\n // (slow path, when range reads are present so phantoms still\n // need detection).\n const commitResult = await db.commitWrites(\n beginTs,\n queries,\n commitTs,\n );\n\n if (!commitResult.success) {\n throw new OccConflictError(\"Commit failed\", { commitResult });\n }\n\n await db.updateLatestSnapshotTimestamp(commitTs);\n await db.commit();\n\n // Notify after successful commit\n this.onAfterCommit?.(writeSet, commitTs);\n\n return { result, writeSet, commitTs };\n } catch (err) {\n await db?.rollback();\n throw err;\n } finally {\n db?.release();\n }\n });\n }\n}\n\nexport const sleep = (ms: number) => new Promise<void>((res) => setTimeout(res, ms));\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,SAAgB,WAAW,QAAsD;CAC/E,MAAM,QAAQ,OAAO,OAAO;CAC5B,MAAM,gBAAiB,OAAe;CACtC,MAAM,UAAkC,CAAC;CACzC,MAAM,QAAgC,CAAC;CACvC,MAAM,SAAgD,CAAC;CACvD,MAAM,eAAe,OAAO,eAAe,UAAU,CAAC;CA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GA,KAAK,MAAM,uBAAuB,cAAc,KAAK,KAAK,qBAAqB,CAAC;IAChF,MAAM,GAAG,MAAM;IAGf,MAAM,WAAW,MAAM,GAAG,iBAAiB;IAC3C,aAAa,QAAQ;IAOrB,MAAM,eAAe,MAAM,GAAG,aAC5B,SACA,SACA,QACF;IAEA,IAAI,CAAC,aAAa,SAChB,MAAM,IAAI,iBAAiB,iBAAiB,EAAE,aAAa,CAAC;IAG9D,MAAM,GAAG,8BAA8B,QAAQ;IAC/C,MAAM,GAAG,OAAO;IAGhB,KAAK,gBAAgB,UAAU,QAAQ;IAEvC,OAAO;KAAE;KAAQ;KAAU;IAAS;GACtC,SAAS,KAAK;IACZ,MAAM,IAAI,SAAS;IACnB,MAAM;GACR,UAAU;IACR,IAAI,QAAQ;GACd;EACF,CAAC;CACH;AACF;AAEA,MAAa,SAAS,OAAe,IAAI,SAAe,QAAQ,WAAW,KAAK,EAAE,CAAC"}
|
|
@@ -39,13 +39,15 @@ var ContextRegistry = class {
|
|
|
39
39
|
if (this.procedureRegistry.has(name)) throw new Error(`[router] Procedure "${name}" is already registered. Each procedure name must be unique across the application.`);
|
|
40
40
|
if (proc.internal) this.markInternalProcedure(name);
|
|
41
41
|
const queryIdentity = proc.procedureType === "query" ? proc.queryIdentity : void 0;
|
|
42
|
+
const cron = proc.procedureType === "job" ? proc.cron : void 0;
|
|
42
43
|
this.procedureRegistry.set(name, {
|
|
43
44
|
name,
|
|
44
45
|
type: proc.procedureType,
|
|
45
46
|
internal: proc.internal,
|
|
46
47
|
inputSchema: proc.inputSchema,
|
|
47
48
|
fn: proc.fn,
|
|
48
|
-
queryIdentity
|
|
49
|
+
queryIdentity,
|
|
50
|
+
cron
|
|
49
51
|
});
|
|
50
52
|
}
|
|
51
53
|
/** Get a registered procedure by name (runtime lookup) */
|
|
@@ -60,6 +62,10 @@ var ContextRegistry = class {
|
|
|
60
62
|
getAllProcedures() {
|
|
61
63
|
return new Map(this.procedureRegistry);
|
|
62
64
|
}
|
|
65
|
+
/** Get all registered job procedures (server-only, scheduler-triggered). */
|
|
66
|
+
getJobProcedures() {
|
|
67
|
+
return [...this.procedureRegistry.values()].filter((p) => p.type === "job");
|
|
68
|
+
}
|
|
63
69
|
/** Clear the registry (for testing only) */
|
|
64
70
|
clearRegistry() {
|
|
65
71
|
this.procedureRegistry.clear();
|
|
@@ -78,4 +84,4 @@ var ContextRegistry = class {
|
|
|
78
84
|
//#endregion
|
|
79
85
|
export { getContextRegistry as n, router as r, ContextRegistry as t };
|
|
80
86
|
|
|
81
|
-
//# sourceMappingURL=router-
|
|
87
|
+
//# sourceMappingURL=router-CiWYeWUR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"router-CiWYeWUR.js","names":[],"sources":["../src/router/router.ts"],"sourcesContent":["import type { AnyProcedure } from \"./procedure\";\n\n// ─── Router Types ────────────────────────────────────────────────────────────\n\n/**\n * A router maps procedure names (keys) to their definitions.\n * This is the type that's exported from your app and used by the client.\n */\nexport type Router<TProcedures extends Record<string, AnyProcedure<TContext>>, TContext = unknown> = {\n _type: \"router\";\n procedures: TProcedures;\n contextName: string;\n};\n\n/**\n * Inferred AppRouter type from router() call.\n * Captures the full procedure map for client type inference.\n */\nexport type AppRouter<\n TProcedures extends Record<string, AnyProcedure<TContext>> = Record<string, AnyProcedure>,\n TContext = unknown\n> = Router<TProcedures, TContext>;\n\n// ─── Type Helpers for Client ─────────────────────────────────────────────────\n\n/** Get query procedures only from a router */\nexport type QueryProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"query\" } ? K : never]: T[K];\n};\n\n/** Get mutation procedures only from a router */\nexport type MutationProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"mutation\" } ? K : never]: T[K];\n};\n\n/** Get action procedures only from a router */\nexport type ActionProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"action\" } ? K : never]: T[K];\n};\n\n/** Get job procedures only from a router */\nexport type JobProcedures<T extends Record<string, AnyProcedure>> = {\n [K in keyof T as T[K] extends { procedureType: \"job\" } ? K : never]: T[K];\n};\n\n/** Get public (non-internal) procedures - for client type safety */\nexport type PublicProcedures<T extends Record<string, AnyProcedure>> = Pick<\n T,\n { [K in keyof T]: T[K] extends { internal: true } ? never : K }[keyof T]\n>;\n\n/** Extract procedure names from a router */\nexport type ProcedureNames<T extends Router<any>> =\n T extends Router<infer P> ? keyof P : never;\n\nexport type RouterConfig<T> = {\n procedures: T;\n contextName?: string;\n};\n\n/**\n* Create a router from procedure definitions.\n* Procedure names are inferred from the object keys.\n* \n* @example\n* const appRouter = router({\n* procedures: {\n* getUser,\n* createUser,\n* internalGetAll,\n* },\n* });\n* \n* export type AppRouter = typeof appRouter;\n*/\nexport function router<TProcedures extends Record<string, AnyProcedure<any>>, TContext = unknown>(\n config: RouterConfig<TProcedures>,\n): Router<TProcedures, TContext> {\n const registry = getContextRegistry(config.contextName ?? \"default\");\n\n // Register all procedures at router creation time\n for (const [name, proc] of Object.entries(config.procedures)) {\n registry.registerProcedure(name, proc);\n }\n\n\n return {\n _type: \"router\",\n procedures: config.procedures,\n contextName: config.contextName ?? \"default\",\n };\n}\n\nexport interface RegisteredProcedure<TContext = unknown> {\n name: string;\n type: \"query\" | \"mutation\" | \"action\" | \"job\";\n internal: boolean;\n inputSchema: AnyProcedure<TContext>[\"inputSchema\"];\n fn: AnyProcedure<TContext>[\"fn\"];\n /** Only present for `type === \"query\"`. See `QueryIdentitySpec`. */\n queryIdentity?: false | string | ((serverCtx: TContext | undefined, input: unknown) => string | null | undefined);\n /** Only present for `type === \"job\"`. Cron expression for recurring jobs. */\n cron?: string;\n}\n\n\nconst contextRegistry = new Map<string, ContextRegistry>();\n\nexport function getContextRegistry(inContext: string): ContextRegistry {\n let registry = contextRegistry.get(inContext);\n if (!registry) {\n registry = new ContextRegistry();\n contextRegistry.set(inContext, registry);\n }\n return registry;\n}\n\nexport class ContextRegistry {\n procedureRegistry = new Map<string, RegisteredProcedure<any>>();\n internalProcedureNames = new Set<string>();\n\n registerProcedure<TContext>(name: string, proc: AnyProcedure<TContext>): void {\n if (this.procedureRegistry.has(name)) {\n throw new Error(\n `[router] Procedure \"${name}\" is already registered. ` +\n `Each procedure name must be unique across the application.`\n );\n }\n\n // Track internal procedures by name\n if (proc.internal) {\n this.markInternalProcedure(name);\n }\n\n const queryIdentity =\n proc.procedureType === \"query\"\n ? (proc as { queryIdentity?: RegisteredProcedure<TContext>[\"queryIdentity\"] }).queryIdentity\n : undefined;\n\n const cron =\n proc.procedureType === \"job\"\n ? (proc as { cron?: string }).cron\n : undefined;\n\n this.procedureRegistry.set(name, {\n name,\n type: proc.procedureType,\n internal: proc.internal,\n inputSchema: proc.inputSchema,\n fn: proc.fn,\n queryIdentity,\n cron,\n });\n }\n\n /** Get a registered procedure by name (runtime lookup) */\n getProcedure<TContext = unknown>(name: string): RegisteredProcedure<TContext> | undefined {\n return this.procedureRegistry.get(name);\n }\n\n /** Get all registered procedure names */\n getProcedureNames(): string[] {\n return [...this.procedureRegistry.keys()];\n }\n\n /** Get all registered procedures */\n getAllProcedures(): Map<string, RegisteredProcedure> {\n return new Map(this.procedureRegistry);\n }\n\n /** Get all registered job procedures (server-only, scheduler-triggered). */\n getJobProcedures(): RegisteredProcedure[] {\n return [...this.procedureRegistry.values()].filter((p) => p.type === \"job\");\n }\n\n /** Clear the registry (for testing only) */\n clearRegistry(): void {\n this.procedureRegistry.clear();\n this.clearInternalProcedures();\n }\n\n markInternalProcedure(name: string): void {\n this.internalProcedureNames.add(name);\n }\n\n isInternalProcedure(name: string): boolean {\n return this.internalProcedureNames.has(name);\n }\n\n clearInternalProcedures(): void {\n this.internalProcedureNames.clear();\n }\n}"],"mappings":";;;;;;;;;;;;;;;;AA2EA,SAAgB,OACd,QAC+B;CAC/B,MAAM,WAAW,mBAAmB,OAAO,eAAe,SAAS;CAGnE,KAAK,MAAM,CAAC,MAAM,SAAS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A,sBAAsB,MAAoB;EACxC,KAAK,uBAAuB,IAAI,IAAI;CACtC;CAEA,oBAAoB,MAAuB;EACzC,OAAO,KAAK,uBAAuB,IAAI,IAAI;CAC7C;CAEA,0BAAgC;EAC9B,KAAK,uBAAuB,MAAM;CACpC;AACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as
|
|
1
|
+
import { $ as ProcedureNames, $n as AndPredicate, $t as ColumnCodec, Ar as RawPointReadSchema, At as SupaliveDb, Br as WriteOp, Bt as DbWriter, Cr as QueryCacheEntrySchema, Ct as QueryFn, Dr as RangeRead, Er as QuerySpec, Et as createActionBuilder, Fr as ReadEntry, Ft as QueryDefinition, G as RPCError, Hr as bytesFromJson, Ir as ReadEntrySchema, It as ResultOf, J as ActionProcedures, K as WSClientOptions, Lr as RetryConfig, Lt as _resetGlobalDefs, Mn as PooledClient, Mr as RawRangeReadSchema, Mt as AnyQueryDef, Nr as RawReadEntry, Nt as DefsToMap, On as Database, Or as RangeReadSchema, Ot as createMutationBuilder, Pn as RawClient, Pr as RawReadEntrySchema, Pt as ParamsOf, Q as MutationProcedures, Rr as WriteEntry, Rt as defineQuery, Sn as defineSchema, Sr as QueryCacheEntry, St as QueryCtx, Tr as QueryCacheMetadataSchema, Tt as TypeOf, U as ClientPublicState, Ur as normalizeIdToBytes, Vr as WriteOpSchema, Vt as TxContext, W as HeartbeatOptions, Wr as normalizeToBytes, Y as AppRouter, Zt as matchesPredicate, _r as OrPredicateSchema, _t as MutationCtx, a as CallOptions, ar as CommitTs, at as router, br as Predicate, bt as OutputOf, c as LiveQueryHandle, cn as InsertData, cr as DEFAULT_RETRY, ct as ActionFn, d as WSClientMethods, dr as LiveResult, dt as ContextOf, er as AndPredicateSchema, et as PublicProcedures, f as createClient, fr as MutationResult, gn as SchemaCodecs, gr as OrPredicate, gt as MutationConfig, hr as OccConflictError, i as createCaller, ir as CommitLogEntry, jr as RawRangeRead, jt as sleep, kn as DbQueryResult, kr as RawPointRead, kt as createQueryBuilder, l as LiveQueryState, ln as Model, lr as LeafPredicate, lt as ActionProcedure, mr as OccAbortError, n as CallerFromRouter, nr as CachedPgMetadata, nt as RegisteredProcedure, o as ClientFromProcedures, or as CompareOperator, ot as ActionConfig, pr as NO_RETRY, q as WsClientManager, r as CallerOptions, rn as ComputedFieldConfig, rr as CachedPgMetadataSchema, rt as Router, s as ClientOptions, sn as InferSchema, sr as CompareOperatorSchema, st as ActionCtx, t as CallerFromProcedures, tr as BigIntSchema, tt as QueryProcedures, u as LiveQueryStatus, ur as LeafPredicateSchema, ut as AnyProcedure, vn as SchemaColumnsOptions, vr as PointRead, vt as MutationFn, wr as QueryCacheMetadata, wt as QueryProcedure, xn as defineComputedField, xr as PredicateSchema, xt as QueryConfig, yn as SchemaDefinition, yr as PointReadSchema, yt as MutationProcedure, zr as WriteEntrySchema, zt as DbReader } from "../../index-DJYvJYR4.js";
|
|
2
2
|
export { type ActionConfig, type ActionCtx, type ActionFn, type ActionProcedure, type ActionProcedures, AndPredicate, AndPredicateSchema, type AnyProcedure, type AnyQueryDef, type AppRouter, BigIntSchema, CachedPgMetadata, CachedPgMetadataSchema, type CallOptions, CallerFromProcedures, CallerFromRouter, CallerOptions, type ClientFromProcedures, type ClientOptions, type ClientPublicState, type ColumnCodec, CommitLogEntry, CommitTs, CompareOperator, CompareOperatorSchema, type ComputedFieldConfig, type ContextOf, DEFAULT_RETRY, type Database, type DbQueryResult, DbReader, DbReader as ReadContext, DbWriter, DbWriter as WritableContext, type DefsToMap, type HeartbeatOptions, type InferSchema, type InsertData, LeafPredicate, LeafPredicateSchema, type LiveQueryHandle, type LiveQueryState, type LiveQueryStatus, LiveResult, type Model, type MutationConfig, type MutationCtx, type MutationFn, type MutationProcedure, type MutationProcedures, MutationResult, NO_RETRY, OccAbortError, OccConflictError, OrPredicate, OrPredicateSchema, type OutputOf, type ParamsOf, PointRead, PointReadSchema, type PooledClient, Predicate, PredicateSchema, type ProcedureNames, type PublicProcedures, QueryCacheEntry, QueryCacheEntrySchema, QueryCacheMetadata, QueryCacheMetadataSchema, type QueryConfig, type QueryCtx, type QueryDefinition, type QueryFn, type QueryProcedure, type QueryProcedures, QuerySpec, RPCError, RangeRead, RangeReadSchema, type RawClient, RawPointRead, RawPointReadSchema, RawRangeRead, RawRangeReadSchema, RawReadEntry, RawReadEntrySchema, ReadEntry, ReadEntrySchema, type RegisteredProcedure, type ResultOf, RetryConfig, type Router, type SchemaCodecs, type SchemaColumnsOptions, type SchemaDefinition, SupaliveDb, TxContext, type TypeOf, type WSClientMethods, type WSClientOptions, WriteEntry, WriteEntrySchema, WriteOp, WriteOpSchema, WsClientManager, _resetGlobalDefs, bytesFromJson, createActionBuilder, createCaller, createClient, createMutationBuilder, createQueryBuilder, defineComputedField, defineQuery, defineSchema, matchesPredicate, normalizeIdToBytes, normalizeToBytes, router, sleep };
|
package/dist/src/client/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as getContextRegistry, r as router } from "../../router-
|
|
3
|
-
import { o as matchesPredicate } from "../../query-
|
|
1
|
+
import { i as createQueryBuilder, r as createMutationBuilder, t as createActionBuilder } from "../../procedure-Ze1GE-N9.js";
|
|
2
|
+
import { n as getContextRegistry, r as router } from "../../router-CiWYeWUR.js";
|
|
3
|
+
import { o as matchesPredicate } from "../../query-CrbJ_W0W.js";
|
|
4
4
|
import { n as defineSchema, t as defineComputedField } from "../../schema-Dd7u0A1L.js";
|
|
5
5
|
import { r as supaliveStringify } from "../../helper-wGbzz6zo.js";
|
|
6
|
-
import { C as normalizeIdToBytes, S as bytesFromJson, _ as RawRangeReadSchema, a as DEFAULT_RETRY, b as WriteEntrySchema, c as OccAbortError, d as PointReadSchema, f as PredicateSchema, g as RawPointReadSchema, h as RangeReadSchema, i as CompareOperatorSchema, l as OccConflictError, m as QueryCacheMetadataSchema, n as BigIntSchema, o as LeafPredicateSchema, p as QueryCacheEntrySchema, r as CachedPgMetadataSchema, s as NO_RETRY, t as AndPredicateSchema, u as OrPredicateSchema, v as RawReadEntrySchema, w as normalizeToBytes, x as WriteOpSchema, y as ReadEntrySchema } from "../../types_db-
|
|
6
|
+
import { C as normalizeIdToBytes, S as bytesFromJson, _ as RawRangeReadSchema, a as DEFAULT_RETRY, b as WriteEntrySchema, c as OccAbortError, d as PointReadSchema, f as PredicateSchema, g as RawPointReadSchema, h as RangeReadSchema, i as CompareOperatorSchema, l as OccConflictError, m as QueryCacheMetadataSchema, n as BigIntSchema, o as LeafPredicateSchema, p as QueryCacheEntrySchema, r as CachedPgMetadataSchema, s as NO_RETRY, t as AndPredicateSchema, u as OrPredicateSchema, v as RawReadEntrySchema, w as normalizeToBytes, x as WriteOpSchema, y as ReadEntrySchema } from "../../types_db-CTRm_awX.js";
|
|
7
7
|
import { l as ServerMessageSchema } from "../../types_client_rpc-CIsjQQGG.js";
|
|
8
|
-
import { a as TxContext, i as DbWriter, n as sleep, r as DbReader, t as SupaliveDb } from "../../realtime_db-
|
|
8
|
+
import { a as TxContext, i as DbWriter, n as sleep, r as DbReader, t as SupaliveDb } from "../../realtime_db-BtwBABDY.js";
|
|
9
9
|
import { sha1 } from "hash-wasm";
|
|
10
10
|
//#region src/db/query_definition.ts
|
|
11
11
|
const _globalDefs = /* @__PURE__ */ new Map();
|
|
@@ -1112,6 +1112,24 @@ function createCaller(options) {
|
|
|
1112
1112
|
return procedure.fn(ctx, validatedInput);
|
|
1113
1113
|
});
|
|
1114
1114
|
},
|
|
1115
|
+
runQuery: async (input, parentCtx) => {
|
|
1116
|
+
if (procedure.type !== "query") throw new Error(`Procedure "${procedureName}" is not a query`);
|
|
1117
|
+
const validatedInput = validateInput(input);
|
|
1118
|
+
if (parentCtx.db instanceof TxContext) {
|
|
1119
|
+
const ctx = {
|
|
1120
|
+
db: parentCtx.db,
|
|
1121
|
+
serverCtx: parentCtx.serverCtx
|
|
1122
|
+
};
|
|
1123
|
+
return procedure.fn(ctx, validatedInput);
|
|
1124
|
+
}
|
|
1125
|
+
return parentCtx.db.query(async (dbCtx) => {
|
|
1126
|
+
const ctx = {
|
|
1127
|
+
db: dbCtx,
|
|
1128
|
+
serverCtx: parentCtx.serverCtx
|
|
1129
|
+
};
|
|
1130
|
+
return procedure.fn(ctx, validatedInput);
|
|
1131
|
+
});
|
|
1132
|
+
},
|
|
1115
1133
|
mutate: async (input, serverCtx) => {
|
|
1116
1134
|
if (procedure.type !== "mutation") throw new Error(`Procedure "${procedureName}" is not a mutation`);
|
|
1117
1135
|
const validatedInput = validateInput(input);
|
|
@@ -1123,6 +1141,18 @@ function createCaller(options) {
|
|
|
1123
1141
|
return procedure.fn(ctx, validatedInput);
|
|
1124
1142
|
})).result;
|
|
1125
1143
|
},
|
|
1144
|
+
runMutation: async (input, parentCtx) => {
|
|
1145
|
+
if (procedure.type !== "mutation") throw new Error(`Procedure "${procedureName}" is not a mutation`);
|
|
1146
|
+
const validatedInput = validateInput(input);
|
|
1147
|
+
return (await (parentCtx.db instanceof TxContext ? db : parentCtx.db).mutation(async (dbCtx) => {
|
|
1148
|
+
const ctx = {
|
|
1149
|
+
db: dbCtx,
|
|
1150
|
+
serverCtx: parentCtx.serverCtx
|
|
1151
|
+
};
|
|
1152
|
+
if (parentCtx.db instanceof TxContext) ctx.db.appendInternalReadSet(parentCtx.db.internalGetReadSet());
|
|
1153
|
+
return procedure.fn(ctx, validatedInput);
|
|
1154
|
+
})).result;
|
|
1155
|
+
},
|
|
1126
1156
|
action: async (input, serverCtx) => {
|
|
1127
1157
|
if (procedure.type !== "action") throw new Error(`Procedure "${procedureName}" is not an action`);
|
|
1128
1158
|
const validatedInput = validateInput(input);
|
|
@@ -1132,6 +1162,15 @@ function createCaller(options) {
|
|
|
1132
1162
|
};
|
|
1133
1163
|
return procedure.fn(ctx, validatedInput);
|
|
1134
1164
|
},
|
|
1165
|
+
run: async (input, serverCtx) => {
|
|
1166
|
+
if (procedure.type !== "job") throw new Error(`Procedure "${procedureName}" is not a job`);
|
|
1167
|
+
const validatedInput = validateInput(input);
|
|
1168
|
+
const ctx = {
|
|
1169
|
+
db,
|
|
1170
|
+
serverCtx
|
|
1171
|
+
};
|
|
1172
|
+
return procedure.fn(ctx, validatedInput);
|
|
1173
|
+
},
|
|
1135
1174
|
liveQuery: procedure.type === "query" ? async (input, serverCtx) => {
|
|
1136
1175
|
const validatedInput = validateInput(input);
|
|
1137
1176
|
return db.liveQuery(async (dbCtx) => {
|