@appgrowstack/app-contract 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,13 @@
1
+ export * from "./generated/schema.js";
2
+ export * from "./rpc.js";
3
+ export * from "./http.js";
4
+ export * from "./events.js";
5
+ export * from "./access.js";
6
+ export * from "./sessions.js";
7
+ export * from "./registry.js";
8
+ export * from "./reviews.js";
9
+ export * from "./creatives.js";
10
+ export * from "./ledger.js";
11
+ export * from "./signals.js";
12
+ export * from "./audience.js";
13
+ export * from "./client.js";
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ export * from "./generated/schema.js";
2
+ export * from "./rpc.js";
3
+ export * from "./http.js";
4
+ export * from "./events.js";
5
+ export * from "./access.js";
6
+ export * from "./sessions.js";
7
+ export * from "./registry.js";
8
+ export * from "./reviews.js";
9
+ export * from "./creatives.js";
10
+ export * from "./ledger.js";
11
+ export * from "./signals.js";
12
+ export * from "./audience.js";
13
+ export * from "./client.js";
@@ -0,0 +1,4 @@
1
+ export declare const LEDGER_HYPOTHESIS_ID: RegExp;
2
+ export declare const TITLE_MAX = 30;
3
+ export declare function titleProblem(title: string): string | null;
4
+ export declare function fitTitle(...candidates: readonly string[]): string;
package/dist/ledger.js ADDED
@@ -0,0 +1,18 @@
1
+ export const LEDGER_HYPOTHESIS_ID = /^hyp_[A-Za-z0-9]{16}$/;
2
+ export const TITLE_MAX = 30;
3
+ export function titleProblem(title) {
4
+ const n = [...title.trim()].length;
5
+ if (n === 0)
6
+ return "題が空";
7
+ if (n > TITLE_MAX)
8
+ return `題は${TITLE_MAX}字まで(${n}字)。何を変えて、何が上がるかだけを書き、長い説明は本文に書く`;
9
+ if (/[\n。]/.test(title))
10
+ return "題は1行の句にする(改行と「。」を入れない)";
11
+ return null;
12
+ }
13
+ export function fitTitle(...candidates) {
14
+ const fit = candidates.find((c) => titleProblem(c) === null);
15
+ if (fit === undefined)
16
+ throw new Error(`${TITLE_MAX}字に収まる題が無い: ${candidates.join(" / ")}`);
17
+ return fit;
18
+ }
@@ -0,0 +1,2 @@
1
+ import { type JsonSchema } from "./operations.js";
2
+ export declare function buildOpenApi(): JsonSchema;
@@ -0,0 +1,78 @@
1
+ import { pendingApprovalBody, workers } from "./http.js";
2
+ import { listOperations, SchemaBundler } from "./operations.js";
3
+ const ERROR_BODY = ["common.schema.json", "errorBody"];
4
+ const STATUS_TEXT = {
5
+ 101: "WebSocket に切り替える",
6
+ 200: "成功",
7
+ 201: "作った",
8
+ 202: "承認の依頼を作った(実行していない)",
9
+ 204: "成功(本文なし)",
10
+ 302: "行き先へ移る",
11
+ 304: "変わっていない",
12
+ };
13
+ function openApiPath(path) {
14
+ return path.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, "{$1}");
15
+ }
16
+ function operationObject(op, b) {
17
+ const responses = {};
18
+ const ok = op.response;
19
+ responses[String(ok.status)] = ok.body
20
+ ? { description: STATUS_TEXT[ok.status] ?? "成功", content: { "application/json": { schema: { $ref: b.ref(ok.body) } } } }
21
+ : ok.status === 200
22
+ ? { description: "成功(本文はファイルそのもの)", content: { "application/octet-stream": {} } }
23
+ : { description: STATUS_TEXT[ok.status] ?? "成功" };
24
+ if (op.mayReturnPendingApproval)
25
+ responses["202"] = { description: STATUS_TEXT[202], content: { "application/json": { schema: { $ref: b.ref(pendingApprovalBody) } } } };
26
+ const error = { content: { "application/json": { schema: { $ref: b.ref(ERROR_BODY) } } } };
27
+ responses["4XX"] = { description: "受けられない(ErrorBody)", ...error };
28
+ responses["5XX"] = { description: "サーバーの誤り(ErrorBody)", ...error };
29
+ const out = {
30
+ operationId: op.name,
31
+ tags: [op.context],
32
+ summary: op.name,
33
+ ...(op.description ? { description: op.description } : {}),
34
+ };
35
+ if (op.pathParams.length > 0)
36
+ out.parameters = op.pathParams.map((p) => ({ name: p, in: "path", required: true, schema: { type: "string" } }));
37
+ if (op.streamedBody)
38
+ out.requestBody = { required: true, content: { "application/octet-stream": {} } };
39
+ else if (op.request)
40
+ out.requestBody = { required: true, content: { "application/json": { schema: { $ref: b.ref(op.request) } } } };
41
+ out.responses = responses;
42
+ out["x-permission"] = op.permission;
43
+ out["x-ai"] = op.ai;
44
+ out["x-approval"] = op.approval;
45
+ return out;
46
+ }
47
+ export function buildOpenApi() {
48
+ const b = new SchemaBundler("#/components/schemas/");
49
+ const paths = {};
50
+ for (const op of listOperations()) {
51
+ const p = (paths[openApiPath(op.path)] ??= {});
52
+ const method = op.method.toLowerCase();
53
+ if (p[method])
54
+ throw new Error(`道と動詞が重なっている: ${op.method} ${op.path}`);
55
+ p[method] = operationObject(op, b);
56
+ }
57
+ const schemas = Object.fromEntries(Object.entries(b.defs).sort(([a], [z]) => a.localeCompare(z)));
58
+ return {
59
+ openapi: "3.1.0",
60
+ jsonSchemaDialect: "https://json-schema.org/draft/2020-12/schema",
61
+ info: {
62
+ title: "appgrowstack 管理の API",
63
+ version: "v1",
64
+ description: "appgrowstack-core の管理の API。packages/contract の coreEndpoints と access.ts から bun run docs:gen が作る。手で直さない。" +
65
+ "外の扉は Cloudflare Access、中は core のトークン(ut_・at_)。x-permission は権限の名前、x-ai はエージェントの上限、x-approval は承認と記録(access.ts)",
66
+ },
67
+ servers: [{ url: `https://${workers.core.host}` }, { url: `https://${workers.core.stagingHost}` }],
68
+ security: [{ accessServiceToken: [], coreToken: [] }],
69
+ paths,
70
+ components: {
71
+ schemas,
72
+ securitySchemes: {
73
+ accessServiceToken: { type: "apiKey", in: "header", name: "CF-Access-Client-Id", description: "Cloudflare Access のサービストークン(CF-Access-Client-Secret と組)" },
74
+ coreToken: { type: "http", scheme: "bearer", description: "core のトークン。本人は ut_、エージェントは at_" },
75
+ },
76
+ },
77
+ };
78
+ }
@@ -0,0 +1,53 @@
1
+ import { type AgentGrant, type ApprovalRule, type DataLevel, type PermissionName } from "./access.js";
2
+ import type { PermissionGroup } from "./generated/schema.js";
3
+ import { coreEndpoints, type Endpoint, type SchemaRef } from "./http.js";
4
+ export type OperationName = keyof typeof coreEndpoints;
5
+ export type JsonSchema = Record<string, unknown>;
6
+ export interface Operation {
7
+ name: OperationName;
8
+ method: Endpoint["method"];
9
+ path: string;
10
+ pathParams: string[];
11
+ context: string;
12
+ permission: PermissionName | null;
13
+ group: PermissionGroup | null;
14
+ ai: AgentGrant | null;
15
+ approval: ApprovalRule | null;
16
+ level: DataLevel;
17
+ mayReturnPendingApproval: boolean;
18
+ streamedBody: boolean;
19
+ request: SchemaRef | null;
20
+ response: Endpoint["response"];
21
+ description: string;
22
+ permissionNote: string;
23
+ }
24
+ export declare function pathParamsOf(path: string): string[];
25
+ export declare function listOperations(): Operation[];
26
+ export declare function isOperationName(name: string): name is OperationName;
27
+ export declare function getOperation(name: string): Operation | null;
28
+ export declare function findOperations(query: string, filter?: {
29
+ context?: string;
30
+ permission?: PermissionName;
31
+ writes?: boolean;
32
+ }): Operation[];
33
+ export declare class SchemaBundler {
34
+ private readonly refPrefix;
35
+ private readonly documents;
36
+ readonly defs: Record<string, JsonSchema>;
37
+ private readonly seen;
38
+ constructor(refPrefix: string, documents?: Readonly<Record<string, unknown>>);
39
+ ref(ref: SchemaRef): string;
40
+ inline(ref: SchemaRef): JsonSchema;
41
+ private node;
42
+ private add;
43
+ private rewrite;
44
+ private resolve;
45
+ }
46
+ export declare function resolveSchema(ref: SchemaRef): JsonSchema;
47
+ export declare function operationInputSchema(name: OperationName): JsonSchema;
48
+ export declare function operationOutputSchema(name: OperationName): JsonSchema | null;
49
+ export declare function describeOperation(name: string): (Operation & {
50
+ input: JsonSchema;
51
+ output: JsonSchema | null;
52
+ pendingApproval: JsonSchema | null;
53
+ }) | null;
@@ -0,0 +1,205 @@
1
+ import { permissions } from "./access.js";
2
+ import { schemaDocuments } from "./generated/schemas.js";
3
+ import { coreEndpoints, pendingApprovalBody, STREAMED_BODY_ENDPOINTS } from "./http.js";
4
+ function toOperation(name) {
5
+ const e = coreEndpoints[name];
6
+ const auth = e.auth;
7
+ const permission = auth.kind === "member" ? auth.permission : null;
8
+ const rule = permission ? permissions[permission] : null;
9
+ return {
10
+ name,
11
+ method: e.method,
12
+ path: e.path,
13
+ pathParams: pathParamsOf(e.path),
14
+ context: e.path.split("/")[2] ?? "",
15
+ permission,
16
+ group: rule?.group ?? null,
17
+ ai: rule?.ai ?? null,
18
+ approval: rule?.approval ?? null,
19
+ level: rule?.level ?? null,
20
+ mayReturnPendingApproval: permission ? mayReturnPendingApproval(permission) : false,
21
+ streamedBody: STREAMED_BODY_ENDPOINTS.has(name),
22
+ request: e.request,
23
+ response: e.response,
24
+ description: e.note,
25
+ permissionNote: rule?.note ?? "",
26
+ };
27
+ }
28
+ function mayReturnPendingApproval(name) {
29
+ const ai = permissions[name].ai;
30
+ return ai === "request" || ai === "request_own";
31
+ }
32
+ export function pathParamsOf(path) {
33
+ return [...path.matchAll(/:([A-Za-z_][A-Za-z0-9_]*)/g)].map((m) => m[1]);
34
+ }
35
+ export function listOperations() {
36
+ return Object.keys(coreEndpoints).map(toOperation);
37
+ }
38
+ export function isOperationName(name) {
39
+ return Object.hasOwn(coreEndpoints, name);
40
+ }
41
+ export function getOperation(name) {
42
+ return isOperationName(name) ? toOperation(name) : null;
43
+ }
44
+ export function findOperations(query, filter = {}) {
45
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);
46
+ return listOperations().filter((op) => {
47
+ if (filter.context !== undefined && op.context !== filter.context)
48
+ return false;
49
+ if (filter.permission !== undefined && op.permission !== filter.permission)
50
+ return false;
51
+ if (filter.writes !== undefined && (op.method !== "GET") !== filter.writes)
52
+ return false;
53
+ const text = `${op.name} ${op.method} ${op.path} ${op.permission ?? ""} ${op.description} ${op.permissionNote}`.toLowerCase();
54
+ return words.every((w) => text.includes(w));
55
+ });
56
+ }
57
+ const SCHEMA_BASE = "https://appgrowstack.com/schema/v1/";
58
+ const SCHEMA_MAPS = new Set(["properties", "patternProperties", "$defs", "dependentSchemas"]);
59
+ function decodePointer(seg) {
60
+ return seg.replace(/~1/g, "/").replace(/~0/g, "~");
61
+ }
62
+ function at(doc, pointer) {
63
+ let node = doc;
64
+ for (const seg of pointer.split("/").filter(Boolean).map(decodePointer)) {
65
+ if (node === null || typeof node !== "object")
66
+ return undefined;
67
+ node = node[seg];
68
+ }
69
+ return node;
70
+ }
71
+ function joinPath(fromFile, ref) {
72
+ const parts = fromFile.split("/").slice(0, -1);
73
+ for (const seg of ref.split("/")) {
74
+ if (seg === "..")
75
+ parts.pop();
76
+ else if (seg !== "." && seg !== "")
77
+ parts.push(seg);
78
+ }
79
+ return parts.join("/");
80
+ }
81
+ function defKey(file, pointer) {
82
+ const head = file.replace(/\.schema\.json$/, "").replace(/\//g, ".");
83
+ const segs = pointer.split("/").filter(Boolean).map(decodePointer);
84
+ const tail = segs[0] === "$defs" && segs.length === 2 ? [segs[1]] : segs;
85
+ return [head, ...tail].join(".").replace(/[^A-Za-z0-9._-]/g, "_");
86
+ }
87
+ export class SchemaBundler {
88
+ refPrefix;
89
+ documents;
90
+ defs = {};
91
+ seen = new Map();
92
+ constructor(refPrefix, documents = schemaDocuments) {
93
+ this.refPrefix = refPrefix;
94
+ this.documents = documents;
95
+ }
96
+ ref(ref) {
97
+ return this.refPrefix + this.add(ref[0], ref[1] ? `/$defs/${ref[1]}` : "");
98
+ }
99
+ inline(ref) {
100
+ const pointer = ref[1] ? `/$defs/${ref[1]}` : "";
101
+ return this.rewrite(this.node(ref[0], pointer), ref[0], pointer === "");
102
+ }
103
+ node(file, pointer) {
104
+ const doc = this.documents[file];
105
+ if (doc === undefined)
106
+ throw new Error(`schema が無い: ${file}`);
107
+ const node = at(doc, pointer);
108
+ if (node === undefined)
109
+ throw new Error(`schema の中に無い: ${file}#${pointer}`);
110
+ return node;
111
+ }
112
+ add(file, pointer) {
113
+ const id = `${file}#${pointer}`;
114
+ const known = this.seen.get(id);
115
+ if (known)
116
+ return known;
117
+ const key = defKey(file, pointer);
118
+ if (Object.hasOwn(this.defs, key))
119
+ throw new Error(`部品の名前がぶつかった: ${key}(${id})`);
120
+ this.seen.set(id, key);
121
+ this.defs[key] = {};
122
+ this.defs[key] = this.rewrite(this.node(file, pointer), file, pointer === "");
123
+ return key;
124
+ }
125
+ rewrite(node, file, isRoot, schemaMap = false) {
126
+ if (Array.isArray(node))
127
+ return node.map((n) => this.rewrite(n, file, false));
128
+ if (node === null || typeof node !== "object")
129
+ return node;
130
+ const out = {};
131
+ if (schemaMap) {
132
+ for (const [k, v] of Object.entries(node))
133
+ out[k] = this.rewrite(v, file, false);
134
+ return out;
135
+ }
136
+ for (const [k, v] of Object.entries(node)) {
137
+ if (SCHEMA_MAPS.has(k)) {
138
+ if (!(isRoot && k === "$defs"))
139
+ out[k] = this.rewrite(v, file, false, true);
140
+ continue;
141
+ }
142
+ if (isRoot && (k === "$id" || k === "$schema" || k === "$defs"))
143
+ continue;
144
+ if (k === "$ref" && typeof v === "string") {
145
+ out[k] = this.refPrefix + this.resolve(v, file);
146
+ continue;
147
+ }
148
+ out[k] = k === "const" || k === "enum" || k === "examples" || k === "default" ? v : this.rewrite(v, file, false);
149
+ }
150
+ return out;
151
+ }
152
+ resolve(ref, fromFile) {
153
+ const [target, fragment = ""] = (ref.startsWith(SCHEMA_BASE) ? ref.slice(SCHEMA_BASE.length) : ref).split("#");
154
+ const file = target ? (ref.startsWith(SCHEMA_BASE) ? target : joinPath(fromFile, target)) : fromFile;
155
+ return this.add(file, fragment);
156
+ }
157
+ }
158
+ export function resolveSchema(ref) {
159
+ const b = new SchemaBundler("#/$defs/");
160
+ const root = b.inline(ref);
161
+ return withDefs({ $schema: "https://json-schema.org/draft/2020-12/schema", ...root }, b.defs);
162
+ }
163
+ function withDefs(schema, defs) {
164
+ return Object.keys(defs).length > 0 ? { ...schema, $defs: defs } : schema;
165
+ }
166
+ export function operationInputSchema(name) {
167
+ const op = toOperation(name);
168
+ const b = new SchemaBundler("#/$defs/");
169
+ const properties = {};
170
+ const required = [];
171
+ if (op.pathParams.length > 0) {
172
+ properties.path = {
173
+ type: "object",
174
+ additionalProperties: false,
175
+ required: op.pathParams,
176
+ properties: Object.fromEntries(op.pathParams.map((p) => [p, { type: "string", minLength: 1 }])),
177
+ };
178
+ required.push("path");
179
+ }
180
+ properties.query = {
181
+ type: "object",
182
+ description: `クエリ。使える名前は操作の説明に書いてある: ${op.description}`,
183
+ additionalProperties: { type: ["string", "number", "boolean"] },
184
+ };
185
+ if (op.request && !op.streamedBody) {
186
+ properties.body = b.inline(op.request);
187
+ required.push("body");
188
+ }
189
+ return withDefs({ $schema: "https://json-schema.org/draft/2020-12/schema", type: "object", additionalProperties: false, required, properties }, b.defs);
190
+ }
191
+ export function operationOutputSchema(name) {
192
+ const body = coreEndpoints[name].response.body;
193
+ return body ? resolveSchema(body) : null;
194
+ }
195
+ export function describeOperation(name) {
196
+ if (!isOperationName(name))
197
+ return null;
198
+ const op = toOperation(name);
199
+ return {
200
+ ...op,
201
+ input: operationInputSchema(name),
202
+ output: operationOutputSchema(name),
203
+ pendingApproval: op.mayReturnPendingApproval ? resolveSchema(pendingApprovalBody) : null,
204
+ };
205
+ }
@@ -0,0 +1,3 @@
1
+ import type { PendingItem } from "./generated/schema.js";
2
+ export declare const RESERVED_PROJECT_IDS: readonly ["approvals", "search", "audit", "settings", "login", "logout", "static", "new", "api", "portfolio", "findings", "hypotheses", "templates", "references", "experiments"];
3
+ export declare function pendingCommand(item: PendingItem): string;
@@ -0,0 +1,15 @@
1
+ export const RESERVED_PROJECT_IDS = ["approvals", "search", "audit", "settings", "login", "logout", "static", "new", "api", "portfolio", "findings", "hypotheses", "templates", "references", "experiments"];
2
+ export function pendingCommand(item) {
3
+ switch (item.kind) {
4
+ case "access_approval":
5
+ return `app-growth approvals show ${item.id}`;
6
+ case "notify_variant":
7
+ return `app-growth notify show ${item.project ?? "<project>"} ${item.id}`;
8
+ case "support_draft":
9
+ return `app-growth inbox show ${item.ticket_id ?? item.id}`;
10
+ case "insights_finding":
11
+ return `app-growth insights findings show ${item.id}`;
12
+ case "creative_variant":
13
+ return `app-growth creatives variants show ${item.project ?? "<project>"} ${item.id}`;
14
+ }
15
+ }
@@ -0,0 +1,3 @@
1
+ import type { ReviewStore } from "./generated/schema.js";
2
+ export declare const REVIEW_STORES: readonly ["app_store", "google_play"];
3
+ export declare const REVIEW_REPLY_LIMITS: Record<ReviewStore, number>;
@@ -0,0 +1,2 @@
1
+ export const REVIEW_STORES = ["app_store", "google_play"];
2
+ export const REVIEW_REPLY_LIMITS = { app_store: 5970, google_play: 350 };