aicommunicator-plugin-check 0.0.0-stage → 0.2.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.
@@ -0,0 +1,76 @@
1
+ export interface Manifest {
2
+ id: string;
3
+ version: string;
4
+ dataVersion: number;
5
+ title?: string;
6
+ license?: string;
7
+ logic: string;
8
+ ui?: string;
9
+ /** 이 화면에서 무엇을 할 수 있는지(034 2절). 1,000자까지. */
10
+ about?: string;
11
+ /** 사람이 하려는 일과 그 일을 이 화면에서 하는 방법. 다섯 개까지, 각 글 300자까지. */
12
+ examples?: PluginExample[];
13
+ /** 실행 환경(034 2.1절). 없으면 { os: "any", external: [] } 로 본다. */
14
+ requires?: PluginRequires;
15
+ /** 이 플러그인이 맞춘 코어 계약의 버전 범위(036 4절). 지금은 `0.<숫자>` 한 가지다. 없으면 검사하지 않는다. */
16
+ protocol?: string;
17
+ /** 함께 설치되어 있어야 하는 다른 플러그인과 버전 범위(036 4절). 스무 개까지. */
18
+ dependencies?: Record<string, string>;
19
+ /** 상세 사용 설명서(037 5.1절). 패키지 안의 Markdown 파일 경로. 예: docs/manual.md */
20
+ manual?: string;
21
+ /** 사용 예제(037 5.1절). 다섯 개까지. file 은 패키지 안의 aic-sample/1 파일이다. */
22
+ samples?: PluginSample[];
23
+ /** 대표 아이콘(036 16절). ui/ 바로 아래의 SVG 파일 경로. 예: ui/icon.svg. 없어도 된다. 파일의 검사는 icon.ts 의 iconProblem 이다. */
24
+ icon?: string;
25
+ }
26
+ /** manifest 의 samples 항목(037 5.1절). */
27
+ export interface PluginSample {
28
+ /** 예제 id. 영어 소문자, 숫자, - 로 1자에서 40자. */
29
+ id: string;
30
+ title: string;
31
+ about: string;
32
+ file: string;
33
+ }
34
+ export interface PluginExample {
35
+ ask: string;
36
+ does: string;
37
+ }
38
+ export type OsName = 'windows' | 'macos' | 'linux';
39
+ /** 바깥 도구 하나(034 2.1절). */
40
+ export interface ExternalTool {
41
+ name: string;
42
+ kind: 'program' | 'web' | 'mcp';
43
+ account: 'none' | 'free' | 'paid';
44
+ install: boolean;
45
+ note?: string;
46
+ }
47
+ export interface PluginRequires {
48
+ os: 'any' | OsName[];
49
+ external: ExternalTool[];
50
+ }
51
+ /** 코어 안에 든 외부 연결의 패키지 이름(core 의 switch/editing.ts LINK_PACKAGE). 플러그인 id 로 받지 않는다. */
52
+ export declare const RESERVED_IDS: readonly string[];
53
+ /** dependencies 의 항목 수 한도. */
54
+ export declare const MAX_DEPENDENCIES = 20;
55
+ /** samples 의 항목 수 한도(037 7절 4번). */
56
+ export declare const MAX_SAMPLES = 5;
57
+ /** `계정이름.플러그인이름` 모양인가. 각 부분은 영어 소문자, 숫자, `-` 이고 2자에서 40자다(036 4절). */
58
+ export declare function isPluginId(id: unknown): id is string;
59
+ /** id 의 앞부분(계정 이름). */
60
+ export declare function idOwner(id: string): string;
61
+ /** 파일 이름 한 조각으로 쓸 수 있는가. `.` 과 `..` 은 폴더를 가리키므로 받지 않는다. */
62
+ export declare function isFileName(name: string): boolean;
63
+ /** 플러그인 폴더 안의 상대 경로인가. `/` 로 나눈 조각마다 파일 이름 모양이어야 한다. 절대 경로, `..`, `\` 는 받지 않는다. */
64
+ export declare function isPluginPath(p: unknown): p is string;
65
+ /** 화면 파일 경로인가. `ui/` 바로 아래의 파일 하나다. */
66
+ export declare function isUiPath(p: unknown): p is string;
67
+ /**
68
+ * manifest 의 칸 검사. 문제의 설명이고 없으면 null 이다. 소개, 예, 실행 환경, 계약 버전, 의존은 없어도 되지만 있으면 모양이
69
+ * 맞아야 한다. 조용히 자르면 등록 사이트와 코어가 다른 글을 보이게 되기 때문이다. 맨 위 층의 모르는 칸은 거절하지 않는다.
70
+ */
71
+ export declare function checkManifest(manifest: unknown): string | null;
72
+ /**
73
+ * 등록 사이트에 올릴 때의 검사. checkManifest 를 지나고, 사이트의 목록과 AI 의 추천을 만드는 칸(protocol, license, title, about)이
74
+ * 있어야 한다(036 4절). 묶음에 LICENSE 파일이 있는지는 checkBundleForRegistry 가 본다.
75
+ */
76
+ export declare function checkForRegistry(manifest: unknown): string | null;
@@ -0,0 +1,244 @@
1
+ // manifest 의 칸 검사(034 2절, 2.1절, 036 4절). 코어, aic 명령, 등록 사이트가 같은 검사를 쓴다(036 7절 5번).
2
+ import { isProtocolRange, isRange, isVersion } from "./version.js";
3
+ /** 코어 안에 든 외부 연결의 패키지 이름(core 의 switch/editing.ts LINK_PACKAGE). 플러그인 id 로 받지 않는다. */
4
+ export const RESERVED_IDS = ['aic.link'];
5
+ /** dependencies 의 항목 수 한도. */
6
+ export const MAX_DEPENDENCIES = 20;
7
+ /** samples 의 항목 수 한도(037 7절 4번). */
8
+ export const MAX_SAMPLES = 5;
9
+ const ID_PART = /^[a-z0-9-]{2,40}$/;
10
+ /** 예제 id. 읽기 도구와 화면 주소에 그대로 쓰므로 좁게 받는다. */
11
+ const SAMPLE_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
12
+ /** 폴더 없는 파일 이름. 코어가 `/plugin/<id>/ui/<파일>` 로 내보내는 모양과 같다. */
13
+ const FILE_NAME = /^[\w.-]+$/;
14
+ const OS_NAMES = ['windows', 'macos', 'linux'];
15
+ const TOOL_KINDS = ['program', 'web', 'mcp'];
16
+ const ACCOUNTS = ['none', 'free', 'paid'];
17
+ /** `계정이름.플러그인이름` 모양인가. 각 부분은 영어 소문자, 숫자, `-` 이고 2자에서 40자다(036 4절). */
18
+ export function isPluginId(id) {
19
+ if (typeof id !== 'string')
20
+ return false;
21
+ const parts = id.split('.');
22
+ return parts.length === 2 && parts.every((p) => ID_PART.test(p));
23
+ }
24
+ /** id 의 앞부분(계정 이름). */
25
+ export function idOwner(id) {
26
+ return id.split('.')[0];
27
+ }
28
+ /** 파일 이름 한 조각으로 쓸 수 있는가. `.` 과 `..` 은 폴더를 가리키므로 받지 않는다. */
29
+ export function isFileName(name) {
30
+ return FILE_NAME.test(name) && name !== '.' && name !== '..';
31
+ }
32
+ /** 플러그인 폴더 안의 상대 경로인가. `/` 로 나눈 조각마다 파일 이름 모양이어야 한다. 절대 경로, `..`, `\` 는 받지 않는다. */
33
+ export function isPluginPath(p) {
34
+ return typeof p === 'string' && p.length > 0 && p.length <= 200 && p.split('/').every(isFileName);
35
+ }
36
+ /** 화면 파일 경로인가. `ui/` 바로 아래의 파일 하나다. */
37
+ export function isUiPath(p) {
38
+ if (typeof p !== 'string' || !p.startsWith('ui/'))
39
+ return false;
40
+ return isFileName(p.slice(3));
41
+ }
42
+ /** 글자 수. 길이 한도는 UTF-16 코드 단위가 아니라 글자(코드 포인트)로 잰다. */
43
+ function chars(s) {
44
+ return [...s].length;
45
+ }
46
+ /** 비어 있지 않은 글이고 한도 안인가. 문제가 있으면 그 설명이다. */
47
+ function textProblem(where, value, max) {
48
+ if (typeof value !== 'string' || value.trim() === '')
49
+ return `${where} 은 비어 있지 않은 글이어야 한다`;
50
+ if (chars(value) > max)
51
+ return `${where} 이 ${max.toLocaleString('en-US')}자를 넘는다(${chars(value)}자)`;
52
+ return null;
53
+ }
54
+ /** 칸을 모두 아는 객체인가. 칸 이름을 잘못 적으면 조용히 빠지므로 모르는 칸은 받지 않는다. */
55
+ function objectProblem(where, value, known) {
56
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
57
+ return `${where} 은 객체여야 한다`;
58
+ const extra = Object.keys(value).filter((k) => !known.includes(k));
59
+ return extra.length > 0 ? `${where} 에 모르는 칸이 있다: ${extra.join(', ')}` : null;
60
+ }
61
+ function requiresProblem(value) {
62
+ const problem = objectProblem('requires', value, ['os', 'external']);
63
+ if (problem)
64
+ return problem;
65
+ const r = value;
66
+ if (r.os !== undefined && r.os !== 'any') {
67
+ if (!Array.isArray(r.os) || r.os.length === 0)
68
+ return 'requires.os 는 "any" 이거나 windows, macos, linux 의 목록이어야 한다';
69
+ const bad = r.os.filter((o) => typeof o !== 'string' || !OS_NAMES.includes(o));
70
+ if (bad.length > 0)
71
+ return `requires.os 에 모르는 운영체제가 있다: ${bad.map((o) => JSON.stringify(o)).join(', ')}`;
72
+ if (new Set(r.os).size !== r.os.length)
73
+ return 'requires.os 에 같은 운영체제가 반복된다';
74
+ }
75
+ if (r.external !== undefined) {
76
+ if (!Array.isArray(r.external))
77
+ return 'requires.external 은 바깥 도구의 목록이어야 한다';
78
+ if (r.external.length > 10)
79
+ return `requires.external 은 열 개까지다(${r.external.length}개)`;
80
+ for (const [i, t] of r.external.entries()) {
81
+ const where = `requires.external[${i}]`;
82
+ const shape = objectProblem(where, t, ['name', 'kind', 'account', 'install', 'note']);
83
+ if (shape)
84
+ return shape;
85
+ const tool = t;
86
+ const name = textProblem(`${where}.name`, tool.name, 100);
87
+ if (name)
88
+ return name;
89
+ if (typeof tool.kind !== 'string' || !TOOL_KINDS.includes(tool.kind))
90
+ return `${where}.kind 는 program, web, mcp 가운데 하나여야 한다`;
91
+ if (typeof tool.account !== 'string' || !ACCOUNTS.includes(tool.account))
92
+ return `${where}.account 는 none, free, paid 가운데 하나여야 한다`;
93
+ if (typeof tool.install !== 'boolean')
94
+ return `${where}.install 은 참이나 거짓이어야 한다`;
95
+ if (tool.note !== undefined) {
96
+ const note = textProblem(`${where}.note`, tool.note, 200);
97
+ if (note)
98
+ return note;
99
+ }
100
+ }
101
+ }
102
+ return null;
103
+ }
104
+ /**
105
+ * 설명서와 예제의 칸(037 5.1절). 파일이 묶음에 있는지와 글의 한도는 묶음 검사(readBundle)가 본다. 여기는 경로와 글의 모양만 본다.
106
+ * 설명서는 Markdown(.md), 예제는 JSON(.json) 파일이고 둘 다 플러그인 폴더 안의 상대 경로다. 같은 예제 id 나 같은 파일이 둘이면 거절한다.
107
+ */
108
+ function manualProblem(m) {
109
+ if (m.manual !== undefined && (!isPluginPath(m.manual) || !m.manual.endsWith('.md'))) {
110
+ return `manual ${JSON.stringify(m.manual)} 는 플러그인 폴더 안의 Markdown 파일(.md) 상대 경로여야 한다(예: docs/manual.md)`;
111
+ }
112
+ if (m.samples === undefined)
113
+ return null;
114
+ if (!Array.isArray(m.samples))
115
+ return 'samples 는 { id, title, about, file } 의 목록이어야 한다';
116
+ if (m.samples.length > MAX_SAMPLES)
117
+ return `samples 는 다섯 개까지다(${m.samples.length}개)`;
118
+ const ids = new Set();
119
+ const files = new Set();
120
+ for (const [i, s] of m.samples.entries()) {
121
+ const where = `samples[${i}]`;
122
+ const shape = objectProblem(where, s, ['id', 'title', 'about', 'file']);
123
+ if (shape)
124
+ return shape;
125
+ const sample = s;
126
+ if (typeof sample.id !== 'string' || !SAMPLE_ID.test(sample.id))
127
+ return `${where}.id 는 영어 소문자, 숫자, - 로 1자에서 40자여야 한다`;
128
+ const text = textProblem(`${where}.title`, sample.title, 100) ?? textProblem(`${where}.about`, sample.about, 300);
129
+ if (text)
130
+ return text;
131
+ if (!isPluginPath(sample.file) || !sample.file.endsWith('.json'))
132
+ return `${where}.file ${JSON.stringify(sample.file)} 는 플러그인 폴더 안의 예제 파일(.json) 상대 경로여야 한다(예: samples/first.json)`;
133
+ if (ids.has(sample.id))
134
+ return `samples 에 같은 id ${sample.id} 가 둘이다`;
135
+ if (files.has(sample.file))
136
+ return `samples 에 같은 파일 ${sample.file} 이 둘이다`;
137
+ ids.add(sample.id);
138
+ files.add(sample.file);
139
+ }
140
+ return null;
141
+ }
142
+ function dependenciesProblem(id, value) {
143
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
144
+ return 'dependencies 는 { "<id>": "<버전 범위>" } 객체여야 한다';
145
+ const entries = Object.entries(value);
146
+ if (entries.length > MAX_DEPENDENCIES)
147
+ return `dependencies 는 ${MAX_DEPENDENCIES}개까지다(${entries.length}개)`;
148
+ for (const [dep, range] of entries) {
149
+ if (!isPluginId(dep))
150
+ return `dependencies 의 ${JSON.stringify(dep)} 는 플러그인 id 모양이 아니다`;
151
+ if (RESERVED_IDS.includes(dep))
152
+ return `dependencies 에 ${dep} 를 적지 않는다. 코어 안에 든 이름이다`;
153
+ if (dep === id)
154
+ return 'dependencies 에 자기 자신을 적지 않는다';
155
+ if (!isRange(range))
156
+ return `dependencies.${dep} 의 ${JSON.stringify(range)} 는 1.2.3, ^1.2.3, ~1.2.3, >=1.2.3 가운데 한 모양이어야 한다`;
157
+ }
158
+ return null;
159
+ }
160
+ /**
161
+ * manifest 의 칸 검사. 문제의 설명이고 없으면 null 이다. 소개, 예, 실행 환경, 계약 버전, 의존은 없어도 되지만 있으면 모양이
162
+ * 맞아야 한다. 조용히 자르면 등록 사이트와 코어가 다른 글을 보이게 되기 때문이다. 맨 위 층의 모르는 칸은 거절하지 않는다.
163
+ */
164
+ export function checkManifest(manifest) {
165
+ if (typeof manifest !== 'object' || manifest === null || Array.isArray(manifest))
166
+ return 'manifest 는 객체여야 한다';
167
+ const m = manifest;
168
+ for (const key of ['id', 'version', 'logic']) {
169
+ if (typeof m[key] !== 'string')
170
+ return `manifest 에 ${key} 가 없다`;
171
+ }
172
+ const id = m.id;
173
+ if (!isPluginId(id))
174
+ return `id ${JSON.stringify(id)} 는 계정이름.플러그인이름 모양이어야 한다. 각 부분은 영어 소문자, 숫자, - 로 2자에서 40자다`;
175
+ if (RESERVED_IDS.includes(id))
176
+ return `id ${id} 는 코어 안에 든 이름이라 플러그인 id 로 쓰지 않는다`;
177
+ if (!isVersion(m.version))
178
+ return `version ${JSON.stringify(m.version)} 는 semver(숫자.숫자.숫자, 뒤에 -미리보기이름 가능)여야 한다`;
179
+ if (typeof m.dataVersion !== 'number' || !Number.isInteger(m.dataVersion) || m.dataVersion < 1)
180
+ return 'dataVersion 은 1 이상의 정수여야 한다';
181
+ if (!isPluginPath(m.logic))
182
+ return `logic ${JSON.stringify(m.logic)} 는 플러그인 폴더 안의 상대 경로여야 한다(.. 과 절대 경로는 받지 않는다)`;
183
+ if (m.ui !== undefined && !isUiPath(m.ui))
184
+ return `ui ${JSON.stringify(m.ui)} 는 ui/ 바로 아래의 파일이어야 한다(예: ui/index.html)`;
185
+ // 아이콘은 코어가 내보내는 ui/ 의 파일이어야 화면이 읽는다. icon.ts 의 isIconPath 와 같은 모양이다(서로 불러오지 않게 여기에 적는다)
186
+ if (m.icon !== undefined && (!isUiPath(m.icon) || !m.icon.toLowerCase().endsWith('.svg'))) {
187
+ return `icon ${JSON.stringify(m.icon)} 는 ui/ 바로 아래의 SVG 파일(.svg)이어야 한다(예: ui/icon.svg)`;
188
+ }
189
+ if (m.title !== undefined) {
190
+ const problem = textProblem('title', m.title, 100);
191
+ if (problem)
192
+ return problem;
193
+ }
194
+ if (m.license !== undefined) {
195
+ const problem = textProblem('license', m.license, 100);
196
+ if (problem)
197
+ return problem;
198
+ }
199
+ if (m.about !== undefined) {
200
+ const problem = textProblem('about', m.about, 1000);
201
+ if (problem)
202
+ return problem;
203
+ }
204
+ if (m.examples !== undefined) {
205
+ if (!Array.isArray(m.examples))
206
+ return 'examples 는 { ask, does } 의 목록이어야 한다';
207
+ if (m.examples.length > 5)
208
+ return `examples 는 다섯 개까지다(${m.examples.length}개)`;
209
+ for (const [i, e] of m.examples.entries()) {
210
+ const where = `examples[${i}]`;
211
+ const problem = objectProblem(where, e, ['ask', 'does']) ??
212
+ textProblem(`${where}.ask`, e.ask, 300) ??
213
+ textProblem(`${where}.does`, e.does, 300);
214
+ if (problem)
215
+ return problem;
216
+ }
217
+ }
218
+ if (m.requires !== undefined) {
219
+ const problem = requiresProblem(m.requires);
220
+ if (problem)
221
+ return problem;
222
+ }
223
+ if (m.protocol !== undefined && !isProtocolRange(m.protocol)) {
224
+ return `protocol ${JSON.stringify(m.protocol)} 는 0.<숫자> 모양이어야 한다(예: "0.1")`;
225
+ }
226
+ if (m.dependencies !== undefined) {
227
+ const problem = dependenciesProblem(id, m.dependencies);
228
+ if (problem)
229
+ return problem;
230
+ }
231
+ return manualProblem(m);
232
+ }
233
+ /**
234
+ * 등록 사이트에 올릴 때의 검사. checkManifest 를 지나고, 사이트의 목록과 AI 의 추천을 만드는 칸(protocol, license, title, about)이
235
+ * 있어야 한다(036 4절). 묶음에 LICENSE 파일이 있는지는 checkBundleForRegistry 가 본다.
236
+ */
237
+ export function checkForRegistry(manifest) {
238
+ const problem = checkManifest(manifest);
239
+ if (problem)
240
+ return problem;
241
+ const m = manifest;
242
+ const missing = ['protocol', 'license', 'title', 'about'].filter((k) => m[k] === undefined);
243
+ return missing.length > 0 ? `사이트에 올리려면 manifest 에 ${missing.join(', ')} 칸이 있어야 한다` : null;
244
+ }
@@ -0,0 +1,60 @@
1
+ export declare const MESSAGE_TABLE_FORMAT = "aic-link-messages/1";
2
+ /** 표 파일의 크기 한도(바이트). */
3
+ export declare const MESSAGE_TABLE_MAX_BYTES: number;
4
+ /** 한 표의 메시지 수 한도. */
5
+ export declare const MESSAGE_TABLE_MAX_MESSAGES = 100;
6
+ /** 메시지 글 하나의 길이 한도. 글은 ASCII 라 글자 수와 바이트 수가 같다. */
7
+ export declare const MESSAGE_TEXT_MAX = 200;
8
+ /** enum 값의 낱말 수와 낱말 하나의 길이 한도. */
9
+ export declare const MESSAGE_ENUM_MAX_VALUES = 20;
10
+ export declare const MESSAGE_ENUM_WORD_MAX = 40;
11
+ /** 값을 넣어 푼 글의 길이 한도. 넘으면 값이 틀린 것으로 다룬다. */
12
+ export declare const MESSAGE_RENDERED_MAX = 400;
13
+ /** date 값의 길이 한도. RFC 3339 의 소수 자리로 글을 길게 늘이지 못하게 한다. */
14
+ export declare const MESSAGE_DATE_MAX = 40;
15
+ export type MessageValueType = 'integer' | 'number' | 'date' | 'id' | 'enum';
16
+ export declare const MESSAGE_VALUE_TYPES: readonly MessageValueType[];
17
+ /** 값 하나의 종류. 자유 글 값은 없다. */
18
+ export type MessageValueSpec = {
19
+ type: 'integer' | 'number' | 'date' | 'id';
20
+ } | {
21
+ type: 'enum';
22
+ values: string[];
23
+ };
24
+ export interface MessageDef {
25
+ /** 영어 글. {이름} 은 values 에 적은 값이 들어갈 자리다. */
26
+ text: string;
27
+ values?: Record<string, MessageValueSpec>;
28
+ }
29
+ export interface MessageTable {
30
+ format: typeof MESSAGE_TABLE_FORMAT;
31
+ version: string;
32
+ messages: Record<string, MessageDef>;
33
+ }
34
+ export type MessageTableCheck = {
35
+ ok: true;
36
+ table: MessageTable;
37
+ } | {
38
+ ok: false;
39
+ problems: string[];
40
+ };
41
+ /** 메시지 id 의 모양인가. 모양이 틀린 id 는 AI 에게 옮겨 적지 않는다. */
42
+ export declare function isMessageId(v: unknown): v is string;
43
+ /**
44
+ * 메시지 표 파일을 검사한다(032 31.3절). 통과하지 못한 표는 통째로 쓰지 않는다. 파일은 64KB 까지, 메시지는 100개까지, id 는
45
+ * `^[a-z][a-z0-9_]{0,63}$`, 글과 값의 규칙은 textProblems 와 valuesProblems 다. 까닭은 사람의 화면에만 보인다.
46
+ */
47
+ export declare function checkMessageTable(data: Uint8Array | string): MessageTableCheck;
48
+ /**
49
+ * 메시지 id 와 값을 글로 푼다(032 31.3절). 표가 없거나 등록하지 않은 id 는 unknown_id, 값이 빠지거나 더 있거나 종류가 틀리면
50
+ * bad_values, id 의 모양이 틀리면 malformed_id 다. 값을 넣은 글에 표의 글과 같은 주소 검사를 다시 하고, 걸리거나 400자를 넘으면
51
+ * bad_values 다. 주소 검사에서 수와 날짜 값 안의 소수점(0.5, 10:00:00.5Z)은 주소로 보지 않는다. 그 값 하나로는 주소가 되지 않고, 보면
52
+ * 소수가 든 number 값을 늘 거절하게 되기 때문이다. 풀지 못하면 글을 만들지 않는다.
53
+ */
54
+ export declare function renderMessage(table: MessageTable | null, id: unknown, values: unknown): {
55
+ ok: true;
56
+ text: string;
57
+ } | {
58
+ ok: false;
59
+ why: 'malformed_id' | 'unknown_id' | 'bad_values';
60
+ };
@@ -0,0 +1,256 @@
1
+ // 외부 연결의 메시지 표(032 31.3절). 제조사가 AI 에게 보낼 글을 미리 표로 내고, 실행할 때는 자유 글 대신 메시지 id 와 값만 보낸다.
2
+ // 등록할 때 검사한 글만 AI 에게 간다. 코어는 연결 정의의 messages 파일을 이 검사로 받고, 등록 사이트(036)가 열리면 같은 검사에
3
+ // 사람의 검토를 더한다. 표 파일을 읽는 것과 지문(sha256)은 부르는 쪽이 한다. 여기는 글과 값만 본다.
4
+ import { isVersion } from "./version.js";
5
+ export const MESSAGE_TABLE_FORMAT = 'aic-link-messages/1';
6
+ /** 표 파일의 크기 한도(바이트). */
7
+ export const MESSAGE_TABLE_MAX_BYTES = 64 * 1024;
8
+ /** 한 표의 메시지 수 한도. */
9
+ export const MESSAGE_TABLE_MAX_MESSAGES = 100;
10
+ /** 메시지 글 하나의 길이 한도. 글은 ASCII 라 글자 수와 바이트 수가 같다. */
11
+ export const MESSAGE_TEXT_MAX = 200;
12
+ /** enum 값의 낱말 수와 낱말 하나의 길이 한도. */
13
+ export const MESSAGE_ENUM_MAX_VALUES = 20;
14
+ export const MESSAGE_ENUM_WORD_MAX = 40;
15
+ /** 값을 넣어 푼 글의 길이 한도. 넘으면 값이 틀린 것으로 다룬다. */
16
+ export const MESSAGE_RENDERED_MAX = 400;
17
+ /** date 값의 길이 한도. RFC 3339 의 소수 자리로 글을 길게 늘이지 못하게 한다. */
18
+ export const MESSAGE_DATE_MAX = 40;
19
+ /** 검사가 돌려주는 까닭의 수 한도. 나머지는 수만 적는다. */
20
+ const MAX_PROBLEMS = 50;
21
+ const MESSAGE_ID = /^[a-z][a-z0-9_]{0,63}$/;
22
+ /** 글 안의 {이름}. 설계(032 31.3절)가 정하지 않아 메시지 id 와 같은 모양에 32자로 정했다. */
23
+ const VALUE_NAME = /^[a-z][a-z0-9_]{0,31}$/;
24
+ const PLACEHOLDER = /\{([^{}]*)\}/g;
25
+ /** id 값. 마침표와 : 와 / 를 받지 않는다. 값을 넣어 주소(evil.com, https:)를 만들지 못하게 하기 위해서다. */
26
+ const ID_VALUE = /^[A-Za-z0-9_-]{1,64}$/;
27
+ /** {이름} 바로 앞과 뒤에 올 수 있는 글자. 빈칸과 문장 부호뿐이다. 글 끝의 마침표는 valueEdgeProblems 가 따로 본다. */
28
+ const VALUE_EDGE = /^[ ,;!?()'"]$/;
29
+ const ENUM_WORD = /^[A-Za-z0-9 _-]+$/;
30
+ const DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
31
+ const RFC3339 = /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/;
32
+ export const MESSAGE_VALUE_TYPES = ['integer', 'number', 'date', 'id', 'enum'];
33
+ /** 메시지 id 의 모양인가. 모양이 틀린 id 는 AI 에게 옮겨 적지 않는다. */
34
+ export function isMessageId(v) {
35
+ return typeof v === 'string' && MESSAGE_ID.test(v);
36
+ }
37
+ function isPlainObject(v) {
38
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
39
+ }
40
+ /** 글에 주소처럼 보이는 것(://, www., 글자 사이의 마침표, @)이 있는가. 표의 글과 값을 넣어 푼 글에 같이 쓴다. */
41
+ function hasAddress(text) {
42
+ return text.includes('://') || /www\./i.test(text) || /[A-Za-z0-9]\.[A-Za-z0-9]/.test(text) || text.includes('@');
43
+ }
44
+ /**
45
+ * {이름} 의 앞뒤 글자. 바로 앞과 뒤는 글 처음이나 끝, 빈칸, 문장 부호(, ; ! ? ( ) ' ")여야 한다. 마침표는 {이름} 바로 뒤에서 그 뒤가 빈칸이나
46
+ * 글 끝일 때(문장 끝)만 받는다. 값을 마침표, /, : 나 다른 값과 붙여 주소를 만들지 못하게 하기 위해서다(`{s}//{h}.{t}` 같은 것).
47
+ */
48
+ function valueEdgeProblems(text) {
49
+ const out = [];
50
+ for (const m of text.matchAll(PLACEHOLDER)) {
51
+ const start = m.index ?? 0;
52
+ const end = start + m[0].length;
53
+ const before = start === 0 ? null : text[start - 1];
54
+ const after = end >= text.length ? null : text[end];
55
+ const beforeOk = before === null || VALUE_EDGE.test(before);
56
+ const afterOk = after === null || VALUE_EDGE.test(after) || (after === '.' && (end + 1 >= text.length || text[end + 1] === ' '));
57
+ if (!beforeOk || !afterOk) {
58
+ out.push(`{${m[1]}} 의 바로 앞과 뒤는 빈칸이나 문장 부호(, ; ! ? ( ) ' ")여야 한다. 마침표는 문장 끝(뒤가 빈칸이나 글 끝)에만 붙인다`);
59
+ }
60
+ }
61
+ return out;
62
+ }
63
+ /**
64
+ * 메시지 글 하나의 까닭들. 영어(눈에 보이는 ASCII 0x20 에서 0x7E, 글자 하나 이상), 200자까지, 주소를 넣지 못하고(://, www., 글자
65
+ * 사이의 마침표, @), < > [ ] 역따옴표 역슬래시를 받지 않는다. {이름} 은 values 에 적은 것만 쓰고, 적은 것은 한 번 이상 나와야 하며, 앞뒤는
66
+ * 빈칸이나 문장 부호다(valueEdgeProblems).
67
+ */
68
+ function textProblems(text, names) {
69
+ if (typeof text !== 'string' || text === '')
70
+ return ['text 는 비어 있지 않은 글이어야 한다'];
71
+ const out = [];
72
+ if (text.length > MESSAGE_TEXT_MAX)
73
+ out.push(`글이 ${MESSAGE_TEXT_MAX}자를 넘는다(${text.length}자)`);
74
+ if ([...text].some((c) => c.charCodeAt(0) < 0x20 || c.charCodeAt(0) > 0x7e))
75
+ out.push('글에는 눈에 보이는 ASCII(0x20 에서 0x7E)만 쓴다. 줄바꿈과 영어 밖의 글자를 받지 않는다');
76
+ if (!/[A-Za-z]/.test(text))
77
+ out.push('글은 영어 문장이어야 한다');
78
+ if (hasAddress(text))
79
+ out.push('글에 주소를 넣지 못한다(://, www., 글자 사이의 마침표, @ 를 받지 않는다)');
80
+ if (/[<>[\]`\\]/.test(text))
81
+ out.push('글에 < > [ ] 역따옴표 역슬래시를 쓰지 않는다');
82
+ out.push(...valueEdgeProblems(text));
83
+ const used = new Set();
84
+ for (const m of text.matchAll(PLACEHOLDER)) {
85
+ const name = m[1];
86
+ if (!VALUE_NAME.test(name))
87
+ out.push(`{${name}} 은 값의 이름 모양(영어 소문자로 시작, 소문자와 숫자와 _ 로 32자까지)이 아니다`);
88
+ else if (!names.includes(name))
89
+ out.push(`{${name}} 은 values 에 없다`);
90
+ used.add(name);
91
+ }
92
+ if (/[{}]/.test(text.replace(PLACEHOLDER, '')))
93
+ out.push('짝이 맞지 않는 { 나 } 가 있다');
94
+ for (const n of names)
95
+ if (!used.has(n))
96
+ out.push(`values 의 ${n} 이 글에 나오지 않는다`);
97
+ return out;
98
+ }
99
+ /** values 의 까닭들. 이름마다 종류 하나이고, enum 은 낱말 목록을 함께 적는다. */
100
+ function valuesProblems(values) {
101
+ if (values === undefined)
102
+ return [];
103
+ if (!isPlainObject(values))
104
+ return ['values 는 이름마다 종류를 적은 객체여야 한다'];
105
+ const out = [];
106
+ for (const [name, spec] of Object.entries(values)) {
107
+ const at = `값 ${name}`;
108
+ if (!VALUE_NAME.test(name))
109
+ out.push(`${at}: 이름은 영어 소문자로 시작하고 소문자와 숫자와 _ 로 32자까지다`);
110
+ if (!isPlainObject(spec) || !MESSAGE_VALUE_TYPES.includes(spec.type)) {
111
+ out.push(`${at}: type 은 ${MESSAGE_VALUE_TYPES.join(', ')} 가운데 하나다. 자유 글 값은 없다`);
112
+ continue;
113
+ }
114
+ const extra = Object.keys(spec).filter((k) => k !== 'type' && !(spec.type === 'enum' && k === 'values'));
115
+ if (extra.length)
116
+ out.push(`${at}: 모르는 칸 ${extra.join(', ')}`);
117
+ if (spec.type !== 'enum')
118
+ continue;
119
+ const words = spec.values;
120
+ if (!Array.isArray(words) || words.length === 0 || words.length > MESSAGE_ENUM_MAX_VALUES) {
121
+ out.push(`${at}: enum 의 values 는 낱말 1개에서 ${MESSAGE_ENUM_MAX_VALUES}개의 목록이다`);
122
+ continue;
123
+ }
124
+ for (const w of words) {
125
+ if (typeof w !== 'string' || w.length > MESSAGE_ENUM_WORD_MAX || !ENUM_WORD.test(w)) {
126
+ out.push(`${at}: enum 낱말은 영어 글자와 숫자와 빈칸과 _- 로 ${MESSAGE_ENUM_WORD_MAX}자까지다`);
127
+ break;
128
+ }
129
+ }
130
+ if (new Set(words).size !== words.length)
131
+ out.push(`${at}: enum 낱말이 겹친다`);
132
+ }
133
+ return out;
134
+ }
135
+ /**
136
+ * 메시지 표 파일을 검사한다(032 31.3절). 통과하지 못한 표는 통째로 쓰지 않는다. 파일은 64KB 까지, 메시지는 100개까지, id 는
137
+ * `^[a-z][a-z0-9_]{0,63}$`, 글과 값의 규칙은 textProblems 와 valuesProblems 다. 까닭은 사람의 화면에만 보인다.
138
+ */
139
+ export function checkMessageTable(data) {
140
+ const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data;
141
+ if (bytes.byteLength > MESSAGE_TABLE_MAX_BYTES)
142
+ return { ok: false, problems: [`표 파일이 ${MESSAGE_TABLE_MAX_BYTES} 바이트를 넘는다(${bytes.byteLength} 바이트)`] };
143
+ let raw;
144
+ try {
145
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
146
+ raw = JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
147
+ }
148
+ catch {
149
+ // 해석기의 글은 파일의 일부를 옮겨 적을 수 있어 까닭은 적지 않는다.
150
+ return { ok: false, problems: ['표 파일이 UTF-8 JSON 이 아니다'] };
151
+ }
152
+ if (!isPlainObject(raw))
153
+ return { ok: false, problems: ['표는 format, version, messages 를 적은 객체여야 한다'] };
154
+ const problems = [];
155
+ const extra = Object.keys(raw).filter((k) => !['format', 'version', 'messages'].includes(k));
156
+ if (extra.length)
157
+ problems.push(`모르는 칸: ${extra.join(', ')}`);
158
+ if (raw.format !== MESSAGE_TABLE_FORMAT)
159
+ problems.push(`format 은 ${MESSAGE_TABLE_FORMAT} 이어야 한다`);
160
+ if (!isVersion(raw.version))
161
+ problems.push('version 은 1.0.0 같은 semver 여야 한다');
162
+ if (!isPlainObject(raw.messages)) {
163
+ problems.push('messages 는 메시지 id 마다 글을 적은 객체여야 한다');
164
+ return { ok: false, problems };
165
+ }
166
+ const entries = Object.entries(raw.messages);
167
+ if (entries.length === 0)
168
+ problems.push('messages 가 비었다');
169
+ if (entries.length > MESSAGE_TABLE_MAX_MESSAGES)
170
+ problems.push(`메시지가 ${MESSAGE_TABLE_MAX_MESSAGES}개를 넘는다(${entries.length}개)`);
171
+ for (const [id, def] of entries) {
172
+ const at = `메시지 ${MESSAGE_ID.test(id) ? id : '(모양이 틀린 id)'}`;
173
+ if (!MESSAGE_ID.test(id))
174
+ problems.push(`${at}: id 는 영어 소문자로 시작하고 소문자와 숫자와 _ 로 64자까지다`);
175
+ if (!isPlainObject(def)) {
176
+ problems.push(`${at}: text 와 values 를 적은 객체여야 한다`);
177
+ continue;
178
+ }
179
+ const unknown = Object.keys(def).filter((k) => k !== 'text' && k !== 'values');
180
+ if (unknown.length)
181
+ problems.push(`${at}: 모르는 칸 ${unknown.join(', ')}`);
182
+ const vp = valuesProblems(def.values);
183
+ for (const p of vp)
184
+ problems.push(`${at}: ${p}`);
185
+ const names = isPlainObject(def.values) ? Object.keys(def.values) : [];
186
+ for (const p of textProblems(def.text, names))
187
+ problems.push(`${at}: ${p}`);
188
+ }
189
+ if (problems.length > 0) {
190
+ const shown = problems.slice(0, MAX_PROBLEMS);
191
+ if (problems.length > MAX_PROBLEMS)
192
+ shown.push(`그 밖에 ${problems.length - MAX_PROBLEMS}개`);
193
+ return { ok: false, problems: shown };
194
+ }
195
+ return { ok: true, table: raw };
196
+ }
197
+ /** 날짜 값: `YYYY-MM-DD` 나 RFC 3339 의 날짜와 시각. 40자까지이고 달력에 있는 날이어야 한다. */
198
+ function isDateValue(v) {
199
+ if (v.length > MESSAGE_DATE_MAX)
200
+ return false;
201
+ const time = RFC3339.exec(v);
202
+ const m = DAY.exec(v) ?? time;
203
+ if (!m)
204
+ return false;
205
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
206
+ const day = new Date(Date.UTC(y, mo - 1, d));
207
+ if (day.getUTCFullYear() !== y || day.getUTCMonth() !== mo - 1 || day.getUTCDate() !== d)
208
+ return false;
209
+ return !time || (Number(time[4]) <= 23 && Number(time[5]) <= 59 && Number(time[6]) <= 60);
210
+ }
211
+ /** 값 하나가 그 종류에 맞는가. */
212
+ function valueFits(spec, v) {
213
+ switch (spec.type) {
214
+ case 'integer':
215
+ return typeof v === 'number' && Number.isSafeInteger(v);
216
+ case 'number':
217
+ return typeof v === 'number' && Number.isFinite(v);
218
+ case 'date':
219
+ return typeof v === 'string' && isDateValue(v);
220
+ case 'id':
221
+ return typeof v === 'string' && ID_VALUE.test(v);
222
+ case 'enum':
223
+ return typeof v === 'string' && spec.values.includes(v);
224
+ default:
225
+ return false;
226
+ }
227
+ }
228
+ /**
229
+ * 메시지 id 와 값을 글로 푼다(032 31.3절). 표가 없거나 등록하지 않은 id 는 unknown_id, 값이 빠지거나 더 있거나 종류가 틀리면
230
+ * bad_values, id 의 모양이 틀리면 malformed_id 다. 값을 넣은 글에 표의 글과 같은 주소 검사를 다시 하고, 걸리거나 400자를 넘으면
231
+ * bad_values 다. 주소 검사에서 수와 날짜 값 안의 소수점(0.5, 10:00:00.5Z)은 주소로 보지 않는다. 그 값 하나로는 주소가 되지 않고, 보면
232
+ * 소수가 든 number 값을 늘 거절하게 되기 때문이다. 풀지 못하면 글을 만들지 않는다.
233
+ */
234
+ export function renderMessage(table, id, values) {
235
+ if (!isMessageId(id))
236
+ return { ok: false, why: 'malformed_id' };
237
+ if (!table || !Object.hasOwn(table.messages, id))
238
+ return { ok: false, why: 'unknown_id' };
239
+ const def = table.messages[id];
240
+ const given = values === undefined ? {} : values;
241
+ if (!isPlainObject(given))
242
+ return { ok: false, why: 'bad_values' };
243
+ const specs = def.values ?? {};
244
+ const names = Object.keys(specs);
245
+ if (Object.keys(given).some((k) => !Object.hasOwn(specs, k)))
246
+ return { ok: false, why: 'bad_values' };
247
+ for (const n of names)
248
+ if (!Object.hasOwn(given, n) || !valueFits(specs[n], given[n]))
249
+ return { ok: false, why: 'bad_values' };
250
+ const text = def.text.replace(PLACEHOLDER, (_, n) => String(given[n]));
251
+ const numeric = (n) => specs[n].type === 'integer' || specs[n].type === 'number' || specs[n].type === 'date';
252
+ const probe = def.text.replace(PLACEHOLDER, (_, n) => (numeric(n) ? String(given[n]).replace(/\./g, '_') : String(given[n])));
253
+ if (text.length > MESSAGE_RENDERED_MAX || hasAddress(probe))
254
+ return { ok: false, why: 'bad_values' };
255
+ return { ok: true, text };
256
+ }