@umituz/web-hono 1.20.2 → 1.22.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umituz/web-hono",
3
- "version": "1.20.2",
3
+ "version": "1.22.0",
4
4
  "description": "API backend platform for Cloudflare Workers + Neon Postgres: createApi skeleton + error envelope layer, full-CRUD resource factory (opt-in create/remove, list params), schema→client type bridge (ClientRow), apiFetch/apiWrite client, reactive fetch-backed store (+React hooks), doc-sync diff/snapshot/push machine (snapshotDocs/diffOps/pushOps), better-auth server integration (tables/getter/mount/session helpers), weak-compare If-None-Match matcher (matchesEtag), cookie channels + request scope/ETag/R2-stream server helpers, TTL resource cache, and db lifecycle scripts (reset / snapshot / seed)",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
package/src/crud.ts CHANGED
@@ -30,13 +30,24 @@ export interface CreateSpec {
30
30
  pre?: (c: RequestContext, body: Record<string, unknown>) => Promise<Response | void>;
31
31
  }
32
32
 
33
+ export interface ThroughSpec {
34
+ column: PgColumn;
35
+ table: PgTable & { id: PgColumn };
36
+ farmColumn: PgColumn;
37
+ }
38
+
33
39
  export interface OrgScopeSpec {
34
40
  column?: PgColumn;
35
41
  farmColumn?: PgColumn;
42
+ through?: ThroughSpec;
36
43
  farms?: PgTable & { id: PgColumn; orgId: PgColumn };
37
44
  resolve: (c: RequestContext) => Promise<string | null | undefined>;
38
45
  }
39
46
 
47
+ export interface AuthSpec {
48
+ resolve: (c: RequestContext) => Promise<string | null | undefined>;
49
+ }
50
+
40
51
  export interface ListSpec {
41
52
  path: string;
42
53
  table: PgTable & { deletedAt: PgColumn };
@@ -50,20 +61,36 @@ export interface CrudSpec extends ListSpec {
50
61
  label: string;
51
62
  create?: CreateSpec;
52
63
  remove?: boolean;
64
+ auth?: AuthSpec;
53
65
  }
54
66
 
55
67
  const MAX_LIST_LIMIT = 500;
56
68
 
57
69
  function assertOrgScope(scope: OrgScopeSpec): void {
58
- if (scope.column && scope.farmColumn) throw new Error('orgScope: pass either column or farmColumn, not both');
59
- if (!scope.column && !scope.farmColumn) throw new Error('orgScope: column or farmColumn is required');
60
- if (scope.farmColumn && !scope.farms) throw new Error('orgScope: farms table is required with farmColumn');
70
+ const modes = [scope.column, scope.farmColumn, scope.through].filter(Boolean).length;
71
+ if (modes > 1) throw new Error('orgScope: pass exactly one of column, farmColumn or through');
72
+ if (modes === 0) throw new Error('orgScope: column, farmColumn or through is required');
73
+ if ((scope.farmColumn || scope.through) && !scope.farms) throw new Error('orgScope: farms table is required with farmColumn/through');
61
74
  }
62
75
 
63
76
  function orgScopeCondition(scope: OrgScopeSpec, db: CrudDb, orgId: string): SQL {
64
77
  if (scope.column) return eq(scope.column, orgId) as SQL;
65
78
  const farms = scope.farms!;
66
- return inArray(scope.farmColumn!, db.select({ id: farms.id }).from(farms).where(eq(farms.orgId, orgId))) as SQL;
79
+ const orgFarmIds = db.select({ id: farms.id }).from(farms).where(eq(farms.orgId, orgId));
80
+ if (scope.through) {
81
+ const t = scope.through;
82
+ return inArray(
83
+ t.column,
84
+ db.select({ id: t.table.id }).from(t.table).where(inArray(t.farmColumn, orgFarmIds)),
85
+ ) as SQL;
86
+ }
87
+ return inArray(scope.farmColumn!, orgFarmIds) as SQL;
88
+ }
89
+
90
+ function scopeColumnKeys(spec: ListSpec, scope: OrgScopeSpec): string[] {
91
+ const cols = getTableColumns(spec.table) as unknown as Record<string, PgColumn>;
92
+ const targets = new Set([scope.column, scope.farmColumn, scope.through?.column].filter(Boolean) as PgColumn[]);
93
+ return Object.keys(cols).filter((k) => cols[k] !== undefined && targets.has(cols[k]!));
67
94
  }
68
95
 
69
96
  async function resolveScopedOrg(spec: ListSpec, c: RequestContext): Promise<string | null | undefined> {
@@ -71,6 +98,12 @@ async function resolveScopedOrg(spec: ListSpec, c: RequestContext): Promise<stri
71
98
  return spec.orgScope?.resolve(c);
72
99
  }
73
100
 
101
+ async function requireWriteAuth(spec: CrudSpec, c: RequestContext): Promise<Response | void> {
102
+ if (spec.orgScope || !spec.auth) return;
103
+ const who = await spec.auth.resolve(c);
104
+ if (!who) return c.json({ error: 'Sign in to write to this resource' }, 401);
105
+ }
106
+
74
107
  function orgColumnKey(spec: ListSpec, column: PgColumn): string | undefined {
75
108
  const cols = getTableColumns(spec.table) as unknown as Record<string, PgColumn>;
76
109
  return Object.keys(cols).find((k) => cols[k] === column);
@@ -142,6 +175,8 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
142
175
  });
143
176
 
144
177
  router.patch(`${path}/:id`, async (c) => {
178
+ const gate = await requireWriteAuth(spec, c);
179
+ if (gate) return gate;
145
180
  const raw = await c.req.json().catch(() => undefined);
146
181
  if (raw === undefined) return c.json({ error: 'Malformed JSON in request body' }, 400);
147
182
  const patch = pickPatch(table, raw);
@@ -154,6 +189,7 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
154
189
  const orgId = await resolveScopedOrg(spec, c);
155
190
  if (!orgId) return c.json({ error: 'Sign in to an organization to update this resource' }, 401);
156
191
  conds.push(orgScopeCondition(spec.orgScope, db, orgId));
192
+ for (const key of scopeColumnKeys(spec, spec.orgScope)) delete (patch as Record<string, unknown>)[key];
157
193
  }
158
194
  const [row] = await db
159
195
  .update(table)
@@ -166,6 +202,8 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
166
202
  if (spec.create) {
167
203
  const { schema, prefix, defaults, pre } = spec.create;
168
204
  router.post(path, async (c) => {
205
+ const gate = await requireWriteAuth(spec, c);
206
+ if (gate) return gate;
169
207
  const raw = await c.req.json().catch(() => undefined);
170
208
  if (raw === undefined || typeof raw !== 'object' || raw === null) {
171
209
  return c.json({ error: 'Malformed JSON in request body' }, 400);
@@ -188,6 +226,25 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
188
226
  if (scope.column) {
189
227
  const key = orgColumnKey(spec, scope.column);
190
228
  if (key) stamped[key] = orgId;
229
+ } else if (scope.through) {
230
+ const t = scope.through;
231
+ const key = orgColumnKey(spec, t.column);
232
+ const parentId = key ? (body[key] as string | undefined) : undefined;
233
+ if (parentId) {
234
+ const farms = scope.farms!;
235
+ const [parent] = await db
236
+ .select({ farm: t.farmColumn })
237
+ .from(t.table)
238
+ .where(eq(t.table.id, parentId))
239
+ .limit(1);
240
+ if (!parent) return c.json({ error: 'Linked record not found' }, 400);
241
+ const [farm] = await db
242
+ .select({ id: farms.id })
243
+ .from(farms)
244
+ .where(and(eq(farms.id, parent.farm), eq(farms.orgId, orgId)))
245
+ .limit(1);
246
+ if (!farm) return c.json({ error: 'Linked record belongs to another organization' }, 400);
247
+ }
191
248
  } else {
192
249
  const key = orgColumnKey(spec, scope.farmColumn!);
193
250
  const farmId = key ? (body[key] as string | undefined) : undefined;
@@ -212,6 +269,8 @@ export function crudRoutes(spec: CrudSpec): Hono<{ Bindings: ApiEnv }> {
212
269
 
213
270
  if (spec.remove) {
214
271
  router.delete(`${path}/:id`, async (c) => {
272
+ const gate = await requireWriteAuth(spec, c);
273
+ if (gate) return gate;
215
274
  const db = getDb(c);
216
275
  const conds: SQL[] = [eq(table.id, c.req.param('id')), isNull(table.deletedAt) as SQL];
217
276
  if (spec.orgScope) {
package/src/index.ts CHANGED
@@ -3,7 +3,7 @@ export type { ApiConfig } from './api';
3
3
  export { healthRouter } from './health';
4
4
  export { ApiError, apiOnError, isUniqueViolation } from './errors';
5
5
  export { crudRoutes, listRoutes } from './crud';
6
- export type { CrudSpec, CrudTable, CrudDb, CrudDbFactory, CreateSpec, ListSpec, OrgScopeSpec } from './crud';
6
+ export type { CrudSpec, CrudTable, CrudDb, CrudDbFactory, CreateSpec, ListSpec, OrgScopeSpec, ThroughSpec } from './crud';
7
7
  export { docStore, canTransition, epoch, WorkflowError, UnknownCollectionError } from './docstore';
8
8
  export type { Doc, DocInput, DocTable, DocCollectionSpec, DocStoreSpec, DocValidateFn, DocAfterWriteFn, DocScopeSpec, DocWriteHookArgs, DocPatchHookArgs } from './docstore';
9
9
  export { getDb } from './db';