@fayz-ai/core 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/access/engine.d.ts +31 -1
- package/dist/access/engine.d.ts.map +1 -1
- package/dist/access/index.d.ts +1 -1
- package/dist/access/index.d.ts.map +1 -1
- package/dist/access/index.js +24 -3
- package/dist/access/index.js.map +1 -1
- package/dist/{chunk-KFBEKFII.js → chunk-BCI743RH.js} +37 -4
- package/dist/chunk-BCI743RH.js.map +1 -0
- package/dist/{chunk-IKZR3WSK.js → chunk-KJUD6JA5.js} +3 -3
- package/dist/{chunk-IKZR3WSK.js.map → chunk-KJUD6JA5.js.map} +1 -1
- package/dist/{chunk-S5FOFKR4.js → chunk-NBKFYGVD.js} +88 -24
- package/dist/chunk-NBKFYGVD.js.map +1 -0
- package/dist/{chunk-7GJTLBG3.js → chunk-OHH26S4N.js} +3 -3
- package/dist/{chunk-7GJTLBG3.js.map → chunk-OHH26S4N.js.map} +1 -1
- package/dist/chunk-RCMFU3RZ.js +13 -0
- package/dist/chunk-RCMFU3RZ.js.map +1 -0
- package/dist/{chunk-RRYFXUQX.js → chunk-UMIZDILP.js} +7 -3
- package/dist/chunk-UMIZDILP.js.map +1 -0
- package/dist/{chunk-X4FRQR2R.js → chunk-ZYHS7T5T.js} +125 -7
- package/dist/chunk-ZYHS7T5T.js.map +1 -0
- package/dist/data/archetype.d.ts +5 -0
- package/dist/data/archetype.d.ts.map +1 -1
- package/dist/data/cached.d.ts +17 -2
- package/dist/data/cached.d.ts.map +1 -1
- package/dist/data/index.js +2 -2
- package/dist/data/offline.d.ts +10 -1
- package/dist/data/offline.d.ts.map +1 -1
- package/dist/data/resolve.d.ts.map +1 -1
- package/dist/data/supabase.d.ts +5 -0
- package/dist/data/supabase.d.ts.map +1 -1
- package/dist/data/unit-scope.d.ts +48 -0
- package/dist/data/unit-scope.d.ts.map +1 -0
- package/dist/events/index.d.ts +2 -0
- package/dist/events/index.d.ts.map +1 -1
- package/dist/events/log.d.ts.map +1 -1
- package/dist/events/useDataVersion.d.ts +28 -0
- package/dist/events/useDataVersion.d.ts.map +1 -0
- package/dist/i18n/index.d.ts.map +1 -1
- package/dist/i18n/index.js +1 -1
- package/dist/i18n/shell-translations.en.d.ts.map +1 -1
- package/dist/i18n/shell-translations.pt-br.d.ts.map +1 -1
- package/dist/index.d.ts +7 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +190 -38
- package/dist/index.js.map +1 -1
- package/dist/integrations/index.js +2 -2
- package/dist/lib/unit.d.ts +20 -0
- package/dist/lib/unit.d.ts.map +1 -0
- package/dist/manifest/index.d.ts +45 -0
- package/dist/manifest/index.d.ts.map +1 -1
- package/dist/manifest/integration-surface.d.ts +16 -0
- package/dist/manifest/integration-surface.d.ts.map +1 -0
- package/dist/plugin/index.js +1 -1
- package/dist/plugin/runtime.d.ts.map +1 -1
- package/dist/{shell-translations.pt-br-PTOWYXNA.js → shell-translations.pt-br-MHKHD3IX.js} +100 -6
- package/dist/shell-translations.pt-br-MHKHD3IX.js.map +1 -0
- package/dist/testing/index.js +3 -3
- package/dist/types/agents.d.ts +97 -0
- package/dist/types/agents.d.ts.map +1 -0
- package/dist/types/auth.d.ts +9 -0
- package/dist/types/auth.d.ts.map +1 -1
- package/dist/types/crud.d.ts +22 -0
- package/dist/types/crud.d.ts.map +1 -1
- package/dist/types/index.d.ts +2 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +1 -1
- package/dist/types/org.d.ts +10 -0
- package/dist/types/org.d.ts.map +1 -1
- package/dist/types/plugins.d.ts +24 -0
- package/dist/types/plugins.d.ts.map +1 -1
- package/package.json +2 -2
- package/dist/chunk-KFBEKFII.js.map +0 -1
- package/dist/chunk-RRYFXUQX.js.map +0 -1
- package/dist/chunk-S5FOFKR4.js.map +0 -1
- package/dist/chunk-X4FRQR2R.js.map +0 -1
- package/dist/shell-translations.pt-br-PTOWYXNA.js.map +0 -1
package/dist/access/engine.d.ts
CHANGED
|
@@ -12,6 +12,19 @@ export interface AccessSubject {
|
|
|
12
12
|
profile: PermissionProfile | null;
|
|
13
13
|
/** The tenant's currently-active plan. */
|
|
14
14
|
plan: Plan | null;
|
|
15
|
+
/**
|
|
16
|
+
* Extra role a person has INSIDE a given unit, keyed by unit id.
|
|
17
|
+
*
|
|
18
|
+
* Additive, never subtractive: the org role applies everywhere and a unit role
|
|
19
|
+
* only adds inside its unit. That choice is what makes this shippable — the
|
|
20
|
+
* answer without a unit is a strict SUBSET of the answer with one, so every
|
|
21
|
+
* existing call site keeps its exact meaning and none of them had to change.
|
|
22
|
+
* The alternative (a unit role that overrides) can take access away by
|
|
23
|
+
* accident, and every screen would have to explain which role won.
|
|
24
|
+
*/
|
|
25
|
+
unitProfiles?: Record<string, PermissionProfile>;
|
|
26
|
+
/** The unit the person is looking at, used when a check does not name one. */
|
|
27
|
+
activeUnitId?: string;
|
|
15
28
|
}
|
|
16
29
|
/**
|
|
17
30
|
* The org owner has every permission implicitly. Owner is represented by the
|
|
@@ -41,6 +54,21 @@ export declare function profileHasSystemPermission(profile: PermissionProfile |
|
|
|
41
54
|
* open rather than silently locking.
|
|
42
55
|
*/
|
|
43
56
|
export declare function isEntitledByPlan(plan: Plan | null, feature: string): boolean;
|
|
57
|
+
/**
|
|
58
|
+
* Union two profiles. Grants merge per feature, system permissions merge, and
|
|
59
|
+
* the result is never smaller than either input — the additive rule, in code.
|
|
60
|
+
*
|
|
61
|
+
* `manage` is not expanded here: {@link profileHasPermission} already treats it
|
|
62
|
+
* as satisfying any action, so expanding it would be a second implementation of
|
|
63
|
+
* the same rule waiting to disagree with the first.
|
|
64
|
+
*/
|
|
65
|
+
export declare function mergeProfiles(base: PermissionProfile | null, overlay: PermissionProfile | null): PermissionProfile | null;
|
|
66
|
+
/**
|
|
67
|
+
* The profile that applies where the person is standing: their org role, plus
|
|
68
|
+
* whatever the unit adds. With no unit — or no binding in it — this is exactly
|
|
69
|
+
* the org role, which is why nothing that predates units changes behaviour.
|
|
70
|
+
*/
|
|
71
|
+
export declare function effectiveProfileFor(subject: AccessSubject, unitId?: string): PermissionProfile | null;
|
|
44
72
|
/**
|
|
45
73
|
* The single access decision: role FIRST, then plan.
|
|
46
74
|
*
|
|
@@ -50,7 +78,9 @@ export declare function isEntitledByPlan(plan: Plan | null, feature: string): bo
|
|
|
50
78
|
* 2. Plan — even the owner does NOT bypass the plan: upgrading is the tenant's
|
|
51
79
|
* decision, not a role power. Denied → `{ allowed:false, reason:'plan' }`.
|
|
52
80
|
*/
|
|
53
|
-
export declare function resolveAccess(subject: AccessSubject, feature: string, action?: PermissionAction
|
|
81
|
+
export declare function resolveAccess(subject: AccessSubject, feature: string, action?: PermissionAction, options?: {
|
|
82
|
+
unitId?: string;
|
|
83
|
+
}): AccessDecision;
|
|
54
84
|
/**
|
|
55
85
|
* Pure numeric side of a limit: given the plan cap, whether a countable
|
|
56
86
|
* declaration exists, and the current usage, derive the limit math. Unlimited
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../src/access/engine.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAA;AACjG,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAA;AAe5C,+EAA+E;AAC/E,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAA;AAElD,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,OAAO,CAAA;IAChB,MAAM,CAAC,EAAE,UAAU,CAAA;CACpB;AAED,iFAAiF;AACjF,MAAM,WAAW,aAAa;IAC5B,wEAAwE;IACxE,OAAO,EAAE,iBAAiB,GAAG,IAAI,CAAA;IACjC,0CAA0C;IAC1C,IAAI,EAAE,IAAI,GAAG,IAAI,CAAA;
|
|
1
|
+
{"version":3,"file":"engine.d.ts","sour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iB,GAAG,IAAI,GAChC,iBAAiB,GAAG,IAAI,CAmB1B;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,aAAa,EACtB,MAAM,CAAC,EAAE,MAAM,GACd,iBAAiB,GAAG,IAAI,CAG1B;AAED;;;;;;;;GAQG;AACH,wBAAgB,aAAa,CAC3B,OAAO,EAAE,aAAa,EACtB,OAAO,EAAE,MAAM,EACf,MAAM,CAAC,EAAE,gBAAgB,EACzB,OAAO,CAAC,EAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAC5B,cAAc,CAShB;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE;IAAE,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC;IAAC,cAAc,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG;IACxG,GAAG,EAAE,MAAM,CAAA;IACX,IAAI,EAAE,MAAM,CAAA;IACZ,SAAS,EAAE,MAAM,CAAA;IACjB,OAAO,EAAE,OAAO,CAAA;IAChB,SAAS,EAAE,OAAO,CAAA;CACnB,CAOA"}
|
package/dist/access/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { isOwnerProfile, profileHasPermission, profileHasSystemPermission, isEntitledByPlan, resolveAccess, resolveLimit, } from './engine';
|
|
1
|
+
export { isOwnerProfile, profileHasPermission, profileHasSystemPermission, isEntitledByPlan, resolveAccess, resolveLimit, mergeProfiles, effectiveProfileFor, } from './engine';
|
|
2
2
|
export type { DenyReason, AccessDecision, AccessSubject } from './engine';
|
|
3
3
|
export { UPGRADE_URL, agentDenial } from './denial';
|
|
4
4
|
export type { AgentDenial, AgentDenialLimit, AgentGuardResult } from './denial';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/access/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,0BAA0B,EAC1B,gBAAgB,EAChB,aAAa,EACb,YAAY,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/access/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,0BAA0B,EAC1B,gBAAgB,EAChB,aAAa,EACb,YAAY,EACZ,aAAa,EACb,mBAAmB,GACpB,MAAM,UAAU,CAAA;AACjB,YAAY,EAAE,UAAU,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAEzE,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,UAAU,CAAA;AACnD,YAAY,EAAE,WAAW,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAA;AAE/E,OAAO,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAA"}
|
package/dist/access/index.js
CHANGED
|
@@ -18,8 +18,29 @@ function profileHasSystemPermission(profile, permission) {
|
|
|
18
18
|
function isEntitledByPlan(plan, feature) {
|
|
19
19
|
return plan?.entitlements?.features?.[feature] !== false;
|
|
20
20
|
}
|
|
21
|
-
function
|
|
22
|
-
if (!
|
|
21
|
+
function mergeProfiles(base, overlay) {
|
|
22
|
+
if (!overlay) return base;
|
|
23
|
+
if (!base) return overlay;
|
|
24
|
+
if (isOwnerProfile(base)) return base;
|
|
25
|
+
const grants = { ...base.grants };
|
|
26
|
+
for (const [feature, actions] of Object.entries(overlay.grants ?? {})) {
|
|
27
|
+
const merged = /* @__PURE__ */ new Set([...grants[feature] ?? [], ...actions]);
|
|
28
|
+
grants[feature] = [...merged];
|
|
29
|
+
}
|
|
30
|
+
const system = /* @__PURE__ */ new Set([...base.systemPermissions ?? [], ...overlay.systemPermissions ?? []]);
|
|
31
|
+
return {
|
|
32
|
+
...base,
|
|
33
|
+
grants,
|
|
34
|
+
systemPermissions: system.size > 0 ? [...system] : void 0
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
function effectiveProfileFor(subject, unitId) {
|
|
38
|
+
if (!unitId) return subject.profile;
|
|
39
|
+
return mergeProfiles(subject.profile, subject.unitProfiles?.[unitId] ?? null);
|
|
40
|
+
}
|
|
41
|
+
function resolveAccess(subject, feature, action, options) {
|
|
42
|
+
const profile = effectiveProfileFor(subject, options?.unitId ?? subject.activeUnitId);
|
|
43
|
+
if (!profileHasPermission(profile, feature, action)) {
|
|
23
44
|
return { allowed: false, reason: "role" };
|
|
24
45
|
}
|
|
25
46
|
if (!isEntitledByPlan(subject.plan, feature)) {
|
|
@@ -51,6 +72,6 @@ function mergeLimitDeclarations(...layers) {
|
|
|
51
72
|
return Array.from(byKey.values());
|
|
52
73
|
}
|
|
53
74
|
|
|
54
|
-
export { UPGRADE_URL, agentDenial, isEntitledByPlan, isOwnerProfile, mergeLimitDeclarations, profileHasPermission, profileHasSystemPermission, resolveAccess, resolveLimit };
|
|
75
|
+
export { UPGRADE_URL, agentDenial, effectiveProfileFor, isEntitledByPlan, isOwnerProfile, mergeLimitDeclarations, mergeProfiles, profileHasPermission, profileHasSystemPermission, resolveAccess, resolveLimit };
|
|
55
76
|
//# sourceMappingURL=index.js.map
|
|
56
77
|
//# sourceMappingURL=index.js.map
|
package/dist/access/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/access/engine.ts","../../src/access/denial.ts","../../src/access/limits.ts"],"names":[],"mappings":";AAuCO,SAAS,eAAe,OAAA,EAAqC;AAClE,EAAA,OAAO,QAAQ,EAAA,KAAO,OAAA,IAAW,OAAA,CAAQ,IAAA,EAAM,aAAY,KAAM,OAAA;AACnE;AAOO,SAAS,oBAAA,CACd,OAAA,EACA,OAAA,EACA,MAAA,EACS;AACT,EAAA,IAAI,CAAC,SAAS,OAAO,IAAA;AAMrB,EAAA,IAAI,cAAA,CAAe,OAAO,CAAA,EAAG,OAAO,IAAA;AAEpC,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,MAAA,CAAO,OAAO,CAAA;AAC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M,GAAA,GAAM,YAAY,QAAA,GAAW,GAAA;AACnC,EAAA,MAAM,YAAY,SAAA,GAAY,QAAA,GAAW,KAAK,GAAA,CAAI,CAAA,EAAG,MAAM,IAAI,CAAA;AAC/D,EAAA,MAAM,OAAA,GAAU,CAAC,SAAA,IAAa,IAAA,IAAQ,GAAA;AACtC,EAAA,OAAO,EAAE,GAAA,EAAK,IAAA,EAAM,SAAA,EAAW,SAAS,SAAA,EAAU;AACpD;;;AC5HO,IAAM,WAAA,GAAc;AAmBpB,SAAS,WAAA,CAAY,QAAoB,KAAA,EAAuC;AACrF,EAAA,OAAO,EAAE,OAAA,EAAS,KAAA,EAAO,MAAA,EAAQ,GAAI,KAAA,GAAQ,EAAE,KAAA,EAAM,GAAI,EAAC,EAAI,UAAA,EAAY,WAAA,EAAY;AACxF;;;ACvBO,SAAS,0BACX,MAAA,EACiB;AACpB,EAAA,MAAM,KAAA,uBAAY,GAAA,EAA8B;AAChD,EAAA,KAAA,MAAW,SAAS,MAAA,EAAQ;AAC1B,IAAA,KAAA,MAAW,IAAA,IAAQ,SAAS,EAAC,QAAS,GAAA,CAAI,IAAA,CAAK,KAAK,IAAI,CAAA;AAAA,EAC1D;AACA,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,KAAA,CAAM,MAAA,EAAQ,CAAA;AAClC","file":"index.js","sourcesContent":["import type { PermissionProfile, PermissionAction, SystemPermission } from '../types/permissions'\nimport type { Plan } from '../types/billing'\n\n// ---------------------------------------------------------------------------\n// The access engine — the ONE implementation of the role × plan × limit\n// decision, shared by every runtime that gates anything:\n//\n// - browser (saas AccessProvider / PermissionsProvider re-export from here)\n// - headless client-plane (saas access/headless.ts)\n// - the Fayz broker (server-side agent authorization imports this package)\n//\n// Hard constraint: this module (and everything under core/src/access) must stay\n// free of React, zustand and supabase — pure functions over plain data — so the\n// exact same code runs in Node/edge. Guarded by scripts/check-access-purity.mjs.\n// ---------------------------------------------------------------------------\n\n/** Why an access request was denied. `limit` only occurs on guarded writes. */\nexport type DenyReason = 'role' | 'plan' | 'limit'\n\nexport interface AccessDecision {\n allowed: boolean\n reason?: DenyReason\n}\n\n/** The minimal subject a decision needs — a projection of any richer session. */\nexport interface AccessSubject {\n /** Effective RBAC profile — the previewed role during impersonation. */\n profile: PermissionProfile | null\n /** The tenant's currently-active plan. */\n plan: Plan | null\n}\n\n/**\n * The org owner has every permission implicitly. Owner is represented by the\n * canonical role id `owner` across adapters (see org/adapters/supabase.ts\n * buildPermissionProfiles, which also grants owner all catalog perms, and the\n * mock adapter's `owner` fallback). We match by id first, falling back to the\n * (possibly localized) name for safety.\n */\nexport function isOwnerProfile(profile: PermissionProfile): boolean {\n return profile.id === 'owner' || profile.name?.toLowerCase() === 'owner'\n}\n\n/**\n * The single role-side permission check. The plan axis composes ON TOP of it in\n * {@link resolveAccess} instead of reimplementing owner-bypass / `manage`\n * semantics.\n */\nexport function profileHasPermission(\n profile: PermissionProfile | null,\n feature: string,\n action?: string,\n): boolean {\n if (!profile) return true\n\n // Owner bypass: never lock the owner out, even if the RBAC catalog is empty\n // or still loading. Because permission checks read the *effective* profile,\n // an owner previewing a non-owner role correctly loses this bypass — the\n // preview stays honest.\n if (isOwnerProfile(profile)) return true\n\n const actions = profile.grants[feature]\n if (!actions) return false\n\n if (!action) return actions.length > 0\n\n return actions.includes(action) || actions.includes('manage')\n}\n\n/**\n * The org-management side of a profile: managing team, billing, settings and\n * permissions themselves. Separate axis from `grants` — these gate the settings\n * tabs, not a feature's rows — and it follows the same owner bypass, so the one\n * person who can hand out access is never locked out of doing it.\n */\nexport function profileHasSystemPermission(\n profile: PermissionProfile | null,\n permission: SystemPermission,\n): boolean {\n if (!profile) return true\n if (isOwnerProfile(profile)) return true\n return profile.systemPermissions?.includes(permission) ?? false\n}\n\n/**\n * Does the current plan entitle `feature`? A plan gates a feature ONLY with an\n * explicit `false`; absent means \"not gated by this plan\" (allowed). This keeps\n * entitlements additive and safe: a feature the plan has never heard of stays\n * open rather than silently locking.\n */\nexport function isEntitledByPlan(plan: Plan | null, feature: string): boolean {\n return plan?.entitlements?.features?.[feature] !== false\n}\n\n/**\n * The single access decision: role FIRST, then plan.\n *\n * 1. Role — reuses `profileHasPermission` (owner bypass + `manage` semantics\n * live there, and impersonation composes for free because `profile` is the\n * previewed role). Denied → `{ allowed:false, reason:'role' }`.\n * 2. Plan — even the owner does NOT bypass the plan: upgrading is the tenant's\n * decision, not a role power. Denied → `{ allowed:false, reason:'plan' }`.\n */\nexport function resolveAccess(\n subject: AccessSubject,\n feature: string,\n action?: PermissionAction,\n): AccessDecision {\n if (!profileHasPermission(subject.profile, feature, action)) {\n return { allowed: false, reason: 'role' }\n }\n if (!isEntitledByPlan(subject.plan, feature)) {\n return { allowed: false, reason: 'plan' }\n }\n return { allowed: true }\n}\n\n/**\n * Pure numeric side of a limit: given the plan cap, whether a countable\n * declaration exists, and the current usage, derive the limit math. Unlimited\n * when there's no declaration to count, no cap on the plan, or the cap is `-1`.\n */\nexport function resolveLimit(params: { cap: number | undefined; hasDeclaration: boolean; used: number }): {\n max: number\n used: number\n remaining: number\n atLimit: boolean\n unlimited: boolean\n} {\n const { cap, hasDeclaration, used } = params\n const unlimited = !hasDeclaration || cap === undefined || cap === -1\n const max = unlimited ? Infinity : cap\n const remaining = unlimited ? Infinity : Math.max(0, max - used)\n const atLimit = !unlimited && used >= max\n return { max, used, remaining, atLimit, unlimited }\n}\n","import type { DenyReason } from './engine'\n\n// ---------------------------------------------------------------------------\n// The structured denial an AGENT surface returns instead of failing silently\n// (docs/saas/ENTITLEMENTS.md § \"Superfície de agentes de IA\"). One shape for every\n// executor — FAB client-plane, the Fayz broker, and the pool RPCs (which emit\n// its jsonb mirror in their `denial` field) — so the model can explain the\n// denial and offer the upgrade path conversationally.\n// ---------------------------------------------------------------------------\n\n/** Where a denied tenant goes to upgrade — the conversational UpgradeModal. */\nexport const UPGRADE_URL = '/settings/subscription'\n\nexport interface AgentDenialLimit {\n key: string\n max: number\n used: number\n}\n\nexport interface AgentDenial {\n allowed: false\n reason: DenyReason\n /** Present when `reason === 'limit'`. */\n limit?: AgentDenialLimit\n upgradeUrl: string\n}\n\nexport type AgentGuardResult = { allowed: true } | AgentDenial\n\n/** Build a denial with the canonical upgrade URL attached. */\nexport function agentDenial(reason: DenyReason, limit?: AgentDenialLimit): AgentDenial {\n return { allowed: false, reason, ...(limit ? { limit } : {}), upgradeUrl: UPGRADE_URL }\n}\n","import type { LimitDeclaration } from '../types/entitlements'\n\n/**\n * The 4-layer limit-declaration merge, extracted so the browser AccessProvider\n * and the manifest derivation (`fayz manifest emit`) resolve the EXACT same\n * final set: core built-ins < entity-derived < plugin `declaredLimits` < app\n * overrides. Later layers win by key. Pure: pass the layers in, get the merge\n * out — deriving a declaration FROM an entity stays at the call site.\n */\nexport function mergeLimitDeclarations(\n ...layers: Array<LimitDeclaration[] | undefined>\n): LimitDeclaration[] {\n const byKey = new Map<string, LimitDeclaration>()\n for (const layer of layers) {\n for (const decl of layer ?? []) byKey.set(decl.key, decl)\n }\n return Array.from(byKey.values())\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/access/engine.ts","../../src/access/denial.ts","../../src/access/limits.ts"],"names":[],"mappings":";AAoDO,SAAS,eAAe,OAAA,EAAqC;AAClE,EAAA,OAAO,QAAQ,EAAA,KAAO,OAAA,IAAW,OAAA,CAAQ,IAAA,EAAM,aAAY,KAAM,OAAA;AACnE;AAOO,SAAS,oBAAA,CACd,OAAA,EACA,OAAA,EACA,MAAA,EACS;AACT,EAAA,IAAI,CAAC,SAAS,OAAO,IAAA;AAMrB,EAAA,IAAI,cAAA,CAAe,OAAO,CAAA,EAAG,OAAO,IAAA;AAEpC,EAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,MAAA,CAAO,OAAO,CAAA;AACtC,EAAA,IAAI,CAAC,SAAS,OAAO,KAAA;AAErB,EAAA,IAAI,CAAC,MAAA,EAAQ,OAAO,OAAA,CAAQ,MAAA,GAAS,CAAA;AAErC,EAAA,OAA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SAAA,IAAa,IAAA,IAAQ,GAAA;AACtC,EAAA,OAAO,EAAE,GAAA,EAAK,IAAA,EAAM,SAAA,EAAW,SAAS,SAAA,EAAU;AACpD;;;ACxLO,IAAM,WAAA,GAAc;AAmBpB,SAAS,WAAA,CAAY,QAAoB,KAAA,EAAuC;AACrF,EAAA,OAAO,EAAE,OAAA,EAAS,KAAA,EAAO,MAAA,EAAQ,GAAI,KAAA,GAAQ,EAAE,KAAA,EAAM,GAAI,EAAC,EAAI,UAAA,EAAY,WAAA,EAAY;AACxF;;;ACvBO,SAAS,0BACX,MAAA,EACiB;AACpB,EAAA,MAAM,KAAA,uBAAY,GAAA,EAA8B;AAChD,EAAA,KAAA,MAAW,SAAS,MAAA,EAAQ;AAC1B,IAAA,KAAA,MAAW,IAAA,IAAQ,SAAS,EAAC,QAAS,GAAA,CAAI,IAAA,CAAK,KAAK,IAAI,CAAA;AAAA,EAC1D;AACA,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,KAAA,CAAM,MAAA,EAAQ,CAAA;AAClC","file":"index.js","sourcesContent":["import type { PermissionProfile, PermissionAction, SystemPermission } from '../types/permissions'\nimport type { Plan } from '../types/billing'\n\n// ---------------------------------------------------------------------------\n// The access engine — the ONE implementation of the role × plan × limit\n// decision, shared by every runtime that gates anything:\n//\n// - browser (saas AccessProvider / PermissionsProvider re-export from here)\n// - headless client-plane (saas access/headless.ts)\n// - the Fayz broker (server-side agent authorization imports this package)\n//\n// Hard constraint: this module (and everything under core/src/access) must stay\n// free of React, zustand and supabase — pure functions over plain data — so the\n// exact same code runs in Node/edge. Guarded by scripts/check-access-purity.mjs.\n// ---------------------------------------------------------------------------\n\n/** Why an access request was denied. `limit` only occurs on guarded writes. */\nexport type DenyReason = 'role' | 'plan' | 'limit'\n\nexport interface AccessDecision {\n allowed: boolean\n reason?: DenyReason\n}\n\n/** The minimal subject a decision needs — a projection of any richer session. */\nexport interface AccessSubject {\n /** Effective RBAC profile — the previewed role during impersonation. */\n profile: PermissionProfile | null\n /** The tenant's currently-active plan. */\n plan: Plan | null\n /**\n * Extra role a person has INSIDE a given unit, keyed by unit id.\n *\n * Additive, never subtractive: the org role applies everywhere and a unit role\n * only adds inside its unit. That choice is what makes this shippable — the\n * answer without a unit is a strict SUBSET of the answer with one, so every\n * existing call site keeps its exact meaning and none of them had to change.\n * The alternative (a unit role that overrides) can take access away by\n * accident, and every screen would have to explain which role won.\n */\n unitProfiles?: Record<string, PermissionProfile>\n /** The unit the person is looking at, used when a check does not name one. */\n activeUnitId?: string\n}\n\n/**\n * The org owner has every permission implicitly. Owner is represented by the\n * canonical role id `owner` across adapters (see org/adapters/supabase.ts\n * buildPermissionProfiles, which also grants owner all catalog perms, and the\n * mock adapter's `owner` fallback). We match by id first, falling back to the\n * (possibly localized) name for safety.\n */\nexport function isOwnerProfile(profile: PermissionProfile): boolean {\n return profile.id === 'owner' || profile.name?.toLowerCase() === 'owner'\n}\n\n/**\n * The single role-side permission check. The plan axis composes ON TOP of it in\n * {@link resolveAccess} instead of reimplementing owner-bypass / `manage`\n * semantics.\n */\nexport function profileHasPermission(\n profile: PermissionProfile | null,\n feature: string,\n action?: string,\n): boolean {\n if (!profile) return true\n\n // Owner bypass: never lock the owner out, even if the RBAC catalog is empty\n // or still loading. Because permission checks read the *effective* profile,\n // an owner previewing a non-owner role correctly loses this bypass — the\n // preview stays honest.\n if (isOwnerProfile(profile)) return true\n\n const actions = profile.grants[feature]\n if (!actions) return false\n\n if (!action) return actions.length > 0\n\n return actions.includes(action) || actions.includes('manage')\n}\n\n/**\n * The org-management side of a profile: managing team, billing, settings and\n * permissions themselves. Separate axis from `grants` — these gate the settings\n * tabs, not a feature's rows — and it follows the same owner bypass, so the one\n * person who can hand out access is never locked out of doing it.\n */\nexport function profileHasSystemPermission(\n profile: PermissionProfile | null,\n permission: SystemPermission,\n): boolean {\n if (!profile) return true\n if (isOwnerProfile(profile)) return true\n return profile.systemPermissions?.includes(permission) ?? false\n}\n\n/**\n * Does the current plan entitle `feature`? A plan gates a feature ONLY with an\n * explicit `false`; absent means \"not gated by this plan\" (allowed). This keeps\n * entitlements additive and safe: a feature the plan has never heard of stays\n * open rather than silently locking.\n */\nexport function isEntitledByPlan(plan: Plan | null, feature: string): boolean {\n return plan?.entitlements?.features?.[feature] !== false\n}\n\n/**\n * Union two profiles. Grants merge per feature, system permissions merge, and\n * the result is never smaller than either input — the additive rule, in code.\n *\n * `manage` is not expanded here: {@link profileHasPermission} already treats it\n * as satisfying any action, so expanding it would be a second implementation of\n * the same rule waiting to disagree with the first.\n */\nexport function mergeProfiles(\n base: PermissionProfile | null,\n overlay: PermissionProfile | null,\n): PermissionProfile | null {\n if (!overlay) return base\n if (!base) return overlay\n // An owner already has everything; merging onto it can only produce noise.\n if (isOwnerProfile(base)) return base\n\n const grants: Record<string, PermissionAction[]> = { ...base.grants }\n for (const [feature, actions] of Object.entries(overlay.grants ?? {})) {\n const merged = new Set([...(grants[feature] ?? []), ...actions])\n grants[feature] = [...merged]\n }\n\n const system = new Set([...(base.systemPermissions ?? []), ...(overlay.systemPermissions ?? [])])\n\n return {\n ...base,\n grants,\n systemPermissions: system.size > 0 ? [...system] : undefined,\n }\n}\n\n/**\n * The profile that applies where the person is standing: their org role, plus\n * whatever the unit adds. With no unit — or no binding in it — this is exactly\n * the org role, which is why nothing that predates units changes behaviour.\n */\nexport function effectiveProfileFor(\n subject: AccessSubject,\n unitId?: string,\n): PermissionProfile | null {\n if (!unitId) return subject.profile\n return mergeProfiles(subject.profile, subject.unitProfiles?.[unitId] ?? null)\n}\n\n/**\n * The single access decision: role FIRST, then plan.\n *\n * 1. Role — reuses `profileHasPermission` (owner bypass + `manage` semantics\n * live there, and impersonation composes for free because `profile` is the\n * previewed role). Denied → `{ allowed:false, reason:'role' }`.\n * 2. Plan — even the owner does NOT bypass the plan: upgrading is the tenant's\n * decision, not a role power. Denied → `{ allowed:false, reason:'plan' }`.\n */\nexport function resolveAccess(\n subject: AccessSubject,\n feature: string,\n action?: PermissionAction,\n options?: { unitId?: string },\n): AccessDecision {\n const profile = effectiveProfileFor(subject, options?.unitId ?? subject.activeUnitId)\n if (!profileHasPermission(profile, feature, action)) {\n return { allowed: false, reason: 'role' }\n }\n if (!isEntitledByPlan(subject.plan, feature)) {\n return { allowed: false, reason: 'plan' }\n }\n return { allowed: true }\n}\n\n/**\n * Pure numeric side of a limit: given the plan cap, whether a countable\n * declaration exists, and the current usage, derive the limit math. Unlimited\n * when there's no declaration to count, no cap on the plan, or the cap is `-1`.\n */\nexport function resolveLimit(params: { cap: number | undefined; hasDeclaration: boolean; used: number }): {\n max: number\n used: number\n remaining: number\n atLimit: boolean\n unlimited: boolean\n} {\n const { cap, hasDeclaration, used } = params\n const unlimited = !hasDeclaration || cap === undefined || cap === -1\n const max = unlimited ? Infinity : cap\n const remaining = unlimited ? Infinity : Math.max(0, max - used)\n const atLimit = !unlimited && used >= max\n return { max, used, remaining, atLimit, unlimited }\n}\n","import type { DenyReason } from './engine'\n\n// ---------------------------------------------------------------------------\n// The structured denial an AGENT surface returns instead of failing silently\n// (docs/saas/ENTITLEMENTS.md § \"Superfície de agentes de IA\"). One shape for every\n// executor — FAB client-plane, the Fayz broker, and the pool RPCs (which emit\n// its jsonb mirror in their `denial` field) — so the model can explain the\n// denial and offer the upgrade path conversationally.\n// ---------------------------------------------------------------------------\n\n/** Where a denied tenant goes to upgrade — the conversational UpgradeModal. */\nexport const UPGRADE_URL = '/settings/subscription'\n\nexport interface AgentDenialLimit {\n key: string\n max: number\n used: number\n}\n\nexport interface AgentDenial {\n allowed: false\n reason: DenyReason\n /** Present when `reason === 'limit'`. */\n limit?: AgentDenialLimit\n upgradeUrl: string\n}\n\nexport type AgentGuardResult = { allowed: true } | AgentDenial\n\n/** Build a denial with the canonical upgrade URL attached. */\nexport function agentDenial(reason: DenyReason, limit?: AgentDenialLimit): AgentDenial {\n return { allowed: false, reason, ...(limit ? { limit } : {}), upgradeUrl: UPGRADE_URL }\n}\n","import type { LimitDeclaration } from '../types/entitlements'\n\n/**\n * The 4-layer limit-declaration merge, extracted so the browser AccessProvider\n * and the manifest derivation (`fayz manifest emit`) resolve the EXACT same\n * final set: core built-ins < entity-derived < plugin `declaredLimits` < app\n * overrides. Later layers win by key. Pure: pass the layers in, get the merge\n * out — deriving a declaration FROM an entity stays at the call site.\n */\nexport function mergeLimitDeclarations(\n ...layers: Array<LimitDeclaration[] | undefined>\n): LimitDeclaration[] {\n const byKey = new Map<string, LimitDeclaration>()\n for (const layer of layers) {\n for (const decl of layer ?? []) byKey.set(decl.key, decl)\n }\n return Array.from(byKey.values())\n}\n"]}
|
|
@@ -56,6 +56,31 @@ function applyRangeToQuery(query, column, range) {
|
|
|
56
56
|
return q;
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
+
// src/data/unit-scope.ts
|
|
60
|
+
var _scoped = {};
|
|
61
|
+
function setScopedResources(map) {
|
|
62
|
+
_scoped = map;
|
|
63
|
+
}
|
|
64
|
+
function getScopedResource(table) {
|
|
65
|
+
if (!table) return void 0;
|
|
66
|
+
return _scoped[table];
|
|
67
|
+
}
|
|
68
|
+
function resolveUnitScope(config) {
|
|
69
|
+
if (!config.unitScoped) return null;
|
|
70
|
+
const id = config.unitId?.();
|
|
71
|
+
if (!id) return null;
|
|
72
|
+
return {
|
|
73
|
+
column: config.unitColumn ?? "unit_id",
|
|
74
|
+
id,
|
|
75
|
+
includeShared: config.includeSharedRows !== false
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
function applyUnitScope(builder, scope) {
|
|
79
|
+
if (!scope) return builder;
|
|
80
|
+
const q = builder;
|
|
81
|
+
return scope.includeShared ? q.or(`${scope.column}.eq.${scope.id},${scope.column}.is.null`) : q.eq(scope.column, scope.id);
|
|
82
|
+
}
|
|
83
|
+
|
|
59
84
|
// src/data/supabase.ts
|
|
60
85
|
function camelToSnake(str) {
|
|
61
86
|
return str.replace(/[A-Z]/g, (c) => "_" + c.toLowerCase());
|
|
@@ -80,7 +105,7 @@ function mapEntity(entity, columnMap) {
|
|
|
80
105
|
}
|
|
81
106
|
const result = {};
|
|
82
107
|
for (const [key, value] of Object.entries(entity)) {
|
|
83
|
-
if (key === "id" || key === "createdAt" || key === "updatedAt" || key === "tenantId" || key === "createdBy") continue;
|
|
108
|
+
if (key === "id" || key === "createdAt" || key === "updatedAt" || key === "tenantId" || key === "createdBy" || key === "ownerId") continue;
|
|
84
109
|
const snakeKey = reverseMap[key] ?? camelToSnake(key);
|
|
85
110
|
result[snakeKey] = value;
|
|
86
111
|
}
|
|
@@ -103,6 +128,9 @@ function createSupabaseProvider(table, config) {
|
|
|
103
128
|
if (!config?.tenantId) return void 0;
|
|
104
129
|
return typeof config.tenantId === "function" ? config.tenantId() : config.tenantId;
|
|
105
130
|
}
|
|
131
|
+
function unitScope() {
|
|
132
|
+
return resolveUnitScope(config ?? {});
|
|
133
|
+
}
|
|
106
134
|
function getClient() {
|
|
107
135
|
const supabase = config?.supabaseClient ?? _globalSupabaseClient;
|
|
108
136
|
if (!supabase) throw new Error(`[@fayz-ai/core] Supabase client not available. Call createFayzApp with a provider first.`);
|
|
@@ -114,6 +142,7 @@ function createSupabaseProvider(table, config) {
|
|
|
114
142
|
let q = getClient().from(table).select(selectCols, wantCount ? { count: "exact" } : void 0);
|
|
115
143
|
const tenantId = resolveTenantId();
|
|
116
144
|
if (tenantId) q = q.eq(tenantIdCol, tenantId);
|
|
145
|
+
q = applyUnitScope(q, unitScope());
|
|
117
146
|
if (config?.filters) {
|
|
118
147
|
for (const [col, val] of Object.entries(config.filters)) {
|
|
119
148
|
q = q.eq(col, val);
|
|
@@ -161,6 +190,8 @@ function createSupabaseProvider(table, config) {
|
|
|
161
190
|
const row = mapEntity(data, columnMap);
|
|
162
191
|
const tenantId = resolveTenantId();
|
|
163
192
|
if (tenantId) row[tenantIdCol] = tenantId;
|
|
193
|
+
const scope = unitScope();
|
|
194
|
+
if (scope && row[scope.column] === void 0) row[scope.column] = scope.id;
|
|
164
195
|
if (config?.defaults) {
|
|
165
196
|
for (const [col, val] of Object.entries(config.defaults)) {
|
|
166
197
|
if (row[col] === void 0) row[col] = val;
|
|
@@ -173,9 +204,11 @@ function createSupabaseProvider(table, config) {
|
|
|
173
204
|
async createMany(rows, options) {
|
|
174
205
|
const tenantId = resolveTenantId();
|
|
175
206
|
const size = Math.max(1, options?.chunkSize ?? 200);
|
|
207
|
+
const scope = unitScope();
|
|
176
208
|
const prepared = rows.map((r) => {
|
|
177
209
|
const row = mapEntity(r, columnMap);
|
|
178
210
|
if (tenantId) row[tenantIdCol] = tenantId;
|
|
211
|
+
if (scope && row[scope.column] === void 0) row[scope.column] = scope.id;
|
|
179
212
|
if (config?.defaults) {
|
|
180
213
|
for (const [col, val] of Object.entries(config.defaults)) {
|
|
181
214
|
if (row[col] === void 0) row[col] = val;
|
|
@@ -315,6 +348,6 @@ function useActiveTenantId() {
|
|
|
315
348
|
return React.useSyncExternalStore(subscribeActiveTenant, getActiveTenantId, getActiveTenantId);
|
|
316
349
|
}
|
|
317
350
|
|
|
318
|
-
export { DEFAULT_CACHE_TTL, applyRangeToQuery, clearGlobalCache, createCacheStore, createSupabaseProvider, getActiveTenantId, getSupabaseClientOptional, globalCache, isFilterObject, matchesRange, parseRangeFilter, setActiveTenantId, setGlobalSupabaseClient, stableKey, subscribeActiveTenant, useActiveTenantId };
|
|
319
|
-
//# sourceMappingURL=chunk-
|
|
320
|
-
//# sourceMappingURL=chunk-
|
|
351
|
+
export { DEFAULT_CACHE_TTL, applyRangeToQuery, applyUnitScope, clearGlobalCache, createCacheStore, createSupabaseProvider, getActiveTenantId, getScopedResource, getSupabaseClientOptional, globalCache, isFilterObject, matchesRange, parseRangeFilter, resolveUnitScope, setActiveTenantId, setGlobalSupabaseClient, setScopedResources, stableKey, subscribeActiveTenant, useActiveTenantId };
|
|
352
|
+
//# sourceMappingURL=chunk-BCI743RH.js.map
|
|
353
|
+
//# sourceMappingURL=chunk-BCI743RH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1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B;AACF;AAEO,SAAS,iBAAA,GAAwC;AACtD,EAAA,OAAO,eAAA;AACT;AAQO,SAAS,sBAAsB,QAAA,EAAkC;AACtE,EAAA,SAAA,CAAU,IAAI,QAAQ,CAAA;AACtB,EAAA,OAAO,MAAM;AAAE,IAAA,SAAA,CAAU,OAAO,QAAQ,CAAA;AAAA,EAAE,CAAA;AAC5C;AAIO,SAAS,iBAAA,GAAwC;AACtD,EAAA,OAAa,KAAA,CAAA,oBAAA,CAAqB,qBAAA,EAAuB,iBAAA,EAAmB,iBAAiB,CAAA;AAC/F","file":"chunk-BCI743RH.js","sourcesContent":["/**\n * ONE filter grammar, shared by the providers and by the agent's data tools.\n *\n * Models express ranges in whatever dialect they were trained on — `{from,to}`,\n * `{gte,lte}`, Mongo's `{$gte,$lt}`. When only some of those are recognised the\n * unrecognised one falls through to an equality compare against\n * \"[object Object]\", which matches nothing and reads as \"there are no\n * appointments today\" instead of \"I did not understand that filter\".\n */\n\nexport interface RangeFilter {\n gte?: unknown\n gt?: unknown\n lte?: unknown\n lt?: unknown\n}\n\nconst LOWER_INCLUSIVE = ['from', 'gte', 'start', 'after', 'since', 'min']\nconst LOWER_EXCLUSIVE = ['gt']\nconst UPPER_INCLUSIVE = ['to', 'lte', 'end', 'until', 'before', 'max']\nconst UPPER_EXCLUSIVE = ['lt']\n\nfunction pick(source: Record<string, unknown>, names: string[]): unknown {\n for (const name of names) {\n if (source[name] !== undefined && source[name] !== null) return source[name]\n const dollar = `$${name}`\n if (source[dollar] !== undefined && source[dollar] !== null) return source[dollar]\n }\n return undefined\n}\n\n/**\n * Parse a filter value into a range, or return null when it is a plain\n * (equality) value. An object that looks like a filter but carries no\n * recognised bound returns `null` too — callers treat that as \"invalid\",\n * never as \"matches nothing\".\n */\nexport function parseRangeFilter(value: unknown): RangeFilter | null {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return null\n const source = value as Record<string, unknown>\n const range: RangeFilter = {}\n const gte = pick(source, LOWER_INCLUSIVE)\n const gt = pick(source, LOWER_EXCLUSIVE)\n const lte = pick(source, UPPER_INCLUSIVE)\n const lt = pick(source, UPPER_EXCLUSIVE)\n if (gte !== undefined) range.gte = gte\n if (gt !== undefined) range.gt = gt\n if (lte !== undefined) range.lte = lte\n if (lt !== undefined) range.lt = lt\n return Object.keys(range).length ? range : null\n}\n\n/** True for any object value — including ones no bound could be read from. */\nexport function isFilterObject(value: unknown): boolean {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction comparable(value: unknown): number {\n if (typeof value === 'number') return value\n if (value instanceof Date) return value.getTime()\n const ts = Date.parse(String(value))\n if (!Number.isNaN(ts)) return ts\n return Number(value)\n}\n\n/** Client-side counterpart of the range a provider would push to SQL. */\nexport function matchesRange(raw: unknown, range: RangeFilter): boolean {\n const value = comparable(raw)\n if (Number.isNaN(value)) return false\n if (range.gte !== undefined && value < comparable(range.gte)) return false\n if (range.gt !== undefined && value <= comparable(range.gt)) return false\n if (range.lte !== undefined && value > comparable(range.lte)) return false\n if (range.lt !== undefined && value >= comparable(range.lt)) return false\n return true\n}\n\n/** Apply a range to a PostgREST query builder. */\nexport function applyRangeToQuery<Q>(\n query: Q,\n column: string,\n range: RangeFilter,\n): Q {\n let q = query as Record<string, (c: string, v: unknown) => unknown>\n for (const op of ['gte', 'gt', 'lte', 'lt'] as const) {\n const bound = range[op]\n if (bound === undefined) continue\n q = q[op](column, bound) as Record<string, (c: string, v: unknown) => unknown>\n }\n return q as Q\n}\n","// ---------------------------------------------------------------------------\n// The one place that turns \"the user is looking at Ipanema\" into a filter.\n//\n// This is a NARROWING and nothing else. Which units a person may reach is\n// decided by row-level security; if this file were deleted the app would show\n// more rows than the switcher promises, and still not one row the database\n// would have refused. That asymmetry is deliberate — it is what lets the filter\n// live in the client at all.\n// ---------------------------------------------------------------------------\n\nexport interface UnitScope {\n column: string\n id: string\n /** Whether rows with no unit (\"belongs to the whole organization\") come too. */\n includeShared: boolean\n}\n\n/** One row of `public.scoped_resources` — which tables carry a unit, and under\n * which column. */\nexport interface ScopedResource {\n unitColumn: string\n shareable: boolean\n}\n\n// The registry, mirrored from the database rather than restated here.\n//\n// The list of scoped tables and their unit columns lives in ONE place —\n// `public.scoped_resources`, seeded by migration 041 — and the shell publishes\n// it at boot. A second copy in TypeScript would drift on the first table anyone\n// adds, and the failure mode of that drift is a screen that quietly stops\n// narrowing while the database still does.\nlet _scoped: Record<string, ScopedResource> = {}\n\nexport function setScopedResources(map: Record<string, ScopedResource>): void {\n _scoped = map\n}\n\nexport function getScopedResource(table: string | undefined): ScopedResource | undefined {\n if (!table) return undefined\n return _scoped[table]\n}\n\nexport interface UnitScopeConfig {\n unitScoped?: boolean\n unitColumn?: string\n /**\n * Default true. A row with no unit belongs to the brand and must survive a\n * unit selection — the Botox that is sold everywhere still shows in Ipanema.\n *\n * False for ledgers and aggregations, where a shared row summed into every\n * unit is a wrong number stated confidently, which is worse than a missing\n * one.\n */\n includeSharedRows?: boolean\n unitId?: () => string | undefined\n}\n\n/**\n * `null` means \"do not narrow\" — unit mode off, \"todas as unidades\", or an\n * entity that never opted in. Callers treat null as a no-op, which is what\n * keeps every provider's behaviour identical for entities that are not scoped.\n */\nexport function resolveUnitScope(config: UnitScopeConfig): UnitScope | null {\n if (!config.unitScoped) return null\n const id = config.unitId?.()\n if (!id) return null\n return {\n column: config.unitColumn ?? 'unit_id',\n id,\n includeShared: config.includeSharedRows !== false,\n }\n}\n\n/**\n * Applies the scope to a PostgREST builder.\n *\n * The shared form is `or(unit.eq.X,unit.is.null)`. Multiple `or=` params AND\n * together in PostgREST, so this composes correctly with the search `.or()` the\n * providers already emit: (name matches) AND (unit is mine or nobody's).\n *\n * Note what is NOT here: an `.in(column, [...myUnits])`. Enumerating the user's\n * units in the browser is the exact mistake this whole design exists to avoid —\n * it would put the answer to \"which units may I see\" in the client, where it\n * can be edited.\n */\nexport function applyUnitScope<Q>(builder: Q, scope: UnitScope | null): Q {\n if (!scope) return builder\n const q = builder as unknown as {\n or: (f: string) => unknown\n eq: (c: string, v: unknown) => unknown\n }\n return (scope.includeShared\n ? q.or(`${scope.column}.eq.${scope.id},${scope.column}.is.null`)\n : q.eq(scope.column, scope.id)) as unknown as Q\n}\n","import type { DataProvider, CrudQuery, CrudResult } from './types'\nimport { applyRangeToQuery, isFilterObject, parseRangeFilter } from './filters'\nimport { applyUnitScope, resolveUnitScope } from './unit-scope'\n\nexport interface SupabaseProviderConfig {\n schema?: string\n tenantId?: string | (() => string | undefined)\n tenantIdColumn?: string\n searchColumns?: string[]\n selectColumns?: string\n columnMap?: Record<string, string>\n filters?: Record<string, string>\n defaults?: Record<string, unknown>\n supabaseClient?: unknown\n /** Franchise scoping. Absent (every entity today) ⇒ nothing below changes. */\n unitScoped?: boolean\n unitColumn?: string\n includeSharedRows?: boolean\n unitId?: () => string | undefined\n}\n\nfunction camelToSnake(str: string): string {\n return str.replace(/[A-Z]/g, (c) => '_' + c.toLowerCase())\n}\n\nfunction snakeToCamel(str: string): string {\n return str.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase())\n}\n\nfunction mapRow<T>(row: Record<string, unknown>, columnMap?: Record<string, string>): T {\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(row)) {\n const camelKey = columnMap?.[key] ?? snakeToCamel(key)\n result[camelKey] = value\n }\n return result as T\n}\n\nfunction mapEntity(entity: Record<string, unknown>, columnMap?: Record<string, string>): Record<string, unknown> {\n const reverseMap: Record<string, string> = {}\n if (columnMap) {\n for (const [snake, camel] of Object.entries(columnMap)) {\n reverseMap[camel] = snake\n }\n }\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(entity)) {\n // `createdBy` entra na lista: quem o escreve é o gatilho do banco, com\n // `auth.uid()`. Deixá-lo passar daria à interface a chance de dizer quem\n // cadastrou — e um autor que o próprio formulário pode escolher não vale\n // como procedência. Ver packages/db/migrations/025_created_by.sql.\n // `ownerId` for the same reason: 041's trigger decides who a record belongs\n // to, and a form that could set it would be handing records to other people.\n if (key === 'id' || key === 'createdAt' || key === 'updatedAt' || key === 'tenantId' || key === 'createdBy' || key === 'ownerId') continue\n const snakeKey = reverseMap[key] ?? camelToSnake(key)\n result[snakeKey] = value\n }\n return result\n}\n\n// Global Supabase client registry — set once via createFayzApp\nlet _globalSupabaseClient: unknown | null = null\n\nexport function setGlobalSupabaseClient(client: unknown): void {\n _globalSupabaseClient = client\n}\n\nexport function getSupabaseClientOptional(): unknown | null {\n return _globalSupabaseClient\n}\n\nexport function createSupabaseProvider<T extends { id: string }>(\n table: string,\n config?: SupabaseProviderConfig,\n): DataProvider<T> {\n const schema = config?.schema ?? 'public'\n const tenantIdCol = config?.tenantIdColumn ?? 'tenant_id'\n const searchCols = config?.searchColumns ?? []\n const selectCols = config?.selectColumns ?? '*'\n const columnMap = config?.columnMap\n\n function resolveTenantId(): string | undefined {\n if (!config?.tenantId) return undefined\n return typeof config.tenantId === 'function' ? config.tenantId() : config.tenantId\n }\n\n function unitScope() {\n return resolveUnitScope(config ?? {})\n }\n\n function getClient() {\n const supabase = (config?.supabaseClient ?? _globalSupabaseClient) as {\n schema: (s: string) => unknown\n from: (t: string) => unknown\n } | null\n if (!supabase) throw new Error(`[@fayz-ai/core] Supabase client not available. Call createFayzApp with a provider first.`)\n return schema === 'public' ? (supabase as { from: (t: string) => unknown }) : (supabase.schema(schema) as { from: (t: string) => unknown })\n }\n\n return {\n async list(query: CrudQuery): Promise<CrudResult<T>> {\n // 'none' skips PostgREST's count aggregate entirely — see CrudQuery.countMode.\n const wantCount = query.countMode !== 'none'\n let q = (getClient().from(table) as { select: (...args: unknown[]) => unknown })\n .select(selectCols, wantCount ? { count: 'exact' } : undefined) as Record<string, unknown>\n\n const tenantId = resolveTenantId()\n if (tenantId) q = (q as { eq: (col: string, val: string) => unknown }).eq(tenantIdCol, tenantId) as Record<string, unknown>\n\n // Narrowing only — the boundary itself is the restrictive policy in the\n // database. Placed before the search `.or()` because PostgREST ANDs the\n // two `or=` params, which is what makes them compose.\n q = applyUnitScope(q, unitScope()) as Record<string, unknown>\n\n if (config?.filters) {\n for (const [col, val] of Object.entries(config.filters)) {\n q = (q as { eq: (c: string, v: string) => unknown }).eq(col, val) as Record<string, unknown>\n }\n }\n\n // Faceted / dynamic filters from the query, mapped to columns. Equality\n // by default; a range object ({from,to} / {gte,lt} / {$gte,$lt}) becomes\n // real SQL bounds instead of an equality compare against \"[object Object]\".\n if (query.filters) {\n for (const [key, val] of Object.entries(query.filters)) {\n if (val == null || val === '') continue\n const col = columnMap?.[key] ?? camelToSnake(key)\n const range = parseRangeFilter(val)\n if (range) {\n q = applyRangeToQuery(q, col, range)\n continue\n }\n if (isFilterObject(val)) {\n throw new Error(\n `[@fayz-ai/core] Filter \"${key}\" is an object with no recognised bound. ` +\n 'Use {from,to} / {gte,lte,gt,lt} for ranges, or a plain value for equality.',\n )\n }\n q = (q as { eq: (c: string, v: unknown) => unknown }).eq(col, val) as Record<string, unknown>\n }\n }\n\n if (query.search && searchCols.length > 0) {\n const term = `%${query.search}%`\n const orClause = searchCols.map((col) => `${camelToSnake(col)}.ilike.${term}`).join(',')\n q = (q as { or: (c: string) => unknown }).or(orClause) as Record<string, unknown>\n }\n\n if (query.sortBy) {\n q = (q as { order: (col: string, opts: unknown) => unknown })\n .order(camelToSnake(query.sortBy), { ascending: query.sortDir !== 'desc' }) as Record<string, unknown>\n } else {\n q = (q as { order: (col: string, opts: unknown) => unknown })\n .order('created_at', { ascending: false }) as Record<string, unknown>\n }\n\n const page = query.page ?? 1\n const pageSize = query.pageSize ?? 50\n const from = (page - 1) * pageSize\n q = (q as { range: (f: number, t: number) => unknown }).range(from, from + pageSize - 1) as Record<string, unknown>\n\n const { data, error, count } = await q as { data: Record<string, unknown>[] | null; error: unknown; count: number | null }\n if (error) throw error\n\n return {\n data: (data ?? []).map((row) => mapRow<T>(row, columnMap)),\n total: count ?? 0,\n }\n },\n\n async create(data) {\n const row = mapEntity(data as Record<string, unknown>, columnMap)\n const tenantId = resolveTenantId()\n if (tenantId) row[tenantIdCol] = tenantId\n const scope = unitScope()\n if (scope && row[scope.column] === undefined) row[scope.column] = scope.id\n if (config?.defaults) {\n for (const [col, val] of Object.entries(config.defaults)) {\n if (row[col] === undefined) row[col] = val\n }\n }\n\n const { data: created, error } = (await (getClient().from(table) as {\n insert: (r: unknown) => { select: () => { single: () => Promise<{ data: unknown; error: unknown }> } }\n }).insert(row).select().single()) as { data: Record<string, unknown> | null; error: unknown }\n\n if (error) throw error\n return mapRow<T>(created!, columnMap)\n },\n\n async createMany(rows, options) {\n const tenantId = resolveTenantId()\n const size = Math.max(1, options?.chunkSize ?? 200)\n const scope = unitScope()\n const prepared = rows.map((r) => {\n const row = mapEntity(r as Record<string, unknown>, columnMap)\n if (tenantId) row[tenantIdCol] = tenantId\n if (scope && row[scope.column] === undefined) row[scope.column] = scope.id\n if (config?.defaults) {\n for (const [col, val] of Object.entries(config.defaults)) {\n if (row[col] === undefined) row[col] = val\n }\n }\n return row\n })\n\n let created = 0\n const failed: Array<{ index: number; message: string }> = []\n for (let start = 0; start < prepared.length; start += size) {\n const chunk = prepared.slice(start, start + size)\n const { error } = (await (getClient().from(table) as {\n insert: (r: unknown) => Promise<{ error: unknown }>\n }).insert(chunk)) as { error: unknown }\n if (!error) {\n created += chunk.length\n } else {\n // One bad row rejects its whole chunk. Retrying it row by row keeps\n // the other 199 — an import that loses 200 records over one malformed\n // phone number is worse than no import.\n const message = error instanceof Error ? error.message : String(error)\n for (let i = 0; i < chunk.length; i++) {\n const { error: rowError } = (await (getClient().from(table) as {\n insert: (r: unknown) => Promise<{ error: unknown }>\n }).insert(chunk[i])) as { error: unknown }\n if (rowError) {\n failed.push({\n index: start + i,\n message: rowError instanceof Error ? rowError.message : String(rowError ?? message),\n })\n } else created += 1\n }\n }\n options?.onProgress?.(Math.min(start + chunk.length, prepared.length), prepared.length)\n }\n return { created, failed }\n },\n\n async update(id, data) {\n const row = mapEntity(data as Record<string, unknown>, columnMap)\n const { data: updated, error } = (await (getClient().from(table) as {\n update: (r: unknown) => { eq: (c: string, v: string) => { select: () => { single: () => Promise<{ data: unknown; error: unknown }> } } }\n }).update(row).eq('id', id).select().single()) as { data: Record<string, unknown> | null; error: unknown }\n\n if (error) throw error\n return mapRow<T>(updated!, columnMap)\n },\n\n async remove(id) {\n const { error } = (await (getClient().from(table) as {\n delete: () => { eq: (c: string, v: string) => Promise<{ error: unknown }> }\n }).delete().eq('id', id)) as { error: unknown }\n if (error) throw error\n },\n\n async removeMany(ids) {\n if (!ids.length) return\n const { error } = (await (getClient().from(table) as {\n delete: () => { in: (c: string, v: string[]) => Promise<{ error: unknown }> }\n }).delete().in('id', ids)) as { error: unknown }\n if (error) throw error\n },\n }\n}\n","// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\ninterface CacheEntry<T = unknown> {\n data: T\n expiresAt: number\n lastAccess: number\n}\n\nexport interface CacheStore {\n get<T>(key: string): T | undefined\n set<T>(key: string, data: T, ttl?: number): void\n /** Clear all entries whose key starts with `prefix` */\n invalidate(prefix: string): void\n clear(): void\n size(): number\n}\n\nexport interface CacheConfig {\n /** Default time-to-live in ms (default: 60 000 — 1 minute) */\n defaultTTL?: number\n /** Maximum cached entries before LRU eviction (default: 500) */\n maxEntries?: number\n}\n\n// ---------------------------------------------------------------------------\n// Stable key helper — deterministic JSON for cache keys\n// ---------------------------------------------------------------------------\n\nfunction sortDeep(value: unknown): unknown {\n if (value === null || value === undefined || typeof value !== 'object') return value\n if (Array.isArray(value)) return value.map(sortDeep)\n const sorted: Record<string, unknown> = {}\n for (const k of Object.keys(value as Record<string, unknown>).sort()) {\n sorted[k] = sortDeep((value as Record<string, unknown>)[k])\n }\n return sorted\n}\n\nexport function stableKey(...parts: unknown[]): string {\n return parts.map((p) => (typeof p === 'string' ? p : JSON.stringify(sortDeep(p)))).join(':')\n}\n\n// ---------------------------------------------------------------------------\n// CacheStore implementation\n// ---------------------------------------------------------------------------\n\n/** Shared so the persistent layer can reconstruct the same `expiresAt` L1 computed. */\nexport const DEFAULT_CACHE_TTL = 60_000\n\nexport function createCacheStore(config?: CacheConfig): CacheStore {\n const defaultTTL = config?.defaultTTL ?? DEFAULT_CACHE_TTL\n const maxEntries = config?.maxEntries ?? 500\n const entries = new Map<string, CacheEntry>()\n\n function evictLRU() {\n if (entries.size <= maxEntries) return\n // Find the entry with the oldest lastAccess\n let oldestKey: string | null = null\n let oldestAccess = Infinity\n for (const [key, entry] of entries) {\n if (entry.lastAccess < oldestAccess) {\n oldestAccess = entry.lastAccess\n oldestKey = key\n }\n }\n if (oldestKey) entries.delete(oldestKey)\n }\n\n return {\n get<T>(key: string): T | undefined {\n const entry = entries.get(key)\n if (!entry) return undefined\n if (Date.now() > entry.expiresAt) {\n entries.delete(key)\n return undefined\n }\n entry.lastAccess = Date.now()\n return entry.data as T\n },\n\n set<T>(key: string, data: T, ttl?: number): void {\n const now = Date.now()\n entries.set(key, {\n data,\n expiresAt: now + (ttl ?? defaultTTL),\n lastAccess: now,\n })\n evictLRU()\n },\n\n invalidate(prefix: string): void {\n for (const key of entries.keys()) {\n if (key.startsWith(prefix)) {\n entries.delete(key)\n }\n }\n },\n\n clear(): void {\n entries.clear()\n },\n\n size(): number {\n return entries.size\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// Global singleton — auto-flushes on tenant/org switch\n// ---------------------------------------------------------------------------\n\nexport const globalCache = createCacheStore()\n\n/** Flush the global cache — called by the tenant accessor when the active\n * tenant changes (replaces the old org-store subscription). */\nexport function clearGlobalCache(): void {\n globalCache.clear()\n}\n","// Active tenant context — a global accessor the data layer reads for tenant\n// scoping and cache keying. The host (saas shell / app) sets it from its org\n// store via setActiveTenantId; the data providers stay decoupled from any\n// specific org-store implementation (runtime DI).\nimport * as React from 'react'\nimport { clearGlobalCache } from './cache'\n\nlet _activeTenantId: string | undefined\nconst listeners = new Set<() => void>()\n\nexport function setActiveTenantId(id: string | undefined): void {\n if (id !== _activeTenantId) {\n _activeTenantId = id\n clearGlobalCache()\n for (const l of listeners) l()\n }\n}\n\nexport function getActiveTenantId(): string | undefined {\n return _activeTenantId\n}\n\n/**\n * Subscribes to tenant changes. A getter alone makes every read a race with the\n * shell: a view that mounts before the org store resolves reads `undefined`,\n * and a tenant-scoped fetch that answers \"no tenant\" looks exactly like \"no\n * rows\" — it never retries and the screen stays empty until a remount.\n */\nexport function subscribeActiveTenant(listener: () => void): () => void {\n listeners.add(listener)\n return () => { listeners.delete(listener) }\n}\n\n/** The active tenant, re-rendering when it resolves or changes. Use this to key\n * effects that fetch tenant-scoped data. */\nexport function useActiveTenantId(): string | undefined {\n return React.useSyncExternalStore(subscribeActiveTenant, getActiveTenantId, getActiveTenantId)\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isConnectorCategory, CONNECTOR_CATEGORIES, requestPlaneSpec, connectorPlanes, invocationPlane, connectorSubscribes, permissionActions, isEventPermission, connectorEntities, connectorSubscribesTo } from './chunk-
|
|
1
|
+
import { isConnectorCategory, CONNECTOR_CATEGORIES, requestPlaneSpec, connectorPlanes, invocationPlane, connectorSubscribes, permissionActions, isEventPermission, connectorEntities, connectorSubscribesTo } from './chunk-OHH26S4N.js';
|
|
2
2
|
|
|
3
3
|
// src/testing.ts
|
|
4
4
|
var PluginContractError = class extends Error {
|
|
@@ -285,5 +285,5 @@ function assertConnectorContract(connector) {
|
|
|
285
285
|
}
|
|
286
286
|
|
|
287
287
|
export { PluginContractError, assertConnectorContract, assertPluginManifestContract, bespokeConnectorTables };
|
|
288
|
-
//# sourceMappingURL=chunk-
|
|
289
|
-
//# sourceMappingURL=chunk-
|
|
288
|
+
//# sourceMappingURL=chunk-KJUD6JA5.js.map
|
|
289
|
+
//# sourceMappingURL=chunk-KJUD6JA5.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/testing.ts"],"names":[],"mappings":";;;AA0BO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC7C,YAAY,OAAA,EAAiB;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c,CAAA;AAC5G,IAAA,IAAI,CAAC,KAAA,CAAM,OAAA,CAAQ,GAAA,CAAI,QAAQ,CAAA,IAAK,GAAA,CAAI,QAAA,CAAS,MAAA,KAAW,CAAA,EAAG,IAAA,CAAK,KAAA,EAAO,CAAA,aAAA,EAAgB,CAAC,CAAA,4BAAA,CAA8B,CAAA;AAC1H,IAAA,KAAA,MAAW,IAAA,IAAQ,IAAI,QAAA,EAAU;AAC/B,MAAA,IAAI,CAAC,QAAA,CAAS,GAAA,CAAI,IAAI,CAAA,EAAG,IAAA,CAAK,KAAA,EAAO,CAAA,aAAA,EAAgB,CAAC,CAAA,uBAAA,EAA0B,IAAI,CAAA,CAAA,CAAG,CAAA;AAAA,IACzF;AAAA,EACF;AACF","file":"chunk-IKZR3WSK.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Plugin contract assertions — the integrity half of the deploy gate.\n// ---------------------------------------------------------------------------\n// Framework-agnostic runtime checks (no test-runner dependency) that any\n// plugin's *.test.ts calls to prove its manifest/connector conform to the\n// platform contract BEFORE it can ship. A plugin that fails these would break\n// the host app at mount time (missing route component, duplicate ids, malformed\n// settings tab). Pair with a capability test (does the plugin do its job?) — see\n// docs/plugins/PLUGIN-PATTERNS.md → capability anatomy. These throw on the first violation.\nimport type { PluginManifest } from './types/plugins'\nimport type { Connector } from './integrations'\nimport {\n CONNECTOR_CATEGORIES,\n connectorEntities,\n connectorPlanes,\n connectorSubscribes,\n connectorSubscribesTo,\n grants,\n invocationPlane,\n isConnectorCategory,\n isEventPermission,\n permissionActions,\n requestPlaneSpec,\n} from './integrations'\nimport type { ConnectorPermission } from './integrations'\n\nexport class PluginContractError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'PluginContractError'\n }\n}\n\nfunction fail(scope: string, msg: string): never {\n throw new PluginContractError(`[${scope}] ${msg}`)\n}\n\nfunction nonEmptyString(v: unknown): v is string {\n return typeof v === 'string' && v.trim().length > 0\n}\n\n/**\n * Assert a PluginManifest is structurally sound enough to mount safely.\n * Checks identity, navigation/route wiring, settings tabs, declared features,\n * and id uniqueness. Throws PluginContractError on the first problem.\n */\nexport function assertPluginManifestContract(manifest: PluginManifest): void {\n const id = manifest?.id\n const scope = nonEmptyString(id) ? id : '<unknown plugin>'\n\n for (const field of ['id', 'name', 'icon', 'version'] as const) {\n if (!nonEmptyString(manifest?.[field])) fail(scope, `manifest.${field} must be a non-empty string`)\n }\n\n if (!Array.isArray(manifest.navigation)) fail(scope, 'manifest.navigation must be an array (use [] for settings-only plugins)')\n if (!Array.isArray(manifest.routes)) fail(scope, 'manifest.routes must be an array (use [] for settings-only plugins)')\n\n // Every nav entry must point at a route; every route needs a path + component.\n for (const [i, nav] of manifest.navigation.entries()) {\n if (!nonEmptyString((nav as any)?.route)) fail(scope, `navigation[${i}].route must be a non-empty string`)\n }\n const routePaths = new Set<string>()\n for (const [i, route] of manifest.routes.entries()) {\n if (!nonEmptyString((route as any)?.path)) fail(scope, `routes[${i}].path must be a non-empty string`)\n if (typeof (route as any)?.component !== 'function') fail(scope, `routes[${i}].component must be a component`)\n if (routePaths.has((route as any).path)) fail(scope, `duplicate route path \"${(route as any).path}\"`)\n routePaths.add((route as any).path)\n }\n // A nav entry that links to a route the plugin doesn't declare is dead UI.\n for (const [i, nav] of manifest.navigation.entries()) {\n const r = (nav as any).route\n if (routePaths.size > 0 && !routePaths.has(r)) {\n fail(scope, `navigation[${i}].route \"${r}\" has no matching route in manifest.routes`)\n }\n }\n\n // Settings tabs (the only UI surface integrations need) must be renderable.\n const settingIds = new Set<string>()\n for (const [i, tab] of (manifest.settings ?? []).entries()) {\n if (!nonEmptyString((tab as any)?.id)) fail(scope, `settings[${i}].id must be a non-empty string`)\n if (!nonEmptyString((tab as any)?.label)) fail(scope, `settings[${i}].label must be a non-empty string`)\n if (typeof (tab as any)?.component !== 'function') fail(scope, `settings[${i}].component must be a component`)\n if (settingIds.has((tab as any).id)) fail(scope, `duplicate settings tab id \"${(tab as any).id}\"`)\n settingIds.add((tab as any).id)\n }\n\n for (const [i, feat] of (manifest.declaredFeatures ?? []).entries()) {\n if (!nonEmptyString((feat as any)?.id)) fail(scope, `declaredFeatures[${i}].id must be a non-empty string`)\n }\n\n for (const [i, src] of (manifest.emitsFrom ?? []).entries()) {\n if (!nonEmptyString(src?.table)) fail(scope, `emitsFrom[${i}].table must be a non-empty string`)\n if (!nonEmptyString(src?.entityKey)) fail(scope, `emitsFrom[${i}].entityKey must be a non-empty string`)\n for (const action of src.actions ?? []) {\n if (!EVENT_ACTIONS.has(action)) fail(scope, `emitsFrom[${i}] has unknown action \"${action}\"`)\n }\n }\n\n const functionSlugs = new Set<string>()\n for (const [i, fn] of (manifest.functions ?? []).entries()) {\n if (!SLUG.test(fn?.slug ?? '')) fail(scope, `functions[${i}].slug must be kebab-case — it becomes the deployed function name`)\n if (functionSlugs.has(fn.slug)) fail(scope, `duplicate function slug \"${fn.slug}\"`)\n functionSlugs.add(fn.slug)\n if (typeof fn.verifyJwt !== 'boolean') fail(scope, `functions[${i}].verifyJwt must be a boolean`)\n if (!FUNCTION_INGRESS.has(fn.ingress)) fail(scope, `functions[${i}].ingress \"${fn.ingress}\" is not one of ${[...FUNCTION_INGRESS].join(', ')}`)\n // The ingress authenticates by signature, not by a caller JWT it does not have.\n if (fn.ingress === 'fayz' && fn.verifyJwt) fail(scope, `functions[${i}] is reached through the Fayz ingress, so verifyJwt must be false`)\n for (const secret of fn.secrets ?? []) {\n // A name, never a value — this is the shape that keeps a key out of git.\n if (!SECRET_NAME.test(secret)) fail(scope, `functions[${i}].secrets must name secrets (SCREAMING_SNAKE_CASE), never carry their values`)\n }\n }\n\n for (const [i, def] of (manifest.connectors ?? []).entries()) {\n // An unlisted category renders NO badge rather than a wrong one, so the\n // mistake is invisible in a screenshot. Caught here instead.\n if (def.category !== undefined && !isConnectorCategory(def.category)) {\n fail(\n scope,\n `connectors[${i}].category \"${def.category}\" is not a catalogue category — ` +\n `use one of ${CONNECTOR_CATEGORIES.join(', ')}, taken from the catalogue row with this connector's slug.`,\n )\n }\n for (const pattern of def.subscribesTo ?? []) {\n if (!nonEmptyString(pattern)) fail(scope, `connectors[${i}].subscribesTo must hold non-empty patterns`)\n // Only a trailing star is honoured; see eventKeyMatches.\n if (pattern.includes('*') && !pattern.endsWith('*')) {\n fail(scope, `connectors[${i}].subscribesTo \"${pattern}\" — \"*\" is only honoured at the end`)\n }\n }\n\n assertConnectorPermissions(scope, `connectors[${i}]`, def)\n // The request plane's two fields are required THERE and meaningless\n // elsewhere. Checked at the manifest so a connector cannot reach a buyer\n // with an undeclared budget — the failure would otherwise be a spinner.\n if ((def.planes ?? []).includes('request')) {\n try {\n requestPlaneSpec(def)\n } catch (error) {\n fail(scope, `connectors[${i}] ${error instanceof Error ? error.message : String(error)}`)\n }\n } else if (def.latencyBudgetMs !== undefined || def.onFailure !== undefined) {\n fail(\n scope,\n `connectors[${i}] declares latencyBudgetMs/onFailure but is not on the request plane — ` +\n `nothing enforces them, so they read as a guarantee that does not exist.`,\n )\n }\n // Authorization vs configuration. Both declarations end up on the same row,\n // and a key in both is a value with two owners: the connect form would write\n // it and the settings form would overwrite it.\n const fieldKeys = new Set((def.fields ?? []).map((f) => f.key))\n const settingKeys = new Set<string>()\n for (const [j, setting] of (def.settings ?? []).entries()) {\n const at = `connectors[${i}].settings[${j}]`\n if (!nonEmptyString(setting?.key)) fail(scope, `${at}.key must be a non-empty string`)\n if (!nonEmptyString(setting?.label)) fail(scope, `${at}.label must be a non-empty string`)\n if (!SETTING_TYPES.has(setting.type)) {\n fail(scope, `${at}.type \"${setting.type}\" is not one of ${[...SETTING_TYPES].join(', ')}`)\n }\n if (settingKeys.has(setting.key)) fail(scope, `${at} duplicates settings key \"${setting.key}\"`)\n settingKeys.add(setting.key)\n if (fieldKeys.has(setting.key)) {\n fail(\n scope,\n `${at}.key \"${setting.key}\" is also a credential field — a key either authorizes the ` +\n `connection (fields) or configures it (settings), never both.`,\n )\n }\n if (setting.type === 'select' || setting.type === 'multi-select') {\n if (!Array.isArray(setting.options) || setting.options.length === 0) {\n fail(scope, `${at} is a ${setting.type} and must declare options — that is what replaces a free-text box`)\n }\n for (const [k, option] of setting.options.entries()) {\n if (!nonEmptyString(option?.value)) fail(scope, `${at}.options[${k}].value must be a non-empty string`)\n if (!nonEmptyString(option?.label)) fail(scope, `${at}.options[${k}].label must be a non-empty string`)\n }\n }\n if (setting.pattern !== undefined) {\n if (setting.type !== 'text') fail(scope, `${at}.pattern only applies to a text setting`)\n try {\n new RegExp(setting.pattern)\n } catch {\n fail(scope, `${at}.pattern is not a valid regular expression`)\n }\n // A refusal with no sentence is a form that says no and not why.\n if (!nonEmptyString(setting.patternHint)) fail(scope, `${at} declares a pattern, so it must declare patternHint`)\n }\n }\n // Declared settings nobody can read or write are a screen that renders empty.\n if (settingKeys.size > 0) {\n if (typeof def.getSettings !== 'function') fail(scope, `connectors[${i}] declares settings but no getSettings()`)\n if (typeof def.saveSettings !== 'function') fail(scope, `connectors[${i}] declares settings but no saveSettings()`)\n }\n\n // \"Acionado em quais momentos\" — a moment on a plane the connector does not\n // have is a promise the code cannot keep.\n const planes = new Set(connectorPlanes(def))\n const momentKeys = new Set<string>()\n for (const [j, moment] of (def.invokedAt ?? []).entries()) {\n const at = `connectors[${i}].invokedAt[${j}]`\n if (!nonEmptyString(moment?.key)) fail(scope, `${at}.key must be a non-empty string`)\n if (!nonEmptyString(moment?.label)) fail(scope, `${at}.label must be a non-empty string`)\n if (momentKeys.has(moment.key)) fail(scope, `${at} duplicates key \"${moment.key}\"`)\n momentKeys.add(moment.key)\n const plane = invocationPlane(moment)\n if (!planes.has(plane)) {\n fail(scope, `${at} is declared on the ${plane} plane, which connectors[${i}].planes does not include`)\n }\n if (moment.trigger !== undefined) {\n if (plane !== 'sync') fail(scope, `${at}.trigger only applies to a sync moment`)\n if (!TRIGGERS.has(moment.trigger)) fail(scope, `${at} has unknown trigger \"${moment.trigger}\"`)\n }\n // A moment that reaches something the connector never asked for is the\n // screen answering \"quando ele age\" with access nobody consented to.\n const declared = new Set((def.permissions ?? []).map((p) => p.resource))\n for (const resource of moment.touches ?? []) {\n if (!declared.has(resource)) {\n fail(\n scope,\n `${at}.touches names \"${resource}\", which connectors[${i}].permissions does not declare — ` +\n `a call site cannot reach what the consent view never showed.`,\n )\n }\n }\n }\n\n for (const [j, auto] of (def.managedAutomations ?? []).entries()) {\n if (!nonEmptyString(auto?.eventKey)) fail(scope, `connectors[${i}].managedAutomations[${j}].eventKey must be a non-empty string`)\n if (!nonEmptyString(auto?.label)) fail(scope, `connectors[${i}].managedAutomations[${j}].label must be a non-empty string`)\n // The screen would promise a reaction the ingress never delivers.\n if (!connectorSubscribes(def, auto.eventKey)) {\n fail(scope, `connectors[${i}].managedAutomations[${j}] fires on \"${auto.eventKey}\", which no subscribesTo pattern covers`)\n }\n }\n }\n\n // A connector brings a ConnectorDefinition, not a pair of tables.\n for (const [i, mig] of (manifest.migrations ?? []).entries()) {\n for (const table of bespokeConnectorTables(mig?.sql)) {\n fail(\n scope,\n `migrations[${i}] (\"${mig?.id ?? '?'}\") creates public.${table} — a connector's own ` +\n `*_integrations / *_sync_log table. Store the connection in plg_connections / ` +\n `plg_sync_runs via createConnectionStore('<connector-id>'): two accounts are two ` +\n `rows separated by instance_key, and connector-specific counters go in stats.`,\n )\n }\n }\n\n // A plugin that contributes nothing mountable is almost always a mistake.\n // (Connector-only addon plugins contribute via `connectors` instead.)\n if (\n manifest.navigation.length === 0 &&\n manifest.routes.length === 0 &&\n (manifest.settings ?? []).length === 0 &&\n (manifest.connectors ?? []).length === 0\n ) {\n fail(scope, 'plugin contributes no navigation, routes, settings, or connectors — it would mount but do nothing')\n }\n}\n\n/**\n * What a connector says it needs — and the four ways that declaration can\n * contradict the ones that already existed.\n *\n * The feature this guards is a consent view. Its whole value is that the list it\n * shows is the list, so every way of ending up with two lists is refused here:\n *\n * 1. an action that does not exist for the resource kind (`listen` on a\n * record type, `write` on an event) — a word the reader would have to guess at;\n * 2. a `data` permission naming a resource the legacy `entities` never listed,\n * or an entity with no permission — the \"writes to an entity it never\n * listed\" case, in both directions;\n * 3. a `listen` permission the legacy `subscribesTo` does not name, or a\n * `subscribesTo` pattern no permission explains — the connector would be\n * delivered facts the consent view never showed, or shown facts the ingress\n * filters out;\n * 4. two permissions for the same resource — two rows, two reasons, and no\n * answer to which one the tenant agreed to.\n *\n * Rules 2 and 3 only bite when BOTH declarations are present. A connector built\n * against an older core declares only the legacy fields and is unaffected; a\n * connector written today declares only `permissions` and both are derived from\n * it. What is refused is saying both things and saying them differently.\n */\nfunction assertConnectorPermissions(\n scope: string,\n path: string,\n def: { permissions?: ConnectorPermission[]; entities?: string[]; subscribesTo?: string[] },\n): void {\n const permissions = def.permissions\n if (permissions === undefined) return\n if (!Array.isArray(permissions)) fail(scope, `${path}.permissions must be an array`)\n\n const seen = new Set<string>()\n for (const [j, permission] of permissions.entries()) {\n const at = `${path}.permissions[${j}]`\n if (permission?.kind !== 'data' && permission?.kind !== 'event') {\n fail(scope, `${at}.kind must be \"data\" or \"event\"`)\n }\n if (!nonEmptyString(permission.resource)) fail(scope, `${at}.resource must be a non-empty string`)\n // The reason is the only part a tenant can actually judge; a blank one turns\n // the screen back into the schema dump it exists to replace.\n if (!nonEmptyString(permission.reason)) {\n fail(scope, `${at} must declare a reason — the sentence the tenant judges before authorizing`)\n }\n if (!Array.isArray(permission.actions) || permission.actions.length === 0) {\n fail(scope, `${at}.actions must name at least one action — a resource with no access is not a permission`)\n }\n const legal = permissionActions(permission.kind)\n for (const action of permission.actions) {\n if (!legal.includes(action)) {\n fail(scope, `${at} asks for \"${action}\" on the ${permission.kind} resource \"${permission.resource}\", which only admits ${legal.join(', ')}`)\n }\n }\n if (isEventPermission(permission) && permission.resource.includes('*') && !permission.resource.endsWith('*')) {\n fail(scope, `${at}.resource \"${permission.resource}\" — \"*\" is only honoured at the end`)\n }\n const key = `${permission.kind}:${permission.resource}`\n if (seen.has(key)) fail(scope, `${at} repeats \"${key}\" — one resource, one row, one reason`)\n seen.add(key)\n }\n\n // (2) data permissions ↔ the legacy entities list.\n if (def.entities !== undefined) {\n const declared = new Set(connectorEntities({ permissions }))\n const legacy = new Set(def.entities)\n for (const entity of declared) {\n if (!legacy.has(entity)) {\n fail(\n scope,\n `${path}.permissions reaches \"${entity}\", which ${path}.entities does not list — ` +\n `the two describe the same access and must name the same set (drop entities; it is derived).`,\n )\n }\n }\n for (const entity of legacy) {\n if (!declared.has(entity)) {\n fail(\n scope,\n `${path}.entities lists \"${entity}\" with no permission saying what it does with it — ` +\n `a record type on the consent view with no read/write is a name, not a declaration.`,\n )\n }\n }\n }\n\n // (3) listen permissions ↔ the legacy subscribesTo list.\n if (def.subscribesTo !== undefined) {\n const declared = new Set(connectorSubscribesTo({ permissions }))\n const legacy = new Set(def.subscribesTo)\n for (const pattern of declared) {\n if (!legacy.has(pattern)) {\n fail(\n scope,\n `${path}.permissions listens to \"${pattern}\", which ${path}.subscribesTo does not — ` +\n `the ingress filters on that list, so the consent view would promise a fact never delivered.`,\n )\n }\n }\n for (const pattern of legacy) {\n if (!declared.has(pattern)) {\n fail(\n scope,\n `${path}.subscribesTo asks for \"${pattern}\" with no listen permission explaining it — ` +\n `the connector would receive a fact the tenant was never shown.`,\n )\n }\n }\n }\n}\n\n/**\n * `CREATE TABLE [IF NOT EXISTS] [schema.]name` where name ends in `_integrations`\n * or `_sync_log` — the pair four connectors each reinvented before\n * `plg_connections` / `plg_sync_runs` existed (FAY-1376). Neither generic table\n * matches, so a connector that stores its connection in them creates nothing.\n *\n * Deliberately duplicated in scripts/check-connector-tables.mjs, which scans the\n * .sql files themselves: that runs in the `contracts` CI job with no install and\n * no build, so it cannot import this. This half catches SQL declared inline on a\n * manifest, which no .sql walk would see. The two are held in agreement by one\n * case table, asserted from both sides — see\n * packages/core/test/integrations/connector-tables.test.ts.\n */\nconst BESPOKE_CONNECTOR_TABLE =\n /\\bcreate\\s+table\\s+(?:if\\s+not\\s+exists\\s+)?(?:[a-z0-9_]+\\s*\\.\\s*)?([a-z0-9_]*(?:_integrations|_sync_log))\\b/gi\n\n/** Table names a CREATE TABLE in this SQL would bring back. Empty = conformant. */\nexport function bespokeConnectorTables(sql: unknown): string[] {\n const text = typeof sql === 'string' ? sql.replace(/\"/g, '') : ''\n const found = new Set<string>()\n for (const m of text.matchAll(BESPOKE_CONNECTOR_TABLE)) found.add(m[1].toLowerCase())\n return [...found]\n}\n\nconst EVENT_ACTIONS = new Set(['created', 'updated', 'deleted'])\nconst FUNCTION_INGRESS = new Set(['fayz', 'none'])\nconst SLUG = /^[a-z0-9][a-z0-9-]*$/\nconst SECRET_NAME = /^[A-Z][A-Z0-9_]*$/\n\nconst SETTING_TYPES = new Set(['text', 'select', 'multi-select', 'toggle'])\nconst AUTH_KINDS = new Set(['oauth', 'api-key', 'mtls'])\nconst DIRECTIONS = new Set(['inbound', 'outbound', 'bidirectional'])\nconst TRIGGERS = new Set(['on-write', 'scheduled', 'manual', 'webhook'])\n\n/**\n * Assert an integration Connector descriptor is well-formed: identity present,\n * a known auth kind, and at least one capability with a valid direction +\n * trigger set. This is the contract a connector must satisfy BEFORE its\n * data-plane (edge function) exists — the TDD anchor for an integration.\n */\nexport function assertConnectorContract(connector: Connector): void {\n const scope = nonEmptyString(connector?.id) ? `connector:${connector.id}` : '<unknown connector>'\n for (const field of ['id', 'provider', 'pluginId'] as const) {\n if (!nonEmptyString(connector?.[field])) fail(scope, `connector.${field} must be a non-empty string`)\n }\n if (!AUTH_KINDS.has(connector.authKind)) fail(scope, `connector.authKind \"${connector.authKind}\" is not one of ${[...AUTH_KINDS].join(', ')}`)\n if (!Array.isArray(connector.capabilities) || connector.capabilities.length === 0) {\n fail(scope, 'connector.capabilities must list at least one capability')\n }\n for (const [i, cap] of connector.capabilities.entries()) {\n if (!nonEmptyString(cap?.entity)) fail(scope, `capabilities[${i}].entity must be a non-empty string`)\n if (!DIRECTIONS.has(cap.direction)) fail(scope, `capabilities[${i}].direction \"${cap.direction}\" is invalid`)\n if (!Array.isArray(cap.triggers) || cap.triggers.length === 0) fail(scope, `capabilities[${i}].triggers must be non-empty`)\n for (const trig of cap.triggers) {\n if (!TRIGGERS.has(trig)) fail(scope, `capabilities[${i}] has unknown trigger \"${trig}\"`)\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/testing.ts"],"names":[],"mappings":";;;AA0BO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC7C,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF;AAEA,SAAS,IAAA,CAAK,OAAe,GAAA,EAAoB;AAC/C,EAAA,MAAM,IAAI,mBAAA,CAAoB,CAAA,CAAA,EAAI,KAAK,CAAA,EAAA,EAAK,GAAG,CAAA,CAAE,CAAA;AACnD;AAEA,SAAS,eAAe,CAAA,EAAyB;AAC/C,EAAA,OAAO,OAAO,CAAA,KAAM,QAAA,IAAY,CAAA,CAAE,IAAA,GAAO,MAAA,GAAS,CAAA;AACpD;AAOO,SAAS,6BAA6B,QAAA,EAAgC;AAC3E,EAAA,MAAM,KAAK,QAAA,EAAU,EAAA;AACrB,EAAA,MAAM,KAAA,GAAQ,cAAA,CAAe,EAAE,CAAA,GAAI,EAAA,GAAK,kBAAA;AAExC,EAAA,KAAA,MAAW,SAAS,CAAC,IAAA,EAAM,MAAA,EAAQ,MAAA,EAAQ,SAAS,CAAA,EAAY;AAC9D,IAAA,IAAI,CAAC,cAAA,CAAe,QAAA,GAAW,KAAK,CAAC,GAAG,IAAA,CAAK,KAAA,EAAO,CAAA,SAAA,EAAY,KAAK,CAAA,2BAAA,CAA6B,CAAA;AAAA,EACpG;AAEA,EAAA,IAAI,CAAC,MAAM,OAAA,CAAQ,QAAA,CAAS,UAAU,CAAA,EAAG,IAAA,CAAK,OAAO,yEAAyE,CAAA;AAC9H,EAAA,IAAI,CAAC,MAAM,OAAA,CAAQ,QA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AI,CAAC,eAAe,GAAA,EAAK,MAAM,GAAG,IAAA,CAAK,KAAA,EAAO,CAAA,aAAA,EAAgB,CAAC,CAAA,mCAAA,CAAqC,CAAA;AACpG,IAAA,IAAI,CAAC,UAAA,CAAW,GAAA,CAAI,GAAA,CAAI,SAAS,CAAA,EAAG,IAAA,CAAK,KAAA,EAAO,CAAA,aAAA,EAAgB,CAAC,CAAA,aAAA,EAAgB,GAAA,CAAI,SAAS,CAAA,YAAA,CAAc,CAAA;AAC5G,IAAA,IAAI,CAAC,KAAA,CAAM,OAAA,CAAQ,GAAA,CAAI,QAAQ,CAAA,IAAK,GAAA,CAAI,QAAA,CAAS,MAAA,KAAW,CAAA,EAAG,IAAA,CAAK,KAAA,EAAO,CAAA,aAAA,EAAgB,CAAC,CAAA,4BAAA,CAA8B,CAAA;AAC1H,IAAA,KAAA,MAAW,IAAA,IAAQ,IAAI,QAAA,EAAU;AAC/B,MAAA,IAAI,CAAC,QAAA,CAAS,GAAA,CAAI,IAAI,CAAA,EAAG,IAAA,CAAK,KAAA,EAAO,CAAA,aAAA,EAAgB,CAAC,CAAA,uBAAA,EAA0B,IAAI,CAAA,CAAA,CAAG,CAAA;AAAA,IACzF;AAAA,EACF;AACF","file":"chunk-KJUD6JA5.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Plugin contract assertions — the integrity half of the deploy gate.\n// ---------------------------------------------------------------------------\n// Framework-agnostic runtime checks (no test-runner dependency) that any\n// plugin's *.test.ts calls to prove its manifest/connector conform to the\n// platform contract BEFORE it can ship. A plugin that fails these would break\n// the host app at mount time (missing route component, duplicate ids, malformed\n// settings tab). Pair with a capability test (does the plugin do its job?) — see\n// docs/plugins/PLUGIN-PATTERNS.md → capability anatomy. These throw on the first violation.\nimport type { PluginManifest } from './types/plugins'\nimport type { Connector } from './integrations'\nimport {\n CONNECTOR_CATEGORIES,\n connectorEntities,\n connectorPlanes,\n connectorSubscribes,\n connectorSubscribesTo,\n grants,\n invocationPlane,\n isConnectorCategory,\n isEventPermission,\n permissionActions,\n requestPlaneSpec,\n} from './integrations'\nimport type { ConnectorPermission } from './integrations'\n\nexport class PluginContractError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'PluginContractError'\n }\n}\n\nfunction fail(scope: string, msg: string): never {\n throw new PluginContractError(`[${scope}] ${msg}`)\n}\n\nfunction nonEmptyString(v: unknown): v is string {\n return typeof v === 'string' && v.trim().length > 0\n}\n\n/**\n * Assert a PluginManifest is structurally sound enough to mount safely.\n * Checks identity, navigation/route wiring, settings tabs, declared features,\n * and id uniqueness. Throws PluginContractError on the first problem.\n */\nexport function assertPluginManifestContract(manifest: PluginManifest): void {\n const id = manifest?.id\n const scope = nonEmptyString(id) ? id : '<unknown plugin>'\n\n for (const field of ['id', 'name', 'icon', 'version'] as const) {\n if (!nonEmptyString(manifest?.[field])) fail(scope, `manifest.${field} must be a non-empty string`)\n }\n\n if (!Array.isArray(manifest.navigation)) fail(scope, 'manifest.navigation must be an array (use [] for settings-only plugins)')\n if (!Array.isArray(manifest.routes)) fail(scope, 'manifest.routes must be an array (use [] for settings-only plugins)')\n\n // Every nav entry must point at a route; every route needs a path + component.\n for (const [i, nav] of manifest.navigation.entries()) {\n if (!nonEmptyString((nav as any)?.route)) fail(scope, `navigation[${i}].route must be a non-empty string`)\n }\n const routePaths = new Set<string>()\n for (const [i, route] of manifest.routes.entries()) {\n if (!nonEmptyString((route as any)?.path)) fail(scope, `routes[${i}].path must be a non-empty string`)\n if (typeof (route as any)?.component !== 'function') fail(scope, `routes[${i}].component must be a component`)\n if (routePaths.has((route as any).path)) fail(scope, `duplicate route path \"${(route as any).path}\"`)\n routePaths.add((route as any).path)\n }\n // A nav entry that links to a route the plugin doesn't declare is dead UI.\n for (const [i, nav] of manifest.navigation.entries()) {\n const r = (nav as any).route\n if (routePaths.size > 0 && !routePaths.has(r)) {\n fail(scope, `navigation[${i}].route \"${r}\" has no matching route in manifest.routes`)\n }\n }\n\n // Settings tabs (the only UI surface integrations need) must be renderable.\n const settingIds = new Set<string>()\n for (const [i, tab] of (manifest.settings ?? []).entries()) {\n if (!nonEmptyString((tab as any)?.id)) fail(scope, `settings[${i}].id must be a non-empty string`)\n if (!nonEmptyString((tab as any)?.label)) fail(scope, `settings[${i}].label must be a non-empty string`)\n if (typeof (tab as any)?.component !== 'function') fail(scope, `settings[${i}].component must be a component`)\n if (settingIds.has((tab as any).id)) fail(scope, `duplicate settings tab id \"${(tab as any).id}\"`)\n settingIds.add((tab as any).id)\n }\n\n for (const [i, feat] of (manifest.declaredFeatures ?? []).entries()) {\n if (!nonEmptyString((feat as any)?.id)) fail(scope, `declaredFeatures[${i}].id must be a non-empty string`)\n }\n\n for (const [i, src] of (manifest.emitsFrom ?? []).entries()) {\n if (!nonEmptyString(src?.table)) fail(scope, `emitsFrom[${i}].table must be a non-empty string`)\n if (!nonEmptyString(src?.entityKey)) fail(scope, `emitsFrom[${i}].entityKey must be a non-empty string`)\n for (const action of src.actions ?? []) {\n if (!EVENT_ACTIONS.has(action)) fail(scope, `emitsFrom[${i}] has unknown action \"${action}\"`)\n }\n }\n\n const functionSlugs = new Set<string>()\n for (const [i, fn] of (manifest.functions ?? []).entries()) {\n if (!SLUG.test(fn?.slug ?? '')) fail(scope, `functions[${i}].slug must be kebab-case — it becomes the deployed function name`)\n if (functionSlugs.has(fn.slug)) fail(scope, `duplicate function slug \"${fn.slug}\"`)\n functionSlugs.add(fn.slug)\n if (typeof fn.verifyJwt !== 'boolean') fail(scope, `functions[${i}].verifyJwt must be a boolean`)\n if (!FUNCTION_INGRESS.has(fn.ingress)) fail(scope, `functions[${i}].ingress \"${fn.ingress}\" is not one of ${[...FUNCTION_INGRESS].join(', ')}`)\n // The ingress authenticates by signature, not by a caller JWT it does not have.\n if (fn.ingress === 'fayz' && fn.verifyJwt) fail(scope, `functions[${i}] is reached through the Fayz ingress, so verifyJwt must be false`)\n for (const secret of fn.secrets ?? []) {\n // A name, never a value — this is the shape that keeps a key out of git.\n if (!SECRET_NAME.test(secret)) fail(scope, `functions[${i}].secrets must name secrets (SCREAMING_SNAKE_CASE), never carry their values`)\n }\n }\n\n for (const [i, def] of (manifest.connectors ?? []).entries()) {\n // An unlisted category renders NO badge rather than a wrong one, so the\n // mistake is invisible in a screenshot. Caught here instead.\n if (def.category !== undefined && !isConnectorCategory(def.category)) {\n fail(\n scope,\n `connectors[${i}].category \"${def.category}\" is not a catalogue category — ` +\n `use one of ${CONNECTOR_CATEGORIES.join(', ')}, taken from the catalogue row with this connector's slug.`,\n )\n }\n for (const pattern of def.subscribesTo ?? []) {\n if (!nonEmptyString(pattern)) fail(scope, `connectors[${i}].subscribesTo must hold non-empty patterns`)\n // Only a trailing star is honoured; see eventKeyMatches.\n if (pattern.includes('*') && !pattern.endsWith('*')) {\n fail(scope, `connectors[${i}].subscribesTo \"${pattern}\" — \"*\" is only honoured at the end`)\n }\n }\n\n assertConnectorPermissions(scope, `connectors[${i}]`, def)\n // The request plane's two fields are required THERE and meaningless\n // elsewhere. Checked at the manifest so a connector cannot reach a buyer\n // with an undeclared budget — the failure would otherwise be a spinner.\n if ((def.planes ?? []).includes('request')) {\n try {\n requestPlaneSpec(def)\n } catch (error) {\n fail(scope, `connectors[${i}] ${error instanceof Error ? error.message : String(error)}`)\n }\n } else if (def.latencyBudgetMs !== undefined || def.onFailure !== undefined) {\n fail(\n scope,\n `connectors[${i}] declares latencyBudgetMs/onFailure but is not on the request plane — ` +\n `nothing enforces them, so they read as a guarantee that does not exist.`,\n )\n }\n // Authorization vs configuration. Both declarations end up on the same row,\n // and a key in both is a value with two owners: the connect form would write\n // it and the settings form would overwrite it.\n const fieldKeys = new Set((def.fields ?? []).map((f) => f.key))\n const settingKeys = new Set<string>()\n for (const [j, setting] of (def.settings ?? []).entries()) {\n const at = `connectors[${i}].settings[${j}]`\n if (!nonEmptyString(setting?.key)) fail(scope, `${at}.key must be a non-empty string`)\n if (!nonEmptyString(setting?.label)) fail(scope, `${at}.label must be a non-empty string`)\n if (!SETTING_TYPES.has(setting.type)) {\n fail(scope, `${at}.type \"${setting.type}\" is not one of ${[...SETTING_TYPES].join(', ')}`)\n }\n if (settingKeys.has(setting.key)) fail(scope, `${at} duplicates settings key \"${setting.key}\"`)\n settingKeys.add(setting.key)\n if (fieldKeys.has(setting.key)) {\n fail(\n scope,\n `${at}.key \"${setting.key}\" is also a credential field — a key either authorizes the ` +\n `connection (fields) or configures it (settings), never both.`,\n )\n }\n if (setting.type === 'select' || setting.type === 'multi-select') {\n if (!Array.isArray(setting.options) || setting.options.length === 0) {\n fail(scope, `${at} is a ${setting.type} and must declare options — that is what replaces a free-text box`)\n }\n for (const [k, option] of setting.options.entries()) {\n if (!nonEmptyString(option?.value)) fail(scope, `${at}.options[${k}].value must be a non-empty string`)\n if (!nonEmptyString(option?.label)) fail(scope, `${at}.options[${k}].label must be a non-empty string`)\n }\n }\n if (setting.pattern !== undefined) {\n if (setting.type !== 'text') fail(scope, `${at}.pattern only applies to a text setting`)\n try {\n new RegExp(setting.pattern)\n } catch {\n fail(scope, `${at}.pattern is not a valid regular expression`)\n }\n // A refusal with no sentence is a form that says no and not why.\n if (!nonEmptyString(setting.patternHint)) fail(scope, `${at} declares a pattern, so it must declare patternHint`)\n }\n }\n // Declared settings nobody can read or write are a screen that renders empty.\n if (settingKeys.size > 0) {\n if (typeof def.getSettings !== 'function') fail(scope, `connectors[${i}] declares settings but no getSettings()`)\n if (typeof def.saveSettings !== 'function') fail(scope, `connectors[${i}] declares settings but no saveSettings()`)\n }\n\n // \"Acionado em quais momentos\" — a moment on a plane the connector does not\n // have is a promise the code cannot keep.\n const planes = new Set(connectorPlanes(def))\n const momentKeys = new Set<string>()\n for (const [j, moment] of (def.invokedAt ?? []).entries()) {\n const at = `connectors[${i}].invokedAt[${j}]`\n if (!nonEmptyString(moment?.key)) fail(scope, `${at}.key must be a non-empty string`)\n if (!nonEmptyString(moment?.label)) fail(scope, `${at}.label must be a non-empty string`)\n if (momentKeys.has(moment.key)) fail(scope, `${at} duplicates key \"${moment.key}\"`)\n momentKeys.add(moment.key)\n const plane = invocationPlane(moment)\n if (!planes.has(plane)) {\n fail(scope, `${at} is declared on the ${plane} plane, which connectors[${i}].planes does not include`)\n }\n if (moment.trigger !== undefined) {\n if (plane !== 'sync') fail(scope, `${at}.trigger only applies to a sync moment`)\n if (!TRIGGERS.has(moment.trigger)) fail(scope, `${at} has unknown trigger \"${moment.trigger}\"`)\n }\n // A moment that reaches something the connector never asked for is the\n // screen answering \"quando ele age\" with access nobody consented to.\n const declared = new Set((def.permissions ?? []).map((p) => p.resource))\n for (const resource of moment.touches ?? []) {\n if (!declared.has(resource)) {\n fail(\n scope,\n `${at}.touches names \"${resource}\", which connectors[${i}].permissions does not declare — ` +\n `a call site cannot reach what the consent view never showed.`,\n )\n }\n }\n }\n\n for (const [j, auto] of (def.managedAutomations ?? []).entries()) {\n if (!nonEmptyString(auto?.eventKey)) fail(scope, `connectors[${i}].managedAutomations[${j}].eventKey must be a non-empty string`)\n if (!nonEmptyString(auto?.label)) fail(scope, `connectors[${i}].managedAutomations[${j}].label must be a non-empty string`)\n // The screen would promise a reaction the ingress never delivers.\n if (!connectorSubscribes(def, auto.eventKey)) {\n fail(scope, `connectors[${i}].managedAutomations[${j}] fires on \"${auto.eventKey}\", which no subscribesTo pattern covers`)\n }\n }\n }\n\n // A connector brings a ConnectorDefinition, not a pair of tables.\n for (const [i, mig] of (manifest.migrations ?? []).entries()) {\n for (const table of bespokeConnectorTables(mig?.sql)) {\n fail(\n scope,\n `migrations[${i}] (\"${mig?.id ?? '?'}\") creates public.${table} — a connector's own ` +\n `*_integrations / *_sync_log table. Store the connection in plg_connections / ` +\n `plg_sync_runs via createConnectionStore('<connector-id>'): two accounts are two ` +\n `rows separated by instance_key, and connector-specific counters go in stats.`,\n )\n }\n }\n\n // A plugin that contributes nothing mountable is almost always a mistake.\n // (Connector-only addon plugins contribute via `connectors` instead.)\n if (\n manifest.navigation.length === 0 &&\n manifest.routes.length === 0 &&\n (manifest.settings ?? []).length === 0 &&\n (manifest.connectors ?? []).length === 0\n ) {\n fail(scope, 'plugin contributes no navigation, routes, settings, or connectors — it would mount but do nothing')\n }\n}\n\n/**\n * What a connector says it needs — and the four ways that declaration can\n * contradict the ones that already existed.\n *\n * The feature this guards is a consent view. Its whole value is that the list it\n * shows is the list, so every way of ending up with two lists is refused here:\n *\n * 1. an action that does not exist for the resource kind (`listen` on a\n * record type, `write` on an event) — a word the reader would have to guess at;\n * 2. a `data` permission naming a resource the legacy `entities` never listed,\n * or an entity with no permission — the \"writes to an entity it never\n * listed\" case, in both directions;\n * 3. a `listen` permission the legacy `subscribesTo` does not name, or a\n * `subscribesTo` pattern no permission explains — the connector would be\n * delivered facts the consent view never showed, or shown facts the ingress\n * filters out;\n * 4. two permissions for the same resource — two rows, two reasons, and no\n * answer to which one the tenant agreed to.\n *\n * Rules 2 and 3 only bite when BOTH declarations are present. A connector built\n * against an older core declares only the legacy fields and is unaffected; a\n * connector written today declares only `permissions` and both are derived from\n * it. What is refused is saying both things and saying them differently.\n */\nfunction assertConnectorPermissions(\n scope: string,\n path: string,\n def: { permissions?: ConnectorPermission[]; entities?: string[]; subscribesTo?: string[] },\n): void {\n const permissions = def.permissions\n if (permissions === undefined) return\n if (!Array.isArray(permissions)) fail(scope, `${path}.permissions must be an array`)\n\n const seen = new Set<string>()\n for (const [j, permission] of permissions.entries()) {\n const at = `${path}.permissions[${j}]`\n if (permission?.kind !== 'data' && permission?.kind !== 'event') {\n fail(scope, `${at}.kind must be \"data\" or \"event\"`)\n }\n if (!nonEmptyString(permission.resource)) fail(scope, `${at}.resource must be a non-empty string`)\n // The reason is the only part a tenant can actually judge; a blank one turns\n // the screen back into the schema dump it exists to replace.\n if (!nonEmptyString(permission.reason)) {\n fail(scope, `${at} must declare a reason — the sentence the tenant judges before authorizing`)\n }\n if (!Array.isArray(permission.actions) || permission.actions.length === 0) {\n fail(scope, `${at}.actions must name at least one action — a resource with no access is not a permission`)\n }\n const legal = permissionActions(permission.kind)\n for (const action of permission.actions) {\n if (!legal.includes(action)) {\n fail(scope, `${at} asks for \"${action}\" on the ${permission.kind} resource \"${permission.resource}\", which only admits ${legal.join(', ')}`)\n }\n }\n if (isEventPermission(permission) && permission.resource.includes('*') && !permission.resource.endsWith('*')) {\n fail(scope, `${at}.resource \"${permission.resource}\" — \"*\" is only honoured at the end`)\n }\n const key = `${permission.kind}:${permission.resource}`\n if (seen.has(key)) fail(scope, `${at} repeats \"${key}\" — one resource, one row, one reason`)\n seen.add(key)\n }\n\n // (2) data permissions ↔ the legacy entities list.\n if (def.entities !== undefined) {\n const declared = new Set(connectorEntities({ permissions }))\n const legacy = new Set(def.entities)\n for (const entity of declared) {\n if (!legacy.has(entity)) {\n fail(\n scope,\n `${path}.permissions reaches \"${entity}\", which ${path}.entities does not list — ` +\n `the two describe the same access and must name the same set (drop entities; it is derived).`,\n )\n }\n }\n for (const entity of legacy) {\n if (!declared.has(entity)) {\n fail(\n scope,\n `${path}.entities lists \"${entity}\" with no permission saying what it does with it — ` +\n `a record type on the consent view with no read/write is a name, not a declaration.`,\n )\n }\n }\n }\n\n // (3) listen permissions ↔ the legacy subscribesTo list.\n if (def.subscribesTo !== undefined) {\n const declared = new Set(connectorSubscribesTo({ permissions }))\n const legacy = new Set(def.subscribesTo)\n for (const pattern of declared) {\n if (!legacy.has(pattern)) {\n fail(\n scope,\n `${path}.permissions listens to \"${pattern}\", which ${path}.subscribesTo does not — ` +\n `the ingress filters on that list, so the consent view would promise a fact never delivered.`,\n )\n }\n }\n for (const pattern of legacy) {\n if (!declared.has(pattern)) {\n fail(\n scope,\n `${path}.subscribesTo asks for \"${pattern}\" with no listen permission explaining it — ` +\n `the connector would receive a fact the tenant was never shown.`,\n )\n }\n }\n }\n}\n\n/**\n * `CREATE TABLE [IF NOT EXISTS] [schema.]name` where name ends in `_integrations`\n * or `_sync_log` — the pair four connectors each reinvented before\n * `plg_connections` / `plg_sync_runs` existed (FAY-1376). Neither generic table\n * matches, so a connector that stores its connection in them creates nothing.\n *\n * Deliberately duplicated in scripts/check-connector-tables.mjs, which scans the\n * .sql files themselves: that runs in the `contracts` CI job with no install and\n * no build, so it cannot import this. This half catches SQL declared inline on a\n * manifest, which no .sql walk would see. The two are held in agreement by one\n * case table, asserted from both sides — see\n * packages/core/test/integrations/connector-tables.test.ts.\n */\nconst BESPOKE_CONNECTOR_TABLE =\n /\\bcreate\\s+table\\s+(?:if\\s+not\\s+exists\\s+)?(?:[a-z0-9_]+\\s*\\.\\s*)?([a-z0-9_]*(?:_integrations|_sync_log))\\b/gi\n\n/** Table names a CREATE TABLE in this SQL would bring back. Empty = conformant. */\nexport function bespokeConnectorTables(sql: unknown): string[] {\n const text = typeof sql === 'string' ? sql.replace(/\"/g, '') : ''\n const found = new Set<string>()\n for (const m of text.matchAll(BESPOKE_CONNECTOR_TABLE)) found.add(m[1].toLowerCase())\n return [...found]\n}\n\nconst EVENT_ACTIONS = new Set(['created', 'updated', 'deleted'])\nconst FUNCTION_INGRESS = new Set(['fayz', 'none'])\nconst SLUG = /^[a-z0-9][a-z0-9-]*$/\nconst SECRET_NAME = /^[A-Z][A-Z0-9_]*$/\n\nconst SETTING_TYPES = new Set(['text', 'select', 'multi-select', 'toggle'])\nconst AUTH_KINDS = new Set(['oauth', 'api-key', 'mtls'])\nconst DIRECTIONS = new Set(['inbound', 'outbound', 'bidirectional'])\nconst TRIGGERS = new Set(['on-write', 'scheduled', 'manual', 'webhook'])\n\n/**\n * Assert an integration Connector descriptor is well-formed: identity present,\n * a known auth kind, and at least one capability with a valid direction +\n * trigger set. This is the contract a connector must satisfy BEFORE its\n * data-plane (edge function) exists — the TDD anchor for an integration.\n */\nexport function assertConnectorContract(connector: Connector): void {\n const scope = nonEmptyString(connector?.id) ? `connector:${connector.id}` : '<unknown connector>'\n for (const field of ['id', 'provider', 'pluginId'] as const) {\n if (!nonEmptyString(connector?.[field])) fail(scope, `connector.${field} must be a non-empty string`)\n }\n if (!AUTH_KINDS.has(connector.authKind)) fail(scope, `connector.authKind \"${connector.authKind}\" is not one of ${[...AUTH_KINDS].join(', ')}`)\n if (!Array.isArray(connector.capabilities) || connector.capabilities.length === 0) {\n fail(scope, 'connector.capabilities must list at least one capability')\n }\n for (const [i, cap] of connector.capabilities.entries()) {\n if (!nonEmptyString(cap?.entity)) fail(scope, `capabilities[${i}].entity must be a non-empty string`)\n if (!DIRECTIONS.has(cap.direction)) fail(scope, `capabilities[${i}].direction \"${cap.direction}\" is invalid`)\n if (!Array.isArray(cap.triggers) || cap.triggers.length === 0) fail(scope, `capabilities[${i}].triggers must be non-empty`)\n for (const trig of cap.triggers) {\n if (!TRIGGERS.has(trig)) fail(scope, `capabilities[${i}] has unknown trigger \"${trig}\"`)\n }\n }\n}\n"]}
|