@feltdb/feltkit 0.3.11 → 0.3.13
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 +4 -3
- package/dist/app.d.ts +98 -3
- package/dist/app.js +63 -0
- package/dist/app.js.map +1 -1
- package/dist/appboundry/build.d.ts +39 -1
- package/dist/appboundry/build.js +57 -6
- package/dist/appboundry/build.js.map +1 -1
- package/dist/appboundry/guest.js +46 -5
- package/dist/appboundry/guest.js.map +1 -1
- package/dist/appboundry/host.d.ts +24 -5
- package/dist/appboundry/host.js +234 -141
- package/dist/appboundry/host.js.map +1 -1
- package/dist/appboundry/runtime.d.ts +44 -0
- package/dist/appboundry/runtime.js +99 -0
- package/dist/appboundry/runtime.js.map +1 -0
- package/dist/cli/entry.d.ts +1 -0
- package/dist/cli/entry.js +4 -0
- package/dist/cli/entry.js.map +1 -0
- package/dist/cli/main.d.ts +5 -0
- package/dist/cli/main.js +550 -13
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/test-reporter.d.ts +9 -0
- package/dist/cli/test-reporter.js +26 -0
- package/dist/cli/test-reporter.js.map +1 -0
- package/dist/client/index.d.ts +3 -0
- package/dist/client/index.js +3 -0
- package/dist/client/index.js.map +1 -1
- package/dist/dashboard/assets/index-BSnW2DC-.js +15 -0
- package/dist/dashboard/assets/{index-91I1zDK-.css → index-BXTNQAg1.css} +1 -1
- package/dist/dashboard/index.html +3 -3
- package/dist/docs.d.ts +12 -0
- package/dist/docs.js +42 -0
- package/dist/docs.js.map +1 -0
- package/dist/errors.d.ts +15 -0
- package/dist/errors.js +9 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js.map +1 -1
- package/dist/platform/changes.d.ts +340 -0
- package/dist/platform/changes.js +355 -0
- package/dist/platform/changes.js.map +1 -0
- package/dist/platform/deployments.d.ts +653 -0
- package/dist/platform/deployments.js +532 -0
- package/dist/platform/deployments.js.map +1 -0
- package/dist/platform/operations.d.ts +74 -0
- package/dist/platform/operations.js +198 -0
- package/dist/platform/operations.js.map +1 -0
- package/dist/platform/platform.d.ts +78 -0
- package/dist/platform/platform.js +264 -0
- package/dist/platform/platform.js.map +1 -0
- package/dist/platform/server.d.ts +25 -0
- package/dist/platform/server.js +165 -0
- package/dist/platform/server.js.map +1 -0
- package/dist/platform/source.d.ts +27 -0
- package/dist/platform/source.js +142 -0
- package/dist/platform/source.js.map +1 -0
- package/dist/runtime/activity.d.ts +25 -0
- package/dist/runtime/activity.js +38 -12
- package/dist/runtime/activity.js.map +1 -1
- package/dist/runtime/agent.d.ts +16 -0
- package/dist/runtime/agent.js +92 -28
- package/dist/runtime/agent.js.map +1 -1
- package/dist/runtime/backup-environment.d.ts +32 -0
- package/dist/runtime/backup-environment.js +92 -0
- package/dist/runtime/backup-environment.js.map +1 -0
- package/dist/runtime/backup.d.ts +129 -0
- package/dist/runtime/backup.js +344 -0
- package/dist/runtime/backup.js.map +1 -0
- package/dist/runtime/capabilities.js +4 -2
- package/dist/runtime/capabilities.js.map +1 -1
- package/dist/runtime/changes.js +2 -2
- package/dist/runtime/changes.js.map +1 -1
- package/dist/runtime/contract.js +4 -3
- package/dist/runtime/contract.js.map +1 -1
- package/dist/runtime/data.d.ts +36 -5
- package/dist/runtime/data.js +165 -55
- package/dist/runtime/data.js.map +1 -1
- package/dist/runtime/decisions.js +2 -1
- package/dist/runtime/decisions.js.map +1 -1
- package/dist/runtime/instance.js +17 -0
- package/dist/runtime/instance.js.map +1 -1
- package/dist/runtime/integrations.js +14 -6
- package/dist/runtime/integrations.js.map +1 -1
- package/dist/runtime/loader.js +28 -4
- package/dist/runtime/loader.js.map +1 -1
- package/dist/runtime/migration-context.d.ts +25 -0
- package/dist/runtime/migration-context.js +69 -0
- package/dist/runtime/migration-context.js.map +1 -0
- package/dist/runtime/outbox.d.ts +6 -82
- package/dist/runtime/outbox.js +14 -59
- package/dist/runtime/outbox.js.map +1 -1
- package/dist/runtime/readiness.js +18 -1
- package/dist/runtime/readiness.js.map +1 -1
- package/dist/runtime/runtime.d.ts +84 -8
- package/dist/runtime/runtime.js +372 -131
- package/dist/runtime/runtime.js.map +1 -1
- package/dist/runtime/services.d.ts +41 -5
- package/dist/runtime/services.js +49 -4
- package/dist/runtime/services.js.map +1 -1
- package/dist/runtime/sessions.js +4 -3
- package/dist/runtime/sessions.js.map +1 -1
- package/dist/runtime/state-contract.d.ts +167 -0
- package/dist/runtime/state-contract.js +438 -0
- package/dist/runtime/state-contract.js.map +1 -0
- package/dist/runtime/transactions.d.ts +199 -0
- package/dist/runtime/transactions.js +246 -0
- package/dist/runtime/transactions.js.map +1 -0
- package/dist/schema.d.ts +13 -1
- package/dist/schema.js +21 -2
- package/dist/schema.js.map +1 -1
- package/dist/server/admin.d.ts +3 -2
- package/dist/server/admin.js +62 -10
- package/dist/server/admin.js.map +1 -1
- package/dist/server/index.d.ts +6 -1
- package/dist/server/index.js +90 -9
- package/dist/server/index.js.map +1 -1
- package/dist/server/mcp.js +1 -1
- package/dist/server/mcp.js.map +1 -1
- package/dist/server/project.d.ts +5 -0
- package/dist/server/project.js +13 -2
- package/dist/server/project.js.map +1 -1
- package/dist/testing/index.d.ts +10 -3
- package/dist/testing/index.js +33 -7
- package/dist/testing/index.js.map +1 -1
- package/docs/AGENT-OPERATIONS.md +515 -0
- package/docs/APPBOUNDRY.md +240 -0
- package/docs/ARCHITECTURE.md +126 -0
- package/docs/BACKUP.md +115 -0
- package/docs/GUARANTEES.md +457 -0
- package/docs/PATH-TO-PRODUCTION.md +117 -0
- package/docs/README.md +15 -0
- package/docs/SECURITY.md +182 -0
- package/docs/TRANSACTIONS.md +216 -0
- package/docs/UPSTREAM-GAPS.md +270 -0
- package/docs/WHY-FELTKIT.md +64 -0
- package/docs/assets/feltkit-logo-dark.png +0 -0
- package/docs/assets/feltkit-logo.png +0 -0
- package/package.json +10 -8
- package/skills/.claude-plugin/marketplace.json +1 -1
- package/skills/.claude-plugin/plugin.json +3 -3
- package/skills/feltkit-agent/SKILL.md +9 -5
- package/skills/feltkit-build/SKILL.md +16 -4
- package/skills/feltkit-data/SKILL.md +20 -3
- package/skills/feltkit-services/SKILL.md +13 -7
- package/dist/dashboard/assets/index-BhFOquA7.js +0 -15
- package/dist/dashboard/theme.js +0 -11
package/dist/runtime/sessions.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { readAll } from "./data.js";
|
|
2
3
|
import { normalizePrincipal, toAppPortPrincipal, fromAppPortPrincipal } from "./authority.js";
|
|
3
4
|
export const SESSIONS_COLLECTION = "_feltkit_sessions";
|
|
4
5
|
const digest = (token) => createHash("sha256").update(token).digest("hex");
|
|
@@ -55,7 +56,7 @@ export class FeltDbSessionStore {
|
|
|
55
56
|
async revoke(ref) {
|
|
56
57
|
if (!/^[0-9a-f]{12,64}$/.test(ref))
|
|
57
58
|
return 0;
|
|
58
|
-
const matches = (await this.#db
|
|
59
|
+
const matches = (await readAll(this.#db, { collection: SESSIONS_COLLECTION })).filter((r) => r.id.startsWith(ref));
|
|
59
60
|
if (matches.length !== 1)
|
|
60
61
|
return 0;
|
|
61
62
|
await this.#remove(matches[0].id);
|
|
@@ -63,14 +64,14 @@ export class FeltDbSessionStore {
|
|
|
63
64
|
}
|
|
64
65
|
/** Revoke every session of a principal (a password reset signs the account out everywhere). */
|
|
65
66
|
async revokePrincipal(principalId) {
|
|
66
|
-
const matches = (await this.#db
|
|
67
|
+
const matches = (await readAll(this.#db, { collection: SESSIONS_COLLECTION })).filter((r) => fromAppPortPrincipal(r.principal)?.id === principalId);
|
|
67
68
|
for (const record of matches)
|
|
68
69
|
await this.#remove(record.id);
|
|
69
70
|
return matches.length;
|
|
70
71
|
}
|
|
71
72
|
async list() {
|
|
72
73
|
const now = Date.now();
|
|
73
|
-
return (await this.#db
|
|
74
|
+
return (await readAll(this.#db, { collection: SESSIONS_COLLECTION }))
|
|
74
75
|
.filter((r) => !r.expiresAt || Date.parse(r.expiresAt) > now)
|
|
75
76
|
.map((r) => {
|
|
76
77
|
const attributes = (r.attributes ?? {});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessions.js","sourceRoot":"","sources":["../../src/runtime/sessions.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,oBAAoB,EAAkB,MAAM,gBAAgB,CAAC;AAE9G,MAAM,CAAC,MAAM,mBAAmB,GAAG,mBAAmB,CAAC;AAuBvD,MAAM,MAAM,GAAG,CAAC,KAAa,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAEnF,MAAM,OAAO,kBAAkB;IACpB,GAAG,CAAe;IAC3B,2HAA2H;IAClH,aAAa,CAAS;IAE/B,YAAY,EAAgB,EAAE,UAAqC,EAAE;QACnE,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;QACd,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,YAAY,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IACvE,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,KAAyB;QACpC,MAAM,KAAK,GAAG,OAAO,WAAW,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC;QAC7D,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,MAAM,GAAG,GAAG,KAAK,CAAC,KAAK,CAAC;QACxB,MAAM,MAAM,GAAkB;YAC5B,EAAE,EAAE,MAAM,CAAC,KAAK,CAAC;YACjB,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,KAAK,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC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F"}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The application's schema lifecycle, on FeltDB state contracts.
|
|
3
|
+
*
|
|
4
|
+
* `app.collection(...)` is the one declaration of the application's data. This module
|
|
5
|
+
* compiles it (with the AppPort Services collections the app enables, which share the
|
|
6
|
+
* instance) into a FeltDB state contract and keeps the store's active contract equal to it.
|
|
7
|
+
* FeltDB enforces the contract in its commit decision (types, required fields, unknown
|
|
8
|
+
* fields, references with restrict on delete, unique constraints) and is the only authority
|
|
9
|
+
* on whether stored records satisfy it: installing or evolving a contract re-validates every
|
|
10
|
+
* governed record in one transaction and refuses the whole change if any record fails.
|
|
11
|
+
*
|
|
12
|
+
* FeltKit owns the lifecycle around that:
|
|
13
|
+
*
|
|
14
|
+
* compile app.collection + s.ref + unique/indexes → StateContractDocument
|
|
15
|
+
* plan active contract vs declared, pending app.migration()s run on a staging copy,
|
|
16
|
+
* every resulting record checked with FeltDB's own validateStateRecord, plus
|
|
17
|
+
* one rule FeltDB does not apply: a collection the schema no longer declares must
|
|
18
|
+
* be empty (otherwise its records would be stranded, unreachable and unchecked)
|
|
19
|
+
* apply db.stateContract.evolve(next, tx => staged migration writes + history record)
|
|
20
|
+
*
|
|
21
|
+
* The plan is advice; the authority decides. A refused evolution writes nothing, so the
|
|
22
|
+
* previous contract and data stay usable. History is `_feltkit_migrations` (an ungoverned
|
|
23
|
+
* platform collection), written in the same transaction as the evolution it describes.
|
|
24
|
+
*
|
|
25
|
+
* Constraints FeltKit's schemas express but a version-1 contract cannot (string lengths,
|
|
26
|
+
* numeric ranges, nested object shapes, arrays) stay FeltKit's: every write through `ctx.db`
|
|
27
|
+
* is still validated with the full schema. The contract enforces the structural subset.
|
|
28
|
+
*/
|
|
29
|
+
import { type StateContract, type StateContractChange, type StateContractDocument, type StateFirstDB } from "@feltdb/core";
|
|
30
|
+
import type { FeltKitApp, MigrationDefinition, StoredRecord } from "../app.js";
|
|
31
|
+
import { MIGRATIONS_COLLECTION } from "./data.js";
|
|
32
|
+
export { MIGRATIONS_COLLECTION };
|
|
33
|
+
/**
|
|
34
|
+
* The application's state contract, at `version`. Throws CONFIGURATION, naming each issue,
|
|
35
|
+
* when the declarations cannot form one (a reference to an undeclared collection, …).
|
|
36
|
+
*/
|
|
37
|
+
export declare function compileStateContract(app: FeltKitApp, version?: number, options?: {
|
|
38
|
+
services?: boolean;
|
|
39
|
+
}): StateContract;
|
|
40
|
+
/** The contract's structure, without its version: equal for equal declarations at any version. */
|
|
41
|
+
export declare function structureHash(document: StateContractDocument): string;
|
|
42
|
+
export interface SchemaViolation {
|
|
43
|
+
collection: string;
|
|
44
|
+
id: string;
|
|
45
|
+
field?: string;
|
|
46
|
+
rule: string;
|
|
47
|
+
message: string;
|
|
48
|
+
}
|
|
49
|
+
export interface SchemaPlan {
|
|
50
|
+
/**
|
|
51
|
+
* current the store's active contract is the declared one
|
|
52
|
+
* activate no contract is active yet; the declared one can be installed (records satisfy it)
|
|
53
|
+
* evolve the declared contract differs and the records (after pending migrations) satisfy it
|
|
54
|
+
* blocked records would violate the declared contract, or be stranded in a collection it
|
|
55
|
+
* no longer declares: a migration is needed
|
|
56
|
+
* unmanaged this FeltDB authority does not take a contract from FeltKit (a FeltDB server or
|
|
57
|
+
* Managed FeltDB enforces the contract published to it: `feltkit contract`)
|
|
58
|
+
*/
|
|
59
|
+
status: "current" | "activate" | "evolve" | "blocked" | "unmanaged";
|
|
60
|
+
active: {
|
|
61
|
+
version: number;
|
|
62
|
+
hash: string;
|
|
63
|
+
} | null;
|
|
64
|
+
declared: {
|
|
65
|
+
version: number;
|
|
66
|
+
hash: string;
|
|
67
|
+
};
|
|
68
|
+
changes: StateContractChange[];
|
|
69
|
+
/** Pending `app.migration()`s, in the order they would run. */
|
|
70
|
+
migrations: string[];
|
|
71
|
+
/** Records that would violate the declared contract after the pending migrations (first 20). */
|
|
72
|
+
violations: SchemaViolation[];
|
|
73
|
+
violationCount: number;
|
|
74
|
+
/** Collections the active contract declares and the declared one does not, that still hold records. */
|
|
75
|
+
stranded: Array<{
|
|
76
|
+
collection: string;
|
|
77
|
+
records: number;
|
|
78
|
+
}>;
|
|
79
|
+
/** Writes the pending migrations stage. */
|
|
80
|
+
writes: {
|
|
81
|
+
put: number;
|
|
82
|
+
delete: number;
|
|
83
|
+
};
|
|
84
|
+
/** Why the plan is blocked or unmanaged, in words. */
|
|
85
|
+
reason?: string;
|
|
86
|
+
}
|
|
87
|
+
interface Staged {
|
|
88
|
+
/** collection → id → record (null = deleted) */
|
|
89
|
+
changes: Map<string, Map<string, StoredRecord | null>>;
|
|
90
|
+
/** collection → id → __version as read (for expectedVersion) */
|
|
91
|
+
versions: Map<string, Map<string, number>>;
|
|
92
|
+
}
|
|
93
|
+
export interface MigrationHistory {
|
|
94
|
+
id: string;
|
|
95
|
+
kind: "evolution";
|
|
96
|
+
from: {
|
|
97
|
+
version: number;
|
|
98
|
+
hash: string;
|
|
99
|
+
} | null;
|
|
100
|
+
to: {
|
|
101
|
+
version: number;
|
|
102
|
+
hash: string;
|
|
103
|
+
};
|
|
104
|
+
changes: StateContractChange[];
|
|
105
|
+
migrations: string[];
|
|
106
|
+
writes: {
|
|
107
|
+
put: number;
|
|
108
|
+
delete: number;
|
|
109
|
+
};
|
|
110
|
+
appliedAt: string;
|
|
111
|
+
by: string;
|
|
112
|
+
environment: string;
|
|
113
|
+
}
|
|
114
|
+
/** Names of migrations recorded as applied in this store. */
|
|
115
|
+
export declare function appliedMigrations(db: StateFirstDB): Promise<Set<string>>;
|
|
116
|
+
/**
|
|
117
|
+
* What it would take to make the store's active contract the declared one. Runs the pending
|
|
118
|
+
* migrations against a staging copy and checks the result; writes nothing.
|
|
119
|
+
*/
|
|
120
|
+
/** Where a declared contract comes from: a FeltKit app, or an artifact's manifest. */
|
|
121
|
+
export interface ContractSource {
|
|
122
|
+
compile(version: number): StateContract;
|
|
123
|
+
migrations: readonly MigrationDefinition[];
|
|
124
|
+
}
|
|
125
|
+
export declare function appSource(app: FeltKitApp): ContractSource;
|
|
126
|
+
/** A serialized contract (an artifact's manifest), at any version. No migrations: a host does not run application code to migrate. */
|
|
127
|
+
export declare function documentSource(document: StateContractDocument): ContractSource;
|
|
128
|
+
export declare function planSchema(db: StateFirstDB, appOrSource: FeltKitApp | ContractSource): Promise<SchemaPlan & {
|
|
129
|
+
staged: Staged;
|
|
130
|
+
next: StateContract;
|
|
131
|
+
intermediate?: StateContract;
|
|
132
|
+
}>;
|
|
133
|
+
/** A plan in words, for the CLI, the dev server and errors. */
|
|
134
|
+
export declare function describePlan(plan: SchemaPlan): string[];
|
|
135
|
+
/** The hint for a blocked plan: what to write. */
|
|
136
|
+
export declare function blockedHint(plan: SchemaPlan): string;
|
|
137
|
+
export interface SchemaApplied {
|
|
138
|
+
from: {
|
|
139
|
+
version: number;
|
|
140
|
+
hash: string;
|
|
141
|
+
} | null;
|
|
142
|
+
to: {
|
|
143
|
+
version: number;
|
|
144
|
+
hash: string;
|
|
145
|
+
};
|
|
146
|
+
changes: StateContractChange[];
|
|
147
|
+
migrations: string[];
|
|
148
|
+
writes: {
|
|
149
|
+
put: number;
|
|
150
|
+
delete: number;
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Install the declared contract: one FeltDB transaction holding the staged migration writes
|
|
155
|
+
* (each conditioned on the version it read), the new contract, and its history record.
|
|
156
|
+
* FeltDB re-validates every governed record and refuses the whole transaction if any fails;
|
|
157
|
+
* then nothing changed. A plan that is blocked is refused here before FeltDB is asked.
|
|
158
|
+
*/
|
|
159
|
+
export declare function applySchema(db: StateFirstDB, app: FeltKitApp | ContractSource, options: {
|
|
160
|
+
by: string;
|
|
161
|
+
environment: string;
|
|
162
|
+
}): Promise<SchemaApplied | null>;
|
|
163
|
+
/** A plan without its staging internals (for JSON output). */
|
|
164
|
+
export declare function publicPlan(plan: SchemaPlan & {
|
|
165
|
+
staged?: unknown;
|
|
166
|
+
next?: unknown;
|
|
167
|
+
}): SchemaPlan;
|
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The application's schema lifecycle, on FeltDB state contracts.
|
|
3
|
+
*
|
|
4
|
+
* `app.collection(...)` is the one declaration of the application's data. This module
|
|
5
|
+
* compiles it (with the AppPort Services collections the app enables, which share the
|
|
6
|
+
* instance) into a FeltDB state contract and keeps the store's active contract equal to it.
|
|
7
|
+
* FeltDB enforces the contract in its commit decision (types, required fields, unknown
|
|
8
|
+
* fields, references with restrict on delete, unique constraints) and is the only authority
|
|
9
|
+
* on whether stored records satisfy it: installing or evolving a contract re-validates every
|
|
10
|
+
* governed record in one transaction and refuses the whole change if any record fails.
|
|
11
|
+
*
|
|
12
|
+
* FeltKit owns the lifecycle around that:
|
|
13
|
+
*
|
|
14
|
+
* compile app.collection + s.ref + unique/indexes → StateContractDocument
|
|
15
|
+
* plan active contract vs declared, pending app.migration()s run on a staging copy,
|
|
16
|
+
* every resulting record checked with FeltDB's own validateStateRecord, plus
|
|
17
|
+
* one rule FeltDB does not apply: a collection the schema no longer declares must
|
|
18
|
+
* be empty (otherwise its records would be stranded, unreachable and unchecked)
|
|
19
|
+
* apply db.stateContract.evolve(next, tx => staged migration writes + history record)
|
|
20
|
+
*
|
|
21
|
+
* The plan is advice; the authority decides. A refused evolution writes nothing, so the
|
|
22
|
+
* previous contract and data stay usable. History is `_feltkit_migrations` (an ungoverned
|
|
23
|
+
* platform collection), written in the same transaction as the evolution it describes.
|
|
24
|
+
*
|
|
25
|
+
* Constraints FeltKit's schemas express but a version-1 contract cannot (string lengths,
|
|
26
|
+
* numeric ranges, nested object shapes, arrays) stay FeltKit's: every write through `ctx.db`
|
|
27
|
+
* is still validated with the full schema. The contract enforces the structural subset.
|
|
28
|
+
*/
|
|
29
|
+
import { compareStateContracts, defineStateContract, field, parseStateContract, validateStateRecord } from "@feltdb/core";
|
|
30
|
+
import { servicesContract } from "@appport/services";
|
|
31
|
+
import { FeltKitError } from "../errors.js";
|
|
32
|
+
import { REFERENCE_KEYWORD } from "../schema.js";
|
|
33
|
+
import { enabledServices } from "./contract.js";
|
|
34
|
+
import { migrationContext as sharedMigrationContext } from "./migration-context.js";
|
|
35
|
+
import { MIGRATIONS_COLLECTION, readAll } from "./data.js";
|
|
36
|
+
export { MIGRATIONS_COLLECTION };
|
|
37
|
+
/**
|
|
38
|
+
* The tuple a unique constraint compares, as FeltDB compares it: a missing value counts as
|
|
39
|
+
* null and two nulls collide, unless the constraint is sparse (then a record with any null
|
|
40
|
+
* or missing value is not compared).
|
|
41
|
+
*/
|
|
42
|
+
function uniqueKey(record, unique) {
|
|
43
|
+
const values = unique.fields.map((f) => record[f] ?? null);
|
|
44
|
+
if (unique.sparse && values.some((v) => v === null))
|
|
45
|
+
return undefined;
|
|
46
|
+
return JSON.stringify(values);
|
|
47
|
+
}
|
|
48
|
+
/** How many violations a plan lists (it counts all of them). */
|
|
49
|
+
const LISTED = 20;
|
|
50
|
+
/** One FeltKit field (as JSON Schema) → a contract field. Anything a v1 contract cannot type is `json`. */
|
|
51
|
+
function contractField(schema, required) {
|
|
52
|
+
const variants = Array.isArray(schema.anyOf) ? schema.anyOf : [schema];
|
|
53
|
+
const nullable = variants.some((v) => v.type === "null");
|
|
54
|
+
const present = variants.filter((v) => v.type !== "null");
|
|
55
|
+
// FeltDB: a required field cannot be nullable. FeltKit still requires presence on its own writes.
|
|
56
|
+
const options = { required: required && !nullable, nullable };
|
|
57
|
+
if (present.length === 1) {
|
|
58
|
+
const only = present[0];
|
|
59
|
+
if (typeof only[REFERENCE_KEYWORD] === "string")
|
|
60
|
+
return field.reference(only[REFERENCE_KEYWORD], options);
|
|
61
|
+
if (only.type === "string" && Array.isArray(only.enum) && only.enum.length && only.enum.every((v) => typeof v === "string"))
|
|
62
|
+
return field.enum(only.enum, options);
|
|
63
|
+
if (typeof only.const === "string")
|
|
64
|
+
return field.enum([only.const], options);
|
|
65
|
+
if (only.type === "string")
|
|
66
|
+
return field.string(options);
|
|
67
|
+
if (only.type === "integer")
|
|
68
|
+
return field.integer(options);
|
|
69
|
+
if (only.type === "number")
|
|
70
|
+
return field.number(options);
|
|
71
|
+
if (only.type === "boolean")
|
|
72
|
+
return field.boolean(options);
|
|
73
|
+
}
|
|
74
|
+
return field.json(options);
|
|
75
|
+
}
|
|
76
|
+
function collectionDeclaration(definition) {
|
|
77
|
+
const json = definition.schema.toJSONSchema();
|
|
78
|
+
const required = new Set(json.required ?? []);
|
|
79
|
+
const fields = {};
|
|
80
|
+
for (const [name, schema] of Object.entries(json.properties ?? {}))
|
|
81
|
+
fields[name] = contractField(schema, required.has(name));
|
|
82
|
+
return {
|
|
83
|
+
fields,
|
|
84
|
+
...(definition.unique?.length ? { unique: definition.unique.map((u) => (Array.isArray(u) ? [...u] : { ...u })) } : {}),
|
|
85
|
+
...(definition.indexes?.length ? { indexes: definition.indexes.map((i) => ({ ...(i.name ? { name: i.name } : {}), fields: [...i.fields] })) } : {}),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
/** AppPort Services' declared collections (its own `servicesContract`), as contract collections. */
|
|
89
|
+
function servicesDeclarations(app) {
|
|
90
|
+
const services = enabledServices(app);
|
|
91
|
+
if (!services.length)
|
|
92
|
+
return { collections: {}, indexes: [] };
|
|
93
|
+
const fragment = servicesContract([...services, "configuration"]);
|
|
94
|
+
const collections = {};
|
|
95
|
+
for (const collection of fragment.collections) {
|
|
96
|
+
const fields = {};
|
|
97
|
+
for (const f of collection.fields) {
|
|
98
|
+
if (f.name === "id")
|
|
99
|
+
continue;
|
|
100
|
+
const options = { required: Boolean(f.required) && !f.nullable, nullable: Boolean(f.nullable) };
|
|
101
|
+
fields[f.name] =
|
|
102
|
+
f.type === "text" || f.type === "string" ? field.string(options)
|
|
103
|
+
: f.type === "integer" ? field.integer(options)
|
|
104
|
+
: f.type === "number" ? field.number(options)
|
|
105
|
+
: f.type === "boolean" ? field.boolean(options)
|
|
106
|
+
: field.json(options);
|
|
107
|
+
}
|
|
108
|
+
collections[collection.name] = { fields };
|
|
109
|
+
}
|
|
110
|
+
for (const index of fragment.indexes) {
|
|
111
|
+
const target = collections[index.collection];
|
|
112
|
+
if (target)
|
|
113
|
+
(target.indexes ??= []).push({ name: index.name, fields: [...index.fields] });
|
|
114
|
+
}
|
|
115
|
+
return { collections, indexes: fragment.indexes };
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* The application's state contract, at `version`. Throws CONFIGURATION, naming each issue,
|
|
119
|
+
* when the declarations cannot form one (a reference to an undeclared collection, …).
|
|
120
|
+
*/
|
|
121
|
+
export function compileStateContract(app, version = 1, options = {}) {
|
|
122
|
+
const collections = {};
|
|
123
|
+
for (const definition of app.collections.values())
|
|
124
|
+
collections[definition.name] = collectionDeclaration(definition);
|
|
125
|
+
// The services share the instance on a FeltKit server; an artifact's host keeps its own.
|
|
126
|
+
if (options.services !== false) {
|
|
127
|
+
for (const [name, declaration] of Object.entries(servicesDeclarations(app).collections)) {
|
|
128
|
+
if (!(name in collections))
|
|
129
|
+
collections[name] = declaration;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
try {
|
|
133
|
+
return defineStateContract({ name: app.name, version, collections });
|
|
134
|
+
}
|
|
135
|
+
catch (error) {
|
|
136
|
+
const issues = (error.issues ?? []).map((i) => `${i.path}: ${i.message}`);
|
|
137
|
+
throw new FeltKitError("CONFIGURATION", `The collections cannot form a FeltDB state contract:\n ${issues.join("\n ") || error.message}`, {
|
|
138
|
+
hint: "Each line names the collection and field. s.ref() must name a declared collection; unique constraints and indexes must name declared fields.",
|
|
139
|
+
details: { issues },
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** The contract's structure, without its version: equal for equal declarations at any version. */
|
|
144
|
+
export function structureHash(document) {
|
|
145
|
+
return parseStateContract({ ...document, version: 1 }).hash;
|
|
146
|
+
}
|
|
147
|
+
/** Committed records of one collection, without system fields (recording each version read). */
|
|
148
|
+
async function committed(db, name, staged) {
|
|
149
|
+
const rows = (await readAll(db, { collection: name }));
|
|
150
|
+
const versions = staged.versions.get(name) ?? new Map();
|
|
151
|
+
staged.versions.set(name, versions);
|
|
152
|
+
return rows.map(({ __version, ...record }) => {
|
|
153
|
+
versions.set(record.id, __version);
|
|
154
|
+
return record;
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
/** The migration API (runtime/migration-context.ts, shared with AppBoundry artifacts) over this store. */
|
|
158
|
+
function migrationContext(db, staged) {
|
|
159
|
+
return sharedMigrationContext((name) => committed(db, name, staged), staged);
|
|
160
|
+
}
|
|
161
|
+
/** Names of migrations recorded as applied in this store. */
|
|
162
|
+
export async function appliedMigrations(db) {
|
|
163
|
+
const rows = (await readAll(db, { collection: MIGRATIONS_COLLECTION }));
|
|
164
|
+
return new Set(rows.flatMap((r) => (Array.isArray(r.migrations) ? r.migrations : [])));
|
|
165
|
+
}
|
|
166
|
+
function supportsContracts(db) {
|
|
167
|
+
try {
|
|
168
|
+
return db.capabilities().stateContract === "enforced";
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
export function appSource(app) {
|
|
175
|
+
return { compile: (version) => compileStateContract(app, version), migrations: app.migrations };
|
|
176
|
+
}
|
|
177
|
+
/** A serialized contract (an artifact's manifest), at any version. No migrations: a host does not run application code to migrate. */
|
|
178
|
+
export function documentSource(document) {
|
|
179
|
+
return { compile: (version) => parseStateContract({ ...document, version }), migrations: [] };
|
|
180
|
+
}
|
|
181
|
+
export async function planSchema(db, appOrSource) {
|
|
182
|
+
const source = "compile" in appOrSource ? appOrSource : appSource(appOrSource);
|
|
183
|
+
const empty = { changes: new Map(), versions: new Map() };
|
|
184
|
+
const declaredAt1 = source.compile(1);
|
|
185
|
+
const base = { violations: [], violationCount: 0, stranded: [], writes: { put: 0, delete: 0 }, migrations: [] };
|
|
186
|
+
if (!supportsContracts(db)) {
|
|
187
|
+
return { ...base, status: "unmanaged", active: null, declared: { version: 1, hash: declaredAt1.hash }, changes: [], staged: empty, next: declaredAt1, reason: "This FeltDB authority enforces the contract published to it (FeltDB server or Managed FeltDB): `feltkit contract`, then `feltdb publish --contract`." };
|
|
188
|
+
}
|
|
189
|
+
const active = await db.stateContract.active();
|
|
190
|
+
const activeContract = active ? parseStateContract(active.document) : null;
|
|
191
|
+
const same = activeContract ? structureHash(activeContract.document) === structureHash(declaredAt1.document) : false;
|
|
192
|
+
let next = activeContract ? (same ? activeContract : source.compile(activeContract.version + 1)) : declaredAt1;
|
|
193
|
+
const applied = await appliedMigrations(db);
|
|
194
|
+
const pending = source.migrations.filter((m) => !applied.has(m.name));
|
|
195
|
+
const changes = activeContract && !same ? compareStateContracts(activeContract, next) : [];
|
|
196
|
+
const summary = { active: active ? { version: active.version, hash: active.hash } : null, declared: { version: next.version, hash: next.hash }, changes };
|
|
197
|
+
if (same && !pending.length)
|
|
198
|
+
return { ...base, ...summary, status: "current", staged: empty, next };
|
|
199
|
+
// Run the pending migrations on a staging copy.
|
|
200
|
+
const staged = { changes: new Map(), versions: new Map() };
|
|
201
|
+
const m = migrationContext(db, staged);
|
|
202
|
+
for (const migration of pending) {
|
|
203
|
+
try {
|
|
204
|
+
await migration.run(m);
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
return { ...base, ...summary, migrations: pending.map((p) => p.name), status: "blocked", staged, next, reason: `Migration "${migration.name}" failed: ${error.message}` };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const writes = { put: 0, delete: 0 };
|
|
211
|
+
for (const changes of staged.changes.values())
|
|
212
|
+
for (const value of changes.values())
|
|
213
|
+
value === null ? writes.delete++ : writes.put++;
|
|
214
|
+
// Migration writes to a collection the new schema removes cannot be in the transaction that
|
|
215
|
+
// removes it (FeltDB refuses writes to an undeclared collection). Those go through an
|
|
216
|
+
// intermediate version that still declares it; the final version then drops it, empty.
|
|
217
|
+
let intermediate;
|
|
218
|
+
if (activeContract && !same) {
|
|
219
|
+
const removedWithWrites = [...staged.changes.keys()].filter((name) => !next.collection(name) && activeContract.collection(name));
|
|
220
|
+
if (removedWithWrites.length) {
|
|
221
|
+
const kept = activeContract.document.collections.filter((c) => removedWithWrites.includes(c.name));
|
|
222
|
+
const keptIndexes = activeContract.document.indexes.filter((i) => removedWithWrites.includes(i.collection));
|
|
223
|
+
intermediate = parseStateContract({ ...next.document, version: activeContract.version + 1, collections: [...next.document.collections, ...kept], indexes: [...next.document.indexes, ...keptIndexes] });
|
|
224
|
+
next = source.compile(activeContract.version + 2);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
// Check the state the evolution would leave, as FeltDB will: fields, unique constraints, references.
|
|
228
|
+
const violations = [];
|
|
229
|
+
let violationCount = 0;
|
|
230
|
+
const add = (v) => {
|
|
231
|
+
violationCount += 1;
|
|
232
|
+
if (violations.length < LISTED)
|
|
233
|
+
violations.push(v);
|
|
234
|
+
};
|
|
235
|
+
const finalState = new Map();
|
|
236
|
+
for (const name of next.collections)
|
|
237
|
+
finalState.set(name, await m.records(name));
|
|
238
|
+
for (const name of next.collections) {
|
|
239
|
+
const collection = next.collection(name);
|
|
240
|
+
const seen = new Map();
|
|
241
|
+
for (const record of finalState.get(name)) {
|
|
242
|
+
const { id, ...value } = record;
|
|
243
|
+
const checked = validateStateRecord(collection, id, value, { applyDefaults: false });
|
|
244
|
+
if (!checked.ok)
|
|
245
|
+
add({ collection: name, id, rule: checked.violation.rule, message: checked.violation.message.startsWith(`${name}:`) ? checked.violation.message : `${name}:${id}: ${checked.violation.message}`, ...(checked.violation.field ? { field: checked.violation.field } : {}) });
|
|
246
|
+
for (const unique of collection.unique) {
|
|
247
|
+
const key = uniqueKey(record, unique);
|
|
248
|
+
if (key === undefined)
|
|
249
|
+
continue;
|
|
250
|
+
const holders = seen.get(unique.name) ?? new Map();
|
|
251
|
+
seen.set(unique.name, holders);
|
|
252
|
+
const other = holders.get(key);
|
|
253
|
+
if (other !== undefined)
|
|
254
|
+
add({ collection: name, id, rule: "unique", message: `${name}:${id} has the same ${unique.fields.join(", ")} as ${name}:${other}` });
|
|
255
|
+
else
|
|
256
|
+
holders.set(key, id);
|
|
257
|
+
}
|
|
258
|
+
for (const f of collection.fields) {
|
|
259
|
+
const target = f.reference ? record[f.name] : undefined;
|
|
260
|
+
if (f.reference && typeof target === "string" && !(finalState.get(f.reference) ?? []).some((r) => r.id === target)) {
|
|
261
|
+
add({ collection: name, id, field: f.name, rule: "reference", message: `${name}:${id}.${f.name} references ${f.reference}:${target}, which does not exist` });
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
// FeltDB accepts dropping a collection that still holds records; FeltKit does not.
|
|
267
|
+
const stranded = [];
|
|
268
|
+
for (const name of activeContract?.collections ?? []) {
|
|
269
|
+
if (next.collection(name))
|
|
270
|
+
continue;
|
|
271
|
+
const left = (await m.records(name)).length;
|
|
272
|
+
if (left)
|
|
273
|
+
stranded.push({ collection: name, records: left });
|
|
274
|
+
}
|
|
275
|
+
const blocked = violationCount > 0 || stranded.length > 0;
|
|
276
|
+
const reason = blocked
|
|
277
|
+
? [
|
|
278
|
+
violationCount ? `${violationCount} record(s) would not satisfy the new schema (first: ${violations[0].message})` : "",
|
|
279
|
+
...stranded.map((s) => `${s.collection} is no longer declared but holds ${s.records} record(s), which would be stranded`),
|
|
280
|
+
].filter(Boolean).join("; ")
|
|
281
|
+
: undefined;
|
|
282
|
+
return {
|
|
283
|
+
...summary,
|
|
284
|
+
status: blocked ? "blocked" : activeContract ? "evolve" : "activate",
|
|
285
|
+
migrations: pending.map((p) => p.name),
|
|
286
|
+
violations,
|
|
287
|
+
violationCount,
|
|
288
|
+
stranded,
|
|
289
|
+
writes,
|
|
290
|
+
staged,
|
|
291
|
+
next,
|
|
292
|
+
...(intermediate ? { intermediate } : {}),
|
|
293
|
+
...(reason ? { reason } : {}),
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
/** A plan in words, for the CLI, the dev server and errors. */
|
|
297
|
+
export function describePlan(plan) {
|
|
298
|
+
const lines = [];
|
|
299
|
+
const from = plan.active ? `v${plan.active.version}` : "none";
|
|
300
|
+
if (plan.status === "current")
|
|
301
|
+
return [`Schema v${plan.declared.version} is active and matches feltkit/ (nothing to migrate).`];
|
|
302
|
+
if (plan.status === "unmanaged")
|
|
303
|
+
return [plan.reason];
|
|
304
|
+
lines.push(`Schema: active ${from} → declared v${plan.declared.version}`);
|
|
305
|
+
for (const change of plan.changes)
|
|
306
|
+
lines.push(` ${change.kind.padEnd(7)} ${change.path}${change.effect === "revalidates" ? " (existing records re-checked)" : ""}`);
|
|
307
|
+
if (!plan.active)
|
|
308
|
+
lines.push(" install the schema your collections declare (existing records are checked first)");
|
|
309
|
+
for (const name of plan.migrations)
|
|
310
|
+
lines.push(` migration "${name}"`);
|
|
311
|
+
if (plan.writes.put || plan.writes.delete)
|
|
312
|
+
lines.push(` writes: ${plan.writes.put} record(s) written, ${plan.writes.delete} deleted`);
|
|
313
|
+
for (const v of plan.violations)
|
|
314
|
+
lines.push(` ✗ ${v.message} (${v.rule})`);
|
|
315
|
+
if (plan.violationCount > plan.violations.length)
|
|
316
|
+
lines.push(` … and ${plan.violationCount - plan.violations.length} more`);
|
|
317
|
+
for (const s of plan.stranded)
|
|
318
|
+
lines.push(` ✗ ${s.collection}: no longer declared, still holds ${s.records} record(s)`);
|
|
319
|
+
return lines;
|
|
320
|
+
}
|
|
321
|
+
/** The hint for a blocked plan: what to write. */
|
|
322
|
+
export function blockedHint(plan) {
|
|
323
|
+
const v = plan.violations[0];
|
|
324
|
+
if (plan.stranded.length) {
|
|
325
|
+
const s = plan.stranded[0];
|
|
326
|
+
return `Declare a migration in feltkit/app.ts that moves or deletes them, e.g. app.migration("drop ${s.collection}", (m) => m.update("${s.collection}", () => null)); then run \`npx feltkit migrate\`.`;
|
|
327
|
+
}
|
|
328
|
+
if (v?.rule === "required" && v.field) {
|
|
329
|
+
return `Declare a migration in feltkit/app.ts that fills it, e.g. app.migration("${v.collection}.${v.field}", (m) => m.update("${v.collection}", (r) => ({ ...r, ${v.field}: /* value */ }))); or make the field optional. Then run \`npx feltkit migrate\`.`;
|
|
330
|
+
}
|
|
331
|
+
if (v?.rule === "unknown_field" && v.field) {
|
|
332
|
+
return `A field was removed while records still hold it. Declare a migration that drops it, e.g. app.migration("drop ${v.collection}.${v.field}", (m) => m.update("${v.collection}", ({ ${v.field}: _, ...r }) => r)); then run \`npx feltkit migrate\`.`;
|
|
333
|
+
}
|
|
334
|
+
return "Declare an app.migration() in feltkit/app.ts that rewrites the records named above, then run `npx feltkit migrate`.";
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Install the declared contract: one FeltDB transaction holding the staged migration writes
|
|
338
|
+
* (each conditioned on the version it read), the new contract, and its history record.
|
|
339
|
+
* FeltDB re-validates every governed record and refuses the whole transaction if any fails;
|
|
340
|
+
* then nothing changed. A plan that is blocked is refused here before FeltDB is asked.
|
|
341
|
+
*/
|
|
342
|
+
export async function applySchema(db, app, options) {
|
|
343
|
+
const plan = await planSchema(db, app);
|
|
344
|
+
if (plan.status === "current" || plan.status === "unmanaged")
|
|
345
|
+
return null;
|
|
346
|
+
if (plan.status === "blocked") {
|
|
347
|
+
throw new FeltKitError("FAILED_PRECONDITION", `The schema cannot be applied: ${plan.reason}. Nothing was changed.`, { hint: blockedHint(plan), details: { plan: publicPlan(plan) } });
|
|
348
|
+
}
|
|
349
|
+
const history = (to) => ({
|
|
350
|
+
// A migration-carrying record gets its own id: a data-only migration keeps the contract (and
|
|
351
|
+
// its hash), and must not overwrite the record of the migrations applied before it.
|
|
352
|
+
id: `v${to.version}-${to.hash.slice(7, 19)}${plan.migrations.length ? `-${Date.now().toString(36)}` : ""}`,
|
|
353
|
+
kind: "evolution",
|
|
354
|
+
from: plan.active,
|
|
355
|
+
to,
|
|
356
|
+
changes: plan.changes,
|
|
357
|
+
migrations: plan.migrations,
|
|
358
|
+
writes: plan.writes,
|
|
359
|
+
appliedAt: new Date().toISOString(),
|
|
360
|
+
by: options.by,
|
|
361
|
+
environment: options.environment,
|
|
362
|
+
});
|
|
363
|
+
const record = history({ version: plan.next.version, hash: plan.next.hash });
|
|
364
|
+
const stage = (tx) => {
|
|
365
|
+
for (const [name, changes] of plan.staged.changes) {
|
|
366
|
+
const versions = plan.staged.versions.get(name);
|
|
367
|
+
for (const [id, value] of changes) {
|
|
368
|
+
const version = versions?.get(id);
|
|
369
|
+
const guard = version === undefined ? { requireAbsent: true } : { expectedVersion: version };
|
|
370
|
+
if (value === null) {
|
|
371
|
+
if (version !== undefined)
|
|
372
|
+
tx.collection(name).delete(id, guard);
|
|
373
|
+
}
|
|
374
|
+
else
|
|
375
|
+
tx.collection(name).set(id, value, guard);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
tx.collection(MIGRATIONS_COLLECTION).set(record.id, record);
|
|
379
|
+
};
|
|
380
|
+
try {
|
|
381
|
+
const sameContract = plan.active?.hash === plan.next.hash;
|
|
382
|
+
if (sameContract) {
|
|
383
|
+
// Data-only migrations: the schema is unchanged.
|
|
384
|
+
await db.transaction(((tx) => stage(tx)));
|
|
385
|
+
}
|
|
386
|
+
else if (plan.intermediate) {
|
|
387
|
+
// 1. The new schema plus the collections it removes, with every migration write. 2. Drop
|
|
388
|
+
// those collections, now empty. A stop between the two leaves a valid, enforced schema;
|
|
389
|
+
// the next start finishes step 2 (dropping an empty collection needs nothing). The
|
|
390
|
+
// migrations are recorded in step 1, with their writes, so that stop never runs them again.
|
|
391
|
+
const step = plan.intermediate;
|
|
392
|
+
await db.stateContract.evolve(step, (tx) => {
|
|
393
|
+
tx.collection(MIGRATIONS_COLLECTION).set(`${record.id}-step`, { ...record, id: `${record.id}-step`, to: { version: step.version, hash: step.hash } });
|
|
394
|
+
for (const [name, changes] of plan.staged.changes) {
|
|
395
|
+
const versions = plan.staged.versions.get(name);
|
|
396
|
+
for (const [id, value] of changes) {
|
|
397
|
+
const version = versions?.get(id);
|
|
398
|
+
const guard = version === undefined ? { requireAbsent: true } : { expectedVersion: version };
|
|
399
|
+
if (value === null) {
|
|
400
|
+
if (version !== undefined)
|
|
401
|
+
tx.collection(name).delete(id, guard);
|
|
402
|
+
}
|
|
403
|
+
else
|
|
404
|
+
tx.collection(name).set(id, value, guard);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
});
|
|
408
|
+
await db.stateContract.evolve(plan.next, (tx) => {
|
|
409
|
+
tx.collection(MIGRATIONS_COLLECTION).set(record.id, record);
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
else {
|
|
413
|
+
await db.stateContract.evolve(plan.next, (tx) => stage(tx));
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
catch (error) {
|
|
417
|
+
throw refusal(error);
|
|
418
|
+
}
|
|
419
|
+
return { from: plan.active, to: record.to, changes: plan.changes, migrations: plan.migrations, writes: plan.writes };
|
|
420
|
+
}
|
|
421
|
+
/** FeltDB's refusal of an evolution, in FeltKit's terms. Nothing was written. */
|
|
422
|
+
function refusal(error) {
|
|
423
|
+
const e = error;
|
|
424
|
+
const violation = e.violation;
|
|
425
|
+
const what = violation?.message ?? e.message ?? String(error);
|
|
426
|
+
const code = e.code === "CONFLICT" || e.code === "VERSION_CONFLICT" || e.code === "PRECONDITION_FAILED" ? "CONFLICT" : "FAILED_PRECONDITION";
|
|
427
|
+
return new FeltKitError(code, `FeltDB refused the schema change: ${what}. Nothing was changed; the previous schema and data are intact.`, {
|
|
428
|
+
cause: error,
|
|
429
|
+
hint: code === "CONFLICT" ? "Records changed while the migration ran. Run it again." : "Declare an app.migration() that rewrites the record named, then run `npx feltkit migrate` again.",
|
|
430
|
+
details: { feltdbCode: e.code, ...(violation ? { violation } : {}) },
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
/** A plan without its staging internals (for JSON output). */
|
|
434
|
+
export function publicPlan(plan) {
|
|
435
|
+
const { staged: _s, next: _n, intermediate: _i, ...rest } = plan;
|
|
436
|
+
return rest;
|
|
437
|
+
}
|
|
438
|
+
//# sourceMappingURL=state-contract.js.map
|