## 데이터와 HTML 안의 로그인
일반 자료 열은 columns의 position을 columnKey로 바꿔 사용한다. 답안 결과 열은 선택한 입력 묶음의 displayedResults.resultColumns와 resultColumnGroups에서 position, entrySetKey, fieldKey를 확인한다. storage=entries인 D열 답안은 short.data.entries(entrySetKey)의 values[fieldKey]로 저장하고 short-tests stored에는 tableKey=entrySetKey, column=fieldKey를 사용한다. readOnly=true 또는 retired=true인 과거 열은 get/getFinal로 조회한다. resultColumnGroups와 displayedResults는 AI 요청문 안내 정보다. short-data-plan에는 기존 허용 schema만 사용한다. 사이트를 수정할 때 기존 entrySets.key와 fields.key를 유지한다.
교사는 데이터 화면의 2열과 2행에 머리글과 자료를 입력한다. 행과 열 추가로 확장하고 열 머리글의 삭제 버튼으로 필요 없는 열을 제거한다. 자료 형식과 권한은 AI의 선언을 플랫폼이 검증한다. 로그인 정보는 같은 데이터 표에 입력한다. HTML의 login 선언에 따라 서버 인증을 자동 적용한다. 사전에 설정한 사람만 접근하는 사이트도 HTML을 먼저 열어 HTML 안의 로그인 화면을 보여 준다. 데이터 조회와 저장은 서버가 로그인 및 현재 신원을 검사한다.
사용자가 복사한 요청문에는 실제 열 위치, columnKey, label, type, siteId, fingerprint와 현재 dataPlan이 포함된다. A열, B열, C열이라는 교사의 설명을 해당 고정 columnKey로 바꿔 사용한다. label과 열 위치는 표시 정보다. 실제 명단과 비밀번호 원문은 요청문에 포함하지 않는다. 플랫폼이 short SDK를 첫 실행 스크립트 앞에 삽입한다. 별도 SDK 설치 없이 await short.ready 후 사용한다. short-data-plan을 사용하는 HTML은 SDK v2 데이터 계약을 사용한다. 기존 short-config를 추가할 필요가 있는 기존 기능은 같은 설정의 key와 revision을 사용한다.
HTML에는 application/json인 short-data-plan을 한 번 선언한다. 닫힌 JSON schema는 다음과 같다. 알 수 없는 속성, 중복 JSON 속성, 같은 저장 key, 잘못된 타입, 참조 순환은 오류다. 전체 선언은 64KiB, 한 데이터 표의 칸은 64개, entrySets는 24개까지다.
{
"version": 1,
"base": {"siteId": "복사한 현재 siteId", "fingerprint": "복사한 현재 fingerprint"},
"login": {"identifierColumns": ["A열 실제 columnKey"], "passwordColumn": "B열 실제 columnKey"},
"profileFields": [
{"columnKey": "A열 실제 columnKey", "use": "current-member-read"},
{"columnKey": "C열 실제 columnKey", "use": "current-member-read"}
],
"entrySets": []
}
데이터를 사용하지 않는 HTML은 {version:1,mode:"no-data",base:{siteId,fingerprint}}로 선언한다. base는 현재 요청문 값을 그대로 쓰고 fingerprint를 계산하거나 추측하지 않는다. 이미 준비한 동일 HTML을 다시 게시하는 경우 플랫폼이 현재 구조와 기존 선언을 확인한다.
profileFields의 기존 칸은 {columnKey,use}, 새 칸은 {key,label,type,use}다. 새 칸을 준비하면 key가 실제 columnKey가 되어 row.data[key]로 읽는다. use는 current-member-read(자기 자료), public-read(모든 방문자), member-shared-read(모든 회원 읽기), member-shared-write(회원 공동 수정)다. 비밀번호 칸은 읽기 선언에서 제외한다. 로그인 식별 칸을 공동 수정으로 선언할 수 없다. type은 text, number, boolean, date, longtext, file, reference다. 신원, 비밀번호, 작성자, 시각, 제출 상태는 서버가 관리한다. 선언에 새 reference profile 칸이 필요하면 기존 참조 계약을 사용해야 한다.
공동 수정은 선언한 열을 회원들이 읽고 고칠 수 있다는 뜻이다. 각 데이터 행은 별도의 값을 가진다. short.data.profile.get()/patch()는 로그인한 자기 행만 선택한다. 모두가 같은 메모를 고치려면 short.db.collection(현재 tableKey).list()로 공동 행을 선택한 다음 그 id로 get(id)/patch(id,{sharedNote:value},{expectedRevision:row.revision})한다. 공동 행을 고르는 기준과 선택 UI를 HTML에 구현하고, 다른 회원도 같은 행을 선택했을 때 저장값이 보이는 흐름을 검사한다. current-member-read 열은 다른 행 조회에서도 자기 행의 값만 반환한다.
login의 식별 열은 1~8개 문자 열이다. 비밀번호 열은 현재 요청문의 columns에서 password:true인 실제 열이다. 교사가 머리글을 비밀번호(또는 암호, password)로 입력한 열을 플랫폼이 안전하게 준비한다. 아직 password:true인 열이 없으면 교사에게 같은 데이터 표에 비밀번호 머리글과 값을 입력하고 저장하도록 요청한다. 비밀번호는 교사가 8~64자로 지정하며 빈 새 비밀번호는 경고 후 저장을 막는다. 앞자리 0을 보존한다. 같은 식별값이 두 행에 있으면 준비가 실패하므로 고유한 학번이나 아이디 열을 함께 선언한다. AI는 교사의 로그인 요청에 맞춰 identifierColumns를 선택한다.
HTML 안의 로그인 예:
await short.ready;
const profile = await short.auth.login({c1: nameInput.value, password: passwordInput.value});
const row = await short.data.profile.get();
scoreOutput.textContent = row?.data.c3 == null ? "미입력" : String(row.data.c3) + "점";
위 c1/c3은 현재 요청문의 실제 key로 바꾼다. short.auth.current()는 Promise<Profile|null>이다. null이면 HTML의 로그인 화면, Profile이면 자신의 화면을 연다. short.auth.subscribe(listener)는 unsubscribe 함수를 반환한다. 로그인 변경 시 이전 사람의 화면과 입력을 정리하고 늦게 도착한 이전 조회를 폐기한다. 오류는 {message,code,status,category,outcome,requestId?,argumentPath?}인 ShortError다. LOGIN_FAILED는 입력 확인, AUTH_REQUIRED/SESSION_EXPIRED/SESSION_REVOKED는 HTML 로그인 화면으로 돌아가 입력을 받는다. 네트워크 오류에도 입력을 보존한다.
## 새 답안과 제출 기록 자동 준비
표에 학번과 이름만 있어도 AI가 entrySets에 필요한 답안 칸을 선언하면 플랫폼이 새 저장 구조를 준비한다. 교사에게 열 형식이나 필수값 설정을 요구하지 않는다. 한 사람의 단일 기록은 single, 차수별 기록은 per-round, 계속 새 기록을 추가하면 repeated다. 회원 로그인에는 actor member, 공개 입력에는 visitor를 사용한다. lifecycle은 draft-final이다.
entrySets 예:
[{"key":"responses","label":"답안","actor":"member","cardinality":"per-round","lifecycle":"draft-final","definition":{"key":"question","revision":1,"content":"질문 원문"},"fields":[{"key":"answer","label":"답안","type":"longtext","requiredOnSubmit":true}]}]
새 key는 영문으로 시작하는 48자 이하 key다. label은 100자 이하다. definition.content는 질문 원문이고 revision은 1 이상의 정수다. 질문을 바꾸면 revision을 높인다. 이미 열린 작성은 시작 당시 fields와 definition에 고정되며 과거 제출에도 질문 원문을 보존한다. fields는 {key,label,type,requiredOnSubmit?,defaultValue?,query?,reference?}다. 기본값은 해당 자료형으로 검증한다. reference는 {entrySetKey,fieldKey}이며 자기 제출 기록의 workId만 연결한다. file은 const {file}=await short.storage.upload(선택한파일,{workId}) 후 file.id를 저장한다. 질문과 새 입력 key는 실제 사용자 요청에 맞춰 작성한다.
const entries = short.data.entries("responses");
let current = await entries.open();
let inputRevision = Math.max(1, current.inputRevision);
answerInput.value = current.values.answer ?? "";
questionOutput.textContent = current.definition.content;
answerInput.addEventListener("input", () => {
inputRevision++;
void entries.autosave({workId:current.workId,inputRevision,values:{answer:answerInput.value}})
.then(result => {current = result.current;}).catch(showError);
});
submitButton.addEventListener("click", async () => {
answerInput.disabled = true;
try {
const result = await entries.submit({workId:current.workId,inputRevision,values:{answer:answerInput.value},definitionRevision:current.definition.revision});
current = result.current;
showSubmitted(await entries.getFinal(current.workId));
} catch (error) { showError(error); answerInput.disabled = false; }
});
사용자가 처음부터 입력을 바꾸지 않았어도 저장/제출 inputRevision은 1 이상으로 전달한다. autosave 대기 Promise를 제출 전에 await하지 않는다. submit은 마지막 화면 값을 복제해 한 요청으로 저장하고 제출한다. 이미 같은 차수와 내용이 자동 저장됐어도 제출할 수 있다. 초안 복구는 open/get 후 entries.restore(workId)에서 draft.values와 inputRevision을 서버 값과 비교해 사용자에게 복구할 내용을 보여 준다. 서버 저장이 확인될 때까지 입력을 유지한다. 예제의 showError/showSubmitted와 DOM 요소는 HTML에서 정의한다.
entries.list({limit:1~50,after:nextCursor,round?})는 {records,nextCursor}, getFinal(workId,finalRevision?)은 {workId,finalRevision,values,definition,submittedAt,round}를 반환한다. 모든 기록과 파일 및 참조는 현재 사용자의 권한으로 검사한다. 페이지 cursor에는 반환한 문자열을 그대로 전달한다.
list.records의 각 항목은 open/get과 같은 {workId,revision,inputRevision,schemaRevision,definition,fields,values,state,round,finalRevision,updatedAt}다. 목록의 첫 항목을 제출본으로 가정하지 말고 state === "final"인 기록을 선택한다. repeated는 open()을 호출할 때마다 새 기록을 만든다. 새로고침에서는 list()로 기존 draft를 찾고 get(workId)로 이어 쓰며, 새 답안 버튼에서 open()을 호출한다. 제출 기록은 getFinal(workId,finalRevision)로 질문과 답안 원문을 함께 연다. single과 per-round는 open()으로 해당 기록을 다시 연다.
entries.restore(workId)는 {draft:null} 또는 {draft:{values,inputRevision,...}}를 반환한다. 입력할 때 autosave가 호스트 복구본을 바로 캡처하며 서버 저장은 최대 60초 간격이다. 새로고침 뒤 같은 사용자와 workId로 restore하여 서버 값과 비교한다. 사용자 A와 B의 복구본은 별도로 보관한다. 제출 확인 뒤 해당 입력의 복구본을 정리한다. 응답 유실 시 같은 requestId와 입력으로 다시 요청하고 short.requests.result(requestId)로 결과를 확인한다.
## 자동 검사와 AI 수정 요청
short-tests의 전체 schema와 예제는 다음 자동 검사 절을 따른다. 실제 로그인 UI에 가상 A와 B의 식별값 및 비밀번호를 입력하고 버튼을 누른다. 자기 자료의 서로 다른 값을 화면에서 확인한다. 저장은 stored에 column=entrySets.fields.key와 tableKey=entrySets.key를 사용하고, 마지막 input의 sample.id를 같게 유지한다. state draft/final을 확인한다. 저장 후 reload와 화면 복원을 검사한다. 플랫폼이 데스크톱 1037px와 휴대폰 390px에서 실행한다. text/value는 비동기 결과를 최대 6초 기다리며 검사 대상은 실제 표시된 DOM selector다. 실행할 버튼마다 이후 결과 확인을 넣는다.
각 scenario와 화면 크기는 새 가상 DB로 시작한다. 한 scenario의 A와 B는 같은 DB를 사용해 사용자별 격리를 검사한다. reload는 DB와 같은 사용자의 호스트 복구본을 유지한다. autosave 단계는 SDK 자동 저장 타이머를 즉시 실행하므로 60초 대기를 넣지 않는다. current-member-read로 선언한 개인 자료 칸은 실제 SDK 조회와 그 반환값을 화면에 표시한 assertion을 각각 포함한다. 이름 로그인 입력란만 확인하는 검사는 성적 조회 검사를 충족하지 못한다.
HTML 업로드 시 플랫폼이 short-data-plan을 검증하고 후보 저장 구조를 준비한다. 후보에는 현재 HTML hash, plan hash, fingerprint, 서버 보호 검사 hash가 묶인다. 자동 화면 검사가 끝난 후보를 HTML과 함께 게시한다. 자료 공개 범위를 넓히는 변경은 구체적 영향 확인 후 게시한다. 오류의 code, 선언/HTML 위치, 원인, 수정 행동과 전체 HTML 및 최신 데이터 계약을 AI 수정 요청에 포함한다. 교사는 수정 요청 전체를 복사해 외부 AI에게 전달한다.
로그인 준비는 한 번에 10행씩 처리하고 플랫폼이 같은 요청을 자동으로 이어 간다. preparing 응답의 preparedRows는 준비한 행 수이며 ready가 되어야 자동 검사와 게시를 진행한다. 동일 HTML과 현재 데이터 구조의 준비 결과는 재사용한다. 식별 열이나 비밀번호, 행 구성이 바뀌면 현재 자료로 다시 준비한다.
현재 HTML의 entrySets에서 빠진 과거 입력 묶음은 제작자의 데이터 화면에서 보관 기록으로 조회한다. 시작 당시 질문, 입력 칸과 제출자 식별값으로 원문과 제출 이력을 표시하며 파일과 CSV를 내려받을 수 있다. 과거 기록을 조회하는 entries.get/getFinal은 유지하고 새 save/submit에는 현재 선언에 있는 묶음 key를 사용한다. 이미 성공한 동일 requestId와 동일 입력의 결과는 재확인할 수 있다.
제작자 전용 RPC data.entries.ownerSets({limit?,after?})는 현재 입력 묶음과 보관 묶음을 1~20개씩 반환한다. records의 각 항목에는 key, label, actor, definition, fields, retired가 있으며 현재 묶음에는 cardinality와 lifecycle도 있다. nextCursor, snapshotAt, snapshotRevision, schemaRevision을 함께 반환한다. data.entries.ownerPage/exportPage({key,limit?,after?})는 같은 snapshot에서 원문과 제출 이력을 1~50개씩 조회하며 retired=true인 묶음은 조회와 회수 화면으로 표시한다. 이 관리 RPC는 제작자의 데이터 화면에서 사용한다.
## 플랫폼의 자동 동작 검사
플랫폼은 제작자가 오류 검사 버튼을 누르면 가상 사용자 A와 B로 로그인, 버튼 실행, 화면 결과와 실제 저장값 및 다시 열기를 자동으로 확인합니다. HTML 안에 아래 short-tests 검사 순서를 함께 제공하세요. 교사가 검사 코드를 작성하거나 가상 계정을 입력할 필요는 없습니다.
<script id="short-tests" type="application/json">
{"version":1,"scenarios":[{"name":"학생별 자료 조회","steps":[{"action":"fill","selector":"#studentNumber","value":{"column":"c1"}},{"action":"fill","selector":"#password","value":{"password":true}},{"action":"click","selector":"#login"},{"action":"text","selector":"#score","value":{"column":"c3"}},{"action":"click","selector":"#logout"},{"action":"text","selector":"#login","value":"로그인"}]}]}
</script>
위 예제의 selector와 column은 실제 HTML 및 현재 데이터의 key에 맞춰 바꾸세요. 시나리오는 목적별 기능 메뉴가 아닌 임의의 동작 순서입니다. 가상 값은 플랫폼이 현재 열 형식에 맞춰 준비하며 실제 운영 자료와 비밀번호는 검사에 전달하지 않습니다. A의 첫 숫자 값은 0, B는 85이며 다른 숫자 열도 서로 다른 값으로 준비합니다.
- 각 scenario에는 name과 steps를 작성합니다. 최대 6개 시나리오, 시나리오당 30단계, 전체 60단계입니다. 플랫폼이 컴퓨터와 휴대폰 화면에서 A와 B 또는 서로 다른 방문자로 각각 같은 순서를 실행합니다. 로그인 정보는 value:{column:"식별 열의 key"}, 비밀번호는 value:{password:true}로 채웁니다. 이름도 식별 열이면 그 입력을 추가하세요.
- fill은 입력, textarea, select 및 체크박스에 value를 넣고 실제 input/change 이벤트를 보냅니다. click은 실제 버튼 selector를 클릭합니다. text는 요소 textContent에 값이 포함되는지, value는 입력값이 같은지 확인합니다. selector는 실제 화면에 표시된 요소를 가리켜야 합니다.
- value에는 문자, 숫자 0과 boolean false도 사용할 수 있습니다. {column:"c3"}은 현재 가상 사용자의 해당 열 값입니다. {sample:"text"}, {sample:"number"}, {sample:"boolean"}, {sample:"date"}는 서로 다른 사용자의 검사 입력입니다. 처음과 마지막 답안을 구분할 때는 {sample:"text",id:"first"}와 {sample:"text",id:"last"}로 입력을 구분하고 stored와 재접속 확인에서도 같은 id를 사용하세요. 다른 사용자의 값이 필요한 단계는 actor:"student-b" 또는 "student-a"를 value 객체에 넣습니다. 기존 다중 자료 연결을 사용하는 HTML은 value.tableKey로 대상 key를 지정할 수 있습니다.
- stored는 column과 value를 사용하여 화면이 아닌 가상 DB에 실제 저장됐는지 확인합니다. 작성 확정을 검사할 때 state:"final"을 추가합니다. removed는 삭제 후 같은 값이 없음을 확인합니다. 저장 또는 삭제 버튼의 실제 SDK 호출과 결과를 연결하세요. 새 입력을 채운 시나리오는 stored를 포함하세요.
- autosave는 SDK에서 예약한 자동 저장을 즉시 실행합니다. 자동 저장을 확인할 때 fill, autosave, stored 순서를 쓰세요.
- reload는 같은 가상 DB와 로그인 세션을 유지한 채 HTML을 다시 엽니다. 저장 뒤에는 reload하고 text 또는 value로 마지막 입력이 화면에 복원됐는지 확인하세요. 단순 조회에서는 로그인한 사용자의 열 값을 text 또는 value로 확인하세요.
- file은 selector의 파일 입력에 가상 텍스트 파일을 선택합니다. 이 파일의 업로드 및 저장 결과도 검사 순서에 연결합니다. value:{uploadedFile:true}는 방금 업로드한 가상 파일 ID입니다. 자동 검사에서는 운영체제 파일 선택창을 열지 않습니다.
- 모든 화면에서 표시되는 주요 버튼의 클릭과 결과 확인을 전체 시나리오에 나누어 포함합니다. 플랫폼은 각 사용자와 화면 크기에서 전체 시나리오의 버튼 검사 결과를 합쳐 확인합니다. 로그아웃, 저장, 제출과 화면 이동 뒤의 결과도 확인하세요. 마지막 저장이나 제출 뒤에는 reload로 복원값을 확인합니다. DOM을 로컬 값으로만 바꾸고 저장을 생략하면 검사가 실패합니다. 자동 검사 중 외부 API와 폼 전송은 차단되고 short SDK는 독립된 가상 DB에 연결됩니다.
- 검사 정보가 빠졌거나 selector, 로그인, 조회와 저장 및 복원이 실패하면 플랫폼이 원인 코드와 short-tests.scenarios[i].steps[j] 위치 및 수정 방법을 AI 수정 요청에 넣습니다. 전체 HTML과 검사 순서를 함께 수정해 주세요.
데이터 화면은 사이트당 하나의 데이터 표를 사용하며 표 이름 입력과 추가 표 만들기를 제공하지 않습니다. 현재 설정의 고정 tableKey와 columnKey를 그대로 사용하고 자료 이름을 별도로 요구하지 마세요.
# 짧은.한국 HTML 작성 전체 매뉴얼
Contract revision: tables-20261011-1
SDK version: 2.0.0
SDK SHA-256: 41c1313d0d1d26ebacca7ce54d6c8fcc5390b5e4ecbd53331d7e2e5e0549a0e3
OpenAPI: https://짧은.한국/openapi.json
## AI가 적용할 순서
사용자가 복사한 AI 요청문의 서버 설정을 원본으로 사용한다. 플랫폼의 데이터 화면에서 머리글과 빈 셀에 자료를 입력한다. AI는 최신 short-data-plan 계약으로 로그인할 열과 자료 이용 및 새 저장 칸을 선언한다. HTML은 그 설정의 tableKey, columnKey, type과 workflowKey를 그대로 사용한다. 표시 이름 label은 화면 표시에 사용하고 통신에는 고정 key를 사용한다. 매뉴얼 예제의 roster, number 같은 key를 실제 사이트 설정의 key로 바꾼다. 표시 이름을 바꿔도 고정 key와 rowId는 유지한다. 매뉴얼 주소를 열 수 없을 때는 복사한 요청문에 포함된 실제 설정, 전체 SDK 인수와 반환값, 연결 코드를 적용한다. 플랫폼 표는 version:2 선언을 사용한다. 마지막 v1 호환 절은 기존 자유 데이터 모음의 계약이다.
완성 결과는 CSS와 JavaScript를 포함한 HTML 파일 하나이며 최대 2MiB이다. 여러 화면은 같은 파일 안에서 전환한다. 플랫폼이 short SDK를 첫 앱 스크립트 앞에 삽입한다. await short.ready 후 초기화하고 로그인 전 current()의 null도 정상 화면으로 처리한다. 세션과 인증값은 호스트가 보관한다. 식별 열은 입력받은 문자 그대로 로그인에 전달한다. 자료와 비밀번호는 플랫폼 표에서 준비하고 HTML에는 설정 선언과 화면 동작을 작성한다.
초기 로딩, 빈 자료, 입력 검증과 오류 및 완료 상태를 연결한다. 사용자 입력은 textContent로 표시한다. 빠른 반복 조회를 피하고 필요한 수만 읽으며 새로고침 버튼을 제공한다. allow-scripts allow-forms allow-downloads sandbox에서 실행한다. 파일 선택과 화면 안의 이동을 사용하고 외부 리소스는 공개 HTTPS 주소를 쓴다. 입력 복구에는 short.drafts를 사용한다.
## HTML의 의존성 선언
다음 short-config에 실제 사용하는 표와 열을 선언한다. 접근 규칙은 플랫폼 설정에 저장된다. required:false인 선택 의존성은 누락될 때 해당 화면을 생략할 수 있다. setupRevision은 작성할 때의 설정 번호다. 게시와 복원은 현재 설정에서 표와 열의 존재 및 형식, 로그인과 작성 규칙을 다시 검사한다. 권한 변경은 현재 설정으로 즉시 적용한다. 열 제거와 자료형 변경은 다음 게시본과 함께 활성화한다.
<script id="short-config" type="application/json">
{
"version": 2,
"contractRevision": "tables-20261011-1",
"setupRevision": 1,
"tables": [
{
"tableKey": "roster",
"columns": [
{
"columnKey": "number",
"type": "text"
},
{
"columnKey": "name",
"type": "text"
},
{
"columnKey": "score",
"type": "number"
}
]
}
],
"login": {
"required": true
},
"workflows": []
}
</script>
## 전체 SDK 인수와 반환값
### short.data.profile.get()
반환: Promise<Row | null>
로그인한 사람의 데이터 행. 선언한 읽기 열만 반환하며 비밀번호는 제외한다. row.data[columnKey]로 성적 등을 읽는다.
### short.data.profile.patch(values, {expectedRevision, requestId?})
반환: Promise<{record,receipt}>
member-shared-write로 선언한 열만 변경한다.
### short.data.entries(key)
반환: Entries
short-data-plan의 entrySets.key를 사용한다. 새 저장 칸은 데이터 준비가 자동 생성한다.
### entries.open({requestId?}?) / entries.get(workId)
반환: Promise<Entry>
Entry: {workId,revision,inputRevision,schemaRevision,definition,fields,values,state,round,finalRevision,updatedAt}. definition은 시작 시 질문 원문과 버전이다.
### entries.save({workId,values,inputRevision,expectedRevision?,requestId?})
반환: Promise<{current:Entry,receipt?}>
입력이 바뀔 때 inputRevision을 올린다. SDK가 같은 화면의 저장 순서를 연결한다.
### entries.autosave(같은 SaveInput)
반환: Promise<{current:Entry,receipt?}>
호스트에 입력을 즉시 보관하고 서버에는 최소 60초 간격으로 저장한다. input 이벤트에서 호출하고 catch를 처리한다. 제출 전에 대기 Promise를 await하지 않는다.
### entries.submit({workId,values,inputRevision,expectedRevision?,definitionRevision?,requestId?})
반환: Promise<{current:Entry,receipt,finalRevision}>
화면의 마지막 입력을 복제해 한 요청으로 저장하고 제출한다. 버튼 실행 중 입력을 잠그고 성공 후 완료 화면을 연다. 이미 저장한 같은 차수와 내용도 제출할 수 있다.
### entries.restore(workId)
반환: Promise<{draft:Buffer|null}>
open/get 후 호출한다. draft.values와 inputRevision을 현재 서버 기록과 비교해 복구 선택을 제공한다.
### entries.list({limit?,after?,round?}?) / entries.getFinal(workId,finalRevision?)
반환: Promise<{records,nextCursor}> / Promise<Final>
현재 사용자의 기록만 조회한다. Final에는 values, definition, fields, schemaRevision, finalRevision, submittedAt, round가 있다. 과거 답안은 Final.fields의 key와 label로 표시한다.
### short.ready
반환: Promise<Project>
로그인 전에도 연결 완료. Project에는 siteId, title, slug, resourceVersion, setup, limits와 capabilities가 있다.
### short.auth.current()
반환: Promise<Profile | null>
Profile: {principalId, values: 설정된 프로필 열}. await로 서버의 현재 계정을 확인한다.
### short.auth.login({...설정된 식별 열 key: 입력, password: 입력})
반환: Promise<Profile>
모든 식별 열은 문자로 전달한다. 학번의 앞자리 0을 유지한다.
### short.auth.logout()
반환: Promise<void>
세션과 호스트 입력 복구본을 정리한다.
### short.auth.subscribe(listener)
반환: unsubscribe 함수
현재 Profile 또는 null을 전달한다. 화면을 초기화하고 이전 사용자 자료를 지운다.
### short.db.collection(tableKey)
반환: Collection
표의 고정 tableKey를 사용한다.
### table.list({limit?, after?, where?: {column, equals}})
반환: Promise<{records: Row[], nextCursor: string | null}>
limit 1~50. after에는 받은 nextCursor. where.column은 설정된 조건 조회 열이다.
### table.get(rowId)
반환: Promise<Row>
Row: {id, tableKey, revision, data, workId, state, createdAt, updatedAt}. 비밀번호 열은 반환값에서 제거한다.
### table.add(values, {requestId?, workId?}?)
반환: Promise<{receipt, record?}>
필수 열을 포함한다. 읽기 권한이 없는 제출 표는 receipt로 저장을 확인한다.
### table.update(id, values, {expectedRevision, requestId?, workId?})
반환: Promise<{receipt, record?}>
설정된 열의 전체 값을 교체한다. 생략한 선택 열은 기본값 또는 null.
### table.patch(id, values, {expectedRevision, requestId?, workId?})
반환: Promise<{receipt, record?}>
전달한 열만 고친다. 충돌이면 현재 값과 입력을 비교한다.
### table.remove(id, {expectedRevision, requestId?})
반환: Promise<{receipt}>
확정 잠금과 참조 및 삭제 권한을 검사한다.
### short.workflows.get(workflowKey)
반환: Workflow
플랫폼에서 설정한 범용 작성 규칙을 선택한다.
### flow.open({referenceRowId?, requestId?}?)
반환: Promise<WorkResult>
같은 신원, 기준 행, 작성 차수의 기존 작업을 우선 반환한다.
### flow.current(workId)
반환: Promise<WorkResult>
WorkResult: {work, records: Row[], references: SourceRow[], receipt?}. work에는 workId, workflowKey, generation, revision, inputRevision, state, finalRevision, referenceRowId가 있다.
### flow.saveDraft({workId, expectedRevision?, inputRevision, rows, requestId?})
반환: Promise<WorkResult>
rows: [{tableKey, rowId?, expectedRevision?, values}]. 기존 행은 id와 revision을 유지한다. 입력이 바뀔 때 inputRevision을 증가시킨다. 대기 자동저장을 취소하고 마지막 입력을 즉시 저장하며 그 자동저장 Promise도 같은 결과로 완료한다. 수동 저장 전에 autosave Promise를 await하지 않는다. 이미 저장된 같은 차수와 같은 내용이면 쓰기를 생략하고 receipt 없는 현재 WorkResult를 반환한다. 이 경우 새 requestId의 결과 조회로 저장을 확인하지 않는다.
### flow.autosave(같은 SaveDraftInput)
반환: Promise<WorkResult>
입력 복구본은 즉시 보관하고 변경한 내용의 서버 저장을 최소 60초 간격으로 묶는다. input 이벤트에서 호출하고 거절을 처리한다. Promise가 대기 중이어도 수동 저장과 제출 버튼은 즉시 saveDraft/finalize를 호출한다.
### flow.finalize({workId, inputRevision, rows, requestId?, saveRequestId?})
반환: Promise<WorkResult>
최신 입력을 복제해 먼저 저장한 뒤 같은 차수를 확정한다. 대기 자동저장을 SDK가 정리하므로 autosave Promise를 먼저 await하지 않는다. 버튼을 누르면 입력을 잠그고 결과 확인 후 완료 화면을 연다. 저장된 내용의 확정은 {workId, expectedInputRevision, expectedRevision?, requestId?}.
### flow.final(workId, finalRevision?)
반환: Promise<{final: {revision, inputRevision, finalizedAt, rows: [{rowId, tableKey, revision, values}], references: Record<rowId, {revision, data}>}}>
과거 확정본을 현재 권한으로 읽는다. final.references는 참조 행 ID를 키로 가진 객체다. 기준 자료는 final.references[current.work.referenceRowId]?.data로 읽고, 전체 참조는 Object.entries(final.references)로 순회한다. WorkResult.references는 SourceRow 배열이다.
### flow.result(requestId)
반환: Promise<OutcomeResult>
short.requests.result와 같다.
### short.requests.issue()
반환: Promise<string>
SDK가 쓰기에 자동 부여한다. unknown 결과 재확인과 재시도에는 같은 ID와 같은 입력을 유지한다.
### short.requests.result(requestId)
반환: Promise<OutcomeResult>
outcome은 committed, rejected 또는 unknown이다. committed 반환값 자체가 Receipt: {requestId, outcome, operation, targetId, revision, workId?, inputRevision?, finalRevision?}. rejected에는 error가 포함된다.
### short.drafts.capture({workflowKey, workId, referenceRowId, generation, inputRevision, rows})
반환: Promise<{captured: true, durable, inputRevision}>
호스트가 같은 계정과 작업의 허용된 입력만 보관한다. durable=false면 현재 화면 입력을 유지하고 서버 저장 결과를 확인한다.
### short.drafts.restore(workId)
반환: Promise<{draft: Buffer | null}>
작업을 먼저 열고 호출한다. draft.rows와 inputRevision을 서버 초안과 비교해 복구 선택을 제공한다. 보관 기한 24시간.
### short.drafts.clear(workId)
반환: Promise<{cleared: true}>
확정 성공 시 SDK가 해당 입력 차수까지 자동 정리한다.
### short.storage.upload(file, {workId?, requestId?}?)
반환: Promise<{file, receipt}>
File 또는 Blob, 하나 10MiB. file: {id, name, size, mimeType, createdAt, rowId, workId, locked}. 반환 file.id를 file 열에 연결한다.
### short.storage.list()
반환: Promise<StoredFile[]>
현재 계정이 올린 접근 가능한 파일.
### short.storage.url(fileId)
반환: Promise<string>
권한을 확인하는 다운로드 주소. 표에는 fileId를 저장한다.
### short.storage.remove(fileId, {requestId?}?)
반환: Promise<{receipt}>
확정한 파일은 보존한다.
SourceRow는 {id, tableKey, revision, data}이다. Row.state와 work.state는 draft 또는 final이다. source version을 고정한 작업의 references에는 시작한 시점의 자료를 반환한다. 새로 작성하는 차수는 플랫폼에서 generation을 올려 설정한다.
## AI 코드 점검 순서
1. 실제 설정의 고정 key로 short-config와 모든 호출을 맞춘다.
2. 로그인 전과 후, 사용자 A와 B, 빈 목록과 숫자 0을 각각 처리한다.
3. list 응답은 {records, nextCursor}, 저장 응답은 {receipt, record?}, 작성 중 WorkResult.references는 배열이며 확정본 final.references는 rowId를 키로 한 객체로 처리한다. 각 반환값의 전체 형식은 아래 SDK 계약을 따른다.
4. read/create/edit/delete 권한과 조건 조회 열을 실제 설정에서 확인한다. 교사만 허용된 기능은 데이터 관리 화면에서 수행한다. 현재 데이터 계약에 맞춰 short-data-plan의 자료 이용과 새 입력 칸을 선언한다.
5. 모든 버튼의 저장과 조회를 연결하고 저장 성공 후 서버 자료를 다시 확인한다. 확정은 화면의 최신 입력과 inputRevision을 전달한다.
6. 플랫폼 자동 검사가 실제로 버튼을 눌러 오류를 확인하고 수정 요청으로 전체 HTML을 고친다.
## 자료형과 권한
text는 문자, number는 유한한 숫자, boolean은 true/false, date는 YYYY-MM-DD 문자, longtext는 긴 문자, reference와 file은 서버가 발급한 행 또는 파일 ID다. 빈 선택 셀은 null이다. 문자열 학번 00101과 숫자 0을 보존한다. patch는 지정 열만 변경하며 update는 전체 열을 교체한다. 필수 열은 일반 저장과 최종 확정에서 검사하며 작성 초안은 빈 필수 열을 보관할 수 있다.
읽기와 만들기 및 수정과 삭제는 각각 독립적으로 설정한다. 교사만, 모든 방문자, 로그인한 사용자, 작성한 사용자, 자기 계정의 행, 참조 열에서 지정한 사용자의 규칙을 조합한다. 로그인 식별과 비밀번호 및 지정 사용자 열은 교사 관리에서 변경한다. 작성 중인 표는 먼저 workId를 연 뒤 해당 작업에 저장한다. 일반 CRUD에도 work revision과 확정 잠금 및 파일 권한이 적용된다.
교사는 데이터 화면의 기본 2열과 2행에 머리글과 자료를 입력하고 행 추가와 열 추가로 확장한다. 자료형과 접근 규칙은 AI 선언을 플랫폼이 준비하고 검증한다. 참조의 표시 열 값은 서버에서 고정 rowId로 해석한다. 여러 행은 최대 25행과 100문서 및 전송 크기에 맞춰 묶고 준비와 저장을 순서대로 진행한다. 연결 실패 시 저장한 행과 jobId를 유지하며 원래 자료로 이어 저장한다.
## 오류와 입력 복구
ShortError: message, code, status, category(code/setup/auth/business/connection), outcome(rejected/unknown), requestId?, argumentPath?. short:diagnostic 이벤트는 catch한 SDK 오류도 검사 화면에 전달한다. short:authchange는 Profile과 authGeneration을 전달하며 이전 사용자의 화면과 대기 요청을 정리한다. short:draftstorage는 {durable:false, workId, inputRevision}을 전달한다.
SESSION_EXPIRED 또는 SESSION_REVOKED이면 같은 계정으로 로그인하고 작업을 연 뒤 drafts.restore와 서버 초안을 비교한다. 명시적인 로그아웃과 사용자 전환은 복구본을 지운다. REVISION_CONFLICT이면 현재 저장값과 화면 입력을 함께 보여 주고 선택을 받는다. WORK_FINALIZED와 WORK_CLOSED는 현재 작성 상태로 표시한다. TABLE_NOT_CONFIGURED, COLUMN_MISMATCH, QUERY_INDEX_REQUIRED와 SETUP_CHANGED는 최신 설정을 다시 읽고 AI 요청문과 코드의 key를 맞춘다.
저장 outcome unknown은 성공 여부를 다시 확인할 상태다. 같은 requestId로 requests.result를 조회하고 committed면 완료 화면, rejected면 error와 해결 행동, unknown이면 같은 입력과 ID로 재시도한다. requestId는 24시간 동안 신원과 사이트에 묶인다. 만료 후에는 현재 행이나 작업의 확정본을 먼저 확인한다. 전송 ID는 별도의 통신 요청 번호다. REQUEST_TIMEOUT은 65초이며 동시 대기 요청은 20개다.
HTML이나 JS 및 SDK 오류를 발견한 연수생은 AI 수정 요청 복사 또는 수정 요청 파일 받기를 사용한다. 생성과 편집 및 복구 요청은 같은 개인정보 제거 처리를 거친다. 원본 HTML 입력은 유지한다.
## v2 기본 한도
- databaseBytes: 134217728
- records: 5000
- physicalDocuments: 20000
- recordBytes: 262144
- chunkBytes: 16384
- workRows: 20
- referenceBytes: 131072
- commitDocuments: 100
- metadataBytes: 16777216
- stagingBytes: 8388608
- stagingDocuments: 1000
- wireBytes: 2097152
- wrapperBytes: 65536
- readsPerDay: 12000
- writesPerDay: 8000
- requestsPerMinute: 600
- accountOperationsPerDay: 15000
- accountRequestsPerMinute: 300
- globalOperationsPerDay: 150000
- requestLifetimeMs: 86400000
- autosaveIntervalMs: 60000
- draftBufferBytes: 2097152
- draftBufferEntries: 20
- importRows: 25
- columns: 64
- indexes: 8
- tables: 100
저장 한도는 자료와 payload 조각, 색인과 유일 키, 참조 및 인증과 세션, 요청 결과와 가져오기 및 work/final 메타를 포함한다. 작성 시작 시 확정 공간을 예약한다. 전송 JSON과 래퍼, 실제 저장 문서 수를 각각 검사한다. 전체 저장과 파일 및 계정 한도는 GET /api/sites/config, 사이트 표의 유효 한도와 capabilities는 GET /api/sites/{siteId}/v2/setup에서 확인한다. 운영자가 낮춘 한도를 적용한다. PATCH /api/sites/admin/settings의 limitsV2에서 조정할 수 있는 항목은 databaseBytes, records, physicalDocuments, recordBytes, metadataBytes, stagingBytes, stagingDocuments, readsPerDay, writesPerDay, requestsPerMinute, accountOperationsPerDay, accountRequestsPerMinute, globalOperationsPerDay이며 각각 기본 한도 안의 양의 정수다. chunkBytes, workRows, referenceBytes, commitDocuments, wireBytes와 복구 및 자동 저장 간격은 실행 계약으로 고정한다.
## 현재 화면의 작성과 관리 흐름
로그인 후 사이트 만들기에서 목적을 적고 데이터를 연다. 기본 2열과 2행의 머리글과 빈 셀을 채우고 필요한 행과 열을 추가한다. 다음 단계에서 공개 범위를 정해 표 저장을 누른다. 로그인 열은 표의 열 이름으로 연결하며 로그인에 쓸 열 바꾸기에서 확인한다. 새 자료 입력, 수정과 삭제 권한, 작성과 확정 규칙, 열 형식과 표 연결은 세부 설정에서 연다. 주소를 정하기 전에도 같은 siteId로 서버 초안과 자료를 보관한다. 신규 초안은 24시간 보관하고 설정 또는 자료 저장 때 30일로 갱신한다. AI 요청문으로 돌아가 확인된 설정과 매뉴얼이 포함된 요청을 복사한다.
AI가 만든 전체 HTML을 넣고 게시 전 확인을 실행한다. 플랫폼이 가상 사용자 A와 B 및 서로 다른 방문자로 로그인, 버튼 실행, 개인별 조회와 실제 저장 및 다시 열기를 자동으로 확인한다. 오류에서 수정 요청을 복사해 같은 AI 대화에 붙여 넣고 새 전체 HTML로 다시 확인한다. 사이트 정보에서 제목, 뒷주소, 공유자와 보관 기간을 지정하고 게시한다. 내 사이트의 데이터에서 운영 자료, 계정 사용과 중지 및 비밀번호를 관리한다. 사이트 편집과 게시본 복원도 현재 서버 설정을 적용한다.
## 작성과 여러 행 저장의 용량 확보
작성 작업 하나를 열 때 확정에 필요한 589824 bytes와 215 documents를 예약한다. 여기에는 256KiB 작성 내용, 64KiB 래퍼, 128KiB 참조 자료 및 요청과 참조 메타가 포함된다. 확정하면 남은 예약 공간을 반환한다. workflow.open은 정의가 삭제되거나 generation이 바뀐 과거 초안의 예약 공간도 반환하며 작성 행과 참조 및 파일, 확정 이력을 보존한다. 같은 generation에서 accepting:false로 마감한 초안의 예약은 유지한다. 과거 generation을 다시 사용해 초안을 열면 정리되지 않은 staging이 이미 사용한 몫을 반영해 예약을 복구한다. freezeReferences:true이면 시작할 때의 기준 자료를 유지하고, false이면 확정할 때의 기준 자료를 보관한다. 두 방식 모두 작성 행에 연결한 모든 참조 자료를 확정본에 포함하고 현재 읽기 권한을 검사한다.
import.stage의 청크는 최대 25행이다. 로그인 명단이나 유일 키 및 연결 열이 있으면 100문서의 원자적 저장 범위 안에서 maxRows를 더 작게 계산한다. IMPORT_CHUNK_SIZE 오류의 details.maxRows, details.index, details.receivedRows와 details.canRetry를 사용해 같은 가져오기 작업의 아직 준비되지 않은 청크를 나눠 다시 준비한다. 플랫폼은 여러 행을 저장할 때 이 크기를 자동으로 적용한다. 이미 committed 상태인 청크는 다시 쓰지 않는다.
## 예제: 한 표의 로그인과 개인별 자료
명단 표의 문자 식별 열 number와 name, 비밀번호 열 secret, 숫자 열 score. 읽기 자기 계정의 행, 만들기와 수정 및 삭제 교사만. 실제 key는 AI 요청문의 설정을 사용한다.
아래 입력란과 출력 요소는 HTML에서 선언한 DOM 요소다. 실제 사이트에서는 같은 동작을 버튼과 입력 이벤트에 연결한다.
<!-- short-example:personal-rows -->
```javascript
await short.ready;
const profile = await short.auth.current();
if (!profile) await short.auth.login({ number: numberInput.value, name: nameInput.value, password: passwordInput.value });
const { records } = await short.db.collection("roster").list({ limit: 10 });
scoreOutput.textContent = records.length ? String(records[0].data.score ?? "") : "등록된 자료가 없습니다.";
```
<!-- /short-example -->
## 예제: 별도 표에 연결한 개인 자료
feedback 표의 recipient 참조 열을 로그인 명단에 연결한다. 읽기와 기존 행 수정은 recipient에서 지정한 사용자, 만들기와 삭제는 교사. text는 긴 글.
아래 입력란과 출력 요소는 HTML에서 선언한 DOM 요소다. 실제 사이트에서는 같은 동작을 버튼과 입력 이벤트에 연결한다.
<!-- short-example:recipients -->
```javascript
await short.ready;
const feedback = short.db.collection("feedback");
const { records } = await feedback.list({ limit: 10 });
if (records.length) {
const row = records[0];
const result = await feedback.patch(row.id, { text: replyInput.value }, { expectedRevision: row.revision });
statusOutput.textContent = result.receipt.outcome === "committed" ? "저장됨" : "저장 결과 확인";
}
```
<!-- /short-example -->
## 예제: 방명록
guestbook 표의 name 문자와 text 긴 글. 읽기와 만들기 모든 방문자, 수정과 삭제 작성한 사용자.
아래 입력란과 출력 요소는 HTML에서 선언한 DOM 요소다. 실제 사이트에서는 같은 동작을 버튼과 입력 이벤트에 연결한다.
<!-- short-example:guestbook -->
```javascript
await short.ready;
const guestbook = short.db.collection("guestbook");
await guestbook.add({ name: nameInput.value, text: replyInput.value });
const { records, nextCursor } = await guestbook.list({ limit: 10 });
for (const row of records) { const item = document.createElement("li"); item.textContent = row.data.name + ": " + row.data.text; listOutput.append(item); }
if (nextCursor) await guestbook.list({ limit: 10, after: nextCursor });
```
<!-- /short-example -->
## 예제: 익명 설문이나 신청서 제출
survey 표의 response 긴 글. 만들기 모든 방문자, 읽기 교사만. 제출 성공은 receipt로 확인한다.
아래 입력란과 출력 요소는 HTML에서 선언한 DOM 요소다. 실제 사이트에서는 같은 동작을 버튼과 입력 이벤트에 연결한다.
<!-- short-example:anonymous-submit -->
```javascript
await short.ready;
const result = await short.db.collection("survey").add({ response: replyInput.value });
if (result.receipt.outcome === "committed") statusOutput.textContent = "접수됨";
```
<!-- /short-example -->
## 예제: 로그인 후 긴 글 작성과 마지막 입력 확정
questions 표의 title과 body는 로그인한 사용자 읽기. answers 표의 source를 questions에 연결하고 text는 필수 긴 글, attachment는 선택 파일. 읽기와 수정 및 삭제 작성한 사용자, 만들기 로그인한 사용자. writing 규칙에서 기준 source 연결, 시작 자료 유지, 작성 받기를 켠다. HTML에는 replyInput, saveButton, submitButton, statusOutput, scoreOutput과 복구할 내용을 보여 주는 recoveryOutput, restoreButton 및 keepServerButton을 선언한다. 로그인한 뒤 실행하고 저장과 확정은 사용자가 누른 버튼에서만 수행한다.
아래 입력란과 출력 요소는 HTML에서 선언한 DOM 요소다. 실제 사이트에서는 같은 동작을 버튼과 입력 이벤트에 연결한다.
<!-- short-example:workflow -->
```javascript
await short.ready;
const { records: sources } = await short.db.collection("questions").list({ limit: 10 });
const flow = short.workflows.get("writing");
recoveryOutput.hidden = true; restoreButton.hidden = true; keepServerButton.hidden = true;
if (!sources.length) {
statusOutput.textContent = "작성할 자료가 없습니다.";
replyInput.disabled = true; saveButton.disabled = true; submitButton.disabled = true;
} else {
let current = await flow.open({ referenceRowId: sources[0].id });
let inputRevision = current.work.inputRevision;
let rows = current.records.map(row => ({ tableKey: row.tableKey, rowId: row.id, expectedRevision: row.revision, values: structuredClone(row.data) }));
let pendingFinal;
async function showFinal() {
const { final } = await flow.final(current.work.workId);
const pinned = final.references[current.work.referenceRowId];
scoreOutput.title = String(pinned?.data.title ?? "");
replyInput.value = String(final.rows[0]?.values.text ?? "");
scoreOutput.textContent = replyInput.value;
replyInput.disabled = true; saveButton.disabled = true; submitButton.disabled = true;
statusOutput.textContent = "확정됨";
}
function showError(error) { statusOutput.textContent = error.message; }
function bindSavedRows() {
rows = rows.map(row => {
const saved = current.records.find(record => record.id === row.rowId) || current.records.find(record => record.tableKey === row.tableKey);
return saved ? { ...row, rowId: saved.id, expectedRevision: saved.revision } : row;
});
}
if (current.work.state === "final") {
await showFinal();
} else {
if (!rows.length) rows = [{ tableKey: "answers", values: { text: "", attachment: null } }];
replyInput.value = String(rows[0].values.text ?? "");
const { draft } = await short.drafts.restore(current.work.workId);
const recovery = draft && draft.inputRevision > inputRevision ? draft : null;
if (recovery) {
recoveryOutput.textContent = String(recovery.rows[0]?.values.text ?? "");
recoveryOutput.hidden = false; restoreButton.hidden = false; keepServerButton.hidden = false;
replyInput.disabled = true; saveButton.disabled = true; submitButton.disabled = true;
statusOutput.textContent = "서버에 저장한 글과 복구할 글을 확인하고 사용할 내용을 선택해 주세요.";
}
function finishRecovery() {
recoveryOutput.hidden = true; restoreButton.hidden = true; keepServerButton.hidden = true;
replyInput.disabled = false; saveButton.disabled = false; submitButton.disabled = false;
statusOutput.textContent = "";
}
restoreButton.addEventListener("click", () => {
rows = structuredClone(recovery.rows); inputRevision = recovery.inputRevision;
bindSavedRows(); replyInput.value = String(rows[0]?.values.text ?? "");
finishRecovery();
});
keepServerButton.addEventListener("click", async () => {
try { await short.drafts.clear(current.work.workId); inputRevision = Math.max(inputRevision, recovery.inputRevision); finishRecovery(); }
catch (error) { showError(error); }
});
async function captureLatest() {
inputRevision++; rows[0].values.text = replyInput.value;
const input = { workId: current.work.workId, inputRevision, rows: structuredClone(rows) };
await short.drafts.capture({ ...input, workflowKey: "writing", referenceRowId: current.work.referenceRowId, generation: current.work.generation });
return input;
}
async function saveLatest() {
saveButton.disabled = true;
try { current = await flow.saveDraft(await captureLatest()); bindSavedRows(); statusOutput.textContent = inputRevision === current.work.inputRevision ? "저장됨" : "새 입력을 계속 작성 중입니다."; }
catch (error) { showError(error); }
finally { saveButton.disabled = replyInput.disabled || current.work.state === "final"; }
}
async function confirmLatest() {
submitButton.disabled = true; saveButton.disabled = true; replyInput.disabled = true;
try {
if (!pendingFinal) pendingFinal = { ...await captureLatest(), requestId: await short.requests.issue(), saveRequestId: await short.requests.issue() };
current = await flow.finalize(pendingFinal);
await showFinal(); pendingFinal = undefined;
} catch (error) {
showError(error); submitButton.disabled = false;
if (error.outcome !== "unknown" && current.work.state !== "final") { pendingFinal = undefined; replyInput.disabled = false; saveButton.disabled = false; }
}
}
replyInput.addEventListener("input", () => captureLatest().catch(showError));
saveButton.addEventListener("click", saveLatest);
submitButton.addEventListener("click", confirmLatest);
}
}
```
<!-- /short-example -->
## 예제: 파일을 작성 행에 연결
작성 중인 answers 행에 attachment 파일 열이 있다. 확정 후에는 연결된 파일이 함께 잠긴다. 파일과 저장 결과가 unknown이면 기존 fileId와 requestId를 유지한다.
아래 입력란과 출력 요소는 HTML에서 선언한 DOM 요소다. 실제 사이트에서는 같은 동작을 버튼과 입력 이벤트에 연결한다.
<!-- short-example:files -->
```javascript
await short.ready;
const { records: sources } = await short.db.collection("questions").list({ limit: 10 });
const flow = short.workflows.get("writing");
const current = await flow.open({ referenceRowId: sources[0].id });
const { file } = await short.storage.upload(selectedFile, { workId: current.work.workId });
const row = current.records[0];
const saved = await flow.saveDraft({ workId: current.work.workId, inputRevision: current.work.inputRevision + 1, rows: [{ tableKey: "answers", ...(row ? { rowId: row.id, expectedRevision: row.revision } : {}), values: { text: replyInput.value, attachment: file.id } }] });
fileLink.href = await short.storage.url(file.id);
statusOutput.textContent = saved.work.inputRevision === current.work.inputRevision + 1 ? "파일과 글 저장됨" : "저장 결과 확인";
```
<!-- /short-example -->
## 예제: 연결 실패와 저장 결과 확인
명시적인 저장 ID를 발급하고 저장할 값을 고정한다. unknown 결과에는 같은 ID와 같은 값으로 확인과 재시도를 수행한다.
아래 입력란과 출력 요소는 HTML에서 선언한 DOM 요소다. 실제 사이트에서는 같은 동작을 버튼과 입력 이벤트에 연결한다.
<!-- short-example:lost-result -->
```javascript
await short.ready;
const table = short.db.collection("guestbook");
const requestId = await short.requests.issue();
const values = { name: nameInput.value, text: replyInput.value };
try { await table.add(values, { requestId }); }
catch (error) {
if (error.outcome !== "unknown") throw error;
const result = await short.requests.result(requestId);
if (result.outcome === "unknown") await table.add(values, { requestId });
else if (result.outcome === "rejected") throw new Error(result.error.message);
}
const result = await short.requests.result(requestId);
statusOutput.textContent = result.outcome;
```
<!-- /short-example -->
## 관리와 게시 HTTP 계약
OpenAPI는 서버 초안과 v2 설정, 로그인 및 현재 계정, runtime/manage RPC, 파일 업로드와 기존 게시 API를 함께 제공한다. 교사 관리에는 Firebase ID token 또는 서버 개발 token을 Authorization: Bearer 값으로 전달한다. 방문자와 학생의 token은 호스트가 처리한다.
POST /api/sites/drafts {requestId} -> {project}. GET /api/sites/{site}/v2/manage/setup -> {setup,pendingSetup,limits,usage,capabilities}. PATCH /api/sites/{site}/v2/setup {setup,expectedRevision,stageStructure:true} -> 같은 설정 응답. 관리 RPC에는 {operation,payload,setupRevision?}를 전달한다. import.begin/stage/commit/status/cancel 및 auth.accounts/auth.manage와 workflow.reopen은 교사 전용이다.
게시 업로드와 publish는 아래 v1 호환 게시 계약을 함께 사용한다. v2 publish에 expectedSetupRevision과 expectedDeploymentId를 보내 HTML 및 설정 번호와 게시본을 묶어 검증한다. 게시 후 실제 SDK는 내용 hash가 포함된 /site-sdk/{siteId}/{hash}.js 주소로 삽입한다. SDK 계약과 capabilities를 함께 확인한다.
# Compatibility contract: v1 visitor collections
Contract version: 1.0.0
SDK compatibility mode: short-config version 1
Canonical manual: https://xn--zs5bn2c.xn--3e0b707e/llms-full.txt
HTTP schema: https://xn--zs5bn2c.xn--3e0b707e/openapi.json
## Instructions for coding agents
Use this section for HTML declaring short-config version 1. It describes existing visitor collections and their direct record and file return values. Data configured in the platform uses the v2 dependency manifest and generated SDK reference above; use the copied setup's stable keys and access rules. The injected SDK reports its current implementation version through short.version, while the HTML configuration selects the compatibility mode.
1. Deliver exactly one complete HTML file, including its CSS and JavaScript. Provide the finished HTML as a downloadable file. Use the user's language for the website interface.
2. Implement saved application data with window.short.db and user file uploads with window.short.storage. Data that should survive refresh or reopening belongs in these APIs.
3. The platform injects window.short before application scripts and binds it to the published project. Initialize the application after await short.ready. Project IDs, sessions and storage credentials are supplied by the host.
4. Declare shared collections and shared files with the inline short-config JSON shown below. Undeclared collections and files use visitor access.
5. Include loading, empty and error states. Disable duplicate submissions while saving. Preserve user input when a request fails and show the error message with a useful next action.
6. Render user content with textContent or safe DOM operations. Use actual saved data for counts, dates and results.
7. Verify saving, refreshing, reopening and any file upload in the published website. The SDK is available in the platform preview and when the HTML is served through its short address.
## Artifact and runtime
The artifact is one HTML file up to 2 MiB (2,097,152 bytes). Put styles in <style> and scripts in <script>. The original filename may be any .html or .htm name; the platform publishes it as index.html. Multiple screens use JavaScript or hash routing within the same file. Default images can be inline SVG, data URLs or public HTTPS resources. Visitor uploads use short.storage.
The HTML runs in an iframe with sandbox="allow-scripts allow-forms allow-downloads". HTTPS scripts, styles, fonts, images and CORS-enabled network services are available. Use the short SDK for persistent data and files. The runtime has an opaque origin: implement application dialogs in the DOM, and keep screens in this HTML. Nested frames, popups, top-level navigation, camera, microphone and geolocation are restricted by the host policy. External services that require a normal same-origin cookie session need a different design.
The short SDK communicates with its parent host through a project-bound bridge. Owner credentials and visitor session tokens stay in the host. Keep deployment tokens and Firebase owner credentials in the deployment tool's environment, outside the visitor HTML.
## Access declaration
Place exactly one configuration script inside the HTML. Its JSON is limited to 32 KiB. It is read when a version is published or restored.
```html
<script type="application/json" id="short-config">
{
"version": 1,
"collections": {
"posts": { "access": "public" },
"responses": { "access": "submit" },
"todos": { "access": "visitor" },
"settings": { "access": "private" }
},
"files": { "access": "public" },
"spa": false
}
</script>
```
| Collection access | Visitor capabilities | Owner capabilities |
| --- | --- | --- |
| visitor | Read and create their own records; update and delete their own records | Manage all records in My Sites |
| public | Read all records; create, update and delete their own records | Manage all records in My Sites |
| submit | Read, create, update and delete their own submissions | Review and manage all submissions in My Sites |
| private | Owner-only collection | Read and edit in My Sites |
Collection names match ^[A-Za-z][A-Za-z0-9_-]{0,47}$. Each record contains a JSON object. Undeclared collections default to visitor access. Visitor identity is maintained per project in the host browser. Clearing browser storage or using another browser creates a different visitor identity. Owner management is performed through the authenticated My Sites interface.
File access accepts visitor, public or private. Public files can be viewed by all visitors while the project is active. Visitor files are visible to their uploader. Private files are managed by the owner. Only the uploader or owner can delete a file. A shared photo board therefore declares both its collection and files as public.
## Database SDK
```javascript
await short.ready;
const posts = short.db.collection('posts');
const record = await posts.add({ title: 'First post', body: 'Hello' });
const saved = await posts.get(record.id);
console.log(saved.data.title);
const page = await posts.list({ limit: 10 });
for (const item of page.records) console.log(item.id, item.data);
if (page.nextCursor) {
const next = await posts.list({ limit: 10, after: page.nextCursor });
}
// update replaces the complete data object. Preserve fields you still need.
await posts.update(record.id, { title: 'Edited post', body: 'Updated text' });
await posts.remove(record.id);
```
Records return {id, data, createdAt, updatedAt}; timestamps are ISO 8601 strings. Lists return {records, nextCursor}, newest first. Request 1 to 50 records per page, default 20. Pass nextCursor as after to load another page. The list quota is charged by the requested limit: list({limit:20}) reserves 20 reads even if fewer records exist. get costs one read; add, update and remove each cost one write.
A data object is limited to 16 KiB of UTF-8 JSON, 10 levels of nesting and 1,000 fields in total. Arrays, nested arrays, strings, booleans, null and finite numbers are supported. Keep binary content in file storage and store file IDs in records.
## File SDK
```javascript
await short.ready;
const selected = document.querySelector('input[type=file]').files[0];
const file = await short.storage.upload(selected);
try {
await short.db.collection('posts').add({ title: 'Photo', fileId: file.id });
} catch (error) {
if (error.outcome === 'rejected') await short.storage.remove(file.id);
// An unknown outcome keeps the file and entered data for result checking.
throw error;
}
const image = document.createElement('img');
image.src = await short.storage.url(file.id);
image.alt = 'Uploaded photo';
document.body.append(image);
const files = await short.storage.list();
```
upload accepts a nonempty File or Blob up to 10 MiB and returns {id, name, size, mimeType, createdAt}. A Blob without a filename is named file.bin. list returns files permitted by the current access policy. Fetch a display URL with storage.url(id) when rendering; store the file ID in the database. Visitor-file URLs expire after 10 minutes and authorize one file. Public-file URLs use the project's active-file transfer endpoint. The endpoint checks transfer quotas and provides CORS access for the sandbox runtime.
After uploading, remove an unlinked file only when record creation has a confirmed rejected outcome. An unknown outcome preserves file.id and the entered data: the server may already have stored the record. For version 1, reopen the saved records and check the retained file ID before another write or cleanup. Version 2 uses the same logical request ID with short.requests.result to confirm the outcome. When the user deletes a post, remove its associated files after the post deletion is confirmed. Photo selectors use accept="image/*" and validate the selected file before uploading. Handle a missing or removed file without losing the rest of the page.
## Complete single-file example: shared guestbook
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Our guestbook</title>
<style>
body{font:16px/1.6 system-ui;max-width:640px;margin:40px auto;padding:0 20px}
form,label{display:grid;gap:10px}form{gap:18px}input,textarea,button{font:inherit;padding:10px}
li{white-space:pre-wrap;overflow-wrap:anywhere;margin:16px 0}button{cursor:pointer}
</style>
<script type="application/json" id="short-config">
{"version":1,"collections":{"messages":{"access":"public"}}}
</script>
</head>
<body>
<h1>Our guestbook</h1>
<form id="form">
<label>Name<input name="name" required maxlength="30"></label>
<label>Message<textarea name="message" required maxlength="1000"></textarea></label>
<button disabled>Leave a message</button>
</form>
<p id="status" role="status">Loading…</p>
<ul id="messages"></ul>
<script>
const messages = short.db.collection('messages');
const status = document.querySelector('#status');
const form = document.querySelector('#form');
const button = form.querySelector('button');
async function render() {
const page = await messages.list({limit:10});
const list = document.querySelector('#messages');
list.replaceChildren();
for (const record of page.records) {
const li = document.createElement('li');
li.textContent = record.data.name + ': ' + record.data.message;
list.append(li);
}
status.textContent = page.records.length ? '' : 'No messages yet.';
}
form.addEventListener('submit', async event => {
event.preventDefault(); button.disabled = true; status.textContent = 'Saving…';
try {
await messages.add({name:form.elements.name.value,message:form.elements.message.value});
form.reset(); await render();
} catch (error) { status.textContent = error.message; }
finally { button.disabled = false; }
});
short.ready.then(async () => {
button.disabled = false; await render();
}).catch(error => { status.textContent = error.message; });
</script>
</body>
</html>
```
## Quotas and retention
| Resource | Default limit |
| --- | --- |
| Projects | 5 per account |
| Deployment | Exactly one HTML file, up to 2 MiB |
| Visitor upload | 10 MiB per file |
| Storage including versions, uploads and reservations | 100 MiB per account |
| Database | 10 MiB JSON, 5,000 records and 100 collections per project |
| Single record | 16 KiB JSON |
| Uploaded files | 200 per project |
| Retained versions | Latest 3, preserving the active version |
| Database reads | 3,000 per project per day |
| Database writes | 1,000 per project per day |
| Account operations | 15,000 per day |
| Request rate | 120 per project per minute; 300 per account per minute |
| Account transfer | 1 GiB per month |
| Global operations | 150,000 per day |
| Global transfer | 20 GiB per day |
1 KiB = 1,024 bytes; 1 MiB = 1,048,576 bytes; 1 GiB = 1,073,741,824 bytes. Database size is measured from UTF-8 JSON. Daily and monthly counters reset in Asia/Seoul time. Operators can lower limits or pause the service. GET /api/sites/config returns the effective limits and enabled state.
Account and global operations include page visits, visitor sessions, management requests and file-transfer requests. Lists charge their requested page size; other requests charge at least one operation. Owner deletions used to release storage remain available when daily quotas are exhausted.
Project creation accepts retentionDays 30, 90 or 365, default 30. The user selects 1 month, 3 months or 1 year. An owner can extend by 90 days during the last 7 days. Expired and owner-deleted projects stop serving and enter a 30-day recoverable deletion period. Stored records, files and versions remain reserved against the owner quota. The owner may POST /api/sites/{site}/renew during this period to resume the same address for 90 days. Cleanup releases storage and project quota after the deadline. Operator moderation remains authoritative. Deployment upload reservations last 1 hour; visitor-file reservations last 15 minutes. Cleanup releases failed and expired reservations.
## User publishing workflow
The entire creation and management flow requires login from the beginning.
1. AI request page: the user describes a website and copies a prompt containing this manual's URL and the essential SDK contract. When editing, the prompt includes the current HTML and asks to preserve collection names, fields and stored file IDs.
2. HTML page: the user selects one HTML file or pastes its code. Its <title> supplies the initial site name. Intake checks catch explanation text, code fences, missing local files and invalid short-config. The user runs an isolated preview with the real SDK and an in-memory test store, can switch between two visitors, and copies a repair request including errors and current HTML. Preview data is test-only. Runtime errors must be resolved before continuing.
3. Site information page: the user confirms the name, chooses a 2 to 10 character Korean, Latin or numeric suffix, enters the required sharer name (1 to 10 characters) and selects retention. The login display name is the initial sharer value. Publishing creates the project and automatically connects the SDK.
My Sites provides a clickable short address with copy and QR icons, saved records, uploaded files and settings. Site Edit uses the same three pages and preloads the current HTML, title, suffix, sharer name and retention. Owners may change those fields together with the HTML while keeping project data and uploaded files. Settings has separate pages for retained versions, usage and deletion, each with a return control. Record edits use ordinary input fields while preserving structured data.
Drafts retain the HTML, original filename, purpose, title, suffix, sharer, retention and current step in this browser tab for 24 hours. Create and edit drafts are scoped to the signed-in account and project. Signing out clears that account's drafts. After reload, run the preview again before publishing.
For classroom applications, request small pages (for example limit:10), offer a manual refresh button and avoid rapid polling. Handle quota and network errors visibly and re-enable the form after failure. Test shared collections with a second visitor.
## Deployment tools
Owner deployment tools issue a 7-day development token with POST /api/sites/developer-tokens using Firebase login credentials. Store it in the deployment tool's SHORT_DEPLOY_TOKEN environment variable. Authorize HTTP requests with Authorization: Bearer <SHORT_DEPLOY_TOKEN>. The token supports the owner's site deployment and management; issue and revoke tokens using Firebase login credentials. Up to 3 active development tokens are allowed.
Use the following sequence; exact field and response schemas are in /openapi.json.
1. POST /api/sites with {title, slug, sharedBy, retentionDays} to reserve a project and suffix. Use the existing siteId when updating a project. retentionDays is 30, 90 or 365, default 30.
2. Compute the HTML byte size and lowercase SHA-256. Its path is index.html.
3. POST /api/sites/{site}/deployments with {assets:[{path:"index.html",size,sha256}]}.
4. Use deploymentId and assets[0].id to PUT the original bytes to /api/sites/{site}/deployments/{deployment}/assets/{asset}, with Content-Type: application/octet-stream. Retrying identical bytes is supported.
5. POST /api/sites/{site}/deployments/{deployment}/publish after the asset upload completes. Publication validates the bytes and inline access declaration, then atomically switches the active version. To update project metadata at the same time, send {"details":{"title":"Class album","slug":"우리사진첩","sharedBy":"Teacher","retentionDays":90}}. All four detail fields are required when details is present. A suffix conflict rejects the entire publication and preserves the previous version and metadata. A changed retention choice starts that duration at successful publication; keeping the same choice preserves the current expiry. The project ID, database records, uploaded files and visitor sessions remain the same after a suffix change. The previous suffix is retired for 30 days and the same owner may move this project back to it during that period.
6. DELETE /api/sites/{site}/deployments/{deployment} to cancel a failed upload. The previously published version stays active during an update.
Include expectedDeploymentId in the publication body to protect concurrent editors: use the currently active deployment ID, or null for a project that has never been published. If another editor publishes first, the server responds with 409 SITE_CHANGED. Reopen the project before making a new edit. A retry for the already active deployment remains idempotent.
## Error handling
SDK errors provide message, code and status. Preserve entered content and show message in a status or alert area. Use bounded retries for transient failures and offer an explicit retry action.
| HTTP status | Recovery |
| --- | --- |
| 400 | Correct the input, JSON, path or access declaration |
| 401 | Reopen the short address or refresh deployment authentication |
| 403 | Check the collection or file access policy and ownership |
| 404 | Handle a removed record or file |
| 409 | Check suffix availability, storage quotas or deployment state |
| 410 | Check publishing state and retention, then reopen the website |
| 413 | Reduce the file or record size |
| 423 | Resolve the frozen or merging account state before retrying |
| 429 | Wait for the relevant quota or rate counter to reset |
| 503 or 504 | Preserve input and retry when the service or connection recovers |
The SDK also reports HOST_UNAVAILABLE when it cannot connect to the short-address host, REQUEST_TIMEOUT for a request exceeding 35 seconds, and TOO_MANY_PENDING when 20 bridge requests are already pending. Batch and paginate work to stay within these limits.