@colspec/server 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Om Prakash Das
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/README.md CHANGED
@@ -1,3 +1,85 @@
1
- # Temporary Holding Version
1
+ # @colspec/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Store, version and serve [colspec](https://github.com/Om1938/colspec) table
4
+ definitions from your own backend. It works with any database and any Node.js
5
+ framework, and needs no ORM or separate service.
6
+
7
+ ```sh
8
+ npm install @colspec/server @colspec/core
9
+ ```
10
+
11
+ ## 1. Implement storage
12
+
13
+ One row or document per revision, unique by `(tableId, revision)`.
14
+
15
+ ```ts
16
+ import type { TableDefinitionRepository } from "@colspec/server";
17
+
18
+ const repository: TableDefinitionRepository = {
19
+ find: (tableId, revision) => /* one record or undefined */,
20
+ findLatest: (tableId, status) => /* highest revision with that status */,
21
+ list: (tableId) => /* all revisions, oldest first */,
22
+ save: (record) => /* insert or replace */,
23
+ };
24
+ ```
25
+
26
+ `createMemoryRepository()` is included for tests and prototypes.
27
+
28
+ ## 2. Manage definitions
29
+
30
+ ```ts
31
+ import { createTableDefinitionService } from "@colspec/server";
32
+
33
+ const definitions = createTableDefinitionService(repository);
34
+
35
+ await definitions.saveDraft(json); // validates; throws ContractError if invalid
36
+ await definitions.publish("crm.contacts", 4);
37
+ await definitions.getPublished("crm.contacts"); // latest published revision
38
+ await definitions.listRevisions("crm.contacts");
39
+ ```
40
+
41
+ Drafts can be saved repeatedly. A published revision is immutable; change a
42
+ table by saving a new revision number.
43
+
44
+ ## 3. Serve them
45
+
46
+ `getDefinitionResponse` returns `{ status, headers, body }` with an `ETag` and
47
+ `304 Not Modified` handling.
48
+
49
+ ```ts
50
+ app.get("/api/table-definitions/:tableId", async (req, res) => {
51
+ const { status, headers, body } = await getDefinitionResponse(definitions, {
52
+ tableId: req.params.tableId,
53
+ ifNoneMatch: req.get("if-none-match"),
54
+ });
55
+ res.status(status).set(headers).json(body);
56
+ });
57
+ ```
58
+
59
+ ## 4. Accept sort and filter requests safely
60
+
61
+ Clients send operation keys, not field names. Map every key through a list
62
+ you control.
63
+
64
+ ```ts
65
+ import { resolveServerQuery } from "@colspec/server";
66
+
67
+ const result = resolveServerQuery(untrustedJson, {
68
+ "contact.created_at": "contacts.created_at",
69
+ status: "contacts.status",
70
+ });
71
+
72
+ if (!result.ok) return badRequest(result.diagnostics);
73
+ const { sort, filters, page } = result.value; // only fields from your list
74
+ ```
75
+
76
+ Malformed input and unlisted keys are rejected. Filter _values_ are still
77
+ untrusted: validate or coerce them before they reach a query.
78
+
79
+ ## Not included
80
+
81
+ Authentication and authorization. Decide in your application who may save,
82
+ publish and read definitions.
83
+
84
+ [Documentation](https://github.com/Om1938/colspec/tree/main/apps/docs/guide) ·
85
+ [NestJS + MongoDB example](https://github.com/Om1938/colspec/tree/main/examples) · MIT
@@ -0,0 +1,99 @@
1
+ import { Result, ServerQuery, TableContract, ValidateOptions } from "@colspec/core";
2
+ //#region src/repository.d.ts
3
+ export type DefinitionStatus = "draft" | "published";
4
+ /** One stored revision of a table definition; unique by `(tableId, revision)`. */
5
+ export interface TableDefinitionRecord {
6
+ tableId: string;
7
+ revision: number;
8
+ schemaVersion: string;
9
+ definition: TableContract;
10
+ status: DefinitionStatus;
11
+ createdAt: Date;
12
+ updatedAt: Date;
13
+ }
14
+ /**
15
+ * The storage boundary. Implement it over any database: one row or document
16
+ * per revision, with the contract kept as JSON.
17
+ */
18
+ export interface TableDefinitionRepository {
19
+ find(tableId: string, revision: number): Promise<TableDefinitionRecord | undefined>;
20
+ /** The highest revision with the given status. */
21
+ findLatest(tableId: string, status: DefinitionStatus): Promise<TableDefinitionRecord | undefined>;
22
+ /** Every revision of a table, oldest first. */
23
+ list(tableId: string): Promise<TableDefinitionRecord[]>;
24
+ /** Inserts the record, or replaces the one with the same `(tableId, revision)`. */
25
+ save(record: TableDefinitionRecord): Promise<void>;
26
+ }
27
+ //#endregion
28
+ //#region src/service.d.ts
29
+ export declare class DefinitionNotFoundError extends Error {
30
+ constructor(tableId: string, revision?: number);
31
+ }
32
+ export declare class RevisionPublishedError extends Error {
33
+ constructor(tableId: string, revision: number);
34
+ }
35
+ export interface ServiceOptions {
36
+ /** Passed to `validateContract` for every definition the service handles. */
37
+ validation?: ValidateOptions;
38
+ now?: () => Date;
39
+ }
40
+ export interface TableDefinitionService {
41
+ validate(input: unknown): Result<TableContract>;
42
+ /** Stores a draft. Throws `ContractError` if invalid, `RevisionPublishedError` if published. */
43
+ saveDraft(input: unknown): Promise<TableDefinitionRecord>;
44
+ /** Makes a draft visible to consumers and freezes it. Publishing twice is a no-op. */
45
+ publish(tableId: string, revision: number): Promise<TableDefinitionRecord>;
46
+ /** The latest published revision, or a specific one. Drafts are never returned. */
47
+ getPublished(tableId: string, revision?: number): Promise<TableDefinitionRecord | undefined>;
48
+ listRevisions(tableId: string): Promise<TableDefinitionRecord[]>;
49
+ }
50
+ /** The definition lifecycle on top of any storage implementation. */
51
+ export declare function createTableDefinitionService(repository: TableDefinitionRepository, { validation, now }?: ServiceOptions): TableDefinitionService;
52
+ //#endregion
53
+ //#region src/http.d.ts
54
+ /** Published revisions never change, so identity plus revision is a strong validator. */
55
+ export declare function etagFor({ tableId, revision }: Pick<TableDefinitionRecord, "tableId" | "revision">): string;
56
+ /** A response any HTTP framework can send: status, headers and a JSON body. */
57
+ export interface DefinitionResponse {
58
+ status: 200 | 304 | 404;
59
+ headers: Record<string, string>;
60
+ body?: TableContract | {
61
+ error: string;
62
+ };
63
+ }
64
+ export interface DefinitionRequest {
65
+ tableId: string;
66
+ revision?: number;
67
+ /** The request's `If-None-Match` header, if any. */
68
+ ifNoneMatch?: string | null;
69
+ }
70
+ /**
71
+ * Answers a contract retrieval request, including conditional requests, so
72
+ * clients revalidate with a 304 instead of downloading an unchanged contract.
73
+ */
74
+ export declare function getDefinitionResponse(service: TableDefinitionService, { tableId, revision, ifNoneMatch }: DefinitionRequest): Promise<DefinitionResponse>;
75
+ //#endregion
76
+ //#region src/memory-repository.d.ts
77
+ /** A repository held in memory, for tests, examples and prototypes. */
78
+ export declare function createMemoryRepository(): TableDefinitionRepository;
79
+ //#endregion
80
+ //#region src/server-query.d.ts
81
+ /** A client's query with every key replaced by its approved backend field. */
82
+ export interface ResolvedQuery<TField> {
83
+ sort: Array<{
84
+ field: TField;
85
+ desc: boolean;
86
+ }>;
87
+ filters: Array<{
88
+ field: TField;
89
+ value: unknown;
90
+ }>;
91
+ page?: ServerQuery["page"];
92
+ }
93
+ /**
94
+ * Validates an untrusted query and maps its operation keys to fields the
95
+ * backend has approved. Keys are looked up, never interpolated, so an
96
+ * unlisted key is rejected rather than reaching a query.
97
+ */
98
+ export declare function resolveServerQuery<TField>(input: unknown, fields: Readonly<Record<string, TField>>): Result<ResolvedQuery<TField>>;
99
+ //#endregion
package/dist/index.mjs ADDED
@@ -0,0 +1,147 @@
1
+ import { ContractError, issuesToDiagnostics, serverQuerySchema, toResult, validateContract } from "@colspec/core";
2
+ //#region src/http.ts
3
+ /** Published revisions never change, so identity plus revision is a strong validator. */
4
+ function etagFor({ tableId, revision }) {
5
+ return `"${encodeURIComponent(tableId)}@${revision}"`;
6
+ }
7
+ /**
8
+ * Answers a contract retrieval request, including conditional requests, so
9
+ * clients revalidate with a 304 instead of downloading an unchanged contract.
10
+ */
11
+ async function getDefinitionResponse(service, { tableId, revision, ifNoneMatch }) {
12
+ const record = await service.getPublished(tableId, revision);
13
+ if (!record) return {
14
+ status: 404,
15
+ headers: {},
16
+ body: { error: `No published definition for "${tableId}".` }
17
+ };
18
+ const etag = etagFor(record);
19
+ const headers = {
20
+ ETag: etag,
21
+ "Cache-Control": "no-cache"
22
+ };
23
+ return ifNoneMatch?.split(",").some((candidate) => candidate.trim() === etag) ? {
24
+ status: 304,
25
+ headers
26
+ } : {
27
+ status: 200,
28
+ headers,
29
+ body: record.definition
30
+ };
31
+ }
32
+ //#endregion
33
+ //#region src/memory-repository.ts
34
+ /** A repository held in memory, for tests, examples and prototypes. */
35
+ function createMemoryRepository() {
36
+ const records = /* @__PURE__ */ new Map();
37
+ const keyOf = (tableId, revision) => JSON.stringify([tableId, revision]);
38
+ const list = (tableId) => [...records.values()].filter((record) => record.tableId === tableId).sort((a, b) => a.revision - b.revision);
39
+ return {
40
+ find: async (tableId, revision) => records.get(keyOf(tableId, revision)),
41
+ findLatest: async (tableId, status) => list(tableId).findLast((record) => record.status === status),
42
+ list: async (tableId) => list(tableId),
43
+ save: async (record) => {
44
+ records.set(keyOf(record.tableId, record.revision), record);
45
+ }
46
+ };
47
+ }
48
+ //#endregion
49
+ //#region src/server-query.ts
50
+ /**
51
+ * Validates an untrusted query and maps its operation keys to fields the
52
+ * backend has approved. Keys are looked up, never interpolated, so an
53
+ * unlisted key is rejected rather than reaching a query.
54
+ */
55
+ function resolveServerQuery(input, fields) {
56
+ const parsed = serverQuerySchema.safeParse(input);
57
+ if (!parsed.success) return {
58
+ ok: false,
59
+ diagnostics: issuesToDiagnostics(parsed.error.issues, "invalid-query")
60
+ };
61
+ const query = parsed.data;
62
+ const diagnostics = [];
63
+ const resolve = (entries, section) => (entries ?? []).flatMap(({ key, ...rest }, index) => {
64
+ if (Object.hasOwn(fields, key)) return [{
65
+ field: fields[key],
66
+ ...rest
67
+ }];
68
+ diagnostics.push({
69
+ code: "unapproved-key",
70
+ severity: "error",
71
+ path: [
72
+ section,
73
+ index,
74
+ "key"
75
+ ],
76
+ message: `"${key}" is not an approved ${section} key.`
77
+ });
78
+ return [];
79
+ });
80
+ const resolved = {
81
+ sort: resolve(query.sort, "sort"),
82
+ filters: resolve(query.filters, "filters"),
83
+ page: query.page
84
+ };
85
+ return toResult(resolved, diagnostics);
86
+ }
87
+ //#endregion
88
+ //#region src/service.ts
89
+ var DefinitionNotFoundError = class extends Error {
90
+ constructor(tableId, revision) {
91
+ super(`No definition found for "${tableId}"${revision ? ` revision ${revision}` : ""}.`);
92
+ this.name = "DefinitionNotFoundError";
93
+ }
94
+ };
95
+ var RevisionPublishedError = class extends Error {
96
+ constructor(tableId, revision) {
97
+ super(`Revision ${revision} of "${tableId}" is published and can no longer change.`);
98
+ this.name = "RevisionPublishedError";
99
+ }
100
+ };
101
+ /** The definition lifecycle on top of any storage implementation. */
102
+ function createTableDefinitionService(repository, { validation, now = () => /* @__PURE__ */ new Date() } = {}) {
103
+ const validate = (input) => validateContract(input, validation);
104
+ return {
105
+ validate,
106
+ async saveDraft(input) {
107
+ const result = validate(input);
108
+ if (!result.ok) throw new ContractError(result.diagnostics);
109
+ const definition = result.value;
110
+ const { tableId, revision, schemaVersion } = definition;
111
+ const existing = await repository.find(tableId, revision);
112
+ if (existing?.status === "published") throw new RevisionPublishedError(tableId, revision);
113
+ const timestamp = now();
114
+ const record = {
115
+ tableId,
116
+ revision,
117
+ schemaVersion,
118
+ definition,
119
+ status: "draft",
120
+ createdAt: existing?.createdAt ?? timestamp,
121
+ updatedAt: timestamp
122
+ };
123
+ await repository.save(record);
124
+ return record;
125
+ },
126
+ async publish(tableId, revision) {
127
+ const record = await repository.find(tableId, revision);
128
+ if (!record) throw new DefinitionNotFoundError(tableId, revision);
129
+ if (record.status === "published") return record;
130
+ const published = {
131
+ ...record,
132
+ status: "published",
133
+ updatedAt: now()
134
+ };
135
+ await repository.save(published);
136
+ return published;
137
+ },
138
+ async getPublished(tableId, revision) {
139
+ if (revision === void 0) return repository.findLatest(tableId, "published");
140
+ const record = await repository.find(tableId, revision);
141
+ return record?.status === "published" ? record : void 0;
142
+ },
143
+ listRevisions: (tableId) => repository.list(tableId)
144
+ };
145
+ }
146
+ //#endregion
147
+ export { DefinitionNotFoundError, RevisionPublishedError, createMemoryRepository, createTableDefinitionService, etagFor, getDefinitionResponse, resolveServerQuery };
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@colspec/server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "devDependencies": {
5
+ "@repo/eslint-config": "0.0.0",
6
+ "@repo/typescript-config": "0.0.0"
7
+ },
8
+ "dependencies": {
9
+ "@colspec/core": "0.1.0"
10
+ },
11
+ "type": "module",
12
+ "license": "MIT",
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "sideEffects": false,
20
+ "exports": {
21
+ ".": "./dist/index.mjs",
22
+ "./package.json": "./package.json"
23
+ },
24
+ "description": "Store, version, publish and serve colspec table definitions from any database or Node.js framework.",
25
+ "author": "Om Prakash Das",
26
+ "homepage": "https://github.com/Om1938/colspec/tree/main/packages/server#readme",
27
+ "bugs": {
28
+ "url": "https://github.com/Om1938/colspec/issues"
29
+ },
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/Om1938/colspec.git",
33
+ "directory": "packages/server"
34
+ },
35
+ "keywords": [
36
+ "tanstack-table",
37
+ "tanstack",
38
+ "table",
39
+ "datagrid",
40
+ "dynamic-columns",
41
+ "colspec",
42
+ "backend persistence mongodb postgresql"
43
+ ],
44
+ "scripts": {
45
+ "lint": "eslint . --max-warnings 0",
46
+ "build": "tsdown",
47
+ "test": "vitest run",
48
+ "check-types": "tsc --noEmit"
49
+ }
6
50
  }