@thinkfree.dev/tfo-sdk 0.2.0 → 0.2.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.
package/README.md CHANGED
@@ -1,133 +1,214 @@
1
- # Thinkfree Office SDK
1
+ # Thinkfree Editor SDK (`@thinkfree.dev/tfo-sdk`)
2
2
 
3
- 브라우저에 iframe 으로 임베드된 Thinkfree Office 편집기(워드 · 셀 · 쇼)를 postMessage 로 제어하는 JavaScript / TypeScript SDK 입니다.
3
+ A JavaScript / TypeScript SDK for controlling a Thinkfree Office editor (Word, Spreadsheet, Presentation) that is embedded in your web page as an iframe. The SDK talks to the editor over exact-origin `postMessage`; your page never touches the editor's internals.
4
4
 
5
- - **개발자 API** — `Office.word` / `Office.cell` / `Office.show` 또는 `getDocument()` 로 문서 객체 모델을 직접 조작
6
- - **AI 에이전트 통합** — 편집기 모듈이 제공하는 도구 카탈로그를 실행 가능한 도구 배열로 회수 (`getTools`) 하거나 콜백 프레임워크에 자동 등록 (`registerTools`)
7
- - **타입 완비** — 단일 번들 `index.d.ts` 로 word / cell / show 전 모듈 타입 제공
5
+ - **Document API** — get an app handle with `Office.word` / `Office.cell` / `Office.show`, then work on the document object model through `getDocument()`.
6
+ - **AI agent integration** — fetch the editor's tool catalog as executable tools (`getTools`) or register them into a tool-calling framework (`registerTools`).
7
+ - **Fully typed** — one bundled `index.d.ts` covers the Word, Spreadsheet, and Presentation APIs.
8
8
 
9
- ## 설치
9
+ > **Private developer preview.** This is a 0.x release. The public surface may change between minor versions.
10
+
11
+ ## Try it first
12
+
13
+ You can run the SDK against a live document before installing anything.
14
+
15
+ - **Playground** — <https://playground.developers.thinkfree.com/playground/>: an in-browser console with a sample Word, Spreadsheet, or Presentation document. Pick a module, load an example, and run it. The code you write there is the same code you ship with this package.
16
+ - **Overview** — <https://www.developers.thinkfree.com/docs/editor-sdk/>: what the SDK does, how the pieces fit, and how to open a document.
17
+
18
+ Module API references:
19
+
20
+ | module | reference |
21
+ |--------|-----------|
22
+ | Word (`Office.word`) | <https://www.developers.thinkfree.com/docs/editor-sdk/word-api/> |
23
+ | Spreadsheet (`Office.cell`) | <https://www.developers.thinkfree.com/docs/editor-sdk/spreadsheet-api/> |
24
+ | Presentation (`Office.show`) | <https://www.developers.thinkfree.com/docs/editor-sdk/presentation-api/> |
25
+
26
+ ## Installation
10
27
 
11
28
  ```bash
12
29
  npm install @thinkfree.dev/tfo-sdk
13
30
  ```
14
31
 
15
- ## 요구 사항
32
+ Without a bundler, load the ESM build through an import map so that `import ... from "@thinkfree.dev/tfo-sdk"` resolves in the browser:
33
+
34
+ ```html
35
+ <script type="importmap">
36
+ { "imports": { "@thinkfree.dev/tfo-sdk": "./node_modules/@thinkfree.dev/tfo-sdk/dist/index.js" } }
37
+ </script>
38
+ ```
16
39
 
17
- - **실행 환경**: 브라우저 (DOM 필요 — Node.js 전용 환경은 지원하지 않습니다)
18
- - **모듈 형식**: ESM 전용 (CommonJS `require()` 미지원 — 필요하면 dynamic `import()` 사용)
19
- - **TypeScript** (선택): 4.7 이상, `compilerOptions.lib` 에 `"dom"` 포함
40
+ If you copy the SDK files instead of installing the package, ship `apiReference.generated.js` next to `index.js`. It is a lazily loaded chunk used by the `get_api_reference` tool (see [AI agent integration](#ai-agent-integration)).
20
41
 
21
- ## 시작하기
42
+ ## Requirements
22
43
 
23
- 가장 간단한 진입점은 iframe 요소에서 바로 시작하는 `Office.word/cell/show` 입니다.
44
+ - **Runtime**: a browser (the SDK needs the DOM; Node.js-only environments are not supported).
45
+ - **Module format**: ESM only. CommonJS `require()` is not supported; use dynamic `import()` if needed.
46
+ - **TypeScript** (optional): 4.7 or later, with `"dom"` in `compilerOptions.lib`.
47
+ - **Editor**: a Thinkfree Office deployment that you can open in an iframe. The SDK does not host or open documents by itself.
48
+
49
+ ## Getting started
50
+
51
+ The simplest entry point is `Office.word` / `Office.cell` / `Office.show`, called with the iframe element that hosts the editor. The returned object is an **app handle** that represents the editor application. The document object model comes from `getDocument()`.
24
52
 
25
53
  ```ts
26
54
  import { Office, ShapePreset } from '@thinkfree.dev/tfo-sdk';
27
55
 
28
56
  const show = Office.show(document.getElementById('office-iframe') as HTMLIFrameElement);
29
57
 
30
- await show.whenReady(); // 편집기 부팅 대기 (선택, 기본 한도 60초)
31
- const slides = await show.getSlides(); // 문서 메서드 직접 호출
58
+ await show.whenReady(); // wait for the editor to boot (optional, default limit 60 s)
59
+ const doc = show.getDocument(); // Show.Document — the root handle (synchronous, no round trip)
60
+ const slides = await doc.getSlides();
32
61
  await slides[0].insertShape(ShapePreset.RECT);
33
62
  ```
34
63
 
35
- - 같은 iframe 요소로 다시 부르면 같은 앱 핸들을 돌려줍니다 (get-or-create — `disconnect()` 전까지).
36
- - `frameworkOrigin` 은 iframe 의 `src` 에서 자동 유도됩니다. src 가 없거나 `data:` / `blob:` URL 이면 옵션으로 명시하세요.
37
- - 앱 핸들에 없는 프로퍼티는 `getDocument()` 핸들로 위임됩니다 — `show.getSlides()` 는 `show.getDocument().getSlides()` 와 같습니다.
38
- - 한 페이지에 여러 iframe(여러 문서)을 띄워도 안전합니다 — 인스턴스별로 응답이 격리됩니다.
39
- - MS Office.js 를 같은 페이지에서 쓰면 전역 `Office` 와 이름이 겹칩니다 — `import { Office as TfoOffice }` 로 별칭 import 하세요.
64
+ Things to know:
40
65
 
41
- ### createOffice — 저수준 팩토리
66
+ - Calling `Office.x(iframe)` again with the same iframe element returns the same app handle (get-or-create) until you call `disconnect()`.
67
+ - `frameworkOrigin` is derived from the iframe's `src`. Pass it explicitly when the iframe has no `src`, or uses a `data:` / `blob:` URL.
68
+ - The app handle (`Office.show(el)`) and the document (`show.getDocument()`) are separate objects. Document methods such as `getSlides()` live on the document handle only; they are not proxied through the app handle.
69
+ - Multiple iframes (multiple documents) on one page are safe. Responses are isolated per instance.
70
+ - If MS Office.js is loaded on the same page, the global `Office` name collides. Import with an alias: `import { Office as TfoOffice } from '@thinkfree.dev/tfo-sdk'`.
42
71
 
43
- `targetWindow` 통신이나 세부 옵션이 필요하면 팩토리를 직접 사용합니다.
72
+ ### `createOffice` — low-level factory
73
+
74
+ Use the factory directly when you need `targetWindow` transport or explicit options.
44
75
 
45
76
  ```ts
46
77
  import { createOffice } from '@thinkfree.dev/tfo-sdk';
47
78
 
48
79
  const office = createOffice({
49
80
  module: 'cell', // 'word' | 'cell' | 'show'
50
- frameworkOrigin: 'https://office.example.com', // 필수 ('*' 금지)
51
- iframeEl: document.querySelector('iframe') as HTMLIFrameElement, // 또는 targetWindow (택1)
52
- // timeoutMs: 5000, // 응답 타임아웃 (기본 5000ms)
81
+ frameworkOrigin: 'https://office.example.com', // required; '*' is rejected
82
+ iframeEl: document.querySelector('iframe') as HTMLIFrameElement, // or targetWindow (pick one)
83
+ // timeoutMs: 5000, // per-call response timeout (default 5000 ms)
53
84
  });
54
85
 
55
- const wb = office.getDocument(); // Cell.Workbook — module 리터럴로 타입 추론
86
+ const wb = office.getDocument(); // Cell.Workbook — typed from the module literal
56
87
  const ws = await wb.getWorksheet('Sheet1');
57
88
  const rg = await ws.getRange('A1:B2');
58
89
  const values = await rg.getValues();
59
90
 
60
- office.disconnect(); // 연결만 해제 — 편집기·문서는 그대로
91
+ office.getVersion(); // SDK bundle version, e.g. '0.2.0' — synchronous, no connection needed
92
+ office.disconnect(); // releases the connection only; the editor and document stay as they are
61
93
  ```
62
94
 
63
- ## 문서 핸들 (getDocument)
95
+ > `getVersion()` returns the installed SDK library version (the same value the SDK reports as `sdkVersion` in every message envelope). It works after `disconnect()` and is not the version of the connected editor.
64
96
 
65
- | module | 최상위 핸들 |
66
- |--------|-------------------------|
67
- | `word` | `Word.WordDocument` |
68
- | `cell` | `Cell.Workbook` |
69
- | `show` | `Show.Document` |
97
+ ## Application and document metadata
70
98
 
71
- 핸들 메서드는 모두 postMessage 왕복이므로 `Promise` 를 반환하며, 다른 엔티티 핸들(`Show.Slide`, `Cell.Worksheet` 등)을 다시 반환할 수 있습니다.
99
+ Both the app handle and the document handle expose metadata. The editor answers these calls, so they behave the same in all three modules.
72
100
 
73
- cell 핸들은 **경로 참조(lazy)** 입니다: `getWorksheet` / `getRange` 같은 네비게이션 메서드는 통신 없이 하위 핸들을 즉시 반환하고(존재 확인 안 함), `getValues` / `setValues` 같은 실행 메서드를 호출하는 시점에 1왕복으로 경로를 평가합니다. 경로 중간 대상이 없으면 그 호출이 `SDKError` 로 reject 됩니다.
101
+ ```ts
102
+ import { Office, OfficeType } from '@thinkfree.dev/tfo-sdk';
74
103
 
75
- ## AI 에이전트 통합
104
+ const app = Office.word(iframeEl);
105
+
106
+ app.getApplicationType(); // 'word' — synchronous. Equals OfficeType.WORD
107
+ await app.getApplicationName(); // 'Word Processor' — display name
108
+ await app.getApplicationVersion(); // 'V17.0.0' — editor server build (null when the deployment does not expose it)
109
+
110
+ const doc = app.getDocument();
111
+ await doc.isReadOnly(); // reflects the mode the document actually opened in
112
+ await doc.getFileName(); // 'report.docx' — current name, including renames
113
+ ```
76
114
 
77
- 편집기 모듈이 자기 도구 카탈로그를 소유하고(`SDK.toolList`), SDK 는 schema 를 회수해 전달만 합니다.
115
+ - `getApplicationVersion()` (editor server build, async) and `getVersion()` (SDK bundle, sync) are different values.
116
+ - `isReadOnly()` reports the **actual** opened mode, not the mode requested in the URL. Server-enforced viewer mode, forced viewer for protected or unsupported files, and watcher mode all return `true`.
117
+ - Values are not cached. Renames and mode changes are reflected on every call.
118
+ - Against an older editor that does not implement the metadata command, these methods (except the synchronous `getApplicationType()`) reject with `SDKError(TIMEOUT)`.
119
+
120
+ ## Document handles (`getDocument`)
121
+
122
+ | module | root handle | from the app handle |
123
+ |--------|-------------|---------------------|
124
+ | `word` | `Word.WordDocument` | `word.getDocument()` |
125
+ | `cell` | `Cell.Workbook` | `cell.getDocument()` · `cell.getWorkbook()` |
126
+ | `show` | `Show.Document` | `show.getDocument()` |
127
+
128
+ Every handle method is a `postMessage` round trip and returns a `Promise`. Methods may return further entity handles (`Show.Slide`, `Cell.Worksheet`, and so on).
129
+
130
+ All root handles share the module-independent methods `isReadOnly()` and `getFileName()` described above.
131
+
132
+ > **Spreadsheet alias** — `cell.getWorkbook()` returns exactly the same `Cell.Workbook` as `cell.getDocument()`. Use `getDocument()` in module-independent code and `getWorkbook()` when spreadsheet vocabulary reads better. `word` and `show` have no alias because their root handles are already document-shaped.
133
+
134
+ Spreadsheet handles are **lazy path references**: navigation methods such as `getWorksheet` and `getRange` return child handles immediately without a round trip and without checking that the target exists. The path is evaluated in one round trip when you call an action method such as `getValues` or `setValues`. If an intermediate target does not exist, that call rejects with `SDKError`.
135
+
136
+ ## AI agent integration
137
+
138
+ The editor module owns its tool catalog. The SDK fetches the schemas and hands them to you.
78
139
 
79
140
  ```ts
80
141
  const word = Office.word(iframeEl);
81
142
 
82
- // 실행 가능한 도구 배열 — name · description · inputSchema · execute (개발자 기본 경로)
143
+ // Executable tools — name · description · inputSchema · execute (the usual developer path)
83
144
  const tools = await word.getTools({ include: ['insert_text'] });
84
- const result = await tools[0].execute({ text: 'Hello' }); // 모듈의 MCP CallToolResult
145
+ const result = await tools[0].execute({ text: 'Hello' }); // the module's MCP CallToolResult
85
146
 
86
- // registerTool 콜백을 받는 프레임워크(tf-agent-sdk 등)면 자동 등록
147
+ // Frameworks with a registerTool callback (for example the Thinkfree Agent runtime) — register automatically
87
148
  await word.registerTools(modelContext);
88
149
 
89
- // 또는 직접 dispatch (도구 이름은 모듈 카탈로그가 소유)
150
+ // Or dispatch directly (tool names are owned by the module catalog)
90
151
  await word.execute('insert_text', [{ text: 'Hello' }]);
91
152
 
92
- // 모듈 제공 system prompt (제공하지 않는 모듈은 빈 문자열)
153
+ // System prompt provided by the module ('' when the module has none)
93
154
  const prompt = await word.getSystemPrompt();
94
155
  ```
95
156
 
96
- `registerTools` 의 기본 결과 포맷은 MCP shape(`{ content: [{ type: 'text', text }] }`)이며, `formatResult` / `formatError` 옵션으로 바꿀 수 있습니다.
157
+ `registerTools` returns results in MCP shape (`{ content: [{ type: 'text', text }] }`) by default. Override with the `formatResult` / `formatError` options.
158
+
159
+ In addition to the module catalog, the tool list contains **two SDK-defined tools**:
160
+
161
+ - `get_api_reference` — looks up the document API reference (index, details by name, keyword search). The SDK answers locally from a bundled reference; the data lives in a separate chunk, `apiReference.generated.js`, loaded on first use.
162
+ - `execute_script` — runs a JavaScript snippet inside the editor so multi-step or repetitive edits happen in one call. It reports without throwing, as `{ ok, status, logs }`.
163
+
164
+ Keep the tool set small and task-specific with `include`. See the guide on [document tools and errors](https://www.developers.thinkfree.com/docs/editor-sdk/tools-and-errors/) for framework-specific schema mappings, and the [Editor AI SDK](https://www.developers.thinkfree.com/docs/editor-ai-sdk/) docs for a complete tool-calling loop.
97
165
 
98
- ## 에러 처리
166
+ ## Error handling
99
167
 
100
- 실패는 `SDKError` 로 reject 됩니다. 문서 핸들 호출 실패 시 `SDKError.data` 에 구조화 응답(`ApiErrorResponse`)이 실립니다 — message 문자열을 파싱하지 말고 코드로 분기하세요.
168
+ Failures reject with `SDKError`. When a document handle call fails, `SDKError.data` carries the structured response (`ApiErrorResponse`). Branch on the code; do not parse the message string.
101
169
 
102
170
  ```ts
103
171
  import { SDKError, type ApiErrorResponse } from '@thinkfree.dev/tfo-sdk';
104
172
 
105
173
  try {
106
- const ws = wb.getWorksheet('Nope'); // 네비게이션 — 통신 없음 (lazy)
107
- await ws.getRange('A1').getValues(); // 실행 시점에 경로 평가 → 여기서 reject
174
+ const ws = wb.getWorksheet('Nope'); // navigation — no round trip (lazy)
175
+ await ws.getRange('A1').getValues(); // the path is evaluated here → rejects
108
176
  } catch (e) {
109
177
  if (e instanceof SDKError && e.data && typeof e.data === 'object') {
110
178
  const { error } = e.data as ApiErrorResponse;
111
- error.code; // 'SHEET_NOT_FOUND' 같은 UPPERCASE_SNAKE 상수
112
- error.message; // 사람이 읽을 실패 사유
179
+ error.code; // UPPERCASE_SNAKE constant such as 'SHEET_NOT_FOUND'
180
+ error.message; // human-readable reason
113
181
  }
114
182
  }
115
183
  ```
116
184
 
117
- SDK 자체 오류는 `SDK_ERROR_CODE` 상수로 분기합니다 — `INVALID_ARGUMENT` · `TIMEOUT` · `DESTROYED` · `INVALID_RESPONSE` · `NETWORK_ERROR` · `FRAMEWORK_ERROR`.
185
+ SDK-level errors use the `SDK_ERROR_CODE` constants: `INVALID_ARGUMENT` · `TIMEOUT` · `DESTROYED` · `INVALID_RESPONSE` · `NETWORK_ERROR` · `FRAMEWORK_ERROR`.
186
+
187
+ ## Types
188
+
189
+ - Module namespaces (types and values): `Word.*` · `Cell.*` · `Show.*` — for example the `Show.Slide` type and the `Word.RangePosition.END` value.
190
+ - Shared enums (flat, types and values): `LineDash` · `ShapePreset` · `ShapeZOrder`.
191
+ - Key types: `Office<M>` · `OfficeApp` · `OfficeOptions` · `OfficeAppOptions` · `OfficeTool` · `ToolSchema` · `ApiResponse` · `ApiErrorResponse`.
192
+
193
+ The type definitions (`index.d.ts`) are generated from the API JSDoc in the private implementation repository and shipped with the package.
118
194
 
119
- ## 타입
195
+ ## Security notes
120
196
 
121
- - 모듈 네임스페이스 (타입 + 값): `Word.*` · `Cell.*` · `Show.*` — 예: `Show.Slide` 타입, `Word.RangePosition.END` 값
122
- - 공통 enum (flat, 타입 + 값): `LineDash` · `ShapePreset` · `ShapeZOrder`
123
- - 주요 타입: `Office<M>` · `OfficeApp` · `OfficeOptions` · `OfficeAppOptions` · `OfficeTool` · `ToolSchema` · `ApiResponse` · `ApiErrorResponse`
197
+ - Always pass the exact editor origin. `frameworkOrigin: '*'` is rejected.
198
+ - The SDK does not send anything to a model provider by itself. If you forward document-read results to an LLM, document content leaves the browser; your application controls what is sent, authorization, and user approval.
199
+ - Release the connection when the page goes away: `window.addEventListener('pagehide', () => app.disconnect())`.
124
200
 
125
- 타입 정의(`index.d.ts`)는 비공개 구현 저장소의 API JSDoc 에서 생성되어 패키지에 포함됩니다. 이 저장소 단독으로는 빌드·재생성이 지원되지 않습니다.
201
+ ## Versioning
126
202
 
127
- ## 버전
203
+ This package is at 0.x; the public surface may change in minor releases. At runtime the `SDK_VERSION` constant exposes the installed version. The SDK also reports it as `sdkVersion` in every message envelope so the editor can apply per-tool and per-API minimum-version gates (compatibility negotiation, not a security boundary).
128
204
 
129
- 현재 0.x 입니다 — 공개 표면이 마이너 릴리스에서 바뀔 수 있습니다.
205
+ ## Links
130
206
 
131
- 런타임에서는 `SDK_VERSION` 상수로 설치된 패키지 버전을 확인할 수 있습니다. 이 값은 매 호출의
132
- 메시지 envelope 에 `sdkVersion` 으로 자기 신고되어, 편집기 모듈이 도구·API 별 최소 버전 게이트를
133
- 적용하는 데 쓰입니다 (호환성 협상용 — 보안 경계가 아닙니다).
207
+ - Playground (try before installing): <https://playground.developers.thinkfree.com/playground/>
208
+ - Overview: <https://www.developers.thinkfree.com/docs/editor-sdk/>
209
+ - Quickstart: <https://www.developers.thinkfree.com/docs/editor-sdk/quickstart/>
210
+ - Word API: <https://www.developers.thinkfree.com/docs/editor-sdk/word-api/>
211
+ - Spreadsheet API: <https://www.developers.thinkfree.com/docs/editor-sdk/spreadsheet-api/>
212
+ - Presentation API: <https://www.developers.thinkfree.com/docs/editor-sdk/presentation-api/>
213
+ - Document tools and errors: <https://www.developers.thinkfree.com/docs/editor-sdk/tools-and-errors/>
214
+ - Editor AI SDK (LLM tool-calling on top of this package): <https://www.developers.thinkfree.com/docs/editor-ai-sdk/> · npm: <https://www.npmjs.com/package/@thinkfree.dev/tfo-ai-sdk>