@storystick/types 0.1.0-rc.3 → 0.1.0-rc.5
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/PUBLIC-API.md +8 -2
- package/README.md +5 -0
- package/dist/editorial-target.d.ts +46 -0
- package/dist/editorial-target.js +74 -0
- package/dist/internal/content-plane-work.d.ts +40 -0
- package/dist/internal/content-plane-work.js +35 -0
- package/dist/internal/workspace-preview-address.d.ts +9 -0
- package/dist/internal/workspace-preview-address.js +18 -0
- package/dist/live-query-overlay.d.ts +1 -1
- package/dist/live-query-overlay.js +3 -1
- package/dist/read-progress.d.ts +3 -0
- package/dist/read-progress.js +9 -0
- package/dist/schema-change.d.ts +30 -1
- package/dist/schema-change.js +27 -0
- package/dist/usage-delivery.d.ts +72 -0
- package/dist/usage-delivery.js +93 -0
- package/dist/usage.d.ts +192 -0
- package/dist/usage.js +235 -0
- package/package.json +25 -1
package/PUBLIC-API.md
CHANGED
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
# @storystick/types API contract
|
|
2
2
|
|
|
3
|
-
Install this candidate explicitly with `@storystick/types@0.1.0-rc.
|
|
3
|
+
Install this candidate explicitly with `@storystick/types@0.1.0-rc.5` after registry bootstrap and publication. This repository alone does not make the candidate or beta channel available on npm.
|
|
4
4
|
|
|
5
|
-
Version 0.1.0-rc.
|
|
5
|
+
Version 0.1.0-rc.5, cohort `sdk-0.2.0-rc.8`. ESM distribution; no CommonJS or universal Edge compatibility is promised.
|
|
6
6
|
|
|
7
7
|
This package supports the integration facades; installing it directly is an advanced use. Reserved contracts are required between SDK packages and must be upgraded with the same cohort. Their public export paths do not promise independent stability.
|
|
8
8
|
|
|
9
9
|
| Entry | Status |
|
|
10
10
|
| --- | --- |
|
|
11
|
+
| `./editorial-target` | Reserved SDK contract |
|
|
12
|
+
| `./read-progress` | Reserved SDK contract |
|
|
13
|
+
| `./usage` | Reserved SDK contract |
|
|
14
|
+
| `./internal/content-plane-work` | Reserved SDK contract |
|
|
15
|
+
| `./internal/workspace-preview-address` | Reserved SDK contract |
|
|
11
16
|
| `./internal/private-file-session` | Reserved SDK contract |
|
|
12
17
|
| `./http-failure` | Supported beta entry |
|
|
13
18
|
| `./publication` | Supported beta entry |
|
|
@@ -46,6 +51,7 @@ This package supports the integration facades; installing it directly is an adva
|
|
|
46
51
|
| `./internal/richtext-block-keys` | Reserved SDK contract |
|
|
47
52
|
| `./internal/richtext-embeds` | Reserved SDK contract |
|
|
48
53
|
| `./public-endpoints` | Supported beta entry |
|
|
54
|
+
| `./internal/usage-delivery` | Reserved SDK contract |
|
|
49
55
|
|
|
50
56
|
Supported consumer Node versions: `^22.13.0 || ^24.19.0`. The release build toolchain remains Node 24.19.0 and pnpm 9.15.9. Next uses App Router 15.5.28, Sharp 0.35.5 and React/React DOM 19.2.8; Astro uses 7.4.4 with the Node adapter 11.1.9. Browser delivery is verified by bundling; hosted Preview activation and cross-browser behavior require the staging manual check. Source/CLI are Node tools, server entries belong on the server, and browser entries must never receive a server API key.
|
|
51
57
|
|
package/README.md
CHANGED
|
@@ -14,6 +14,11 @@ in an incomplete draft and are enforced by the publication gate.
|
|
|
14
14
|
|
|
15
15
|
Licensed under [FSL-1.1-MIT](./LICENSE).
|
|
16
16
|
|
|
17
|
+
Local development also uses `./usage` and `./internal/usage-delivery` for exact
|
|
18
|
+
usage quantities, attribution and private delivery proofs. These are reserved
|
|
19
|
+
platform contracts in the workspace, not entries in the published rc.4 cohort.
|
|
20
|
+
They do not authorize billing or expose a customer-writable usage API.
|
|
21
|
+
|
|
17
22
|
## Candidate distribution contract
|
|
18
23
|
|
|
19
24
|
See [PUBLIC-API.md](./PUBLIC-API.md) for supported entries, reserved SDK contracts,
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { PreviewPerspective } from "./preview-query-targeting.js";
|
|
2
|
+
/** A durable content address, independent of comments, presence and agent chats. */
|
|
3
|
+
export type EditorialScope = Exclude<PreviewPerspective, {
|
|
4
|
+
kind: "published";
|
|
5
|
+
}> | {
|
|
6
|
+
kind: "published";
|
|
7
|
+
snapshotId: string;
|
|
8
|
+
};
|
|
9
|
+
export type EditorialPath = Array<string | {
|
|
10
|
+
_key: string;
|
|
11
|
+
}>;
|
|
12
|
+
export type EditorialAnchor = {
|
|
13
|
+
kind: "document";
|
|
14
|
+
} | {
|
|
15
|
+
kind: "field";
|
|
16
|
+
path: EditorialPath;
|
|
17
|
+
} | {
|
|
18
|
+
kind: "block";
|
|
19
|
+
path: EditorialPath;
|
|
20
|
+
blockKey: string;
|
|
21
|
+
};
|
|
22
|
+
export interface EditorialTarget {
|
|
23
|
+
documentId: string;
|
|
24
|
+
locale: string;
|
|
25
|
+
scope: EditorialScope;
|
|
26
|
+
anchor: EditorialAnchor;
|
|
27
|
+
}
|
|
28
|
+
export interface EditorialObservation {
|
|
29
|
+
quote?: string;
|
|
30
|
+
label?: string;
|
|
31
|
+
backingId?: string;
|
|
32
|
+
schemaGenerationId?: string;
|
|
33
|
+
schemaVersion?: string;
|
|
34
|
+
sourceLocale?: string;
|
|
35
|
+
}
|
|
36
|
+
export declare function editorialContextKey(target: Pick<EditorialTarget, "locale" | "scope">): string;
|
|
37
|
+
export declare function editorialAnchorKey(anchor: EditorialAnchor): string;
|
|
38
|
+
/** Explicit identity only: never clamp a deleted key onto its neighbour. */
|
|
39
|
+
export declare function readEditorialPath(fields: unknown, path: EditorialPath): unknown;
|
|
40
|
+
export declare function isEditorialPath(path: EditorialPath): boolean;
|
|
41
|
+
/** Turn an already anchored navigation address into storage identity. A bare
|
|
42
|
+
* array index is deliberately insufficient, including on external previews. */
|
|
43
|
+
export declare function editorialPathFromNavigation(path: string, anchors?: readonly {
|
|
44
|
+
pathPrefix: string;
|
|
45
|
+
key: string;
|
|
46
|
+
}[]): EditorialPath | null;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
export function editorialContextKey(target) {
|
|
2
|
+
const scope = target.scope;
|
|
3
|
+
return JSON.stringify([
|
|
4
|
+
target.locale,
|
|
5
|
+
scope.kind,
|
|
6
|
+
scope.kind === "release"
|
|
7
|
+
? scope.releaseId
|
|
8
|
+
: scope.kind === "variant"
|
|
9
|
+
? scope.variantId
|
|
10
|
+
: scope.kind === "published"
|
|
11
|
+
? scope.snapshotId
|
|
12
|
+
: null,
|
|
13
|
+
]);
|
|
14
|
+
}
|
|
15
|
+
export function editorialAnchorKey(anchor) {
|
|
16
|
+
return JSON.stringify(anchor.kind === "document"
|
|
17
|
+
? ["document"]
|
|
18
|
+
: [
|
|
19
|
+
anchor.kind,
|
|
20
|
+
anchor.path.map((segment) => typeof segment === "string" ? segment : { _key: segment._key }),
|
|
21
|
+
...(anchor.kind === "block" ? [anchor.blockKey] : []),
|
|
22
|
+
]);
|
|
23
|
+
}
|
|
24
|
+
/** Explicit identity only: never clamp a deleted key onto its neighbour. */
|
|
25
|
+
export function readEditorialPath(fields, path) {
|
|
26
|
+
let value = fields;
|
|
27
|
+
for (const segment of path) {
|
|
28
|
+
if (typeof segment === "string") {
|
|
29
|
+
if (!value ||
|
|
30
|
+
typeof value !== "object" ||
|
|
31
|
+
Array.isArray(value) ||
|
|
32
|
+
!Object.hasOwn(value, segment))
|
|
33
|
+
return undefined;
|
|
34
|
+
value = value[segment];
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
if (!Array.isArray(value))
|
|
38
|
+
return undefined;
|
|
39
|
+
value = value.find((item) => item && typeof item === "object" && item._key === segment._key);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
export function isEditorialPath(path) {
|
|
45
|
+
return (path.length > 0 &&
|
|
46
|
+
path.length <= 32 &&
|
|
47
|
+
path.every((part, index) => typeof part === "string"
|
|
48
|
+
? /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(part) &&
|
|
49
|
+
!["__proto__", "constructor", "prototype"].includes(part)
|
|
50
|
+
: index > 0 && /^[A-Za-z0-9_-]{1,128}$/.test(part._key)));
|
|
51
|
+
}
|
|
52
|
+
/** Turn an already anchored navigation address into storage identity. A bare
|
|
53
|
+
* array index is deliberately insufficient, including on external previews. */
|
|
54
|
+
export function editorialPathFromNavigation(path, anchors = []) {
|
|
55
|
+
const tokens = path.match(/[A-Za-z_][A-Za-z0-9_]*|\[\d+\]/g);
|
|
56
|
+
if (!tokens || tokens.join(".").replace(/\.\[/g, "[") !== path)
|
|
57
|
+
return null;
|
|
58
|
+
const result = [];
|
|
59
|
+
let prefix = "";
|
|
60
|
+
for (const token of tokens) {
|
|
61
|
+
if (token.startsWith("[")) {
|
|
62
|
+
const anchor = anchors.find((a) => a.pathPrefix === prefix);
|
|
63
|
+
if (!anchor)
|
|
64
|
+
return null;
|
|
65
|
+
result.push({ _key: anchor.key });
|
|
66
|
+
prefix += token;
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
result.push(token);
|
|
70
|
+
prefix += prefix ? `.${token}` : token;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return isEditorialPath(result) ? result : null;
|
|
74
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export interface ContentPlaneProjectionProof {
|
|
2
|
+
storageProjectId: string;
|
|
3
|
+
seq: number;
|
|
4
|
+
sourceIdentity: string;
|
|
5
|
+
lensHash: string;
|
|
6
|
+
projectionHash: string;
|
|
7
|
+
}
|
|
8
|
+
/** Server-only control state. Source/ACK identities are authoritative; a signal
|
|
9
|
+
* is neither a delivery receipt nor a physical integrity check. No wall clock. */
|
|
10
|
+
export type ContentPlaneWork = {
|
|
11
|
+
version: 1;
|
|
12
|
+
projectId: string;
|
|
13
|
+
headSeq: number | null;
|
|
14
|
+
ackedThroughSeq: number | null;
|
|
15
|
+
viewGeneration: number | null;
|
|
16
|
+
projections?: ContentPlaneProjectionProof[];
|
|
17
|
+
} & ({
|
|
18
|
+
kind: 'caughtUp';
|
|
19
|
+
} | {
|
|
20
|
+
kind: 'pending';
|
|
21
|
+
reason: 'outbox' | 'generation' | 'view';
|
|
22
|
+
} | {
|
|
23
|
+
kind: 'retryAt';
|
|
24
|
+
seq: number;
|
|
25
|
+
nextAttemptAt: number;
|
|
26
|
+
} | {
|
|
27
|
+
kind: 'blocked';
|
|
28
|
+
seq: number;
|
|
29
|
+
} | {
|
|
30
|
+
kind: 'unknown';
|
|
31
|
+
reason: 'unqualified' | 'inconsistent' | 'capacity';
|
|
32
|
+
});
|
|
33
|
+
export interface ContentPlaneProjectTarget {
|
|
34
|
+
projectId: string;
|
|
35
|
+
shortId: string;
|
|
36
|
+
lifecycle: 'active' | 'archived' | 'purgePending' | 'purgeStarted';
|
|
37
|
+
}
|
|
38
|
+
export declare function contentPlaneWorkNeedsReconciliation(work: ContentPlaneWork): boolean;
|
|
39
|
+
/** Network responses must not turn malformed/missing authority into caughtUp. */
|
|
40
|
+
export declare function isContentPlaneWork(value: unknown): value is ContentPlaneWork;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { logicalProjectIdFromSchemaChangeStorage } from '../schema-change.js';
|
|
2
|
+
export function contentPlaneWorkNeedsReconciliation(work) {
|
|
3
|
+
return work.kind === 'unknown' || work.kind === 'pending' && work.reason !== 'outbox';
|
|
4
|
+
}
|
|
5
|
+
/** Network responses must not turn malformed/missing authority into caughtUp. */
|
|
6
|
+
export function isContentPlaneWork(value) {
|
|
7
|
+
if (!value || typeof value !== 'object')
|
|
8
|
+
return false;
|
|
9
|
+
const row = value;
|
|
10
|
+
const sequence = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
|
|
11
|
+
if (row.version !== 1 || typeof row.projectId !== 'string' || !row.projectId ||
|
|
12
|
+
![row.headSeq, row.ackedThroughSeq, row.viewGeneration].every(v => v === null || sequence(v)))
|
|
13
|
+
return false;
|
|
14
|
+
if (row.projections !== undefined && (!Array.isArray(row.projections) || row.projections.length > 65 ||
|
|
15
|
+
row.projections.some(proof => !proof || typeof proof !== 'object' ||
|
|
16
|
+
typeof proof.storageProjectId !== 'string' || logicalProjectIdFromSchemaChangeStorage(proof.storageProjectId) !== row.projectId ||
|
|
17
|
+
!sequence(proof.seq) || !['sourceIdentity', 'lensHash', 'projectionHash'].every(key => typeof proof[key] === 'string' && proof[key])) ||
|
|
18
|
+
new Set(row.projections.map(proof => proof.storageProjectId)).size !== row.projections.length))
|
|
19
|
+
return false;
|
|
20
|
+
if (row.kind === 'unknown')
|
|
21
|
+
return row.reason === 'unqualified' || row.reason === 'inconsistent' || row.reason === 'capacity';
|
|
22
|
+
if (!sequence(row.headSeq) || !sequence(row.ackedThroughSeq) || !sequence(row.viewGeneration) ||
|
|
23
|
+
row.ackedThroughSeq > row.headSeq)
|
|
24
|
+
return false;
|
|
25
|
+
if (row.kind === 'caughtUp')
|
|
26
|
+
return row.headSeq === row.ackedThroughSeq && Array.isArray(row.projections);
|
|
27
|
+
if (row.kind === 'pending')
|
|
28
|
+
return ['outbox', 'generation', 'view'].includes(row.reason);
|
|
29
|
+
if (row.kind !== 'blocked' && row.kind !== 'retryAt')
|
|
30
|
+
return false;
|
|
31
|
+
if (!sequence(row.seq) || row.seq <= row.ackedThroughSeq ||
|
|
32
|
+
row.seq > row.headSeq)
|
|
33
|
+
return false;
|
|
34
|
+
return row.kind === 'blocked' || sequence(row.nextAttemptAt);
|
|
35
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** One DNS label per runtime, including when environments share a wildcard
|
|
2
|
+
* certificate. Addresses identify a route; they never authorize access. */
|
|
3
|
+
export declare function workspacePreviewAddress(origin: string): {
|
|
4
|
+
generation: string;
|
|
5
|
+
namespace: string;
|
|
6
|
+
domain: string;
|
|
7
|
+
connectOrigin: string;
|
|
8
|
+
};
|
|
9
|
+
export declare function workspacePreviewOrigin(generation: string, domain: string, namespace?: string): string;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** One DNS label per runtime, including when environments share a wildcard
|
|
2
|
+
* certificate. Addresses identify a route; they never authorize access. */
|
|
3
|
+
export function workspacePreviewAddress(origin) {
|
|
4
|
+
const url = new URL(origin);
|
|
5
|
+
const match = /^([a-f0-9]{32})(?:-([a-z][a-z0-9-]{0,29}[a-z0-9]|[a-z]))?\.((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,})$/.exec(url.hostname);
|
|
6
|
+
if (url.protocol !== 'https:' || url.port || url.username || url.password || url.pathname !== '/' || url.search || url.hash || !match || url.hostname.split('.')[0].length > 63)
|
|
7
|
+
throw Error('Invalid workspace HTTP origin');
|
|
8
|
+
const [, generation, namespace = '', domain] = match;
|
|
9
|
+
return { generation: generation, namespace, domain: domain,
|
|
10
|
+
connectOrigin: `https://connect${namespace ? `-${namespace}` : ''}.${domain}` };
|
|
11
|
+
}
|
|
12
|
+
export function workspacePreviewOrigin(generation, domain, namespace = '') {
|
|
13
|
+
const origin = `https://${generation}${namespace ? `-${namespace}` : ''}.${domain}`;
|
|
14
|
+
const address = workspacePreviewAddress(origin);
|
|
15
|
+
if (address.generation !== generation || address.domain !== domain || address.namespace !== namespace)
|
|
16
|
+
throw Error('Invalid workspace HTTP origin');
|
|
17
|
+
return origin;
|
|
18
|
+
}
|
|
@@ -5,9 +5,9 @@ export declare const LIVE_QUERY_MAX_DOCUMENTS = 100;
|
|
|
5
5
|
export declare const LIVE_QUERY_MAX_FIELD_PATHS = 256;
|
|
6
6
|
export declare const LIVE_QUERY_MAX_FIELD_PATH_BYTES = 512;
|
|
7
7
|
export declare const LIVE_QUERY_MAX_VALUE_DEPTH = 16;
|
|
8
|
-
export declare const LIVE_QUERY_MAX_STRING_BYTES: number;
|
|
9
8
|
/** Leaves framing headroom under the transport's 64 KiB full-message cap. */
|
|
10
9
|
export declare const LIVE_QUERY_MAX_PROJECTION_BYTES: number;
|
|
10
|
+
export declare const LIVE_QUERY_MAX_STRING_BYTES: number;
|
|
11
11
|
export type LiveQueryScopeV1 = {
|
|
12
12
|
readonly kind: 'living';
|
|
13
13
|
readonly locale: string;
|
|
@@ -3,9 +3,11 @@ export const LIVE_QUERY_MAX_DOCUMENTS = 100;
|
|
|
3
3
|
export const LIVE_QUERY_MAX_FIELD_PATHS = 256;
|
|
4
4
|
export const LIVE_QUERY_MAX_FIELD_PATH_BYTES = 512;
|
|
5
5
|
export const LIVE_QUERY_MAX_VALUE_DEPTH = 16;
|
|
6
|
-
export const LIVE_QUERY_MAX_STRING_BYTES = 8 * 1024;
|
|
7
6
|
/** Leaves framing headroom under the transport's 64 KiB full-message cap. */
|
|
8
7
|
export const LIVE_QUERY_MAX_PROJECTION_BYTES = 60 * 1024;
|
|
8
|
+
// Rich text is stored as JSON text. It shares the whole projection budget;
|
|
9
|
+
// a smaller leaf limit would reject an otherwise bounded article snapshot.
|
|
10
|
+
export const LIVE_QUERY_MAX_STRING_BYTES = LIVE_QUERY_MAX_PROJECTION_BYTES;
|
|
9
11
|
/**
|
|
10
12
|
* Derive the only Query V2 subset eligible for the v1 local overlay.
|
|
11
13
|
* Filters, sorts and relations stay on the causal path because an edit can
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/** Shared progression only; each domain validates the witness it acknowledges. */
|
|
2
|
+
export declare function hasUnreadActivity(attention: number, seen?: number, manualUnread?: boolean): boolean;
|
|
3
|
+
export declare function advanceReadProgress(seen: number, observed: number, latest: number): number;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Shared progression only; each domain validates the witness it acknowledges. */
|
|
2
|
+
export function hasUnreadActivity(attention, seen = 0, manualUnread = false) {
|
|
3
|
+
return manualUnread || attention > seen;
|
|
4
|
+
}
|
|
5
|
+
export function advanceReadProgress(seen, observed, latest) {
|
|
6
|
+
if (!Number.isSafeInteger(observed) || observed < 0 || observed > latest)
|
|
7
|
+
return seen;
|
|
8
|
+
return Math.max(seen, observed);
|
|
9
|
+
}
|
package/dist/schema-change.d.ts
CHANGED
|
@@ -26,8 +26,16 @@ export interface SchemaChangePlanV1 {
|
|
|
26
26
|
changes: SchemaChange[];
|
|
27
27
|
affectedStoryTypes: string[];
|
|
28
28
|
affectedDocumentsUpperBound?: number;
|
|
29
|
+
/** Server-proven exception for removing unreferenced, unused document types.
|
|
30
|
+
* Structural classification remains breaking; only a fresh server check can
|
|
31
|
+
* authorize the push. This witness is part of planDigest. */
|
|
32
|
+
directPush?: {
|
|
33
|
+
kind: 'unused-document-removal';
|
|
34
|
+
storyTypes: string[];
|
|
35
|
+
};
|
|
29
36
|
planDigest: string;
|
|
30
37
|
}
|
|
38
|
+
export declare function schemaChangeAllowsDirectPush(plan: SchemaChangePlanV1): boolean;
|
|
31
39
|
/**
|
|
32
40
|
* JSON values admitted at the schema-migration author boundary. This mirrors
|
|
33
41
|
* Storystick's canonical JSON contract without importing a serializer or a
|
|
@@ -47,6 +55,13 @@ export type SchemaChangeTransformResult = {
|
|
|
47
55
|
} | {
|
|
48
56
|
kind: 'replace';
|
|
49
57
|
value: SchemaChangeJsonValue;
|
|
58
|
+
} | {
|
|
59
|
+
kind: 'remove';
|
|
60
|
+
}
|
|
61
|
+
/** Move the owned value into a declared field of the same object. */
|
|
62
|
+
| {
|
|
63
|
+
kind: 'move';
|
|
64
|
+
path: string[];
|
|
50
65
|
} | {
|
|
51
66
|
kind: 'issue';
|
|
52
67
|
code: string;
|
|
@@ -217,9 +232,23 @@ export interface SchemaChangeReceiptV2 extends Omit<SchemaChangeReceiptV1, 'reci
|
|
|
217
232
|
proposalAggregateDigest?: string;
|
|
218
233
|
recipe?: SchemaChangeRecipeV1;
|
|
219
234
|
}
|
|
220
|
-
export
|
|
235
|
+
export interface ReleaseSchemaChangeReceipt extends Omit<SchemaChangeReceiptV2, 'servingEvidenceId'> {
|
|
236
|
+
releaseId: string;
|
|
237
|
+
reconcile?: boolean;
|
|
238
|
+
mainCheckpoint?: {
|
|
239
|
+
generationId: string;
|
|
240
|
+
schemaVersion: string;
|
|
241
|
+
revision: number;
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
export type SchemaChangeReceipt = SchemaChangeReceiptV1 | SchemaChangeReceiptV2 | ReleaseSchemaChangeReceipt;
|
|
221
245
|
export interface SchemaChangeRunViewV1 {
|
|
222
246
|
runId: string;
|
|
247
|
+
/** Omitted for project activation. A release run never activates Main/public. */
|
|
248
|
+
releaseId?: string;
|
|
249
|
+
/** Rebuild the release against current Main, preserving its decisions. */
|
|
250
|
+
reconcile?: boolean;
|
|
251
|
+
mainCheckpointCurrent?: boolean;
|
|
223
252
|
status: SchemaChangeRunStatus;
|
|
224
253
|
phase: SchemaChangeRunPhase;
|
|
225
254
|
step: number;
|
package/dist/schema-change.js
CHANGED
|
@@ -34,6 +34,20 @@ export function logicalProjectIdFromSchemaChangeStorage(storageProjectId) {
|
|
|
34
34
|
return storageProjectId;
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
|
+
export function schemaChangeAllowsDirectPush(plan) {
|
|
38
|
+
if (['unchanged', 'presentation', 'additive'].includes(plan.classification))
|
|
39
|
+
return true;
|
|
40
|
+
if (plan.classification !== 'breaking' || plan.directPush?.kind !== 'unused-document-removal')
|
|
41
|
+
return false;
|
|
42
|
+
const ids = plan.directPush.storyTypes;
|
|
43
|
+
if (!Array.isArray(ids) || ids.length === 0 || ids.some(id => typeof id !== 'string' || !id))
|
|
44
|
+
return false;
|
|
45
|
+
if (!ids.every(id => plan.changes.some(change => change.kind === 'story-removed' && change.path === `stories.${id}`)))
|
|
46
|
+
return false;
|
|
47
|
+
return plan.changes.every(change => change.classification !== 'unknown' && (change.classification !== 'breaking' || ids.some(id => (change.kind === 'story-removed' && change.path === `stories.${id}`) ||
|
|
48
|
+
(change.kind === 'binding-removed' && change.path.startsWith(`fieldBindings.${id}.`)) ||
|
|
49
|
+
(change.kind === 'zone-mapping-changed' && change.path === `zoneMappings.${id}`))));
|
|
50
|
+
}
|
|
37
51
|
export const SCHEMA_CHANGE_RECIPE_IDS = [
|
|
38
52
|
'text-to-single-line-richtext',
|
|
39
53
|
'enum-contract-fixture',
|
|
@@ -151,6 +165,19 @@ export function decodeSchemaChangeTransformResult(value, path = 'result') {
|
|
|
151
165
|
assertExactKeys(value, ['kind'], path);
|
|
152
166
|
return { kind: 'unchanged' };
|
|
153
167
|
}
|
|
168
|
+
if (value.kind === 'remove') {
|
|
169
|
+
assertExactKeys(value, ['kind'], path);
|
|
170
|
+
return { kind: 'remove' };
|
|
171
|
+
}
|
|
172
|
+
if (value.kind === 'move') {
|
|
173
|
+
assertExactKeys(value, ['kind', 'path'], path);
|
|
174
|
+
if (!Array.isArray(value.path) || value.path.length === 0 || value.path.length > 16 ||
|
|
175
|
+
value.path.some(segment => typeof segment !== 'string' || !/^[A-Za-z][A-Za-z0-9_]*$/.test(segment) ||
|
|
176
|
+
['constructor', 'prototype'].includes(segment))) {
|
|
177
|
+
throw new SchemaChangeContractError(`${path}.path: expected a declared field path`);
|
|
178
|
+
}
|
|
179
|
+
return { kind: 'move', path: [...value.path] };
|
|
180
|
+
}
|
|
154
181
|
if (value.kind === 'replace') {
|
|
155
182
|
assertExactKeys(value, ['kind', 'value'], path);
|
|
156
183
|
return {
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { type UsageAttribution, type UsageMeasurement, type UsageTotals } from './usage.js';
|
|
2
|
+
export declare const USAGE_DELIVERY_HEADER = "x-storystick-usage-receipt";
|
|
3
|
+
export declare const USAGE_DELIVERY_LEASE_HEADER = "x-storystick-usage-lease";
|
|
4
|
+
export type DeliveryOperation = 'content-read' | 'support' | 'asset' | 'editorial' | 'internal';
|
|
5
|
+
/** A short cached authority lease is separate from the immutable content cache key. */
|
|
6
|
+
export interface UsageDeliveryLease {
|
|
7
|
+
attribution: UsageAttribution;
|
|
8
|
+
expiresAt: number;
|
|
9
|
+
}
|
|
10
|
+
export declare function parseDeliveryLease(value: string | null, projectId: string, now: number): UsageDeliveryLease | null;
|
|
11
|
+
/** Created only by the outer trusted server, once per external request, including a cache hit. */
|
|
12
|
+
export interface UsageDeliveryReceipt {
|
|
13
|
+
version: 1;
|
|
14
|
+
source: 'content' | 'asset' | 'api';
|
|
15
|
+
requestId: string;
|
|
16
|
+
rayId: string;
|
|
17
|
+
host: string;
|
|
18
|
+
method: 'GET' | 'POST' | 'HEAD' | 'OPTIONS';
|
|
19
|
+
attribution: UsageAttribution;
|
|
20
|
+
operation: DeliveryOperation;
|
|
21
|
+
outcome: 'success' | 'error' | 'redirect';
|
|
22
|
+
status: number;
|
|
23
|
+
/** Null unless the producer knows the exact outgoing encoded representation size. */
|
|
24
|
+
representation: {
|
|
25
|
+
bodyBytes: string;
|
|
26
|
+
encoding: 'identity' | 'gzip' | 'br';
|
|
27
|
+
} | null;
|
|
28
|
+
}
|
|
29
|
+
export declare function assertDeliveryReceipt(value: UsageDeliveryReceipt): void;
|
|
30
|
+
/** Only the private collector can normalize provider logs into this proof. No customer endpoint accepts it. */
|
|
31
|
+
export interface UsageEdgeObservation {
|
|
32
|
+
rayId: string;
|
|
33
|
+
host: string;
|
|
34
|
+
method: string;
|
|
35
|
+
source: string;
|
|
36
|
+
workerSubrequest: boolean;
|
|
37
|
+
status: number;
|
|
38
|
+
bodyBytes: string;
|
|
39
|
+
encoding: string;
|
|
40
|
+
evidenceRef: string;
|
|
41
|
+
}
|
|
42
|
+
export interface DeliveryQualification {
|
|
43
|
+
revision: string;
|
|
44
|
+
/** A real transport recipe, scoped to this deployment, is required before setting either capability. */
|
|
45
|
+
bodyBytes: boolean;
|
|
46
|
+
representationCompletion: boolean;
|
|
47
|
+
}
|
|
48
|
+
/** Contract v0.1: semantic success is necessary; producing a Response is not proof of emission. */
|
|
49
|
+
export declare function measureDelivery(receipt: UsageDeliveryReceipt, edge: UsageEdgeObservation | null, qualification: DeliveryQualification): {
|
|
50
|
+
reads: UsageMeasurement;
|
|
51
|
+
bodyBytes: UsageMeasurement;
|
|
52
|
+
};
|
|
53
|
+
export type UsageDeliverySegmentScope = Omit<UsageAttribution, 'admittedAt'> & {
|
|
54
|
+
source: UsageDeliveryReceipt['source'];
|
|
55
|
+
window: {
|
|
56
|
+
start: number;
|
|
57
|
+
end: number;
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
export interface UsageDeliverySegment {
|
|
61
|
+
version: 1;
|
|
62
|
+
scope: UsageDeliverySegmentScope;
|
|
63
|
+
qualificationRevision: string;
|
|
64
|
+
requests: number;
|
|
65
|
+
reads: UsageTotals;
|
|
66
|
+
bodyBytes: UsageTotals;
|
|
67
|
+
/** The collector retains the private exact evidence corpus under this immutable digest. */
|
|
68
|
+
evidenceDigest: string;
|
|
69
|
+
}
|
|
70
|
+
export declare function deliverySegmentScope(receipt: UsageDeliveryReceipt): UsageDeliverySegmentScope;
|
|
71
|
+
export declare function assertDeliverySegment(segment: UsageDeliverySegment): void;
|
|
72
|
+
export declare const deliverySegmentKey: (scope: UsageDeliverySegmentScope) => string;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { assertUsageAttribution, usageInteger, usageTime } from './usage.js';
|
|
2
|
+
import { canonicalConversationJson as canonical } from './canonical-json.js';
|
|
3
|
+
export const USAGE_DELIVERY_HEADER = 'x-storystick-usage-receipt';
|
|
4
|
+
export const USAGE_DELIVERY_LEASE_HEADER = 'x-storystick-usage-lease';
|
|
5
|
+
export function parseDeliveryLease(value, projectId, now) {
|
|
6
|
+
if (value === null)
|
|
7
|
+
return null;
|
|
8
|
+
if (value.length > 4096)
|
|
9
|
+
throw new Error('USAGE_DELIVERY_LEASE_INVALID');
|
|
10
|
+
const lease = JSON.parse(value);
|
|
11
|
+
assertUsageAttribution(lease.attribution);
|
|
12
|
+
usageTime(lease.expiresAt);
|
|
13
|
+
usageTime(now);
|
|
14
|
+
if (lease.attribution.projectId !== projectId || lease.expiresAt <= now || lease.attribution.admittedAt > now ||
|
|
15
|
+
lease.expiresAt <= lease.attribution.admittedAt || lease.expiresAt > lease.attribution.period.end ||
|
|
16
|
+
lease.expiresAt - lease.attribution.admittedAt > 5000)
|
|
17
|
+
throw new Error('USAGE_DELIVERY_LEASE_INVALID');
|
|
18
|
+
return lease;
|
|
19
|
+
}
|
|
20
|
+
export function assertDeliveryReceipt(value) {
|
|
21
|
+
assertUsageAttribution(value.attribution);
|
|
22
|
+
if (value.version !== 1 || !['content', 'asset', 'api'].includes(value.source) ||
|
|
23
|
+
!/^[a-f0-9-]{36}$/.test(value.requestId) || !/^[a-f0-9]{16,32}$/.test(value.rayId) ||
|
|
24
|
+
!/^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/.test(value.host) ||
|
|
25
|
+
!['GET', 'POST', 'HEAD', 'OPTIONS'].includes(value.method) ||
|
|
26
|
+
!['content-read', 'support', 'asset', 'editorial', 'internal'].includes(value.operation) ||
|
|
27
|
+
!['success', 'error', 'redirect'].includes(value.outcome) ||
|
|
28
|
+
!Number.isSafeInteger(value.status) || value.status < 100 || value.status > 599)
|
|
29
|
+
throw new Error('USAGE_DELIVERY_RECEIPT_INVALID');
|
|
30
|
+
if (value.representation) {
|
|
31
|
+
usageInteger(value.representation.bodyBytes);
|
|
32
|
+
if (!['identity', 'gzip', 'br'].includes(value.representation.encoding))
|
|
33
|
+
throw new Error('USAGE_DELIVERY_ENCODING_INVALID');
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const zero = () => ({ status: 'measured', quantity: '0' });
|
|
37
|
+
const unknown = () => ({ status: 'unknown', reason: 'missing-proof' });
|
|
38
|
+
/** Contract v0.1: semantic success is necessary; producing a Response is not proof of emission. */
|
|
39
|
+
export function measureDelivery(receipt, edge, qualification) {
|
|
40
|
+
assertDeliveryReceipt(receipt);
|
|
41
|
+
const excluded = ['editorial', 'internal'].includes(receipt.operation) || ['HEAD', 'OPTIONS'].includes(receipt.method) ||
|
|
42
|
+
receipt.outcome !== 'success' || !(receipt.status >= 200 && receipt.status < 300 || receipt.status === 304);
|
|
43
|
+
if (excluded)
|
|
44
|
+
return { reads: zero(), bodyBytes: zero() };
|
|
45
|
+
const isRead = receipt.operation === 'content-read';
|
|
46
|
+
if (!edge)
|
|
47
|
+
return { reads: isRead ? unknown() : zero(), bodyBytes: receipt.status === 304 ? zero() : unknown() };
|
|
48
|
+
usageInteger(edge.bodyBytes);
|
|
49
|
+
if (edge.rayId !== receipt.rayId || edge.host !== receipt.host || edge.method !== receipt.method ||
|
|
50
|
+
edge.status !== receipt.status || edge.source !== 'eyeball' || edge.workerSubrequest || !edge.evidenceRef)
|
|
51
|
+
throw new Error('USAGE_DELIVERY_CORRELATION_CONFLICT');
|
|
52
|
+
if (receipt.status === 304) {
|
|
53
|
+
if (edge.bodyBytes !== '0')
|
|
54
|
+
throw new Error('USAGE_DELIVERY_BODY_FORBIDDEN');
|
|
55
|
+
return { reads: isRead && qualification.bodyBytes && qualification.representationCompletion ? { status: 'measured', quantity: '1' } : isRead ? unknown() : zero(), bodyBytes: zero() };
|
|
56
|
+
}
|
|
57
|
+
let reads = isRead ? unknown() : zero();
|
|
58
|
+
if (isRead && qualification.bodyBytes && qualification.representationCompletion && receipt.representation && edge.encoding === receipt.representation.encoding) {
|
|
59
|
+
const emitted = usageInteger(edge.bodyBytes), expected = usageInteger(receipt.representation.bodyBytes);
|
|
60
|
+
if (emitted > expected)
|
|
61
|
+
throw new Error('USAGE_DELIVERY_REPRESENTATION_DRIFT');
|
|
62
|
+
reads = { status: 'measured', quantity: emitted === expected ? '1' : '0' };
|
|
63
|
+
}
|
|
64
|
+
return { reads, bodyBytes: qualification.bodyBytes ? { status: 'measured', quantity: edge.bodyBytes } : unknown() };
|
|
65
|
+
}
|
|
66
|
+
export function deliverySegmentScope(receipt) {
|
|
67
|
+
assertDeliveryReceipt(receipt);
|
|
68
|
+
const { admittedAt, ...scope } = receipt.attribution;
|
|
69
|
+
const hour = Math.floor(admittedAt / 3_600_000) * 3_600_000;
|
|
70
|
+
return { ...scope, source: receipt.source,
|
|
71
|
+
window: { start: Math.max(hour, scope.period.start), end: Math.min(hour + 3_600_000, scope.period.end) } };
|
|
72
|
+
}
|
|
73
|
+
export function assertDeliverySegment(segment) {
|
|
74
|
+
const scope = segment.scope;
|
|
75
|
+
assertUsageAttribution({ ...scope, admittedAt: scope.window.start });
|
|
76
|
+
usageTime(scope.window.end);
|
|
77
|
+
const hour = Math.floor(scope.window.start / 3_600_000) * 3_600_000;
|
|
78
|
+
if (segment.version !== 1 || scope.window.end <= scope.window.start || scope.window.end > scope.period.end ||
|
|
79
|
+
scope.window.start !== Math.max(hour, scope.period.start) || scope.window.end !== Math.min(hour + 3_600_000, scope.period.end) ||
|
|
80
|
+
scope.window.end - scope.window.start > 3_600_000 || !['content', 'asset', 'api'].includes(scope.source) ||
|
|
81
|
+
!/^[a-zA-Z0-9_.-]{1,100}$/.test(segment.qualificationRevision) || !/^[a-f0-9]{64}$/.test(segment.evidenceDigest) ||
|
|
82
|
+
!Number.isSafeInteger(segment.requests) || segment.requests < 1)
|
|
83
|
+
throw new Error('USAGE_DELIVERY_SEGMENT_INVALID');
|
|
84
|
+
if (usageInteger(segment.reads.measured) + usageInteger(segment.reads.reported) + BigInt(segment.reads.unknownSubjects) > BigInt(segment.requests))
|
|
85
|
+
throw new Error('USAGE_DELIVERY_READS_EXCEED_REQUESTS');
|
|
86
|
+
for (const totals of [segment.reads, segment.bodyBytes]) {
|
|
87
|
+
usageInteger(totals.measured);
|
|
88
|
+
usageInteger(totals.reported);
|
|
89
|
+
if (!Number.isSafeInteger(totals.unknownSubjects) || totals.unknownSubjects < 0 || totals.unknownSubjects > segment.requests)
|
|
90
|
+
throw new Error('USAGE_DELIVERY_SEGMENT_INVALID');
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
export const deliverySegmentKey = (scope) => canonical(scope);
|
package/dist/usage.d.ts
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/** Provider-neutral quantities and admission-time attribution. JSON at boundaries. */
|
|
2
|
+
export type UsageMeasurement = {
|
|
3
|
+
status: 'unknown';
|
|
4
|
+
reason: 'awaiting-receipt' | 'missing-proof';
|
|
5
|
+
} | {
|
|
6
|
+
status: 'reported' | 'measured';
|
|
7
|
+
quantity: string;
|
|
8
|
+
};
|
|
9
|
+
export interface UsageAttribution {
|
|
10
|
+
projectId: string;
|
|
11
|
+
payerId: string;
|
|
12
|
+
admittedAt: number;
|
|
13
|
+
period: {
|
|
14
|
+
start: number;
|
|
15
|
+
end: number;
|
|
16
|
+
};
|
|
17
|
+
contract: {
|
|
18
|
+
assignmentId: string;
|
|
19
|
+
revision: number;
|
|
20
|
+
offerKey: string;
|
|
21
|
+
} | null;
|
|
22
|
+
}
|
|
23
|
+
export interface UsageObservation {
|
|
24
|
+
version: 1;
|
|
25
|
+
source: string;
|
|
26
|
+
eventId: string;
|
|
27
|
+
subjectId: string;
|
|
28
|
+
attribution: UsageAttribution;
|
|
29
|
+
meter: 'provider.gateway-debit-usd-micros';
|
|
30
|
+
measurement: UsageMeasurement;
|
|
31
|
+
previousEventId: string | null;
|
|
32
|
+
reason: 'admission' | 'receipt' | 'correction';
|
|
33
|
+
evidenceRef: string;
|
|
34
|
+
}
|
|
35
|
+
export interface UsageTotals {
|
|
36
|
+
measured: string;
|
|
37
|
+
reported: string;
|
|
38
|
+
unknownSubjects: number;
|
|
39
|
+
}
|
|
40
|
+
export type UsageStockMeter = 'cms.retained-media-bytes' | 'cms.retained-documents';
|
|
41
|
+
/** Resource transitions are ordered replacements, not additive consumption. */
|
|
42
|
+
export interface UsageStockTransition {
|
|
43
|
+
version: 1;
|
|
44
|
+
projectId: string;
|
|
45
|
+
meter: UsageStockMeter;
|
|
46
|
+
resourceId: string;
|
|
47
|
+
revision: number;
|
|
48
|
+
effectiveAt: number;
|
|
49
|
+
before: UsageMeasurement | null;
|
|
50
|
+
after: UsageMeasurement | null;
|
|
51
|
+
evidenceRef: string;
|
|
52
|
+
}
|
|
53
|
+
export declare function projectUsageStock(totals: UsageTotals, before: UsageMeasurement | null, after: UsageMeasurement | null): UsageTotals;
|
|
54
|
+
/** Exact excess unit-milliseconds. Call at stock/quota/payer boundaries, never on an idle timer. */
|
|
55
|
+
export declare function usageStockIntegral(stock: string, included: string, start: number, end: number): string;
|
|
56
|
+
/** Decimal strings preserve integer precision in Convex, JSON and provider adapters. */
|
|
57
|
+
export declare function usageInteger(value: string): bigint;
|
|
58
|
+
export declare function usageTime(value: number): number;
|
|
59
|
+
/** Opaque private reference: no query string, credentials, fragment or free-form content. */
|
|
60
|
+
export declare function usageEvidenceRef(value: string): string;
|
|
61
|
+
/** Month boundaries retain the original UTC anchor, including Jan 31 → Feb → Mar 31. */
|
|
62
|
+
export declare function usagePeriod(anchor: number, at: number): {
|
|
63
|
+
start: number;
|
|
64
|
+
end: number;
|
|
65
|
+
};
|
|
66
|
+
export declare function assertUsageAttribution(scope: UsageAttribution): void;
|
|
67
|
+
/** Projection replacement is not a mutable fact: the caller appends a linked receipt first. */
|
|
68
|
+
export declare function projectUsageMeasurement(totals: UsageTotals, before: UsageMeasurement | null, after: UsageMeasurement): UsageTotals;
|
|
69
|
+
export type UsageStockView = {
|
|
70
|
+
version: 1;
|
|
71
|
+
projectId: string;
|
|
72
|
+
meter: UsageStockMeter;
|
|
73
|
+
billable: false;
|
|
74
|
+
} & ({
|
|
75
|
+
status: 'unknown';
|
|
76
|
+
reason: 'inventory-required';
|
|
77
|
+
} | {
|
|
78
|
+
status: 'inventory' | 'ready';
|
|
79
|
+
measured: string;
|
|
80
|
+
reported: string;
|
|
81
|
+
unknownSubjects: number;
|
|
82
|
+
unqualifiedResources: number;
|
|
83
|
+
revision: number;
|
|
84
|
+
openedAt: number | null;
|
|
85
|
+
updatedAt: number;
|
|
86
|
+
limit: string | null;
|
|
87
|
+
});
|
|
88
|
+
/** Resource allowances, not money and not a provider wallet. All boundaries are JSON. */
|
|
89
|
+
export type CollaborationPolicy = {
|
|
90
|
+
kind: 'tier';
|
|
91
|
+
capacity: number;
|
|
92
|
+
} | {
|
|
93
|
+
kind: 'seats';
|
|
94
|
+
included: number;
|
|
95
|
+
maximum: number;
|
|
96
|
+
};
|
|
97
|
+
export declare function collaborationCapacity(policy: CollaborationPolicy): number;
|
|
98
|
+
/** Explicit project participants only. Team membership and AI habilitation are not seat quantities. */
|
|
99
|
+
export declare function collaborationQuantity(policy: CollaborationPolicy, participants: number): {
|
|
100
|
+
participants: number;
|
|
101
|
+
additionalSeats: number;
|
|
102
|
+
};
|
|
103
|
+
export type AllocationUnit = 'ai-microcredit' | 'compute-millisecond';
|
|
104
|
+
export interface AllocationBalance {
|
|
105
|
+
granted: string;
|
|
106
|
+
available: string;
|
|
107
|
+
held: string;
|
|
108
|
+
consumed: string;
|
|
109
|
+
retired: string;
|
|
110
|
+
}
|
|
111
|
+
export interface AllocationSlice {
|
|
112
|
+
allocationId: string;
|
|
113
|
+
quantity: string;
|
|
114
|
+
}
|
|
115
|
+
export type AllocationChange = {
|
|
116
|
+
kind: 'reserve';
|
|
117
|
+
quantity: string;
|
|
118
|
+
} | {
|
|
119
|
+
kind: 'settle';
|
|
120
|
+
reserved: string;
|
|
121
|
+
consumed: string;
|
|
122
|
+
reusable: boolean;
|
|
123
|
+
} | {
|
|
124
|
+
kind: 'retire';
|
|
125
|
+
};
|
|
126
|
+
export declare function assertAllocationBalance(balance: AllocationBalance): void;
|
|
127
|
+
/** No timeout releases an engagement. Only a settlement with authoritative evidence does. */
|
|
128
|
+
export declare function changeAllocation(balance: AllocationBalance, change: AllocationChange): AllocationBalance;
|
|
129
|
+
/** Earliest expiry first; stable tie-breaker. Selection cannot mutate any balances. */
|
|
130
|
+
export declare function selectAllocations(candidates: {
|
|
131
|
+
id: string;
|
|
132
|
+
available: string;
|
|
133
|
+
startsAt: number;
|
|
134
|
+
endsAt: number;
|
|
135
|
+
revoked: boolean;
|
|
136
|
+
}[], quantity: string, at: number): AllocationSlice[];
|
|
137
|
+
/** Consumes the sealed selection, never today's wallet or another member's allowance. */
|
|
138
|
+
export declare function settleAllocationSlices(slices: AllocationSlice[], consumed: string): {
|
|
139
|
+
allocationId: string;
|
|
140
|
+
reserved: string;
|
|
141
|
+
consumed: string;
|
|
142
|
+
}[];
|
|
143
|
+
/** Exact levels captured by the authoritative stock transaction. No reconstruction
|
|
144
|
+
* from the current head, and no client-declared quantities in a billing window. */
|
|
145
|
+
export type UsageStockLevel = UsageTotals & {
|
|
146
|
+
unqualifiedResources: number;
|
|
147
|
+
at: number;
|
|
148
|
+
revision: number;
|
|
149
|
+
};
|
|
150
|
+
export type UsageStockWindow = {
|
|
151
|
+
from: number;
|
|
152
|
+
to: number;
|
|
153
|
+
} & ({
|
|
154
|
+
status: 'incomplete';
|
|
155
|
+
reason: 'inventory-required' | 'before-opening' | 'window-too-dense' | 'history-incomplete';
|
|
156
|
+
} | {
|
|
157
|
+
status: 'ready';
|
|
158
|
+
openedAt: number;
|
|
159
|
+
sourceRevision: number;
|
|
160
|
+
opening: UsageStockLevel;
|
|
161
|
+
changes: UsageStockLevel[];
|
|
162
|
+
});
|
|
163
|
+
export type UsageStockTerms = {
|
|
164
|
+
from: number;
|
|
165
|
+
to: number;
|
|
166
|
+
payerId: string;
|
|
167
|
+
contractId: string;
|
|
168
|
+
offerKey: string;
|
|
169
|
+
period: {
|
|
170
|
+
start: number;
|
|
171
|
+
end: number;
|
|
172
|
+
};
|
|
173
|
+
included: string;
|
|
174
|
+
};
|
|
175
|
+
export type UsageStockSlice = {
|
|
176
|
+
from: number;
|
|
177
|
+
to: number;
|
|
178
|
+
stockRevision: number;
|
|
179
|
+
terms: UsageStockTerms | null;
|
|
180
|
+
} & ({
|
|
181
|
+
status: 'measured';
|
|
182
|
+
stock: string;
|
|
183
|
+
excessUnitMilliseconds: string;
|
|
184
|
+
} | {
|
|
185
|
+
status: 'unknown';
|
|
186
|
+
reason: 'contract-unavailable' | 'stock-unqualified';
|
|
187
|
+
});
|
|
188
|
+
/** Intersect factual stock levels with acquired quota/payer intervals. This is
|
|
189
|
+
* a quantity calculation, not a price engine, invoice or periodic stock writer. */
|
|
190
|
+
export declare function sliceUsageStock(window: Extract<UsageStockWindow, {
|
|
191
|
+
status: 'ready';
|
|
192
|
+
}>, terms: readonly UsageStockTerms[]): UsageStockSlice[];
|
package/dist/usage.js
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
export function projectUsageStock(totals, before, after) {
|
|
2
|
+
return projectUsageMeasurement(totals, before, after ?? { status: 'measured', quantity: '0' });
|
|
3
|
+
}
|
|
4
|
+
/** Exact excess unit-milliseconds. Call at stock/quota/payer boundaries, never on an idle timer. */
|
|
5
|
+
export function usageStockIntegral(stock, included, start, end) {
|
|
6
|
+
usageTime(start);
|
|
7
|
+
usageTime(end);
|
|
8
|
+
if (end < start)
|
|
9
|
+
throw new Error('USAGE_INVALID_INTERVAL');
|
|
10
|
+
const excess = usageInteger(stock) - usageInteger(included);
|
|
11
|
+
return (excess > 0n ? excess * BigInt(end - start) : 0n).toString();
|
|
12
|
+
}
|
|
13
|
+
/** Decimal strings preserve integer precision in Convex, JSON and provider adapters. */
|
|
14
|
+
export function usageInteger(value) {
|
|
15
|
+
if (typeof value !== 'string' || !/^(0|[1-9][0-9]{0,77})$/.test(value))
|
|
16
|
+
throw new Error('USAGE_INVALID_INTEGER');
|
|
17
|
+
return BigInt(value);
|
|
18
|
+
}
|
|
19
|
+
export function usageTime(value) {
|
|
20
|
+
if (!Number.isSafeInteger(value) || value < 0 || value > 8_640_000_000_000_000)
|
|
21
|
+
throw new Error('USAGE_INVALID_TIME');
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
/** Opaque private reference: no query string, credentials, fragment or free-form content. */
|
|
25
|
+
export function usageEvidenceRef(value) {
|
|
26
|
+
if (typeof value !== 'string' || !/^[a-zA-Z0-9/_.,:-]{1,400}$/.test(value))
|
|
27
|
+
throw new Error('USAGE_EVIDENCE_REFERENCE_INVALID');
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
/** Month boundaries retain the original UTC anchor, including Jan 31 → Feb → Mar 31. */
|
|
31
|
+
export function usagePeriod(anchor, at) {
|
|
32
|
+
usageTime(anchor);
|
|
33
|
+
usageTime(at);
|
|
34
|
+
if (at < anchor)
|
|
35
|
+
throw new Error('USAGE_BEFORE_ANCHOR');
|
|
36
|
+
const origin = new Date(anchor), current = new Date(at);
|
|
37
|
+
const boundary = (offset) => {
|
|
38
|
+
const date = new Date(anchor);
|
|
39
|
+
date.setUTCDate(1);
|
|
40
|
+
date.setUTCMonth(origin.getUTCMonth() + offset);
|
|
41
|
+
const next = new Date(date);
|
|
42
|
+
next.setUTCMonth(next.getUTCMonth() + 1, 0);
|
|
43
|
+
date.setUTCDate(Math.min(origin.getUTCDate(), next.getUTCDate()));
|
|
44
|
+
return usageTime(date.getTime());
|
|
45
|
+
};
|
|
46
|
+
let offset = (current.getUTCFullYear() - origin.getUTCFullYear()) * 12 + current.getUTCMonth() - origin.getUTCMonth();
|
|
47
|
+
if (boundary(offset) > at)
|
|
48
|
+
offset--;
|
|
49
|
+
return { start: boundary(offset), end: boundary(offset + 1) };
|
|
50
|
+
}
|
|
51
|
+
export function assertUsageAttribution(scope) {
|
|
52
|
+
for (const id of [scope.projectId, scope.payerId])
|
|
53
|
+
if (!id || id.length > 200)
|
|
54
|
+
throw new Error('USAGE_INVALID_SCOPE');
|
|
55
|
+
usageTime(scope.admittedAt);
|
|
56
|
+
usageTime(scope.period.start);
|
|
57
|
+
usageTime(scope.period.end);
|
|
58
|
+
if (scope.period.start > scope.admittedAt || scope.admittedAt >= scope.period.end)
|
|
59
|
+
throw new Error('USAGE_INVALID_PERIOD');
|
|
60
|
+
if (scope.contract && (!scope.contract.assignmentId || !scope.contract.offerKey || scope.contract.offerKey.length > 200 ||
|
|
61
|
+
!Number.isSafeInteger(scope.contract.revision) || scope.contract.revision < 1))
|
|
62
|
+
throw new Error('USAGE_INVALID_CONTRACT');
|
|
63
|
+
}
|
|
64
|
+
/** Projection replacement is not a mutable fact: the caller appends a linked receipt first. */
|
|
65
|
+
export function projectUsageMeasurement(totals, before, after) {
|
|
66
|
+
let measured = usageInteger(totals.measured), reported = usageInteger(totals.reported);
|
|
67
|
+
let unknown = totals.unknownSubjects;
|
|
68
|
+
if (!Number.isSafeInteger(unknown) || unknown < 0)
|
|
69
|
+
throw new Error('USAGE_INVALID_TOTAL');
|
|
70
|
+
const apply = (value, direction) => {
|
|
71
|
+
if (value.status === 'unknown')
|
|
72
|
+
unknown += Number(direction);
|
|
73
|
+
else if (value.status === 'measured')
|
|
74
|
+
measured += direction * usageInteger(value.quantity);
|
|
75
|
+
else
|
|
76
|
+
reported += direction * usageInteger(value.quantity);
|
|
77
|
+
};
|
|
78
|
+
if (before)
|
|
79
|
+
apply(before, -1n);
|
|
80
|
+
apply(after, 1n);
|
|
81
|
+
if (measured < 0n || reported < 0n || unknown < 0 || !Number.isSafeInteger(unknown))
|
|
82
|
+
throw new Error('USAGE_PROJECTION_DRIFT');
|
|
83
|
+
return { measured: measured.toString(), reported: reported.toString(), unknownSubjects: unknown };
|
|
84
|
+
}
|
|
85
|
+
export function collaborationCapacity(policy) {
|
|
86
|
+
const capacity = policy.kind === 'tier' ? policy.capacity : policy.maximum;
|
|
87
|
+
if (!Number.isSafeInteger(capacity) || capacity < 1 || capacity > 1000 ||
|
|
88
|
+
policy.kind === 'seats' && (!Number.isSafeInteger(policy.included) || policy.included < 0 || policy.included > capacity))
|
|
89
|
+
throw new Error('USAGE_COLLABORATION_POLICY_INVALID');
|
|
90
|
+
return capacity;
|
|
91
|
+
}
|
|
92
|
+
/** Explicit project participants only. Team membership and AI habilitation are not seat quantities. */
|
|
93
|
+
export function collaborationQuantity(policy, participants) {
|
|
94
|
+
const capacity = collaborationCapacity(policy);
|
|
95
|
+
if (!Number.isSafeInteger(participants) || participants < 0 || participants > capacity)
|
|
96
|
+
throw new Error('USAGE_COLLABORATION_CAPACITY');
|
|
97
|
+
return { participants, additionalSeats: policy.kind === 'seats' ? Math.max(0, participants - policy.included) : 0 };
|
|
98
|
+
}
|
|
99
|
+
export function assertAllocationBalance(balance) {
|
|
100
|
+
const { granted, available, held, consumed, retired } = balance;
|
|
101
|
+
if (usageInteger(granted) !== usageInteger(available) + usageInteger(held) + usageInteger(consumed) + usageInteger(retired))
|
|
102
|
+
throw new Error('USAGE_ALLOCATION_DRIFT');
|
|
103
|
+
}
|
|
104
|
+
/** No timeout releases an engagement. Only a settlement with authoritative evidence does. */
|
|
105
|
+
export function changeAllocation(balance, change) {
|
|
106
|
+
assertAllocationBalance(balance);
|
|
107
|
+
let available = usageInteger(balance.available), held = usageInteger(balance.held);
|
|
108
|
+
let consumed = usageInteger(balance.consumed), retired = usageInteger(balance.retired);
|
|
109
|
+
if (change.kind === 'reserve') {
|
|
110
|
+
const quantity = usageInteger(change.quantity);
|
|
111
|
+
if (quantity === 0n || quantity > available)
|
|
112
|
+
throw new Error('USAGE_ALLOCATION_EXHAUSTED');
|
|
113
|
+
available -= quantity;
|
|
114
|
+
held += quantity;
|
|
115
|
+
}
|
|
116
|
+
else if (change.kind === 'settle') {
|
|
117
|
+
const reserved = usageInteger(change.reserved), used = usageInteger(change.consumed);
|
|
118
|
+
if (reserved > held || used > reserved)
|
|
119
|
+
throw new Error('USAGE_RESERVATION_BOUND_EXCEEDED');
|
|
120
|
+
held -= reserved;
|
|
121
|
+
consumed += used;
|
|
122
|
+
if (change.reusable)
|
|
123
|
+
available += reserved - used;
|
|
124
|
+
else
|
|
125
|
+
retired += reserved - used;
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
retired += available;
|
|
129
|
+
available = 0n;
|
|
130
|
+
}
|
|
131
|
+
const next = { granted: balance.granted, available: String(available), held: String(held), consumed: String(consumed), retired: String(retired) };
|
|
132
|
+
assertAllocationBalance(next);
|
|
133
|
+
return next;
|
|
134
|
+
}
|
|
135
|
+
/** Earliest expiry first; stable tie-breaker. Selection cannot mutate any balances. */
|
|
136
|
+
export function selectAllocations(candidates, quantity, at) {
|
|
137
|
+
usageTime(at);
|
|
138
|
+
let remaining = usageInteger(quantity);
|
|
139
|
+
if (!remaining)
|
|
140
|
+
throw new Error('USAGE_ALLOCATION_QUANTITY_REQUIRED');
|
|
141
|
+
const ids = new Set(), selected = [];
|
|
142
|
+
for (const item of [...candidates].sort((a, b) => a.endsAt - b.endsAt || a.id.localeCompare(b.id))) {
|
|
143
|
+
usageTime(item.startsAt);
|
|
144
|
+
usageTime(item.endsAt);
|
|
145
|
+
if (item.startsAt >= item.endsAt || ids.has(item.id))
|
|
146
|
+
throw new Error('USAGE_ALLOCATION_CANDIDATE_INVALID');
|
|
147
|
+
ids.add(item.id);
|
|
148
|
+
const available = usageInteger(item.available);
|
|
149
|
+
if (!remaining || item.revoked || at < item.startsAt || at >= item.endsAt || !available)
|
|
150
|
+
continue;
|
|
151
|
+
const take = available < remaining ? available : remaining;
|
|
152
|
+
selected.push({ allocationId: item.id, quantity: String(take) });
|
|
153
|
+
remaining -= take;
|
|
154
|
+
}
|
|
155
|
+
if (remaining)
|
|
156
|
+
throw new Error('USAGE_ALLOCATION_EXHAUSTED');
|
|
157
|
+
return selected;
|
|
158
|
+
}
|
|
159
|
+
/** Consumes the sealed selection, never today's wallet or another member's allowance. */
|
|
160
|
+
export function settleAllocationSlices(slices, consumed) {
|
|
161
|
+
let remaining = usageInteger(consumed);
|
|
162
|
+
const ids = new Set();
|
|
163
|
+
const result = slices.map(slice => {
|
|
164
|
+
const reserved = usageInteger(slice.quantity);
|
|
165
|
+
if (!reserved || ids.has(slice.allocationId))
|
|
166
|
+
throw new Error('USAGE_ALLOCATION_SLICE_INVALID');
|
|
167
|
+
ids.add(slice.allocationId);
|
|
168
|
+
const used = remaining < reserved ? remaining : reserved;
|
|
169
|
+
remaining -= used;
|
|
170
|
+
return { allocationId: slice.allocationId, reserved: slice.quantity, consumed: String(used) };
|
|
171
|
+
});
|
|
172
|
+
if (remaining)
|
|
173
|
+
throw new Error('USAGE_RESERVATION_BOUND_EXCEEDED');
|
|
174
|
+
return result;
|
|
175
|
+
}
|
|
176
|
+
/** Intersect factual stock levels with acquired quota/payer intervals. This is
|
|
177
|
+
* a quantity calculation, not a price engine, invoice or periodic stock writer. */
|
|
178
|
+
export function sliceUsageStock(window, terms) {
|
|
179
|
+
usageTime(window.from);
|
|
180
|
+
usageTime(window.to);
|
|
181
|
+
usageTime(window.openedAt);
|
|
182
|
+
if (window.from < window.openedAt || window.to < window.from || !Number.isSafeInteger(window.sourceRevision) || window.sourceRevision < 0 || window.changes.length > 200 || terms.length > 101)
|
|
183
|
+
throw new Error('USAGE_STOCK_WINDOW_INVALID');
|
|
184
|
+
const levels = [window.opening, ...window.changes];
|
|
185
|
+
let prior = window.opening;
|
|
186
|
+
for (const [index, level] of levels.entries()) {
|
|
187
|
+
usageTime(level.at);
|
|
188
|
+
usageInteger(level.measured);
|
|
189
|
+
usageInteger(level.reported);
|
|
190
|
+
if (!Number.isSafeInteger(level.revision) || level.revision < 0 || !Number.isSafeInteger(level.unqualifiedResources) || level.unqualifiedResources < 0 ||
|
|
191
|
+
!Number.isSafeInteger(level.unknownSubjects) || level.unknownSubjects < 0 || level.unknownSubjects > level.unqualifiedResources ||
|
|
192
|
+
(level.unqualifiedResources === 0 && (level.reported !== '0' || level.unknownSubjects !== 0)) ||
|
|
193
|
+
level.revision > window.sourceRevision || (index === 0 ? level.at > window.from :
|
|
194
|
+
level.at <= window.from || level.at < prior.at || level.at >= window.to || level.revision !== prior.revision + 1))
|
|
195
|
+
throw new Error('USAGE_STOCK_WINDOW_GAP');
|
|
196
|
+
prior = level;
|
|
197
|
+
}
|
|
198
|
+
const ordered = [...terms].sort((a, b) => a.from - b.from), cuts = new Set([window.from, window.to]);
|
|
199
|
+
let end = -1;
|
|
200
|
+
for (const item of ordered) {
|
|
201
|
+
for (const at of [item.from, item.to, item.period.start, item.period.end])
|
|
202
|
+
usageTime(at);
|
|
203
|
+
usageInteger(item.included);
|
|
204
|
+
if (!item.payerId || !item.contractId || !item.offerKey || item.from < item.period.start || item.to > item.period.end ||
|
|
205
|
+
item.from >= item.to || item.from < end)
|
|
206
|
+
throw new Error('USAGE_STOCK_TERMS_OVERLAP');
|
|
207
|
+
end = item.to;
|
|
208
|
+
if (item.from > window.from && item.from < window.to)
|
|
209
|
+
cuts.add(item.from);
|
|
210
|
+
if (item.to > window.from && item.to < window.to)
|
|
211
|
+
cuts.add(item.to);
|
|
212
|
+
}
|
|
213
|
+
for (const level of window.changes)
|
|
214
|
+
cuts.add(level.at);
|
|
215
|
+
const boundaries = [...cuts].sort((a, b) => a - b), slices = [];
|
|
216
|
+
let levelIndex = 0, termsIndex = 0;
|
|
217
|
+
for (let i = 1; i < boundaries.length; i++) {
|
|
218
|
+
const from = boundaries[i - 1], to = boundaries[i];
|
|
219
|
+
while (levelIndex + 1 < levels.length && levels[levelIndex + 1].at <= from)
|
|
220
|
+
levelIndex++;
|
|
221
|
+
while (termsIndex < ordered.length && ordered[termsIndex].to <= from)
|
|
222
|
+
termsIndex++;
|
|
223
|
+
const level = levels[levelIndex], acquired = ordered[termsIndex];
|
|
224
|
+
const active = acquired && acquired.from <= from && from < acquired.to ? acquired : null;
|
|
225
|
+
const base = { from, to, stockRevision: level.revision, terms: active };
|
|
226
|
+
if (!active)
|
|
227
|
+
slices.push({ ...base, status: 'unknown', reason: 'contract-unavailable' });
|
|
228
|
+
else if (level.unqualifiedResources)
|
|
229
|
+
slices.push({ ...base, status: 'unknown', reason: 'stock-unqualified' });
|
|
230
|
+
else
|
|
231
|
+
slices.push({ ...base, status: 'measured', stock: level.measured,
|
|
232
|
+
excessUnitMilliseconds: usageStockIntegral(level.measured, active.included, from, to) });
|
|
233
|
+
}
|
|
234
|
+
return slices;
|
|
235
|
+
}
|
package/package.json
CHANGED
|
@@ -1,12 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@storystick/types",
|
|
3
|
-
"version": "0.1.0-rc.
|
|
3
|
+
"version": "0.1.0-rc.5",
|
|
4
4
|
"license": "FSL-1.1-MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"main": "dist/index.js",
|
|
8
8
|
"types": "dist/index.d.ts",
|
|
9
9
|
"exports": {
|
|
10
|
+
"./editorial-target": {
|
|
11
|
+
"types": "./dist/editorial-target.d.ts",
|
|
12
|
+
"import": "./dist/editorial-target.js"
|
|
13
|
+
},
|
|
14
|
+
"./read-progress": {
|
|
15
|
+
"types": "./dist/read-progress.d.ts",
|
|
16
|
+
"import": "./dist/read-progress.js"
|
|
17
|
+
},
|
|
18
|
+
"./usage": {
|
|
19
|
+
"types": "./dist/usage.d.ts",
|
|
20
|
+
"import": "./dist/usage.js"
|
|
21
|
+
},
|
|
22
|
+
"./internal/content-plane-work": {
|
|
23
|
+
"types": "./dist/internal/content-plane-work.d.ts",
|
|
24
|
+
"import": "./dist/internal/content-plane-work.js"
|
|
25
|
+
},
|
|
26
|
+
"./internal/workspace-preview-address": {
|
|
27
|
+
"types": "./dist/internal/workspace-preview-address.d.ts",
|
|
28
|
+
"import": "./dist/internal/workspace-preview-address.js"
|
|
29
|
+
},
|
|
10
30
|
"./internal/private-file-session": {
|
|
11
31
|
"types": "./dist/internal/private-file-session.d.ts",
|
|
12
32
|
"import": "./dist/internal/private-file-session.js"
|
|
@@ -158,6 +178,10 @@
|
|
|
158
178
|
"./public-endpoints": {
|
|
159
179
|
"types": "./dist/public-endpoints.d.ts",
|
|
160
180
|
"import": "./dist/public-endpoints.js"
|
|
181
|
+
},
|
|
182
|
+
"./internal/usage-delivery": {
|
|
183
|
+
"types": "./dist/usage-delivery.d.ts",
|
|
184
|
+
"import": "./dist/usage-delivery.js"
|
|
161
185
|
}
|
|
162
186
|
},
|
|
163
187
|
"files": [
|