@aotter/mantle 0.2.0-alpha.9 → 0.2.1-alpha.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 +15 -5
- package/dist/auth/adapter.js +1 -28
- package/dist/auth/admin.js +2 -5
- package/dist/auth/caller.js +0 -27
- package/dist/auth/consent.js +100 -0
- package/dist/auth/hardening.js +0 -7
- package/dist/auth/identity.js +0 -11
- package/dist/auth/oauth.js +0 -32
- package/dist/auth/resource-seeds.js +0 -2
- package/dist/auth/route-http.js +33 -0
- package/dist/auth/routes.js +5 -151
- package/dist/build/compiler.d.ts +19 -609
- package/dist/build/compiler.js +6 -6896
- package/dist/build/spec/domain/model/ManifestGrammar.d.ts +39 -1
- package/dist/build/spec/domain/model/RuntimePlan.d.ts +16 -3
- package/dist/build/spec/domain/model/SqlIr.d.ts +32 -0
- package/dist/build/spec/domain/model/UserFields.d.ts +1 -0
- package/dist/build/spec/kernel/diagnostic.d.ts +1 -1
- package/dist/bun/assets.js +0 -2
- package/dist/domain/adminOrder.js +0 -2
- package/dist/domain/columns.js +7 -20
- package/dist/domain/describe/chunk-P6PP6VVV.js +1 -0
- package/dist/domain/describe/index.d.ts +1 -0
- package/dist/domain/describe/index.js +1 -115
- package/dist/domain/describe/match.d.ts +19 -0
- package/dist/domain/describe/target-hash.js +1 -12
- package/dist/domain/entry.js +0 -14
- package/dist/domain/generated-tools.js +0 -1
- package/dist/domain/input.js +0 -2
- package/dist/domain/paging.js +0 -17
- package/dist/domain/recipes.js +10 -7
- package/dist/domain/userReferences.js +0 -1
- package/dist/domain/wireScalars.js +0 -6
- package/dist/infrastructure/adminEntries.js +27 -8
- package/dist/infrastructure/adminPaging.js +55 -57
- package/dist/infrastructure/artifacts.js +0 -4
- package/dist/infrastructure/authSchema.js +0 -9
- package/dist/infrastructure/bundle.js +45 -38
- package/dist/infrastructure/cli.js +26 -12
- package/dist/infrastructure/generate.js +26 -19
- package/dist/infrastructure/generateAuth.js +1 -9
- package/dist/infrastructure/help.js +55 -0
- package/dist/infrastructure/init.js +50 -0
- package/dist/infrastructure/inputs.js +0 -9
- package/dist/infrastructure/mounts.js +22 -0
- package/dist/infrastructure/wrangler.js +0 -6
- package/dist/kernel/authorization.js +0 -1
- package/dist/kernel/binds.d.ts +34 -7
- package/dist/kernel/binds.js +5 -11
- package/dist/kernel/caller-identity.d.ts +0 -3
- package/dist/kernel/caller-identity.js +0 -15
- package/dist/kernel/caller-mode.d.ts +4 -0
- package/dist/kernel/caller-mode.js +14 -0
- package/dist/kernel/contracts.d.ts +13 -10
- package/dist/kernel/contracts.js +14 -41
- package/dist/kernel/cron.js +0 -4
- package/dist/kernel/dialect/common.js +0 -3
- package/dist/kernel/dialect/postgres.js +0 -2
- package/dist/kernel/dialect/sqlite.js +1 -6
- package/dist/kernel/drain.js +2 -8
- package/dist/kernel/driver/bun-sqlite.js +3 -7
- package/dist/kernel/driver/d1.d.ts +1 -1
- package/dist/kernel/driver/d1.js +6 -4
- package/dist/kernel/driver/postgres.d.ts +2 -1
- package/dist/kernel/driver/postgres.js +12 -22
- package/dist/kernel/driver/transaction-context.js +0 -1
- package/dist/kernel/email.js +0 -4
- package/dist/kernel/host-access.js +2 -3
- package/dist/kernel/host-caller.d.ts +1 -1
- package/dist/kernel/host-caller.js +3 -6
- package/dist/kernel/json-body.js +0 -2
- package/dist/kernel/mcp-apps.js +0 -5
- package/dist/kernel/mcp-call.js +0 -1
- package/dist/kernel/mcp-handler.js +4 -27
- package/dist/kernel/mcp.js +0 -5
- package/dist/kernel/media.js +0 -18
- package/dist/kernel/paging.js +1 -9
- package/dist/kernel/publishing.js +3 -4
- package/dist/kernel/r2-media.js +0 -7
- package/dist/kernel/rest-dispatch.js +0 -1
- package/dist/kernel/rest-router.js +5 -8
- package/dist/kernel/rest.d.ts +2 -1
- package/dist/kernel/rest.js +1 -3
- package/dist/kernel/route-pattern.d.ts +26 -0
- package/dist/kernel/route-pattern.js +34 -0
- package/dist/kernel/scalars.js +1 -9
- package/dist/kernel/search.js +0 -1
- package/dist/kernel/site.js +0 -2
- package/dist/kernel/store.d.ts +26 -2
- package/dist/kernel/store.js +69 -49
- package/dist/kernel/surface-failure.d.ts +10 -0
- package/dist/kernel/surface-failure.js +29 -0
- package/dist/kernel/surface.js +0 -3
- package/dist/kernel/sweep.js +0 -1
- package/dist/kernel/translations.js +0 -1
- package/dist/kernel/user-caller.js +2 -8
- package/dist/kernel/user-fields.d.ts +3 -2
- package/dist/kernel/user-fields.js +9 -9
- package/dist/kernel/validation.js +0 -8
- package/dist/kernel/web-gateway.js +0 -2
- package/dist/kernel/web-head.js +0 -1
- package/dist/kernel/web-index.js +0 -1
- package/dist/kernel/web-response.js +0 -1
- package/dist/kernel/web-serve.js +97 -0
- package/dist/kernel/web.d.ts +1 -1
- package/dist/kernel/web.js +10 -91
- package/dist/kernel/where.js +0 -6
- package/dist/usecase/adminBindings.js +32 -23
- package/dist/usecase/adminClient.js +4 -22
- package/dist/usecase/adminDescriptors.js +2 -9
- package/dist/usecase/generate.js +14 -17
- package/dist/usecase/handlers.js +1 -4
- package/dist/usecase/mcp-media.js +0 -1
- package/dist/usecase/mcp.js +0 -4
- package/dist/usecase/paging.js +1 -3
- package/dist/usecase/publishing.js +20 -11
- package/dist/usecase/rest.js +5 -6
- package/dist/usecase/site.js +0 -1
- package/dist/usecase/stores.js +12 -17
- package/dist/usecase/tool-version.js +0 -3
- package/dist/usecase/translations.js +0 -2
- package/dist/usecase/validation.js +0 -20
- package/docs/examples/README.md +13 -5
- package/docs/examples/app-shell/README.md +91 -12
- package/docs/examples/app-shell/accept.mjs +91 -0
- package/docs/examples/app-shell/gitignore +7 -0
- package/docs/examples/app-shell/package.json +10 -9
- package/docs/examples/app-shell/smoke-kit.mjs +29 -15
- package/docs/examples/app-shell/src/routes.ts +6 -3
- package/docs/examples/app-shell/src/service.ts +2 -1
- package/docs/examples/club-events/README.md +7 -2
- package/docs/examples/club-events/manifests/club-events.yaml +17 -0
- package/docs/examples/club-events/smoke.mjs +7 -1
- package/docs/examples/generated-web/seed.sql +5 -4
- package/docs/examples/purchasing/README.md +12 -3
- package/docs/examples/purchasing/manifests/purchasing.yaml +24 -4
- package/docs/examples/purchasing/smoke.mjs +14 -0
- package/docs/examples/recipes/README.md +5 -3
- package/docs/handbook/cloudflare/media-r2.md +6 -3
- package/docs/handbook/cloudflare/service-entry.md +5 -0
- package/docs/handbook/concepts/lifecycle-and-locales.md +21 -1
- package/docs/handbook/examples/hub.md +1 -1
- package/docs/handbook/guides/admin-ui.md +1 -1
- package/docs/handbook/guides/agent-setup.md +20 -10
- package/docs/handbook/guides/agent-workflow-acceptance.md +225 -105
- package/docs/handbook/guides/local-testing.md +85 -0
- package/docs/handbook/guides/native-admin.md +242 -16
- package/docs/handbook/guides/native-execution.md +10 -8
- package/docs/handbook/guides/public-pages.md +44 -4
- package/docs/handbook/guides/revisions.md +584 -0
- package/docs/handbook/guides/size-and-startup.md +140 -0
- package/docs/handbook/guides/sql-patterns.md +312 -0
- package/docs/handbook/guides/typed-queries.md +146 -3
- package/docs/handbook/navigation.json +20 -0
- package/docs/handbook/reference/admin-descriptors.md +4 -1
- package/docs/handbook/reference/authorization.md +3 -1
- package/docs/handbook/reference/describe.md +42 -0
- package/docs/handbook/reference/diagnostics.md +16 -2
- package/docs/handbook/reference/procedure.md +6 -6
- package/docs/handbook/reference/schema.md +79 -9
- package/docs/handbook/reference/sql.md +65 -0
- package/docs/handbook/reference/surface.md +8 -4
- package/docs/handbook/reference/trigger.md +12 -0
- package/docs/handbook/reference/view.md +11 -3
- package/docs/handbook/releases/index.md +71 -7
- package/docs/handbook/start/agents.md +49 -0
- package/docs/handbook/start/project-and-cli.md +10 -0
- package/docs/handbook/start/quickstart-worker.md +1 -1
- package/docs/skills/develop/SKILL.md +19 -6
- package/docs/skills/integrate/SKILL.md +3 -1
- package/docs/skills/performance/SKILL.md +169 -0
- package/docs/skills/update/SKILL.md +10 -4
- package/docs/upgrade-0.1-to-0.2.md +151 -39
- package/package.json +31 -11
- package/skills/README.md +6 -2
- package/skills/mantle/SKILL.md +53 -120
- package/dist/domain/describe/chunk-ZVXBGP7Y.js +0 -424
- package/skills/mantle/references/local-testing.md +0 -20
- package/skills/mantle/references/web.md +0 -41
- package/skills/mantle/references/website.md +0 -51
|
@@ -195,6 +195,11 @@ export interface SchemaManifestSpec {
|
|
|
195
195
|
* editable in place, and have no publish/unpublish transitions — the
|
|
196
196
|
* admin hides the content-lifecycle chrome for them. */
|
|
197
197
|
readonly lifecycle?: LifecycleMode;
|
|
198
|
+
/** `lifecycle: publishing` options (#1822). `liveEdits: true` lets a caller's generic patch edit a published row in place (an
|
|
199
|
+
* archived one stays draft-only); a published row must still pass `publish`'s checks. Default: generic patches edit drafts only. */
|
|
200
|
+
readonly publishing?: {
|
|
201
|
+
readonly liveEdits?: boolean;
|
|
202
|
+
};
|
|
198
203
|
/** Logical expiry policy. Physical removal requires an explicit sweep. */
|
|
199
204
|
readonly ttl?: {
|
|
200
205
|
readonly field: string;
|
|
@@ -203,6 +208,21 @@ export interface SchemaManifestSpec {
|
|
|
203
208
|
/** The Schema's row template (ADR-0046 amendment): AND-joined `column = auth.uid()` /
|
|
204
209
|
* `column IN auth.user('field')` terms, enforced on every read and write of the Schema. */
|
|
205
210
|
readonly scope?: string;
|
|
211
|
+
/** Data-state invariants (#1822): while a lock's `when` holds for the existing row, a caller's update or delete of it is
|
|
212
|
+
* refused, whatever the caller's role. Only a trusted (system) write bypasses it. */
|
|
213
|
+
readonly lock?: readonly SchemaLock[];
|
|
214
|
+
}
|
|
215
|
+
export declare const LOCK_VERBS: readonly ["update", "delete"];
|
|
216
|
+
export type LockVerb = (typeof LOCK_VERBS)[number];
|
|
217
|
+
export interface SchemaLock {
|
|
218
|
+
/** Unique within the Schema; named by the `kind: "lock"` conflict. */
|
|
219
|
+
readonly name: string;
|
|
220
|
+
readonly on: readonly LockVerb[];
|
|
221
|
+
/** A SQL boolean over the existing row: its columns, comparisons, AND/OR/NOT, IS [NOT] NULL and [NOT] EXISTS over declared
|
|
222
|
+
* Schemas. True (or NULL) means locked. */
|
|
223
|
+
readonly when: string;
|
|
224
|
+
/** Static text the refusal carries. */
|
|
225
|
+
readonly message: string;
|
|
206
226
|
}
|
|
207
227
|
export interface TranslatesBinding {
|
|
208
228
|
/** Name of the parent Schema this translation table joins to. Must
|
|
@@ -336,10 +356,28 @@ export interface HandlerRefBinding {
|
|
|
336
356
|
readonly ref: string;
|
|
337
357
|
}
|
|
338
358
|
/** One or more write statements (`INSERT`, `UPDATE`, `DELETE`), applied as
|
|
339
|
-
* one batch. Reads `input.<name>`, `auth.uid()`, `auth.role()`, `now()`.
|
|
359
|
+
* one batch. Reads `input.<name>`, `auth.uid()`, `auth.role()`, `now()`.
|
|
360
|
+
* Authored as `sql` (the program) or as `steps`, one statement each; the parser
|
|
361
|
+
* joins steps into `sql`, so everything that reads the program reads `sql`. */
|
|
340
362
|
export interface HandlerSqlBinding {
|
|
341
363
|
readonly sql: string;
|
|
364
|
+
/** Present when authored as `handler.steps` (ADR-0034 decision 4, #1874): statement i of the program is step i. */
|
|
365
|
+
readonly steps?: readonly HandlerStep[];
|
|
342
366
|
}
|
|
367
|
+
/** One statement of a `steps` program. `onNoRows: conflict`: a set-op write that writes no row is
|
|
368
|
+
* `CONFLICT` kind "row" and the whole program rolls back. */
|
|
369
|
+
export interface HandlerStep {
|
|
370
|
+
readonly sql: string;
|
|
371
|
+
readonly onNoRows?: "conflict";
|
|
372
|
+
}
|
|
373
|
+
export declare const HANDLER_STEP_KEYS: readonly ["sql", "onNoRows"];
|
|
374
|
+
/** The program `steps` compile as: the statements in order, each on its own lines. `lines[i]` is the 0-based line step i starts
|
|
375
|
+
* on, so a diagnostic in the program points back into its step. A step's own trailing `;` is dropped; after a step ending in a
|
|
376
|
+
* `--` comment the separator goes on the next line, where the comment cannot swallow it. */
|
|
377
|
+
export declare function stepProgram(steps: readonly HandlerStep[]): {
|
|
378
|
+
readonly sql: string;
|
|
379
|
+
readonly lines: readonly number[];
|
|
380
|
+
};
|
|
343
381
|
/** Closed predicate vocabulary. `ctx.user` and `ctx.auth` are bare
|
|
344
382
|
* strings; `ctx.admin` and `ctx.auth.scope` carry scalar data under
|
|
345
383
|
* literal object keys.
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
* The sealed plan (ADR-0032 decision 5, ADR-0034): what the CLI compiles from the manifests and Core executes.
|
|
3
3
|
* Every SQL source is already IR here, so no Worker parses SQL. Pure types and constants.
|
|
4
4
|
*/
|
|
5
|
-
import type { AuthorizationRequirements, JsonSchema, LocalizedText, ProcedureMcpAnnotations, ProcedureTarget, TriggerSource } from "./ManifestGrammar.js";
|
|
6
|
-
import type { SqlNode, SqlPlan } from "./SqlIr.js";
|
|
5
|
+
import type { AuthorizationRequirements, HandlerStep, JsonSchema, LocalizedText, ProcedureMcpAnnotations, ProcedureTarget, TriggerSource } from "./ManifestGrammar.js";
|
|
6
|
+
import type { SqlLock, SqlNode, SqlPlan } from "./SqlIr.js";
|
|
7
7
|
import type { UserScope, UserFieldSpec } from "./UserFields.js";
|
|
8
8
|
export declare const RUNTIME_PLAN_VERSION: 6;
|
|
9
9
|
/** A Schema as storage and Store see it. Keys of `fields` and `names` are lower case: SQL folds unquoted identifiers. */
|
|
@@ -20,6 +20,8 @@ export interface PlanSchema {
|
|
|
20
20
|
readonly ttl?: string;
|
|
21
21
|
readonly ttlSeconds?: number;
|
|
22
22
|
readonly publishing?: boolean;
|
|
23
|
+
/** `spec.publishing.liveEdits` (#1822): a caller's generic patch may edit a non-draft row in place. */
|
|
24
|
+
readonly liveEdits?: true;
|
|
23
25
|
/** column -> Mantle type: text integer real bool json timestamptz date numeric(p,s) geo */
|
|
24
26
|
readonly fields: Readonly<Record<string, string>>;
|
|
25
27
|
/** lower-cased column -> the name the JSON Schema declares */
|
|
@@ -28,6 +30,8 @@ export interface PlanSchema {
|
|
|
28
30
|
readonly schema: JsonSchema;
|
|
29
31
|
/** Boolean expressions over the row's own columns, as IR. */
|
|
30
32
|
readonly checks?: readonly SqlNode[];
|
|
33
|
+
/** `spec.lock` (#1822): each `when` as IR, its subqueries reading stored rows. A caller's update or delete gets `AND NOT (when)`. */
|
|
34
|
+
readonly locks?: readonly SqlLock[];
|
|
31
35
|
/** A translation publishes only once the parent entry that shares `on` is published (ADR-0010). Names as declared. */
|
|
32
36
|
readonly translates?: {
|
|
33
37
|
readonly parent: string;
|
|
@@ -75,12 +79,14 @@ export interface PlanProcedure {
|
|
|
75
79
|
readonly requires?: AuthorizationRequirements;
|
|
76
80
|
readonly target?: ProcedureTarget;
|
|
77
81
|
readonly mcp?: ProcedureMcpAnnotations;
|
|
78
|
-
/** An inline handler carries its SQL as authored
|
|
82
|
+
/** An inline handler carries its SQL (`source`: as authored, or its `steps` joined), which Admin shows; the IR is what runs.
|
|
83
|
+
* `steps` is the authored form when the handler was written as steps (#1874): statement i is step i. */
|
|
79
84
|
readonly handler: {
|
|
80
85
|
readonly ref: string;
|
|
81
86
|
} | {
|
|
82
87
|
readonly sql: SqlPlan;
|
|
83
88
|
readonly source: string;
|
|
89
|
+
readonly steps?: readonly HandlerStep[];
|
|
84
90
|
};
|
|
85
91
|
}
|
|
86
92
|
export interface PlanTrigger {
|
|
@@ -97,6 +103,8 @@ export interface LoweredStatement {
|
|
|
97
103
|
readonly kind: "read" | "row" | "set";
|
|
98
104
|
readonly schema?: string;
|
|
99
105
|
readonly verb?: "insert" | "update" | "delete";
|
|
106
|
+
/** A set op whose step says `onNoRows: conflict`: writing no row is CONFLICT (#1874). Omitted otherwise. */
|
|
107
|
+
readonly onNoRows?: "conflict";
|
|
100
108
|
/** Omitted when false. */
|
|
101
109
|
readonly hooked?: true;
|
|
102
110
|
/** Omitted when false. */
|
|
@@ -105,6 +113,11 @@ export interface LoweredStatement {
|
|
|
105
113
|
readonly returns?: true;
|
|
106
114
|
/** A write's table, lower case (D1's unique-conflict op mapping). */
|
|
107
115
|
readonly target?: string;
|
|
116
|
+
/** A row write a Schema lock guards: the read that tells a lock from the row conflict (#1822). */
|
|
117
|
+
readonly probe?: {
|
|
118
|
+
readonly sql: string;
|
|
119
|
+
readonly binds: LoweredStatement["binds"];
|
|
120
|
+
};
|
|
108
121
|
}
|
|
109
122
|
/** A paged statement of a View under one request shape, printed. The page size is a bind (`limit`), so one statement serves every page size. */
|
|
110
123
|
export interface LoweredPage {
|
|
@@ -34,6 +34,8 @@ export interface SqlSchemaDef {
|
|
|
34
34
|
/** lower-cased column -> the name the JSON Schema declares (the plan has it; `notNullColumns` reads it with `schema`) */
|
|
35
35
|
readonly names?: Readonly<Record<string, string>>;
|
|
36
36
|
/** the Schema's JSON Schema, of which storage reads only what is required and nullable */
|
|
37
|
+
/** `spec.lock` (#1822): `when` is the IR of its boolean over the existing row, whose subqueries read stored rows (`system`). */
|
|
38
|
+
readonly locks?: readonly SqlLock[];
|
|
37
39
|
readonly schema?: {
|
|
38
40
|
readonly required?: readonly string[];
|
|
39
41
|
readonly properties?: Readonly<Record<string, {
|
|
@@ -46,6 +48,12 @@ export interface SqlSchemaDef {
|
|
|
46
48
|
}>>;
|
|
47
49
|
};
|
|
48
50
|
}
|
|
51
|
+
export interface SqlLock {
|
|
52
|
+
readonly name: string;
|
|
53
|
+
readonly on: readonly ("update" | "delete")[];
|
|
54
|
+
readonly when: SqlNode;
|
|
55
|
+
readonly message: string;
|
|
56
|
+
}
|
|
49
57
|
/**
|
|
50
58
|
* What the allowlist reads off every Schema of a context: computed from `schemas` (`schemaColumns`), once per plan by a caller that
|
|
51
59
|
* checks many programs against one plan, or per program when absent.
|
|
@@ -101,6 +109,8 @@ export declare function storageColumns(s: {
|
|
|
101
109
|
readonly scope?: string;
|
|
102
110
|
readonly publishing?: boolean;
|
|
103
111
|
}): Map<string, string>;
|
|
112
|
+
/** The aggregate functions either dialect's SQL may call: outside a window and without GROUP BY, one makes a select return one row even over none. */
|
|
113
|
+
export declare const AGGREGATES: ReadonlySet<string>;
|
|
104
114
|
/** The native columns storage declares NOT NULL (`status` only on a publishing Schema, the only one that has it); `author_id` is nullable. */
|
|
105
115
|
export declare const NATIVE_NOT_NULL: ReadonlySet<string>;
|
|
106
116
|
/** Each native field a manifest names (in an index, say) -> its storage column, which SQL names. */
|
|
@@ -125,3 +135,25 @@ export declare const CHECK_FUNCTIONS: ReadonlyMap<string, {
|
|
|
125
135
|
* its own way. Operand types beyond the functions' arguments are the database's to check at boot.
|
|
126
136
|
*/
|
|
127
137
|
export declare function checkShapeProblem(v: unknown, columns: ReadonlyMap<string, string>): string | undefined;
|
|
138
|
+
/**
|
|
139
|
+
* Why a Schema lock's `when` (the compiled WHERE of a read of `table`) is outside the lock subset, or undefined (#1822). It names
|
|
140
|
+
* the locked row's columns (unqualified, or qualified with the Schema's name) through comparisons, AND/OR/NOT and IS [NOT] NULL,
|
|
141
|
+
* and `[NOT] EXISTS (SELECT … FROM <declared Schema> [alias] WHERE …)`. Inside a subquery every column is qualified, so an
|
|
142
|
+
* unqualified name can never silently read the subquery's table instead of the locked row. No function call (`now()`, `auth.*`,
|
|
143
|
+
* aggregates, windows), cast, parameter or write.
|
|
144
|
+
*/
|
|
145
|
+
export declare function lockShapeProblem(where: SqlNode, schemas: Readonly<Record<string, SqlSchemaDef>>, table: string): string | undefined;
|
|
146
|
+
/**
|
|
147
|
+
* Whether every EXISTS of a lock (already `lockShapeProblem`-free) is index-served (#1822): its equality predicates (top-level AND
|
|
148
|
+
* terms `col = <constant or outer column>` on the subquery's own Schema) must include the first column of a declared index, unique
|
|
149
|
+
* index or `id` of that Schema. Each lock runs on every guarded write, so an unindexed EXISTS would scan its table each time.
|
|
150
|
+
* Returns the first unproved subquery: its Schema and the columns an index could lead with.
|
|
151
|
+
*/
|
|
152
|
+
export declare function lockIndexProblem(where: SqlNode, schemas: Readonly<Record<string, SqlSchemaDef & {
|
|
153
|
+
readonly unique?: readonly (readonly string[])[];
|
|
154
|
+
readonly indexes?: readonly (readonly string[])[];
|
|
155
|
+
}>>): {
|
|
156
|
+
schema: string;
|
|
157
|
+
columns: string[];
|
|
158
|
+
or?: true;
|
|
159
|
+
} | undefined;
|
|
@@ -25,7 +25,7 @@ export type Phase = "validate" | "test" | "boot" | "runtime";
|
|
|
25
25
|
* Single source of truth: the const array drives `DiagnosticCode`
|
|
26
26
|
* (type), so adding a code is one edit.
|
|
27
27
|
*/
|
|
28
|
-
export declare const DIAGNOSTIC_CODES: readonly ["AUTH_ROLE_REMOVED", "USER_FIELD_VALUES_UNENUMERATED", "USER_FIELD_INVALID", "USER_FIELD_CONFLICT", "USER_FIELD_POSITION", "USER_REF_SCOPE_ONLY", "USER_SCOPE_PUBLIC_ANON_EMPTY", "RESOURCE_EXHAUSTED", "RESOURCE_UNAVAILABLE", "RATE_LIMITED", "OUTCOME_UNKNOWN", "PARTIAL_FAILURE", "PRECONDITION_FAILED", "INVALID_MANIFEST_ENVELOPE", "DUPLICATE_NAME", "VIEW_INPUT_INVALID_SHAPE", "VIEW_INPUT_RESERVED_NAME", "VIEW_CACHE_INVALID", "VIEW_UI_INVALID", "REQUIRED_FIELD_UNKNOWN", "INVALID_PATTERN", "JSON_SCHEMA_UNSUPPORTED", "JSON_SCHEMA_REF_INVALID", "JSON_SCHEMA_LIMIT_EXCEEDED", "AUTH_PREDICATE_NOT_IN_ENUM", "GUARD_PROCEDURE_UNKNOWN", "GUARD_SELF_REFERENCE", "GUARD_PROCEDURE_NOT_REF", "GUARD_CHAIN_NOT_ALLOWED", "SCHEMA_INDEX_INVALID", "SCHEMA_INDEX_FIELD_UNKNOWN", "UNIQUE_INDEX_FIELD_UNKNOWN", "SCHEMA_SEARCH_INVALID", "SCHEMA_SEARCH_FIELD_UNKNOWN", "SCHEMA_TTL_INVALID", "SCHEMA_UI_INVALID", "SCHEMA_NAME_CASE_COLLISION", "SCHEMA_READER_NAME_COLLISION", "FIELD_NAME_CASE_COLLISION", "MANIFEST_ROOT_NOT_FOUND", "MANIFEST_READ_FAILED", "GENERATE_FEATURE_DEPENDENCY_MISSING", "SQL_SYNTAX", "SQL_UNSUPPORTED", "SQL_FUNCTION", "SQL_RELATION", "SQL_COLUMN", "SQL_WRITE", "SQL_SHAPE", "SQL_TYPE", "FIXTURE_SCHEMA_VIOLATION", "HANDLER_NOT_REGISTERED", "HANDLER_NOT_DECLARED", "PLAN_FINGERPRINT_MISMATCH", "SCHEDULE_NOT_WIRED", "STORAGE_CHANGE_BLOCKED", "STORAGE_TABLE_NOT_OWNED", "INVOCATION_DEPTH_EXCEEDED", "TRIGGER_TARGET_PROCEDURE_UNKNOWN", "SCHEDULE_INPUT_INVALID", "SCHEDULE_AUTH_INVALID", "TRIGGER_PATH_COLLISION", "TRIGGER_PATH_INVALID", "MCP_TOOL_NAME_COLLISION", "MCP_TOOL_DESCRIPTION_MISSING", "MCP_TOOL_INPUT_UNION_AMBIGUOUS", "MCP_TOOL_INPUT_UNBOUNDED", "MANTLE_REF_INVALID", "PROCEDURE_TARGET_INVALID", "PROCEDURE_NOT_FOUND", "NOT_FOUND", "METHOD_NOT_ALLOWED", "LIFECYCLE_SCHEMA_UNKNOWN", "LIFECYCLE_HOOK_REJECTED", "LIFECYCLE_TARGET_NOT_REF", "SCHEMA_LOCALIZED_REQUIRES_SITE_LOCALES", "TRANSLATES_PARENT_UNKNOWN", "TRANSLATES_REQUIRES_LOCALIZED", "TRANSLATES_REQUIRES_CONTENT_FIELD", "TRANSLATES_FIELD_NOT_IN_PARENT", "TRANSLATES_FIELD_NOT_IN_CHILD", "TRANSLATES_PARENT_IS_LOCALIZED", "SCHEMA_TTL_TRANSLATION_UNSUPPORTED", "INPUT_VALIDATION_FAILED", "UNAUTHENTICATED", "AUTH_DENIED", "ENTITLEMENT_REQUIRED", "CONFLICT", "DISPATCHER_NOT_BUILT", "INTERNAL_ERROR", "OUTPUT_VALIDATION_FAILED", "INVALID_LOCALE", "MEDIA_NOT_CONFIGURED", "SITE_NOT_CONFIGURED", "MEDIA_UPLOAD_EXPIRED", "MEDIA_OBJECT_NOT_FOUND", "MEDIA_MIME_REJECTED", "MEDIA_SIZE_EXCEEDED", "MEDIA_SVG_REJECTED", "MEDIA_CHECKSUM_MISMATCH", "MEDIA_PURPOSE_REJECTED", "MEDIA_VARIANTS_INCOMPLETE", "MEDIA_VARIANT_SIZE_EXCEEDED", "MEDIA_VARIANTS_SUSPICIOUS_SIZE", "MEDIA_ASSET_NOT_FOUND"];
|
|
28
|
+
export declare const DIAGNOSTIC_CODES: readonly ["AUTH_ROLE_REMOVED", "USER_FIELD_VALUES_UNENUMERATED", "USER_FIELD_INVALID", "USER_FIELD_CONFLICT", "USER_FIELD_POSITION", "USER_REF_SCOPE_ONLY", "USER_SCOPE_PUBLIC_ANON_EMPTY", "RESOURCE_EXHAUSTED", "RESOURCE_UNAVAILABLE", "RATE_LIMITED", "OUTCOME_UNKNOWN", "PARTIAL_FAILURE", "PRECONDITION_FAILED", "INVALID_MANIFEST_ENVELOPE", "DUPLICATE_NAME", "VIEW_INPUT_INVALID_SHAPE", "VIEW_INPUT_RESERVED_NAME", "VIEW_CACHE_INVALID", "VIEW_UI_INVALID", "REQUIRED_FIELD_UNKNOWN", "INVALID_PATTERN", "JSON_SCHEMA_UNSUPPORTED", "JSON_SCHEMA_REF_INVALID", "JSON_SCHEMA_LIMIT_EXCEEDED", "AUTH_PREDICATE_NOT_IN_ENUM", "GUARD_PROCEDURE_UNKNOWN", "GUARD_SELF_REFERENCE", "GUARD_PROCEDURE_NOT_REF", "GUARD_CHAIN_NOT_ALLOWED", "SCHEMA_INDEX_INVALID", "SCHEMA_INDEX_FIELD_UNKNOWN", "UNIQUE_INDEX_FIELD_UNKNOWN", "SCHEMA_SEARCH_INVALID", "SCHEMA_SEARCH_FIELD_UNKNOWN", "SCHEMA_TTL_INVALID", "SCHEMA_LOCK_INVALID", "LOCK_INDEX_MISSING", "SCHEMA_PUBLISHING_INVALID", "SCHEMA_UI_INVALID", "SCHEMA_NAME_CASE_COLLISION", "SCHEMA_READER_NAME_COLLISION", "FIELD_NAME_CASE_COLLISION", "MANIFEST_ROOT_NOT_FOUND", "MANIFEST_READ_FAILED", "GENERATE_FEATURE_DEPENDENCY_MISSING", "SQL_SYNTAX", "SQL_UNSUPPORTED", "SQL_FUNCTION", "SQL_RELATION", "SQL_COLUMN", "SQL_WRITE", "SQL_SHAPE", "SQL_TYPE", "FIXTURE_SCHEMA_VIOLATION", "HANDLER_NOT_REGISTERED", "HANDLER_NOT_DECLARED", "PLAN_FINGERPRINT_MISMATCH", "SCHEDULE_NOT_WIRED", "STORAGE_CHANGE_BLOCKED", "STORAGE_TABLE_NOT_OWNED", "INVOCATION_DEPTH_EXCEEDED", "TRIGGER_TARGET_PROCEDURE_UNKNOWN", "SCHEDULE_INPUT_INVALID", "SCHEDULE_AUTH_INVALID", "TRIGGER_PATH_COLLISION", "TRIGGER_PATH_INVALID", "MCP_TOOL_NAME_COLLISION", "MCP_TOOL_DESCRIPTION_MISSING", "MCP_TOOL_INPUT_UNION_AMBIGUOUS", "MCP_TOOL_INPUT_UNBOUNDED", "MANTLE_REF_INVALID", "PROCEDURE_TARGET_INVALID", "PROCEDURE_NOT_FOUND", "NOT_FOUND", "METHOD_NOT_ALLOWED", "LIFECYCLE_SCHEMA_UNKNOWN", "LIFECYCLE_HOOK_REJECTED", "LIFECYCLE_TARGET_NOT_REF", "SCHEMA_LOCALIZED_REQUIRES_SITE_LOCALES", "TRANSLATES_PARENT_UNKNOWN", "TRANSLATES_REQUIRES_LOCALIZED", "TRANSLATES_REQUIRES_CONTENT_FIELD", "TRANSLATES_FIELD_NOT_IN_PARENT", "TRANSLATES_FIELD_NOT_IN_CHILD", "TRANSLATES_PARENT_IS_LOCALIZED", "SCHEMA_TTL_TRANSLATION_UNSUPPORTED", "INPUT_VALIDATION_FAILED", "UNAUTHENTICATED", "AUTH_DENIED", "ENTITLEMENT_REQUIRED", "CONFLICT", "DISPATCHER_NOT_BUILT", "INTERNAL_ERROR", "OUTPUT_VALIDATION_FAILED", "INVALID_LOCALE", "MEDIA_NOT_CONFIGURED", "SITE_NOT_CONFIGURED", "MEDIA_UPLOAD_EXPIRED", "MEDIA_OBJECT_NOT_FOUND", "MEDIA_MIME_REJECTED", "MEDIA_SIZE_EXCEEDED", "MEDIA_SVG_REJECTED", "MEDIA_CHECKSUM_MISMATCH", "MEDIA_PURPOSE_REJECTED", "MEDIA_VARIANTS_INCOMPLETE", "MEDIA_VARIANT_SIZE_EXCEEDED", "MEDIA_VARIANTS_SUSPICIOUS_SIZE", "MEDIA_ASSET_NOT_FOUND"];
|
|
29
29
|
export type DiagnosticCode = (typeof DIAGNOSTIC_CODES)[number];
|
|
30
30
|
export interface SourcePosition {
|
|
31
31
|
readonly line: number;
|
package/dist/bun/assets.js
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
/** Bun owns files; no SQLite, runtime or compiler import enters this optional host reader. */
|
|
2
1
|
import { realpath, stat } from "node:fs/promises";
|
|
3
2
|
import { resolve, sep } from "node:path";
|
|
4
|
-
/** Native file response, or null for missing or invalid paths. */
|
|
5
3
|
export function bunAdminAssets(root) {
|
|
6
4
|
const base = resolve(root);
|
|
7
5
|
return async (path) => {
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
/** Selected Admin orders mirror the existing UI's indexed, required fields and native controls. */
|
|
2
1
|
import { adminIndexColumns, NATIVE_NOT_NULL, notNullColumns } from "../build/compiler.js";
|
|
3
2
|
import { dialect as sqlite } from "../kernel/dialect/sqlite.js";
|
|
4
3
|
import { dialect as postgres } from "../kernel/dialect/postgres.js";
|
|
@@ -12,7 +11,6 @@ export function adminOrder(schema) {
|
|
|
12
11
|
return kind ? [[f, [kind, !NATIVE_NOT_NULL.has(f) && !notNull.has(f)]]] : [];
|
|
13
12
|
}));
|
|
14
13
|
}
|
|
15
|
-
/** Deployment-only indexes; no request attempts to converge storage. */
|
|
16
14
|
export function adminIndexes(schemas, isSqlite) {
|
|
17
15
|
const d = isSqlite ? sqlite : postgres;
|
|
18
16
|
return Object.values(schemas).flatMap(s => ["created_at", "updated_at", ...(s.publishing ? ["status"] : [])].flatMap(field => [[], ...(s.scope ? [[s.scope]] : [])].flatMap(prefix => {
|
package/dist/domain/columns.js
CHANGED
|
@@ -1,55 +1,42 @@
|
|
|
1
|
-
|
|
2
|
-
import { viewOutputs } from "../build/compiler.js";
|
|
3
|
-
/** A column's declared type, including the system version and timestamps. @internal */
|
|
4
|
-
/** A JSON Schema `readOnly` property is server-maintained (counters, totals): Admin's generic writes never set it. */
|
|
1
|
+
import { jsonOutputs, viewOutputs } from "../build/compiler.js";
|
|
5
2
|
export const serverOwned = (schema, column) => Object.entries(schema.properties ?? {}).some(([name, property]) => name.toLowerCase() === column && property?.readOnly === true);
|
|
6
3
|
export const declaredType = (fields, column) => fields[column] ?? (column === "version" ? "integer" : column === "created_at" || column === "updated_at" || column === "published_at" ? "timestamptz" : undefined);
|
|
7
|
-
|
|
4
|
+
const computedJson = (plan, view, key) => jsonOutputs(plan.views[view]).has(key);
|
|
8
5
|
export function outputType(plan, view, key) {
|
|
9
6
|
const columns = plan.views[view]?.columns;
|
|
10
7
|
const field = columns && Object.hasOwn(columns, key) ? columns[key] : undefined;
|
|
11
8
|
const schema = field && plan.schemas[field.schema];
|
|
12
|
-
return schema
|
|
9
|
+
return schema ? declaredType(schema.fields, field.field) : computedJson(plan, view, key) ? "json" : undefined;
|
|
13
10
|
}
|
|
14
|
-
/** Transport lineage excludes expressions/aggregates; existing temporal SQL formatting is retained. */
|
|
15
11
|
export function boundaryType(plan, view, key) {
|
|
16
12
|
const field = viewOutputs(plan.views[view], plan.schemas, new Map(), false, false).columns[key];
|
|
17
13
|
const type = outputType(plan, view, key);
|
|
18
|
-
return field || type === "date" || type === "timestamptz" ? type : undefined;
|
|
14
|
+
return field || type === "date" || type === "timestamptz" || computedJson(plan, view, key) ? type : undefined;
|
|
19
15
|
}
|
|
20
|
-
/** Declared output lineage only; computed columns retain their native values. */
|
|
21
16
|
export function outputConversions(plan, view, target) {
|
|
22
17
|
const postgres = target.endsWith("postgres");
|
|
23
18
|
const columns = viewOutputs(plan.views[view], plan.schemas, new Map(), false, false).columns;
|
|
24
|
-
return Object.keys(columns).flatMap(key => {
|
|
19
|
+
return [...Object.keys(columns), ...jsonOutputs(plan.views[view])].flatMap(key => {
|
|
25
20
|
const type = outputType(plan, view, key);
|
|
26
21
|
return conversion(key, type, !postgres);
|
|
27
22
|
});
|
|
28
23
|
}
|
|
29
|
-
/** Shared static conversion recipe for Views and Admin collections. */
|
|
30
24
|
export function conversion(key, type, sqlite) {
|
|
31
25
|
return type && ["integer", "int8", "int4"].includes(type) ? [[key, "int"]]
|
|
32
26
|
: sqlite && (type === "json" || type === "bool") ? [[key, type]] : [];
|
|
33
27
|
}
|
|
34
|
-
|
|
35
|
-
export function wireType(type) {
|
|
28
|
+
export function wireType(type, notNull = false) {
|
|
36
29
|
const value = !type ? "unknown" : ["integer", "int8", "int4"].includes(type) ? "number | string"
|
|
37
30
|
: scalarType(type);
|
|
38
|
-
return value === "unknown" ? value : `${value} | null`;
|
|
31
|
+
return value === "unknown" || notNull ? value : `${value} | null`;
|
|
39
32
|
}
|
|
40
33
|
const scalarType = (type) => type === "bool" ? "boolean" : ["integer", "int4", "int8", "real", "float8"].includes(type) ? "number" : type === "json" ? "unknown" : type === "geo" ? "{lat:number;lng:number}" : "string";
|
|
41
|
-
/**
|
|
42
|
-
* The driver-native value a column of this type comes back as, `| null` unless `notNull`; declared timestamps and dates arrive as the
|
|
43
|
-
* SQL's wire-form text. A column with no declared type (a computed output) is `unknown`, which already includes null. @internal
|
|
44
|
-
*/
|
|
45
34
|
export function nativeType(type, sqlite, notNull = false) {
|
|
46
35
|
const native = !type ? "unknown" : ["date", "timestamptz"].includes(type) ? "string" : sqlite
|
|
47
36
|
? type === "bool" ? "number" : type === "json" ? "string" : scalarType(type)
|
|
48
37
|
: ["integer", "int8"].includes(type) ? "number | string | bigint" : scalarType(type);
|
|
49
38
|
return notNull || native === "unknown" ? native : `${native} | null`;
|
|
50
39
|
}
|
|
51
|
-
/** The value a caller of the typed Store passes for a column of this type. JSON is an object or array (the Store tells it by its JS type, so a bare string would be bound as text). @internal */
|
|
52
40
|
export const inputType = (type) => type === "timestamptz" ? "string | Date" : type === "json" ? "object" : scalarType(type);
|
|
53
|
-
/** Wrap only a selected transport page. */
|
|
54
41
|
export const boundaryPage = (page, fields) => fields.length
|
|
55
42
|
? `(db, caller, input, paging) => ${page}(db, caller, input, paging).then(page => ({ ...page, rows: wireRows(page.rows, ${JSON.stringify(fields)}) }))` : page;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function resolveLocalizedText(value,preferred,canonical2){if(value==null)return null;if(typeof value=="string")return value;if(Object.prototype.hasOwnProperty.call(value,preferred))return value[preferred];if(canonical2&&Object.prototype.hasOwnProperty.call(value,canonical2))return value[canonical2];let firstKey=Object.keys(value)[0];return firstKey!==void 0?value[firstKey]:null}var INPUT_RULE_KEYWORDS=["dependentRequired","anyOf","if","then","else"];function lookupLocalRef(root,ref){if(typeof ref!="string"||!ref.startsWith("#/"))return;let value=root;try{for(let key of decodeURIComponent(ref.slice(2)).split("/").map(key2=>key2.replace(/~1/g,"/").replace(/~0/g,"~")))value=value&&typeof value=="object"&&Object.hasOwn(value,key)?value[key]:void 0}catch{return}return value&&typeof value=="object"?value:void 0}function rootRefChain(input){let chain=[];for(let schema=input;schema!==void 0;schema=lookupLocalRef(input,schema.$ref)){if(chain.includes(schema))return;if(chain.push(schema),schema.$ref===void 0)return chain}}function mcpToolNameSegment(name){return name.toLowerCase().replace(/-/g,"_")}function toolTitle(name){let words=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[-_.\s]+/g," ").trim().toLowerCase();return words.charAt(0).toUpperCase()+words.slice(1)}var viewAnnotations={readOnlyHint:!0,destructiveHint:!1};function procedureAnnotations(p){let readOnlyHint=p.mcp?.readOnlyHint??!1;return{readOnlyHint,destructiveHint:!readOnlyHint&&("ref"in p.handler||overwrites(p.handler.sql.stmts)),...p.mcp}}var overwrites=node=>!!node&&typeof node=="object"&&("DeleteStmt"in node||"UpdateStmt"in node||node.onConflictClause?.action==="ONCONFLICT_UPDATE"||Object.values(node).some(overwrites));function mcpTools(plan,surface,locale="en"){let text=t=>resolveLocalizedText(t,locale,"en")??void 0,tools=new Map,add=tool=>{let prior=tools.get(tool.name);if(prior&&(prior.kind!==tool.kind||prior.source!==tool.source))throw new TypeError(`MCP tool '${tool.name}' comes from both '${prior.source}' and '${tool.source}'.`);tools.set(tool.name,tool)};for(let t of Object.values(plan.triggers)){if(t.source.kind!=="mcp"||t.source.surface!==surface)continue;let p=plan.procedures[t.procedure],title=text(p.title);add({name:mcpToolNameSegment(t.procedure),kind:"procedure",source:t.procedure,title:title??toolTitle(t.procedure),description:text(p.description)??title??t.procedure,inputSchema:p.input,...p.output.type==="object"?{outputSchema:p.output}:{},annotations:procedureAnnotations(p),requires:p.requires})}for(let[name,v]of Object.entries(plan.views)){if(v.surface!==surface)continue;let chain=(v.input?rootRefChain(v.input)??[v.input]:[]).reverse(),props=Object.assign({},...chain.map(s=>s.properties??{})),required=[...new Set(chain.flatMap(s=>s.required??[]))];if("limit"in props||"cursor"in props)throw new TypeError(`View '${name}' declares an input named limit or cursor; the MCP tool reserves both for paging.`);let rules=chain.map(s=>Object.fromEntries(INPUT_RULE_KEYWORDS.flatMap(k=>s[k]===void 0?[]:[[k,s[k]]]))).filter(r=>Object.keys(r).length),defs=v.input?referencedDefs(v.input,props):{},title=text(v.title);add({name:mcpToolNameSegment(name),kind:"view",source:name,title:title??toolTitle(name),description:text(v.description)??title??name,inputSchema:{type:"object",properties:{...props,limit:{type:"integer",minimum:1,maximum:500},cursor:{type:"string"}},...required.length?{required}:{},...rules.length>1?{allOf:rules}:rules[0],...Object.keys(defs).length?{$defs:defs}:{}},annotations:viewAnnotations,requires:v.requires})}return[...tools.values()]}function referencedDefs(root,node,found={}){if(!node||typeof node!="object")return found;let ref=node.$ref,[head,segment]=typeof ref=="string"&&ref.startsWith("#/")?decoded(ref.slice(2)).split("/"):[],key=head==="$defs"?segment?.replace(/~1/g,"/").replace(/~0/g,"~"):void 0;key!==void 0&&!Object.hasOwn(found,key)&&root.$defs&&Object.hasOwn(root.$defs,key)&&(found[key]=root.$defs[key],referencedDefs(root,found[key],found));for(let child of Object.values(node))referencedDefs(root,child,found);return found}var decoded=pointer=>{try{return decodeURIComponent(pointer)}catch{return""}};function canonical(v){return Array.isArray(v)?`[${v.map(canonical).join(",")}]`:v&&typeof v=="object"?`{${Object.keys(v).sort().filter(k=>v[k]!==void 0).map(k=>`${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`:JSON.stringify(v)??"null"}var publishingTransitions=[["publish",["draft"],"published"],["unpublish",["published","archived"],"draft"],["archive",["draft","published"],"archived"]];var publishingInput={type:"object",properties:{id:{type:"string",minLength:1},expectedVersion:{type:"integer",minimum:1}},required:["id","expectedVersion"],additionalProperties:!1};function mediaDefinitions(){let define=(name,description,inputSchema,action,readOnlyHint=!1)=>({name,description,inputSchema,action,annotations:{readOnlyHint,destructiveHint:action==="delete",openWorldHint:!0}}),string={type:"string"},texts={alt:{type:"string",maxLength:1e3},caption:{type:"string",maxLength:1e3}},input=(properties,required=[])=>({type:"object",properties,required,additionalProperties:!1});return[define("get_media_upload_policy","Read declared image purpose MIME slots and byte caps before preparing variants or requesting an upload. Optimization runs locally, never in the host.",input({}),"policy",!0),define("create_media_upload","Create short-lived PUT capabilities for image variants. Read site media purpose policy first; optimize images locally. Obtain attachment bytes yourself, then PUT each variant with its requiredHeaders and call commit_media_upload. Never store upload URLs as published images or ask the user to run terminal commands.",input({filename:{type:"string",maxLength:255},purpose:string,variants:{type:"array",minItems:1,items:input({mimeType:string,byteSize:{type:"integer",minimum:1},role:{type:"string",enum:["primary","alternate","fallback"]}},["mimeType","byteSize","role"])},...texts},["filename","purpose","variants"]),"create"),define("commit_media_upload","Verify all uploaded variants and commit one permanent media asset. Store the returned asset id in fields referencing media_assets.id, never a temporary upload URL. Unknown or expired upload groups require a new create_media_upload.",input({uploadGroupId:string,...texts},["uploadGroupId"]),"commit"),define("list_media_assets","List committed image assets, newest first, with their permanent variants and alt/caption. Search matches id, alt or caption; reuse only a returned cursor.",input({limit:{type:"integer",minimum:1,maximum:500},cursor:string,search:string}),"list",!0),define("get_media_asset","Read one committed media asset and its permanent variant URLs.",input({id:string},["id"]),"get",!0),define("update_media_asset","Update committed asset alt or caption; omitted fields remain unchanged and empty strings clear text.",input({id:string,...texts},["id"]),"update"),define("delete_media_asset","Delete an asset's objects and library record. Check application references first. A partial failure can be retried using the same id.",input({id:string},["id"]),"delete")]}var ADMIN_API_BASE="/admin/api",pathTemplate=path=>path.replace(/\{([^}]+)\}/g,":$1"),routePath=template=>template.split("/").map(segment=>segment.startsWith(":")?`{${segment.slice(1)}}`:segment).join("/");function routeSource(template,base="",suffix=!1){let keys=[],path=template.split("/").map(segment=>{let rest=suffix?/^\{([a-zA-Z]\w*)\*\}$/.exec(segment):null,one=/^\{([^}]+)\}$/.exec(segment);return rest||one?(keys.push((rest??one)[1]),rest?"(.*)":"([^/]+)"):encodeURIComponent(segment).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}).join("/");return{source:`^${base}${path}/?$`,keys}}function canonicalPath(pathname){try{return pathname.split("/").map(segment=>encodeURIComponent(decodeURIComponent(segment))).join("/")}catch{return}}var isParameter=segment=>/^\{[^}]+\}$/.test(segment);function routeOrder(a,b){let x=a.split("/"),y=b.split("/"),count=segments=>segments.filter(isParameter).length;if(count(x)!==count(y))return count(x)-count(y);for(let i=0;i<Math.min(x.length,y.length);i++)if(isParameter(x[i])!==isParameter(y[i]))return isParameter(x[i])?1:-1;return a<b?-1:a>b?1:0}function inspectSql(value){let schemas=new Set,readSchemas=new Set,writes=[],readOnly=!0,walk=v=>{if(!v||typeof v!="object")return;let n=v;n.RangeVar?.mantle==="table"&&(schemas.add(n.RangeVar.relname.toLowerCase()),readSchemas.add(n.RangeVar.relname.toLowerCase()));for(let kind of["InsertStmt","UpdateStmt","DeleteStmt"])n[kind]&&(readOnly=!1,n[kind].relation?.relname&&writes.push({schema:n[kind].relation.relname.toLowerCase(),operation:kind==="InsertStmt"?"create":kind==="UpdateStmt"?"update":"delete"}),n[kind].relation?.relname&&(schemas.add(n[kind].relation.relname.toLowerCase()),kind!=="InsertStmt"&&readSchemas.add(n[kind].relation.relname.toLowerCase())));Object.values(n).forEach(walk)};return walk(value),{schemas:[...schemas].sort(),readSchemas:[...readSchemas].sort(),readOnly,writes}}function mergeRestrict(policies,conjunctive){return Object.fromEntries([...new Set(policies.flatMap(p=>Object.keys(p)))].sort().map(schema=>{let rows=policies.map(p=>p[schema]??{terms:[]}),terms=[...new Map(rows.flatMap(p=>p.terms).map(t=>[canonical(t),t])).values()].filter(t=>conjunctive||rows.every(p=>p.terms.some(v=>canonical(v)===canonical(t)))),owner=rows.find(p=>p.owner)?.owner;return[schema,{...owner&&(conjunctive||rows.every(p=>p.owner===owner))?{owner}:{},terms}]}))}function inspectBehavior(plan,ir,opaque,requires,restrict,writes){let inspected=inspectSql(ir);writes&&(inspected.writes=[...writes],inspected.schemas.push(...writes.map(w=>w.schema)),inspected.readSchemas.push(...writes.filter(w=>w.operation!=="create").map(w=>w.schema)));let dependencies=[],policies=[restrict??{}],procedures=new Set,hooks=new Set,visit=name=>{if(procedures.has(name))return;procedures.add(name);let p=plan.procedures[name];if(!p)throw new TypeError(`Unknown dependency '${name}'.`);dependencies.push({procedure:name,declaration:p}),policies.push(p.restrict??{}),opaque||="ref"in p.handler;let g=inspectSql("sql"in p.handler?p.handler.sql.stmts:void 0);inspected.schemas.push(...g.schemas),inspected.readSchemas.push(...g.readSchemas),inspected.writes.push(...g.writes),inspected.readOnly&&=g.readOnly,p.requires?.guard&&visit(p.requires.guard.procedure)};for(requires?.guard&&visit(requires.guard.procedure);;){let before=hooks.size;for(let[id,t]of Object.entries(plan.triggers).sort(([a],[b])=>a<b?-1:a>b?1:0)){if(t.source.kind!=="lifecycle"||hooks.has(id))continue;let source=t.source;!opaque&&!inspected.writes.some(w=>w.schema===source.schema.toLowerCase()&&source.on.some(on=>on.endsWith(`_${w.operation}`)))||(hooks.add(id),dependencies.push({trigger:id,source}),visit(t.procedure))}if(hooks.size===before)break}let related=names=>{let all=new Set(opaque?Object.keys(plan.schemas):names);for(let name of all){let parent=plan.schemas[name]?.translates?.parent.toLowerCase();parent&&all.add(parent)}return[...all].sort()};return{...inspected,schemas:related(inspected.schemas),readSchemas:related(inspected.readSchemas),opaque,restrict:mergeRestrict(policies,!0),dependencies}}var objectInput={type:"object",properties:{}},adminRoutes=["GET /me","GET /site","GET /collections","GET /views-manifest","GET /operations","GET /webmcp","POST /webmcp/:tool","GET /bootstrap","GET /views/:name/export","GET /views/:name","GET /view-batch","GET /developer/views/:name","POST /operations/:name","GET /developer-console","GET /collections/:name/statistics","GET /entries","GET /entries/export","GET /entries/:id","POST /entries","PATCH /entries/:id","POST /entries/:id/publish","POST /entries/:id/unpublish","POST /entries/:id/archive","DELETE /entries/:id","GET /site-settings","PATCH /site-settings","POST /media/uploads","POST /media/uploads/:groupId/commit","GET /media","GET /media/:id","PATCH /media/:id","DELETE /media/:id","GET /admin","GET /members","PATCH /admin/:id/role","POST /admin/invitations","DELETE /admin/invitations/:id"];function targetDefinitions(plan){let out=[],tools=[...mcpTools(plan,"public"),...mcpTools(plan,"admin")];for(let[kind,entries]of[["view",plan.views],["procedure",plan.procedures]])for(let[name,p]of Object.entries(entries).sort(([a],[b])=>a<b?-1:a>b?1:0)){let view=kind==="view"?plan.views[name]:void 0,proc=kind==="procedure"?plan.procedures[name]:void 0,ir=view?.stmts??(proc&&"sql"in proc.handler?proc.handler.sql.stmts:void 0),inspected=inspectBehavior(plan,ir,!!proc&&"ref"in proc.handler,p.requires,p.restrict),tool=tools.find(t=>t.kind===kind&&t.source===name),title=resolveLocalizedText(p.title,"en","en")??name,triggers=Object.entries(plan.triggers).filter(([,t])=>kind==="procedure"&&t.procedure===name).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([id,t])=>({id,source:t.source})),surfaces=[...new Set([...view?[view.surface,"admin",...view.surface==="public"?["rest"]:[]]:[],...triggers.map(t=>t.source.kind==="mcp"?t.source.surface:t.source.kind==="http"?"rest":t.source.kind)])].sort();surfaces.length||surfaces.push("internal"),out.push({id:`${kind}:${name}`,name:tool?.name??mcpToolNameSegment(name),kind,surface:view?.surface??(surfaces.includes("public")||surfaces.includes("rest")?"public":surfaces.includes("admin")?"admin":"internal"),surfaces,triggers,title,description:resolveLocalizedText(p.description,"en","en")??title,inputSchema:tool?.inputSchema??view?.input??proc?.input??objectInput,annotations:tool?.annotations??{},requires:p.requires,restrict:inspected.restrict,schemas:inspected.schemas,readSchemas:inspected.readSchemas,readOnly:!inspected.opaque&&inspected.readOnly,opaque:inspected.opaque,trustedOnly:!!proc?.trustedOnly,variants:[],behavior:{declaration:p,dependencies:inspected.dependencies}})}let addRoute=(id,dependencies,inputSchema=objectInput)=>{let admin=id.startsWith("admin:");out.push({id,name:id.replace(/[^a-zA-Z0-9_-]/g,"_"),title:id,description:id,kind:admin?"admin":"rest",surface:admin?"admin":"public",surfaces:[admin?"admin":"rest"],triggers:dependencies.flatMap(d=>d.triggers),inputSchema,annotations:{},requires:admin?{auth:{all:["ctx.admin"]}}:dependencies[0]?.requires,restrict:mergeRestrict(dependencies.map(d=>d.restrict),!1),schemas:[...new Set(dependencies.flatMap(d=>d.schemas))].sort(),readSchemas:[...new Set(dependencies.flatMap(d=>d.readSchemas))].sort(),readOnly:dependencies.length>0&&dependencies.every(d=>d.readOnly)&&(!admin||id.startsWith("admin:GET ")||id==="admin:POST /operations/:name"||id==="admin:POST /webmcp/:tool"),opaque:dependencies.some(d=>d.opaque),trustedOnly:dependencies.some(d=>d.trustedOnly),variants:dependencies,behavior:dependencies.map(d=>({id:d.id,behavior:d.behavior,surfaces:d.surfaces,triggers:d.triggers,input:d.inputSchema,requires:d.requires,restrict:d.restrict,trustedOnly:d.trustedOnly}))})},declarations=[...out],adminOperations=new Set(mcpTools(plan,"admin").filter(t=>t.kind==="procedure").map(t=>`procedure:${t.source}`));for(let d of declarations)d.kind==="view"&&d.surfaces.includes("public")&&addRoute(`rest:GET /api/views/${d.id.slice(5)}`,[d],d.inputSchema);for(let[,t]of Object.entries(plan.triggers).sort(([a],[b])=>a<b?-1:a>b?1:0))if(t.source.kind==="http"){let d=declarations.find(d2=>d2.id===`procedure:${t.procedure}`);addRoute(`rest:${t.source.method} ${pathTemplate(t.source.path)}`,[d],d.inputSchema)}let generated=[];for(let[schema,s]of Object.entries(plan.schemas).sort(([a],[b])=>a<b?-1:a>b?1:0))if(s.publishing)for(let[verb,from,to]of publishingTransitions){addRoute(`procedure:${s.name}.${verb}`,[],publishingInput);let d=out.at(-1),inspected=inspectBehavior(plan,void 0,!1,void 0,void 0,[{schema,operation:verb==="publish"?"publish":"update"}]);Object.assign(d,{kind:"procedure",name:mcpToolNameSegment(`${verb}_${s.name}`),surface:"admin",surfaces:["admin"],requires:{auth:{all:["ctx.admin"]}},schemas:[...new Set([schema,...inspected.schemas])].sort(),readSchemas:[...new Set([schema,...inspected.readSchemas])].sort(),opaque:inspected.opaque,behavior:{schema,verb,from,to,dependencies:inspected.dependencies}}),generated.push(d)}for(let tool of mediaDefinitions()){addRoute(`admin:tool:${tool.name}`,[],tool.inputSchema);let d=out.at(-1);Object.assign(d,{name:tool.name,readOnly:tool.annotations.readOnlyHint,opaque:!tool.annotations.readOnlyHint,annotations:tool.annotations,behavior:{tool,schemas:plan.schemas}}),generated.push(d)}for(let route of adminRoutes){let deps=route.includes("/views/:")||route==="GET /view-batch"?declarations.filter(d2=>d2.kind==="view"&&(route.includes("/developer/")||plan.views[d2.id.slice(5)]?.surface==="admin")):route.includes("/operations/:")?declarations.filter(d2=>adminOperations.has(d2.id)):route==="POST /webmcp/:tool"?declarations.filter(d2=>mcpTools(plan,"admin").some(t=>`${t.kind}:${t.source}`===d2.id)).concat(generated):[],generic=route.includes("/entries")||route.includes("/statistics")||route==="GET /bootstrap";addRoute(`admin:${route}`,deps,deps.length&&route!=="GET /view-batch"?{...objectInput,anyOf:deps.map(d2=>({type:"object",properties:{[route.includes("/webmcp/")?"tool":"name"]:{type:"string",const:route.includes("/webmcp/")?d2.name:d2.id.slice(d2.kind==="view"?5:10)}}}))}:objectInput);let d=out.at(-1);if(generic){let operation=route==="POST /entries"?"create":route==="DELETE /entries/:id"?"delete":route.startsWith("GET ")?void 0:route.endsWith("/publish")?"publish":"update",inspected=inspectBehavior(plan,void 0,!1,void 0,void 0,operation?Object.keys(plan.schemas).map(schema=>({schema,operation})):[]);d.schemas=Object.keys(plan.schemas).sort(),d.readSchemas=d.schemas,d.opaque=inspected.opaque,d.behavior={schemas:plan.schemas,dependencies:inspected.dependencies}}}return[...new Map(out.map(d=>[d.id,d])).values()].sort((a,b)=>a.id<b.id?-1:a.id>b.id?1:0)}async function hash(value){let digest=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(canonical(value)));return[...new Uint8Array(digest)].map(b=>b.toString(16).padStart(2,"0")).join("")}function hashDefinition(plan,d){return hash({id:d.id,surfaces:d.surfaces,triggers:d.triggers,behavior:d.behavior,input:d.inputSchema,requires:d.requires,restrict:d.restrict,dialect:plan.dialect,schemas:Object.fromEntries(d.schemas.map(name=>[name,plan.schemas[name]])),userFields:plan.access?.userFields,readOnly:d.readOnly,opaque:d.opaque,trustedOnly:d.trustedOnly})}async function targetHash(plan,targetId){let target=targetDefinitions(plan).find(d=>d.id===targetId);if(!target)throw new TypeError(`Unknown target '${targetId}'.`);return hashDefinition(plan,target)}export{canonical,ADMIN_API_BASE,routePath,routeSource,canonicalPath,routeOrder,adminRoutes,targetDefinitions,hash,hashDefinition,targetHash};
|
|
@@ -3,6 +3,7 @@ import type { PlanRestrict } from "../../build/spec/domain/model/RuntimePlan.js"
|
|
|
3
3
|
import type { UserFieldSpec } from "../../build/spec/domain/model/UserFields.js";
|
|
4
4
|
import { type TargetDefinition } from "./targets.js";
|
|
5
5
|
export { targetHash } from "./target-hash.js";
|
|
6
|
+
export { matchTarget, type TargetRequest } from "./match.js";
|
|
6
7
|
export interface DescribeTarget {
|
|
7
8
|
name: string;
|
|
8
9
|
title: string;
|
|
@@ -1,115 +1 @@
|
|
|
1
|
-
import {
|
|
2
|
-
canonical,
|
|
3
|
-
hashDefinition,
|
|
4
|
-
targetDefinitions,
|
|
5
|
-
targetHash
|
|
6
|
-
} from "./chunk-ZVXBGP7Y.js";
|
|
7
|
-
|
|
8
|
-
// src/domain/describe/index.ts
|
|
9
|
-
function requirements(d, surface) {
|
|
10
|
-
const all = d.requires?.auth?.all ?? [];
|
|
11
|
-
return {
|
|
12
|
-
all: surface === "admin" && !all.includes("ctx.admin") ? ["ctx.admin", ...all] : all,
|
|
13
|
-
...d.requires?.guard ? { guard: d.requires.guard.procedure } : {}
|
|
14
|
-
};
|
|
15
|
-
}
|
|
16
|
-
async function describeApp(plan) {
|
|
17
|
-
const targets = await Promise.all(targetDefinitions(plan).map(async (d) => {
|
|
18
|
-
const scope = Object.fromEntries(d.schemas.map((name) => {
|
|
19
|
-
const s = plan.schemas[name];
|
|
20
|
-
return [name, { ...s.scope ? { owner: s.scope } : {}, terms: s.userScopes ?? [] }];
|
|
21
|
-
}));
|
|
22
|
-
return { name: d.name, title: d.title, description: d.description, inputSchema: d.inputSchema, annotations: { ...d.annotations, readOnlyHint: d.readOnly }, _meta: {
|
|
23
|
-
surfaces: d.surfaces,
|
|
24
|
-
triggers: d.triggers,
|
|
25
|
-
id: d.id,
|
|
26
|
-
targetHash: await hashDefinition(plan, d),
|
|
27
|
-
readOnly: d.readOnly,
|
|
28
|
-
scope,
|
|
29
|
-
restrict: d.restrict,
|
|
30
|
-
opaque: d.opaque,
|
|
31
|
-
unscopedReads: d.readSchemas.some((name) => !plan.schemas[name]?.scope && !plan.schemas[name]?.userScopes?.length),
|
|
32
|
-
trustedOnly: d.trustedOnly,
|
|
33
|
-
variants: d.variants.map((v) => ({
|
|
34
|
-
id: v.id,
|
|
35
|
-
restrict: v.restrict,
|
|
36
|
-
requires: requirements(v, d.surface),
|
|
37
|
-
inputSchema: v.inputSchema,
|
|
38
|
-
readOnly: v.readOnly,
|
|
39
|
-
trustedOnly: v.trustedOnly,
|
|
40
|
-
opaque: v.opaque,
|
|
41
|
-
unscopedReads: v.readSchemas.some((name) => !plan.schemas[name]?.scope && !plan.schemas[name]?.userScopes?.length),
|
|
42
|
-
scope: Object.fromEntries(v.schemas.map((name) => {
|
|
43
|
-
const s = plan.schemas[name];
|
|
44
|
-
return [name, { ...s.scope ? { owner: s.scope } : {}, terms: s.userScopes ?? [] }];
|
|
45
|
-
}))
|
|
46
|
-
})),
|
|
47
|
-
requires: requirements(d, d.surface)
|
|
48
|
-
} };
|
|
49
|
-
}));
|
|
50
|
-
return JSON.parse(canonical({ schemaVersion: 1, access: plan.access?.userFields ?? {}, targets }));
|
|
51
|
-
}
|
|
52
|
-
var securityFlags = ["readOnly", "trustedOnly", "opaque", "unscopedReads"];
|
|
53
|
-
var flagDirection = (field, value) => (field === "readOnly" || field === "trustedOnly" ? !value : value) ? "widened" : "narrowed";
|
|
54
|
-
var inclusion = (before, after) => before.some((t) => !after.includes(t)) ? "widened" : after.some((t) => !before.includes(t)) ? "narrowed" : "changed";
|
|
55
|
-
var exposureDirection = (before, after) => after.some((t) => !before.includes(t) && t !== canonical("internal")) ? "widened" : before.some((t) => !after.includes(t) && t !== canonical("internal")) ? "narrowed" : "changed";
|
|
56
|
-
var combine = (directions) => directions.includes("widened") ? "widened" : directions.length && directions.every((d) => d === "narrowed") ? "narrowed" : "changed";
|
|
57
|
-
var terms = (p) => [...p.owner ? [canonical({ owner: p.owner })] : [], ...p.terms.map(canonical)];
|
|
58
|
-
function policyDirection(before, after, scope) {
|
|
59
|
-
const directions = [];
|
|
60
|
-
for (const schema of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])) {
|
|
61
|
-
const x = before[schema], y = after[schema];
|
|
62
|
-
if (canonical(x) === canonical(y)) continue;
|
|
63
|
-
directions.push(scope && (!x || !y) ? x ? "narrowed" : "widened" : inclusion(x ? terms(x) : [], y ? terms(y) : []));
|
|
64
|
-
}
|
|
65
|
-
return combine(directions);
|
|
66
|
-
}
|
|
67
|
-
function requiresDirection(x, y) {
|
|
68
|
-
const directions = [];
|
|
69
|
-
if (canonical(x.all) !== canonical(y.all)) directions.push(inclusion(x.all.map(canonical), y.all.map(canonical)));
|
|
70
|
-
if (x.guard !== y.guard) directions.push(!y.guard ? "widened" : !x.guard ? "narrowed" : "changed");
|
|
71
|
-
return combine(directions);
|
|
72
|
-
}
|
|
73
|
-
function diffApp(a, b) {
|
|
74
|
-
if (a.schemaVersion !== 1 || b.schemaVersion !== 1) throw new TypeError("Unsupported describe schemaVersion.");
|
|
75
|
-
const changes = [], old = new Map(a.targets.map((t) => [t._meta.id, t])), next = new Map(b.targets.map((t) => [t._meta.id, t]));
|
|
76
|
-
for (const id of [.../* @__PURE__ */ new Set([...old.keys(), ...next.keys()])].sort()) {
|
|
77
|
-
const before = old.get(id), after = next.get(id);
|
|
78
|
-
if (!before || !after) {
|
|
79
|
-
changes.push({ id, field: "target", direction: before ? "narrowed" : "widened" });
|
|
80
|
-
continue;
|
|
81
|
-
}
|
|
82
|
-
const x = before._meta, y = after._meta, start = changes.length;
|
|
83
|
-
const record = (field, left, right, direction) => {
|
|
84
|
-
if (canonical(left) !== canonical(right)) changes.push({ id, field, direction, before: left, after: right });
|
|
85
|
-
};
|
|
86
|
-
record("scope", x.scope, y.scope, policyDirection(x.scope, y.scope, true));
|
|
87
|
-
record("restrict", x.restrict, y.restrict, policyDirection(x.restrict, y.restrict, false));
|
|
88
|
-
record("requires", x.requires, y.requires, requiresDirection(x.requires, y.requires));
|
|
89
|
-
for (const field of ["surfaces", "triggers"]) record(field, x[field], y[field], exposureDirection(x[field].map(canonical), y[field].map(canonical)));
|
|
90
|
-
for (const field of securityFlags) record(field, x[field], y[field], flagDirection(field, y[field]));
|
|
91
|
-
record("inputSchema", before.inputSchema, after.inputSchema, "changed");
|
|
92
|
-
const directions = [];
|
|
93
|
-
const variants = new Map(x.variants.map((v) => [v.id, v])), added = new Map(y.variants.map((v) => [v.id, v]));
|
|
94
|
-
for (const name of /* @__PURE__ */ new Set([...variants.keys(), ...added.keys()])) {
|
|
95
|
-
const left = variants.get(name), right = added.get(name);
|
|
96
|
-
if (canonical(left) === canonical(right)) continue;
|
|
97
|
-
if (!left || !right) directions.push(left ? "narrowed" : "widened");
|
|
98
|
-
else {
|
|
99
|
-
if (canonical(left.scope) !== canonical(right.scope)) directions.push(policyDirection(left.scope, right.scope, true));
|
|
100
|
-
if (canonical(left.restrict) !== canonical(right.restrict)) directions.push(policyDirection(left.restrict, right.restrict, false));
|
|
101
|
-
if (canonical(left.requires) !== canonical(right.requires)) directions.push(requiresDirection(left.requires, right.requires));
|
|
102
|
-
if (canonical(left.inputSchema) !== canonical(right.inputSchema)) directions.push("changed");
|
|
103
|
-
for (const field of securityFlags) if (left[field] !== right[field]) directions.push(flagDirection(field, right[field]));
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
record("variants", x.variants, y.variants, combine(directions));
|
|
107
|
-
if (changes.length === start && x.targetHash !== y.targetHash) changes.push({ id, field: "behavior", direction: "changed" });
|
|
108
|
-
}
|
|
109
|
-
return changes;
|
|
110
|
-
}
|
|
111
|
-
export {
|
|
112
|
-
describeApp,
|
|
113
|
-
diffApp,
|
|
114
|
-
targetHash
|
|
115
|
-
};
|
|
1
|
+
import{ADMIN_API_BASE,adminRoutes,canonical,canonicalPath,hashDefinition,routeOrder,routePath,routeSource,targetDefinitions,targetHash}from"./chunk-P6PP6VVV.js";var tables=new WeakMap,route=/^(rest|admin):([A-Z]+) (\/.*)$/,normalized=new Set(["DELETE","GET","HEAD","OPTIONS","POST","PUT"]);function compile(describe){let table={rest:[],admin:[],tools:[]};for(let{name,_meta:meta}of describe.targets){let[,surface,method,template]=route.exec(meta.id)??[];if(surface==="rest")table.rest.push({method,pattern:new RegExp(routeSource(routePath(template)).source),view:meta.variants[0]?.id.startsWith("view:")===!0,meta});else if(surface==="admin")table.admin.push({method,pattern:new RegExp(routeSource(routePath(template),ADMIN_API_BASE).source),meta});else{let s=meta.surfaces,endpoints=meta.id.startsWith("admin:tool:")?["admin"]:meta.id.startsWith("view:")?s.includes("public")?["public"]:s.includes("internal")?[]:["admin"]:meta.id.startsWith("procedure:")?s.filter(x=>x==="public"||x==="admin"):[];endpoints.length&&table.tools.push({name,endpoints,meta})}}let order=id=>adminRoutes.indexOf(id.slice(6))>>>0,path=id=>routePath(id.slice(id.indexOf(" ")+1));return table.rest.sort((a,b)=>routeOrder(path(a.meta.id),path(b.meta.id))),table.admin.sort((a,b)=>order(a.meta.id)-order(b.meta.id)),table}function matchTarget(describe,request){let table=tables.get(describe);if(table||tables.set(describe,table=compile(describe)),request.surface==="mcp"){let path2=request.path?.replace(/\/+$/,""),endpoint=path2===void 0?void 0:path2==="/mcp"?"public":path2==="/mcp/admin"?"admin":null,found=table.tools.filter(t=>t.name===request.tool&&(endpoint===void 0||t.endpoints.includes(endpoint)));return endpoint!==null&&found.length&&found.every(t=>t.meta.id===found[0].meta.id)?found[0].meta:null}let method=normalized.has(request.method.toUpperCase())?request.method.toUpperCase():request.method,path=canonicalPath(request.path);return path===void 0?null:request.surface==="admin"?request.path!==ADMIN_API_BASE&&!request.path.startsWith(ADMIN_API_BASE+"/")?null:table.admin.find(r=>r.method===method&&r.pattern.test(path))?.meta??null:table.rest.find(r=>r.pattern.test(path)&&(r.method===method||method==="HEAD"&&r.method==="GET"&&r.view))?.meta??null}function requirements(d,surface){let all=d.requires?.auth?.all??[];return{all:surface==="admin"&&!all.includes("ctx.admin")?["ctx.admin",...all]:all,...d.requires?.guard?{guard:d.requires.guard.procedure}:{}}}async function describeApp(plan){let targets=await Promise.all(targetDefinitions(plan).map(async d=>{let scope=Object.fromEntries(d.schemas.map(name=>{let s=plan.schemas[name];return[name,{...s.scope?{owner:s.scope}:{},terms:s.userScopes??[]}]}));return{name:d.name,title:d.title,description:d.description,inputSchema:d.inputSchema,annotations:{...d.annotations,readOnlyHint:d.readOnly},_meta:{surfaces:d.surfaces,triggers:d.triggers,id:d.id,targetHash:await hashDefinition(plan,d),readOnly:d.readOnly,scope,restrict:d.restrict,opaque:d.opaque,unscopedReads:d.readSchemas.some(name=>!plan.schemas[name]?.scope&&!plan.schemas[name]?.userScopes?.length),trustedOnly:d.trustedOnly,variants:d.variants.map(v=>({id:v.id,restrict:v.restrict,requires:requirements(v,d.surface),inputSchema:v.inputSchema,readOnly:v.readOnly,trustedOnly:v.trustedOnly,opaque:v.opaque,unscopedReads:v.readSchemas.some(name=>!plan.schemas[name]?.scope&&!plan.schemas[name]?.userScopes?.length),scope:Object.fromEntries(v.schemas.map(name=>{let s=plan.schemas[name];return[name,{...s.scope?{owner:s.scope}:{},terms:s.userScopes??[]}]}))})),requires:requirements(d,d.surface)}}}));return JSON.parse(canonical({schemaVersion:1,access:plan.access?.userFields??{},targets}))}var securityFlags=["readOnly","trustedOnly","opaque","unscopedReads"],flagDirection=(field,value)=>(field==="readOnly"||field==="trustedOnly"?!value:value)?"widened":"narrowed",inclusion=(before,after)=>before.some(t=>!after.includes(t))?"widened":after.some(t=>!before.includes(t))?"narrowed":"changed",exposureDirection=(before,after)=>after.some(t=>!before.includes(t)&&t!==canonical("internal"))?"widened":before.some(t=>!after.includes(t)&&t!==canonical("internal"))?"narrowed":"changed",combine=directions=>directions.includes("widened")?"widened":directions.length&&directions.every(d=>d==="narrowed")?"narrowed":"changed",terms=p=>[...p.owner?[canonical({owner:p.owner})]:[],...p.terms.map(canonical)];function policyDirection(before,after,scope){let directions=[];for(let schema of new Set([...Object.keys(before),...Object.keys(after)])){let x=before[schema],y=after[schema];canonical(x)!==canonical(y)&&directions.push(scope&&(!x||!y)?x?"narrowed":"widened":inclusion(x?terms(x):[],y?terms(y):[]))}return combine(directions)}function requiresDirection(x,y){let directions=[];return canonical(x.all)!==canonical(y.all)&&directions.push(inclusion(x.all.map(canonical),y.all.map(canonical))),x.guard!==y.guard&&directions.push(y.guard?x.guard?"changed":"narrowed":"widened"),combine(directions)}function diffApp(a,b){if(a.schemaVersion!==1||b.schemaVersion!==1)throw new TypeError("Unsupported describe schemaVersion.");let changes=[],old=new Map(a.targets.map(t=>[t._meta.id,t])),next=new Map(b.targets.map(t=>[t._meta.id,t]));for(let id of[...new Set([...old.keys(),...next.keys()])].sort()){let before=old.get(id),after=next.get(id);if(!before||!after){changes.push({id,field:"target",direction:before?"narrowed":"widened"});continue}let x=before._meta,y=after._meta,start=changes.length,record=(field,left,right,direction)=>{canonical(left)!==canonical(right)&&changes.push({id,field,direction,before:left,after:right})};record("scope",x.scope,y.scope,policyDirection(x.scope,y.scope,!0)),record("restrict",x.restrict,y.restrict,policyDirection(x.restrict,y.restrict,!1)),record("requires",x.requires,y.requires,requiresDirection(x.requires,y.requires));for(let field of["surfaces","triggers"])record(field,x[field],y[field],exposureDirection(x[field].map(canonical),y[field].map(canonical)));for(let field of securityFlags)record(field,x[field],y[field],flagDirection(field,y[field]));record("inputSchema",before.inputSchema,after.inputSchema,"changed");let directions=[],variants=new Map(x.variants.map(v=>[v.id,v])),added=new Map(y.variants.map(v=>[v.id,v]));for(let name of new Set([...variants.keys(),...added.keys()])){let left=variants.get(name),right=added.get(name);if(canonical(left)!==canonical(right))if(!left||!right)directions.push(left?"narrowed":"widened");else{canonical(left.scope)!==canonical(right.scope)&&directions.push(policyDirection(left.scope,right.scope,!0)),canonical(left.restrict)!==canonical(right.restrict)&&directions.push(policyDirection(left.restrict,right.restrict,!1)),canonical(left.requires)!==canonical(right.requires)&&directions.push(requiresDirection(left.requires,right.requires)),canonical(left.inputSchema)!==canonical(right.inputSchema)&&directions.push("changed");for(let field of securityFlags)left[field]!==right[field]&&directions.push(flagDirection(field,right[field]))}}record("variants",x.variants,y.variants,combine(directions)),changes.length===start&&x.targetHash!==y.targetHash&&changes.push({id,field:"behavior",direction:"changed"})}return changes}export{describeApp,diffApp,matchTarget,targetHash};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { AppDescription, DescribeTarget } from "./index.js";
|
|
2
|
+
/** A request as a gateway sees it: a REST or Admin method and URL pathname, or an MCP `tools/call` tool name and optional endpoint path. */
|
|
3
|
+
export type TargetRequest = {
|
|
4
|
+
readonly surface: "rest" | "admin";
|
|
5
|
+
readonly method: string;
|
|
6
|
+
readonly path: string;
|
|
7
|
+
} | {
|
|
8
|
+
readonly surface: "mcp";
|
|
9
|
+
readonly tool: string;
|
|
10
|
+
readonly path?: string;
|
|
11
|
+
};
|
|
12
|
+
type Meta = DescribeTarget["_meta"];
|
|
13
|
+
/**
|
|
14
|
+
* The access target a generated router resolves for a request, from `mantle describe` JSON alone: no application, database
|
|
15
|
+
* or network. REST and Admin take the URL pathname (Admin's under `/admin/api`) and follow the routers' path, method and
|
|
16
|
+
* precedence rules; MCP takes the `tools/call` name and, optionally, the `/mcp` or `/mcp/admin` path. Unserved is null.
|
|
17
|
+
*/
|
|
18
|
+
export declare function matchTarget(describe: Pick<AppDescription, "targets">, request: TargetRequest): Meta | null;
|
|
19
|
+
export {};
|
|
@@ -1,12 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
canonical,
|
|
3
|
-
hash,
|
|
4
|
-
hashDefinition,
|
|
5
|
-
targetHash
|
|
6
|
-
} from "./chunk-ZVXBGP7Y.js";
|
|
7
|
-
export {
|
|
8
|
-
canonical,
|
|
9
|
-
hash,
|
|
10
|
-
hashDefinition,
|
|
11
|
-
targetHash
|
|
12
|
-
};
|
|
1
|
+
import{canonical,hash,hashDefinition,targetHash}from"./chunk-P6PP6VVV.js";export{canonical,hash,hashDefinition,targetHash};
|
package/dist/domain/entry.js
CHANGED
|
@@ -1,29 +1,15 @@
|
|
|
1
|
-
/** Direct entry files: one View or Procedure per module, so a request bundle excludes the others. */
|
|
2
|
-
/**
|
|
3
|
-
* Stable, injective build-only export names, so a stale entry file cannot bind a new ordinal: every byte outside [A-Za-z0-9]
|
|
4
|
-
* (including `$` and `_`) is `$` and two hex digits.
|
|
5
|
-
* @internal
|
|
6
|
-
*/
|
|
7
1
|
export const exportName = (kind, name) => kind + "_" + name.replace(/[^A-Za-z0-9]+/g, run => Array.from(new TextEncoder().encode(run), b => "$" + b.toString(16).padStart(2, "0")).join(""));
|
|
8
|
-
/** A direct entry: `import` then `export`, because Bun 1.3 drops a bare `export { x as default } from` binding under "sideEffects": false. `extra` is any further re-export line. */
|
|
9
|
-
/** @internal */
|
|
10
2
|
export const entry = (kind, name, types, extra = "") => `import { ${exportName(kind, name)} as operation } from "../generated.js";\nexport default operation;\nexport type { ${types} } from "../generated.js";\n${extra}`;
|
|
11
|
-
/** Source text of a JSON value. @internal */
|
|
12
3
|
export const q = JSON.stringify;
|
|
13
|
-
/** Whether a target's database is SQLite (bun:sqlite or D1). @internal */
|
|
14
4
|
export const isSqlite = (target) => target === "bun-sqlite" || target === "cloudflare-d1";
|
|
15
|
-
/** A View's lazy paged boundary and validated query reader, bound as `page<index>` and `<query><index>`. @internal */
|
|
16
5
|
export const viewImports = (name, index, query = "query") => [`const page${index}: typeof import("./paged/views/${encodeURIComponent(name)}.js").default = async (...args) => (await import("./paged/views/${encodeURIComponent(name)}.js")).default(...args);`, `import { query as ${query}${index} } from "./validation/views/${encodeURIComponent(name)}.js";`];
|
|
17
|
-
/** A generated host handle import, shared by the optional boundaries. @internal */
|
|
18
6
|
export const driverFor = (target) => target === "bun-sqlite" ? "bun-sqlite" : target === "cloudflare-d1" ? "d1" : "postgres";
|
|
19
7
|
export const databaseImport = (target) => driverFor(target) === "postgres" ? 'import type { Postgres as Database } from "@aotter/mantle/contracts";' : `import type { Handle as Database } from "@aotter/mantle/driver/${driverFor(target)}";`;
|
|
20
|
-
/** Shared source ownership marker; only newly emitted files are wrapped. */
|
|
21
8
|
export const GENERATED = "Generated by mantle generate — do not edit.";
|
|
22
9
|
export function generatedFiles(files) {
|
|
23
10
|
return Object.fromEntries(Object.entries(files).map(([name, source]) => [name,
|
|
24
11
|
`${name.endsWith(".sql") ? "--" : "//"} ${GENERATED}\n${source}`]));
|
|
25
12
|
}
|
|
26
|
-
/** JavaScript data literals preserve own __proto__ keys instead of mutating the object's prototype. */
|
|
27
13
|
export function literal(value) {
|
|
28
14
|
if (Array.isArray(value))
|
|
29
15
|
return `[${value.map(literal).join(",")}]`;
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
export const publishingTransitions = [["publish", ["draft"], "published"], ["unpublish", ["published", "archived"], "draft"], ["archive", ["draft", "published"], "archived"]];
|
|
2
|
-
/** Only archive withdraws an entry from both drafts and the public. */
|
|
3
2
|
export const publishingAnnotations = (verb) => ({ readOnlyHint: false, destructiveHint: verb === "archive" });
|
|
4
3
|
export const publishingInput = { type: "object", properties: { id: { type: "string", minLength: 1 }, expectedVersion: { type: "integer", minimum: 1 } }, required: ["id", "expectedVersion"], additionalProperties: false };
|
|
5
4
|
export function mediaDefinitions() {
|
package/dist/domain/input.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { q } from "./entry.js";
|
|
2
|
-
/** The kernel's `Conversions` for the fields an input bind reads (see kernel/surface), as a literal; empty when none. */
|
|
3
2
|
export function conversions(properties, binds, target) {
|
|
4
3
|
const fields = Object.keys(properties ?? {}).flatMap(field => {
|
|
5
4
|
const bind = binds.find(b => b.k === "input" && String(b.name).toLowerCase() === field.toLowerCase());
|
|
@@ -10,7 +9,6 @@ export function conversions(properties, binds, target) {
|
|
|
10
9
|
});
|
|
11
10
|
return fields.length ? q(fields) : "";
|
|
12
11
|
}
|
|
13
|
-
/** Only build-time authorization assembly; generated queries retain their existing predicates. @internal */
|
|
14
12
|
export const authLines = (requires, path, binds = [], sqlite = true, trustedOnly = false) => [...(trustedOnly ? [` deny(caller, caller.kind === "system", ${q(path)});`] : []), ...(requires?.auth?.all ?? []).map((p, index) => {
|
|
15
13
|
const allowed = typeof p === "string" ? p === "ctx.admin" ? 'isAdmin(caller)' : 'isUser(caller)' : `caller.kind === "user" && caller.scopes.includes(${q(p["ctx.auth.scope"])})`;
|
|
16
14
|
return ` deny(caller, ${allowed}, ${q(`${path}/requires/auth/all/${index}`)});`;
|