@feltdb/feltkit 0.3.2 → 0.3.4

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.
Files changed (58) hide show
  1. package/README.md +7 -0
  2. package/dist/cli/deploy.d.ts +14 -1
  3. package/dist/cli/deploy.js +421 -64
  4. package/dist/cli/deploy.js.map +1 -1
  5. package/dist/cli/main.js +89 -17
  6. package/dist/cli/main.js.map +1 -1
  7. package/dist/dashboard/apple-touch-icon.png +0 -0
  8. package/dist/dashboard/assets/feltkit-mark-BygpVIiS.png +0 -0
  9. package/dist/dashboard/assets/index-B-ra0AY9.css +1 -0
  10. package/dist/dashboard/assets/index-DnJaSnzt.js +15 -0
  11. package/dist/dashboard/favicon.png +0 -0
  12. package/dist/dashboard/index.html +5 -3
  13. package/dist/dashboard/theme.js +6 -0
  14. package/dist/runtime/changes.d.ts +9 -0
  15. package/dist/runtime/changes.js +47 -3
  16. package/dist/runtime/changes.js.map +1 -1
  17. package/dist/runtime/connect.d.ts +65 -0
  18. package/dist/runtime/connect.js +246 -0
  19. package/dist/runtime/connect.js.map +1 -0
  20. package/dist/runtime/contract.d.ts +15 -5
  21. package/dist/runtime/contract.js +36 -12
  22. package/dist/runtime/contract.js.map +1 -1
  23. package/dist/runtime/decisions.d.ts +32 -4
  24. package/dist/runtime/decisions.js +69 -0
  25. package/dist/runtime/decisions.js.map +1 -1
  26. package/dist/runtime/environment.js +41 -0
  27. package/dist/runtime/environment.js.map +1 -1
  28. package/dist/runtime/readiness.js +5 -3
  29. package/dist/runtime/readiness.js.map +1 -1
  30. package/dist/runtime/runtime.d.ts +11 -0
  31. package/dist/runtime/runtime.js +33 -15
  32. package/dist/runtime/runtime.js.map +1 -1
  33. package/dist/runtime/services.d.ts +11 -2
  34. package/dist/runtime/services.js +5 -0
  35. package/dist/runtime/services.js.map +1 -1
  36. package/dist/runtime/storage-check.d.ts +12 -0
  37. package/dist/runtime/storage-check.js +99 -0
  38. package/dist/runtime/storage-check.js.map +1 -0
  39. package/dist/runtime/targets.d.ts +72 -0
  40. package/dist/runtime/targets.js +173 -0
  41. package/dist/runtime/targets.js.map +1 -0
  42. package/dist/server/admin.js +153 -0
  43. package/dist/server/admin.js.map +1 -1
  44. package/dist/server/brand.d.ts +5 -0
  45. package/dist/server/brand.js +6 -0
  46. package/dist/server/brand.js.map +1 -0
  47. package/dist/server/index.js +50 -0
  48. package/dist/server/index.js.map +1 -1
  49. package/dist/server/project.d.ts +8 -0
  50. package/dist/server/project.js +30 -3
  51. package/dist/server/project.js.map +1 -1
  52. package/package.json +5 -5
  53. package/skills/.claude-plugin/marketplace.json +1 -1
  54. package/skills/.claude-plugin/plugin.json +1 -1
  55. package/skills/feltkit-operations/SKILL.md +3 -1
  56. package/skills/feltkit-services/SKILL.md +3 -3
  57. package/dist/dashboard/assets/index-Bo2oHR18.css +0 -1
  58. package/dist/dashboard/assets/index-DK_Jda9P.js +0 -15
Binary file
@@ -5,10 +5,12 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <meta name="color-scheme" content="light dark" />
7
7
  <meta name="referrer" content="no-referrer" />
8
- <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='8' fill='%23111827'/%3E%3Cpath d='M11 7c-4 5-4 13 0 18M21 7c4 5 4 13 0 18' stroke='%2334d399' stroke-width='3' fill='none' stroke-linecap='round'/%3E%3C/svg%3E" />
8
+ <link rel="icon" href="/_feltkit/favicon.png" type="image/png" />
9
+ <link rel="apple-touch-icon" href="/_feltkit/apple-touch-icon.png" />
9
10
  <title>FeltKit</title>
10
- <script type="module" crossorigin src="/_feltkit/assets/index-DK_Jda9P.js"></script>
11
- <link rel="stylesheet" crossorigin href="/_feltkit/assets/index-Bo2oHR18.css">
11
+ <script src="/_feltkit/theme.js"></script>
12
+ <script type="module" crossorigin src="/_feltkit/assets/index-DnJaSnzt.js"></script>
13
+ <link rel="stylesheet" crossorigin href="/_feltkit/assets/index-B-ra0AY9.css">
12
14
  </head>
13
15
  <body>
14
16
  <div id="root"></div>
@@ -0,0 +1,6 @@
1
+ // Applies the chosen theme before first paint, so a dark-mode user never sees a light flash.
2
+ // Same key and values as src/theme.ts. A file, not inline: Studio's CSP allows only 'self' scripts.
3
+ try {
4
+ var theme = localStorage.getItem("feltkit:dashboard-theme");
5
+ if (theme === "light" || theme === "dark") document.documentElement.dataset.theme = theme;
6
+ } catch (e) {}
@@ -18,6 +18,14 @@
18
18
  * Guarantee: within one server process, every committed write produces a change event
19
19
  * naming its collection, at least once, within roughly one poll interval. Local state
20
20
  * has one writing process (FeltDB's owner lock), so there are no other writers to miss.
21
+ *
22
+ * On a FeltDB server (`remote`), there is no journal to read here (the client's sequence
23
+ * is always 0), and other processes write too: several containers, or a platform such as
24
+ * Vercel that runs many instances. There the feed polls FeltKit's own change markers
25
+ * (`_feltkit_collections`, which every FeltKit commit stamps with its transaction id, in
26
+ * the same transaction) and reports each collection whose stamp changed, whichever
27
+ * process committed it. Writes that bypass FeltKit's commit path (AppPort Services'
28
+ * own stores, `ctx.unsafe.feltdb`) stamp no marker, so they are not reported there.
21
29
  */
22
30
  import type { StateFirstDB } from "@feltdb/core";
23
31
  export interface ChangeEvent {
@@ -32,6 +40,7 @@ export declare class ChangeFeed {
32
40
  lastError: string | null;
33
41
  constructor(db: StateFirstDB, options?: {
34
42
  intervalMs?: number;
43
+ remote?: boolean;
35
44
  });
36
45
  get position(): number;
37
46
  start(): void;
@@ -1,3 +1,4 @@
1
+ import { COLLECTION_MARKERS } from "./data.js";
1
2
  export class ChangeFeed {
2
3
  #db;
3
4
  #listeners = new Set();
@@ -6,11 +7,16 @@ export class ChangeFeed {
6
7
  #timer;
7
8
  #running = null;
8
9
  #pending = false;
10
+ #remote;
11
+ /** Remote mode: each collection marker's last seen stamp; null until the first read. */
12
+ #stamps = null;
9
13
  lastError = null;
10
14
  constructor(db, options = {}) {
11
15
  this.#db = db;
12
- this.#intervalMs = options.intervalMs ?? 150;
13
- this.#position = safeSequence(db);
16
+ this.#remote = options.remote ?? false;
17
+ // A FeltDB server is a network round trip away: poll it less often.
18
+ this.#intervalMs = options.intervalMs ?? (this.#remote ? 1000 : 150);
19
+ this.#position = this.#remote ? 0 : safeSequence(db);
14
20
  }
15
21
  get position() {
16
22
  return this.#position;
@@ -20,6 +26,9 @@ export class ChangeFeed {
20
26
  return;
21
27
  this.#timer = setInterval(() => void this.check(), this.#intervalMs);
22
28
  this.#timer.unref();
29
+ // Remote mode compares against the markers as they are now.
30
+ if (this.#remote)
31
+ void this.check();
23
32
  }
24
33
  stop() {
25
34
  if (this.#timer)
@@ -46,6 +55,8 @@ export class ChangeFeed {
46
55
  return this.#running;
47
56
  }
48
57
  async #check() {
58
+ if (this.#remote)
59
+ return this.#checkMarkers();
49
60
  const sequence = safeSequence(this.#db);
50
61
  if (sequence <= this.#position)
51
62
  return;
@@ -63,7 +74,40 @@ export class ChangeFeed {
63
74
  collections = ["*"];
64
75
  }
65
76
  this.#position = sequence;
66
- const event = { sequence, collections, at: new Date().toISOString() };
77
+ this.#emit({ sequence, collections, at: new Date().toISOString() });
78
+ }
79
+ /** Remote mode: report every collection whose change marker was stamped since the last read. */
80
+ async #checkMarkers() {
81
+ let markers;
82
+ try {
83
+ markers = await this.#db.collection(COLLECTION_MARKERS).find({});
84
+ this.lastError = null;
85
+ }
86
+ catch (error) {
87
+ // Unreachable for now: report nothing; the next poll compares against the last read.
88
+ this.lastError = error.message;
89
+ return;
90
+ }
91
+ const first = this.#stamps === null;
92
+ const stamps = this.#stamps ?? new Map();
93
+ const collections = [];
94
+ for (const marker of markers) {
95
+ if (typeof marker.id !== "string")
96
+ continue;
97
+ const stamp = `${String(marker.transactionId)}@${String(marker.changedAt)}`;
98
+ if (stamps.get(marker.id) !== stamp) {
99
+ if (!first)
100
+ collections.push(marker.id);
101
+ stamps.set(marker.id, stamp);
102
+ }
103
+ }
104
+ this.#stamps = stamps;
105
+ if (!collections.length)
106
+ return;
107
+ this.#position += 1;
108
+ this.#emit({ sequence: this.#position, collections, at: new Date().toISOString() });
109
+ }
110
+ #emit(event) {
67
111
  for (const listener of this.#listeners) {
68
112
  try {
69
113
  listener(event);
@@ -1 +1 @@
1
- {"version":3,"file":"changes.js","sourceRoot":"","sources":["../../src/runtime/changes.ts"],"names":[],"mappings":"AAgCA,MAAM,OAAO,UAAU;IACZ,GAAG,CAAe;IAClB,UAAU,GAAG,IAAI,GAAG,EAAkB,CAAC;IACvC,WAAW,CAAS;IAC7B,SAAS,CAAS;IAClB,MAAM,CAA6B;IACnC,QAAQ,GAAyB,IAAI,CAAC;IACtC,QAAQ,GAAG,KAAK,CAAC;IACjB,SAAS,GAAkB,IAAI,CAAC;IAEhC,YAAY,EAAgB,EAAE,UAAmC,EAAE;QACjE,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;QACd,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,UAAU,IAAI,GAAG,CAAC;QAC7C,IAAI,CAAC,SAAS,GAAG,YAAY,CAAC,EAAE,CAAC,CAAC;IACpC,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAED,KAAK;QACH,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO;QACxB,IAAI,CAAC,MAAM,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,KAAK,IAAI,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;QACrE,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;IAED,IAAI;QACF,IAAI,IAAI,CAAC,MAAM;YAAE,aAAa,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAC5C,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;IAC1B,CAAC;IAED,SAAS,CAAC,QAAwB;QAChC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC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CAAC,SAAS,IAAI,CAAC,CAAC;QACpB,IAAI,CAAC,KAAK,CAAC,EAAE,QAAQ,EAAE,IAAI,CAAC,SAAS,EAAE,WAAW,EAAE,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;IACtF,CAAC;IAED,KAAK,CAAC,KAAkB;QACtB,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACvC,IAAI,CAAC;gBACH,QAAQ,CAAC,KAAK,CAAC,CAAC;YAClB,CAAC;YAAC,MAAM,CAAC;gBACP,0DAA0D;YAC5D,CAAC;QACH,CAAC;IACH,CAAC;CACF;AAED,SAAS,YAAY,CAAC,EAAgB;IACpC,IAAI,CAAC;QACH,OAAO,EAAE,CAAC,WAAW,EAAE,CAAC;IAC1B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,CAAC,CAAC;IACX,CAAC;AACH,CAAC"}
@@ -0,0 +1,65 @@
1
+ export type FieldType = "string" | "number" | "integer" | "boolean" | "unknown";
2
+ export type Method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
3
+ export interface OperationDraft {
4
+ name: string;
5
+ method: Method;
6
+ path: string;
7
+ description?: string;
8
+ effect: "observation" | "consequential";
9
+ access: string;
10
+ input: Array<{
11
+ name: string;
12
+ type: FieldType;
13
+ required: boolean;
14
+ }>;
15
+ idempotencyHeader?: string;
16
+ }
17
+ export interface IntegrationDraft {
18
+ name: string;
19
+ description?: string;
20
+ baseUrl: string;
21
+ /** none, `Authorization: Bearer <key>`, or the key in a named header. */
22
+ auth: {
23
+ kind: "none";
24
+ } | {
25
+ kind: "bearer";
26
+ } | {
27
+ kind: "header";
28
+ header: string;
29
+ };
30
+ operations: OperationDraft[];
31
+ }
32
+ /** An AppPort operation name from anything: lowercase letters and digits, starting with a letter. */
33
+ export declare function operationName(text: string): string;
34
+ /** The integration's name from a title or host: what `app.integration(name)` accepts. */
35
+ export declare function integrationName(text: string): string;
36
+ /** Operations, base URL, and title from an OpenAPI 3 document (local `$ref`s resolved). */
37
+ export declare function fromOpenApi(document: unknown, name?: string): {
38
+ title: string | null;
39
+ description: string | null;
40
+ baseUrl: string | null;
41
+ name: string;
42
+ operations: OperationDraft[];
43
+ };
44
+ /** Checks a draft the way `app.integration()` will, before any file is written. */
45
+ export declare function validateDraft(draft: IntegrationDraft): void;
46
+ /** The module source for a draft: what a developer would write by hand. */
47
+ export declare function renderIntegration(draft: IntegrationDraft): string;
48
+ /**
49
+ * Add `<name>.*` to each role's permissions in feltkit/app.ts, where the role is written
50
+ * `role: [ … ]`. Returns the roles granted and those that could not be edited in place.
51
+ */
52
+ export declare function grantRoles(source: string, roles: string[], permission: string): {
53
+ source: string;
54
+ granted: string[];
55
+ skipped: string[];
56
+ };
57
+ /** Write feltkit/<name>.ts (never over an existing file) and grant `<name>.*` to `roles`. */
58
+ export declare function writeIntegration(projectDir: string, draft: IntegrationDraft, options: {
59
+ existing: string[];
60
+ roles: string[];
61
+ }): {
62
+ file: string;
63
+ granted: string[];
64
+ skipped: string[];
65
+ };
@@ -0,0 +1,246 @@
1
+ /**
2
+ * Connect an existing API from Studio: write the integration module a developer would write.
3
+ *
4
+ * Integrations are code (`app.integration(...)` in feltkit/), so connecting one from Studio
5
+ * writes `feltkit/<name>.ts` and, when asked, grants `<name>.*` to roles in feltkit/app.ts.
6
+ * The development server reloads and the integration's operations are published as AppPort
7
+ * capabilities like any other. Nothing here calls the API; the module is ordinary source the
8
+ * developer owns, edits, and commits.
9
+ *
10
+ * Operations come from a form or from an OpenAPI 3 document (JSON): path and query
11
+ * parameters and a JSON request body's top-level properties become the operation's input;
12
+ * GET operations are observations (`<name>.read`), everything else is consequential
13
+ * (`<name>.write`). Output is `s.unknown()` until the developer narrows it.
14
+ */
15
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
16
+ import { join } from "node:path";
17
+ import { FeltKitError } from "../errors.js";
18
+ const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
19
+ const NAME = /^[a-z][a-z0-9]{0,30}$/;
20
+ const OP = /^[a-z][a-z0-9]{0,63}$/;
21
+ const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
22
+ /** An AppPort operation name from anything: lowercase letters and digits, starting with a letter. */
23
+ export function operationName(text) {
24
+ const name = text.toLowerCase().replace(/[^a-z0-9]+/g, "").replace(/^[0-9]+/, "");
25
+ return (name || "op").slice(0, 64);
26
+ }
27
+ /** The integration's name from a title or host: what `app.integration(name)` accepts. */
28
+ export function integrationName(text) {
29
+ return (text.toLowerCase().replace(/^https?:\/\//, "").replace(/^(www|api)\./, "").split(/[.\s/]/)[0] ?? "").replace(/[^a-z0-9]/g, "").replace(/^[0-9]+/, "").slice(0, 31) || "api";
30
+ }
31
+ const ENV_VAR = (name) => `${name.toUpperCase()}_URL`;
32
+ /** Operations, base URL, and title from an OpenAPI 3 document (local `$ref`s resolved). */
33
+ export function fromOpenApi(document, name) {
34
+ const doc = document;
35
+ if (!doc || typeof doc !== "object" || typeof doc.paths !== "object" || !doc.paths) {
36
+ throw new FeltKitError("INVALID_ARGUMENT", "That is not an OpenAPI document: it has no `paths`.");
37
+ }
38
+ if (typeof doc.swagger === "string")
39
+ throw new FeltKitError("INVALID_ARGUMENT", "That is a Swagger 2 document. Convert it to OpenAPI 3 first (for example with swagger2openapi).");
40
+ const title = typeof doc.info?.title === "string" ? doc.info.title : null;
41
+ const server = Array.isArray(doc.servers) ? doc.servers.find((s) => typeof s?.url === "string" && /^https?:\/\//.test(s.url)) : null;
42
+ const baseUrl = server ? server.url.replace(/\{[^}]+\}/g, (v) => server.variables?.[v.slice(1, -1)]?.default ?? v) : null;
43
+ const integration = name && NAME.test(name) ? name : integrationName(title ?? baseUrl ?? "api");
44
+ const resolve = (value, depth = 0) => {
45
+ if (depth > 8 || !value || typeof value !== "object")
46
+ return value;
47
+ if (typeof value.$ref === "string" && value.$ref.startsWith("#/")) {
48
+ const target = value.$ref.slice(2).split("/").reduce((at, key) => at?.[key.replace(/~1/g, "/").replace(/~0/g, "~")], doc);
49
+ return resolve(target, depth + 1);
50
+ }
51
+ return value;
52
+ };
53
+ const typeOf = (schema) => {
54
+ const s = resolve(schema);
55
+ const t = Array.isArray(s?.type) ? s.type.find((x) => x !== "null") : s?.type;
56
+ return t === "string" || t === "number" || t === "integer" || t === "boolean" ? t : "unknown";
57
+ };
58
+ const used = new Set();
59
+ const operations = [];
60
+ for (const [path, item] of Object.entries(doc.paths)) {
61
+ if (!path.startsWith("/"))
62
+ continue;
63
+ const shared = Array.isArray(item?.parameters) ? item.parameters : [];
64
+ for (const method of METHODS) {
65
+ const op = item?.[method.toLowerCase()];
66
+ if (!op || typeof op !== "object")
67
+ continue;
68
+ let opName = operationName(op.operationId ?? `${method}${path.replace(/\{[^}]+\}/g, "by")}`);
69
+ for (let i = 2; used.has(opName); i++)
70
+ opName = `${operationName(op.operationId ?? `${method}${path}`)}${i}`;
71
+ used.add(opName);
72
+ const input = new Map();
73
+ for (const raw of [...shared, ...(Array.isArray(op.parameters) ? op.parameters : [])]) {
74
+ const p = resolve(raw);
75
+ if (!p || (p.in !== "path" && p.in !== "query") || typeof p.name !== "string" || !IDENT.test(p.name))
76
+ continue;
77
+ input.set(p.name, { name: p.name, type: p.in === "path" ? "string" : typeOf(p.schema), required: p.in === "path" || p.required === true });
78
+ }
79
+ const body = resolve(resolve(op.requestBody)?.content?.["application/json"]?.schema);
80
+ if (body && typeof body === "object" && body.properties && method !== "GET") {
81
+ const required = new Set(Array.isArray(body.required) ? body.required : []);
82
+ for (const [field, schema] of Object.entries(body.properties)) {
83
+ if (!IDENT.test(field) || input.has(field))
84
+ continue;
85
+ input.set(field, { name: field, type: typeOf(schema), required: required.has(field) });
86
+ }
87
+ }
88
+ const observation = method === "GET";
89
+ operations.push({
90
+ name: opName,
91
+ method,
92
+ path,
93
+ ...(typeof (op.summary ?? op.description) === "string" ? { description: String(op.summary ?? op.description).split("\n")[0].slice(0, 200) } : {}),
94
+ effect: observation ? "observation" : "consequential",
95
+ access: `${integration}.${observation ? "read" : "write"}`,
96
+ input: [...input.values()],
97
+ });
98
+ }
99
+ }
100
+ if (!operations.length)
101
+ throw new FeltKitError("INVALID_ARGUMENT", "The document has no GET, POST, PUT, PATCH, or DELETE operations.");
102
+ return { title, description: typeof doc.info?.description === "string" ? doc.info.description.split("\n")[0].slice(0, 200) : null, baseUrl, name: integration, operations };
103
+ }
104
+ /** Checks a draft the way `app.integration()` will, before any file is written. */
105
+ export function validateDraft(draft) {
106
+ const bad = (message) => {
107
+ throw new FeltKitError("INVALID_ARGUMENT", message);
108
+ };
109
+ if (!NAME.test(draft.name))
110
+ bad(`The name "${draft.name}" must be lowercase letters and digits, starting with a letter (e.g. "crm").`);
111
+ let url = null;
112
+ try {
113
+ url = new URL(draft.baseUrl);
114
+ }
115
+ catch {
116
+ /* reported below */
117
+ }
118
+ if (!url || !/^https?:$/.test(url.protocol))
119
+ bad("The base URL must be an http(s) URL, like https://api.example.com.");
120
+ if (draft.auth.kind === "header" && !/^[A-Za-z0-9-]{1,64}$/.test(draft.auth.header))
121
+ bad("The API key header must be a header name, like X-API-Key.");
122
+ if (!draft.operations.length)
123
+ bad("Add at least one operation.");
124
+ const names = new Set();
125
+ for (const op of draft.operations) {
126
+ if (!OP.test(op.name))
127
+ bad(`Operation "${op.name}" must be lowercase letters and digits, starting with a letter.`);
128
+ if (names.has(op.name))
129
+ bad(`Operation "${op.name}" is listed twice.`);
130
+ names.add(op.name);
131
+ if (!METHODS.includes(op.method))
132
+ bad(`${op.name}: method must be GET, POST, PUT, PATCH, or DELETE.`);
133
+ if (typeof op.path !== "string" || !op.path.startsWith("/") || /[`$\\]/.test(op.path))
134
+ bad(`${op.name}: the path must start with "/".`);
135
+ if (op.effect !== "observation" && op.effect !== "consequential")
136
+ bad(`${op.name}: effect must be observation or consequential.`);
137
+ if (op.effect === "observation" && op.method !== "GET")
138
+ bad(`${op.name}: an observation must be a GET.`);
139
+ if (!/^[a-z][a-z0-9]*(\.[a-z][a-z0-9*]*)+$/.test(op.access))
140
+ bad(`${op.name}: access must be a permission like "${draft.name}.read".`);
141
+ for (const field of op.input)
142
+ if (!IDENT.test(field.name))
143
+ bad(`${op.name}: "${field.name}" is not a field name.`);
144
+ for (const param of op.path.match(/\{([^}]+)\}/g) ?? []) {
145
+ if (!op.input.some((f) => f.name === param.slice(1, -1)))
146
+ bad(`${op.name}: the path uses ${param}, which is not an input field.`);
147
+ }
148
+ }
149
+ }
150
+ const str = (text) => JSON.stringify(text);
151
+ const FIELD = { string: "s.string()", number: "s.number()", integer: "s.integer()", boolean: "s.boolean()", unknown: "s.unknown()" };
152
+ /** The module source for a draft: what a developer would write by hand. */
153
+ export function renderIntegration(draft) {
154
+ validateDraft(draft);
155
+ const credential = draft.auth.kind === "none"
156
+ ? null
157
+ : draft.auth.kind === "bearer"
158
+ ? ` // Sent as "Authorization: Bearer <key>". The key is kept by FeltKit's custody (Studio → Integrations →
159
+ // Set key, or FELTKIT_CREDENTIAL_${draft.name.toUpperCase()} on the host); it is never stored here or in FeltDB.
160
+ credential: ${str(`credential-ref:${draft.name}`)},`
161
+ : ` // Sent in the ${draft.auth.header} header. The key is kept by FeltKit's custody (Studio → Integrations →
162
+ // Set key, or FELTKIT_CREDENTIAL_${draft.name.toUpperCase()} on the host); it is never stored here or in FeltDB.
163
+ credential: { ref: ${str(`credential-ref:${draft.name}`)}, header: ${str(draft.auth.header)} },`;
164
+ const ops = draft.operations
165
+ .map((op) => {
166
+ const input = op.input.length
167
+ ? `\n input: { ${op.input.map((f) => `${f.name}: ${f.required ? FIELD[f.type] : `s.optional(${FIELD[f.type]})`}`).join(", ")} },`
168
+ : "";
169
+ return ` ${op.name}: {
170
+ method: ${str(op.method)},
171
+ path: ${str(op.path)},${op.description ? `\n description: ${str(op.description)},` : ""}${input}
172
+ // Narrow this to what the API returns: AppPort validates every response against it.
173
+ output: s.unknown(),
174
+ effect: ${str(op.effect)},
175
+ access: ${str(op.access)},${op.idempotencyHeader ? `\n idempotencyHeader: ${str(op.idempotencyHeader)},` : ""}
176
+ },`;
177
+ })
178
+ .join("\n");
179
+ return `/**
180
+ * ${(draft.description ?? `The ${draft.name} API`).replace(/\*\//g, "* /")}, connected as an integration from Studio.
181
+ *
182
+ * Each operation is an AppPort capability (${draft.name}.<operation>): discoverable by apps and
183
+ * agents, invocable only with its permission. Every call is recorded with its outcome; a
184
+ * consequential call whose outcome is unknown is never re-sent (add \`verify\` to settle it).
185
+ * Edit freely: this is your code.
186
+ */
187
+ import { s } from "@feltdb/feltkit";
188
+ import { app } from "./app.js";
189
+
190
+ export const ${draft.name} = app.integration(${str(draft.name)}, {${draft.description ? `\n description: ${str(draft.description)},` : ""}
191
+ // Production sets ${ENV_VAR(draft.name)}; this URL is used only in development and test.
192
+ baseUrl: { env: ${str(ENV_VAR(draft.name))}, development: ${str(draft.baseUrl)} },
193
+ ${credential ? `${credential}\n` : ""} operations: {
194
+ ${ops}
195
+ },
196
+ });
197
+ `;
198
+ }
199
+ /**
200
+ * Add `<name>.*` to each role's permissions in feltkit/app.ts, where the role is written
201
+ * `role: [ … ]`. Returns the roles granted and those that could not be edited in place.
202
+ */
203
+ export function grantRoles(source, roles, permission) {
204
+ const granted = [];
205
+ const skipped = [];
206
+ let out = source;
207
+ for (const role of roles) {
208
+ const key = /^[A-Za-z_$][\w$]*$/.test(role) ? role : str(role);
209
+ const pattern = new RegExp(`(\\n[ \\t]*(?:${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}|${str(role).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")})[ \\t]*:[ \\t]*\\[)`, "g");
210
+ const matches = out.match(pattern) ?? [];
211
+ if (matches.length !== 1) {
212
+ skipped.push(role);
213
+ continue;
214
+ }
215
+ const at = out.search(pattern) + matches[0].length;
216
+ const close = out.indexOf("]", at);
217
+ if (out.slice(at, close).includes(str(permission))) {
218
+ granted.push(role);
219
+ continue;
220
+ }
221
+ const empty = out.slice(at, close).trim() === "";
222
+ out = empty ? `${out.slice(0, at)}${str(permission)}${out.slice(close)}` : `${out.slice(0, at)}${str(permission)}, ${out.slice(at)}`;
223
+ granted.push(role);
224
+ }
225
+ return { source: out, granted, skipped };
226
+ }
227
+ /** Write feltkit/<name>.ts (never over an existing file) and grant `<name>.*` to `roles`. */
228
+ export function writeIntegration(projectDir, draft, options) {
229
+ const source = renderIntegration(draft);
230
+ if (options.existing.includes(draft.name))
231
+ throw new FeltKitError("CONFLICT", `An integration named "${draft.name}" already exists.`);
232
+ const file = join(projectDir, "feltkit", `${draft.name}.ts`);
233
+ if (existsSync(file))
234
+ throw new FeltKitError("CONFLICT", `feltkit/${draft.name}.ts already exists. Choose another name; nothing was written.`);
235
+ const appFile = join(projectDir, "feltkit", "app.ts");
236
+ let grant = { granted: [], skipped: [...options.roles] };
237
+ if (options.roles.length && existsSync(appFile)) {
238
+ const result = grantRoles(readFileSync(appFile, "utf8"), options.roles, `${draft.name}.*`);
239
+ grant = result;
240
+ if (result.granted.length)
241
+ writeFileSync(appFile, result.source);
242
+ }
243
+ writeFileSync(file, source, { flag: "wx" });
244
+ return { file: `feltkit/${draft.name}.ts`, granted: grant.granted, skipped: grant.skipped };
245
+ }
246
+ //# sourceMappingURL=connect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect.js","sourceRoot":"","sources":["../../src/runtime/connect.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAyB5C,MAAM,OAAO,GAAa,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;AACpE,MAAM,IAAI,GAAG,uBAAuB,CAAC;AACrC,MAAM,EAAE,GAAG,uBAAuB,CAAC;AACnC,M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AAC,KAAK,CAAC,EAAE,CAAC;IACrE,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,IAAI,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC;QAChD,MAAM,MAAM,GAAG,UAAU,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC,EAAE,OAAO,CAAC,KAAK,EAAE,GAAG,KAAK,CAAC,IAAI,IAAI,CAAC,CAAC;QAC3F,KAAK,GAAG,MAAM,CAAC;QACf,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM;YAAE,aAAa,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACnE,CAAC;IACD,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;IAC5C,OAAO,EAAE,IAAI,EAAE,WAAW,KAAK,CAAC,IAAI,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;AAC9F,CAAC"}
@@ -3,22 +3,30 @@
3
3
  *
4
4
  * An application-scoped FeltDB authority (Managed FeltDB) stores only the collections and
5
5
  * fields its promoted contract declares. FeltKit owns two parts of that contract and
6
- * borrows the third:
6
+ * composes the others, unchanged, from the packages that own them:
7
7
  *
8
8
  * application collections from `app.collection(...)`: each field's type from its schema
9
9
  * FeltKit's records `_feltkit_*`: sessions, activity, change markers, idempotency,
10
- * integration calls, operator grants
11
- * FeltDB's agent state `FELTDB_AGENT_STATE_CONTRACT` from @feltdb/core, unchanged
10
+ * integration calls, operator grants, saved models, and file
11
+ * bytes when Files is enabled
12
+ * FeltDB's agent state `FELTDB_AGENT_STATE_CONTRACT` from @feltdb/core
13
+ * AppPort Services `servicesContract(enabled)` from @appport/services: what the
14
+ * enabled services store and the indexes their reads need, plus
15
+ * configuration's (FeltKit stores credentials through
16
+ * `credential.store`)
12
17
  *
13
18
  * Publishing and promoting it is FeltDB's job (`feltdb publish --contract`); FeltKit only
14
19
  * writes the file. Every collection gets the same FeltDB policy: the application's runtime
15
20
  * key reads and writes it. Who may do what inside the application stays FeltKit's
16
21
  * authorization (roles and permissions); people and agents never hold a FeltDB key.
17
22
  *
18
- * AppPort Services keeps its own collections, which this contract cannot declare, so an
19
- * application with services enabled is refused rather than given a contract it would fail on.
23
+ * FeltKit never lists another package's collections: each package declares what it stores
24
+ * and keeps that declaration true with its own tests. Composition is deterministic, so the
25
+ * same application always writes the same file. An application without services gets the
26
+ * same contract as before services could be declared.
20
27
  */
21
28
  import { type ManifestCollection } from "@feltdb/core";
29
+ import { type ServiceName } from "@appport/services";
22
30
  import type { FeltKitApp } from "../app.js";
23
31
  export interface FeltDBContract {
24
32
  collections: ManifestCollection[];
@@ -36,5 +44,7 @@ export interface FeltDBContract {
36
44
  }>;
37
45
  }
38
46
  export declare function feltdbContract(app: FeltKitApp): FeltDBContract;
47
+ /** The AppPort Services this application enables, by AppPort Services' own names. */
48
+ export declare function enabledServices(app: FeltKitApp): ServiceName[];
39
49
  /** The contract file's text: stable, so an unchanged application writes an identical file. */
40
50
  export declare function formatContract(contract: FeltDBContract): string;
@@ -3,28 +3,38 @@
3
3
  *
4
4
  * An application-scoped FeltDB authority (Managed FeltDB) stores only the collections and
5
5
  * fields its promoted contract declares. FeltKit owns two parts of that contract and
6
- * borrows the third:
6
+ * composes the others, unchanged, from the packages that own them:
7
7
  *
8
8
  * application collections from `app.collection(...)`: each field's type from its schema
9
9
  * FeltKit's records `_feltkit_*`: sessions, activity, change markers, idempotency,
10
- * integration calls, operator grants
11
- * FeltDB's agent state `FELTDB_AGENT_STATE_CONTRACT` from @feltdb/core, unchanged
10
+ * integration calls, operator grants, saved models, and file
11
+ * bytes when Files is enabled
12
+ * FeltDB's agent state `FELTDB_AGENT_STATE_CONTRACT` from @feltdb/core
13
+ * AppPort Services `servicesContract(enabled)` from @appport/services: what the
14
+ * enabled services store and the indexes their reads need, plus
15
+ * configuration's (FeltKit stores credentials through
16
+ * `credential.store`)
12
17
  *
13
18
  * Publishing and promoting it is FeltDB's job (`feltdb publish --contract`); FeltKit only
14
19
  * writes the file. Every collection gets the same FeltDB policy: the application's runtime
15
20
  * key reads and writes it. Who may do what inside the application stays FeltKit's
16
21
  * authorization (roles and permissions); people and agents never hold a FeltDB key.
17
22
  *
18
- * AppPort Services keeps its own collections, which this contract cannot declare, so an
19
- * application with services enabled is refused rather than given a contract it would fail on.
23
+ * FeltKit never lists another package's collections: each package declares what it stores
24
+ * and keeps that declaration true with its own tests. Composition is deterministic, so the
25
+ * same application always writes the same file. An application without services gets the
26
+ * same contract as before services could be declared.
20
27
  */
21
28
  import { FELTDB_AGENT_STATE_CONTRACT } from "@feltdb/core";
29
+ import { SERVICE_NAMES, servicesContract } from "@appport/services";
22
30
  import { FeltKitError } from "../errors.js";
23
31
  import { ACTIVITY_COLLECTION } from "./activity.js";
24
32
  import { COLLECTION_MARKERS } from "./data.js";
25
33
  import { IDEMPOTENCY_COLLECTION } from "./idempotency.js";
26
34
  import { INTEGRATION_CALLS } from "./integrations.js";
35
+ import { SAVED_MODELS } from "./decisions.js";
27
36
  import { SESSIONS_COLLECTION } from "./sessions.js";
37
+ import { FILE_CONTENT_COLLECTION } from "./content.js";
28
38
  /**
29
39
  * FeltKit's own records, by collection and field. These are FeltKit's to keep current: the
30
40
  * contract test runs a runtime through every write path and fails on any field written here
@@ -47,6 +57,7 @@ const PLATFORM_COLLECTIONS = {
47
57
  "startedAt", "finishedAt", "status", "output", "error", "determinedBy", "verification", "environment",
48
58
  ],
49
59
  _feltkit_operator_grants: ["subject", "usedAt", "expiresAt"],
60
+ [SAVED_MODELS]: ["provider", "model", "endpoint", "credentialRef", "savedAt", "savedBy"],
50
61
  };
51
62
  const ID = { name: "id", type: "text", required: true, nullable: false };
52
63
  /** A FeltKit field's FeltDB type, from its JSON Schema. Anything structured is JSON. */
@@ -60,12 +71,7 @@ function fieldType(schema) {
60
71
  return { type, nullable: nullable || type === "json" };
61
72
  }
62
73
  export function feltdbContract(app) {
63
- const services = Object.entries(app.options.services ?? {}).filter(([, value]) => value).map(([name]) => name);
64
- if (services.length) {
65
- throw new FeltKitError("CONFIGURATION", `This application enables AppPort Services (${services.join(", ")}), whose collections a FeltDB application contract cannot declare yet, so it cannot run on Managed FeltDB.`, {
66
- hint: "Remove `services` from feltkit({ ... }) to run on Managed FeltDB, or keep a local or self-hosted FeltDB (FELTKIT_STATE_DIR) for this application.",
67
- });
68
- }
74
+ const services = enabledServices(app);
69
75
  const collections = [];
70
76
  for (const definition of app.collections.values()) {
71
77
  const json = definition.schema.toJSONSchema();
@@ -80,10 +86,20 @@ export function feltdbContract(app) {
80
86
  for (const [name, fields] of Object.entries(PLATFORM_COLLECTIONS)) {
81
87
  collections.push({ name, fields: [ID, ...fields.map((field) => ({ name: field, type: "json", required: false, nullable: true }))] });
82
88
  }
89
+ if (services.includes("files")) {
90
+ collections.push({ name: FILE_CONTENT_COLLECTION, fields: [ID, ...["data", "size", "checksum"].map((field) => ({ name: field, type: "json", required: false, nullable: true }))] });
91
+ }
83
92
  collections.push(...FELTDB_AGENT_STATE_CONTRACT.collections);
93
+ const indexes = FELTDB_AGENT_STATE_CONTRACT.indexes.map((index) => ({ ...index, fields: [...index.fields] }));
94
+ if (services.length) {
95
+ // Credentials are stored through AppPort Services' credential.store (configuration).
96
+ const fragment = servicesContract([...services, "configuration"]);
97
+ collections.push(...fragment.collections.map((c) => ({ name: c.name, fields: c.fields.map((f) => ({ ...f })) })));
98
+ indexes.push(...fragment.indexes.map((index) => ({ ...index, fields: [...index.fields] })));
99
+ }
84
100
  return {
85
101
  collections,
86
- indexes: FELTDB_AGENT_STATE_CONTRACT.indexes.map((index) => ({ ...index, fields: [...index.fields] })),
102
+ indexes,
87
103
  policies: collections.map((collection) => ({
88
104
  name: collection.name,
89
105
  resource: collection.name,
@@ -93,6 +109,14 @@ export function feltdbContract(app) {
93
109
  })),
94
110
  };
95
111
  }
112
+ /** The AppPort Services this application enables, by AppPort Services' own names. */
113
+ export function enabledServices(app) {
114
+ const on = Object.entries(app.options.services ?? {}).filter(([, value]) => value).map(([name]) => name);
115
+ const unknown = on.filter((name) => !SERVICE_NAMES.includes(name));
116
+ if (unknown.length)
117
+ throw new FeltKitError("CONFIGURATION", `Unknown AppPort service(s) in feltkit({ services }): ${unknown.join(", ")}.`, { hint: `Services: ${SERVICE_NAMES.join(", ")}.` });
118
+ return on;
119
+ }
96
120
  /** The contract file's text: stable, so an unchanged application writes an identical file. */
97
121
  export function formatContract(contract) {
98
122
  return `${JSON.stringify(contract, null, 2)}\n`;