@wae/open-word 0.0.1 → 0.0.2

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
@@ -15,6 +15,8 @@ A session-oriented TypeScript API and the `open-word` CLI for creating, revising
15
15
  - **Review and delivery:** `inspect({ path }, { checks })`, `export({ format, target, overwrite })`
16
16
  - **CLI:** `open-word capabilities | create | open | save | inspect | find | stats | outline | edit | replace | template | undo | redo | merge | export | gui`
17
17
 
18
+ The CLI `open` command prints a document summary and exits; it opens no window. `open-word gui` is the only GUI entry.
19
+
18
20
  An edit batch is validated as a whole before the first mutation, and each applied operation advances the revision once. `expectedRevision` rejects a stale write with `document/revision-conflict`.
19
21
 
20
22
  ## Example
package/dist/errors.d.ts CHANGED
@@ -5,8 +5,8 @@
5
5
  * never parse the message. A failure therefore keeps its code even when the
6
6
  * text is translated.
7
7
  */
8
- /** Every stable code the authoring surface may report. */
9
- export declare const errorCodes: readonly ["session/disposed", "session/argument-invalid", "session/budget-exceeded", "document/not-found", "document/revision-conflict", "object/not-found", "object/unsupported", "format/unsupported", "format/invalid", "capability/not-implemented"];
8
+ /** Every stable code the document surface may report. */
9
+ export declare const errorCodes: readonly ["session/disposed", "session/argument-invalid", "session/budget-exceeded", "document/not-found", "document/revision-conflict", "io/read", "io/write", "io/exists", "io/failure", "object/not-found", "object/unsupported", "format/unsupported", "format/invalid", "capability/not-implemented", "binding/failure"];
10
10
  /** Union of {@link errorCodes}. */
11
11
  export type OpenWordErrorCode = (typeof errorCodes)[number];
12
12
  /** Optional locators a failure can carry so callers can point at the object. */
@@ -14,26 +14,138 @@ export interface OpenWordErrorDetails {
14
14
  readonly revision?: number;
15
15
  readonly documentId?: string;
16
16
  readonly objectId?: string;
17
- /** Document format involved in the failure, without the leading dot. */
17
+ /** Format involved in the failure, without the leading dot. */
18
18
  readonly format?: string;
19
- /** Authoring capability involved in the failure, e.g. `document.export`. */
19
+ /** Capability involved in the failure, e.g. `document.export`. */
20
20
  readonly feature?: string;
21
21
  }
22
+ /** A payload that carries no parameters of its own. */
23
+ type NoParams = {
24
+ readonly [key: string]: never;
25
+ };
26
+ /**
27
+ * Frozen payload of every code.
28
+ *
29
+ * These shapes are contract: the binding validates against them and the product
30
+ * renders copy from them, so a code never carries prose it has to be re-parsed.
31
+ * Only the translation changes between locales, never the payload.
32
+ */
33
+ export interface ErrorParamsByCode {
34
+ 'session/disposed': NoParams;
35
+ 'session/argument-invalid': {
36
+ readonly reason: string;
37
+ };
38
+ 'session/budget-exceeded': NoParams;
39
+ 'document/not-found': {
40
+ readonly handle?: number;
41
+ };
42
+ 'document/revision-conflict': {
43
+ readonly actual: number;
44
+ readonly expected?: number;
45
+ };
46
+ 'io/read': {
47
+ readonly path: string;
48
+ readonly kind: string;
49
+ };
50
+ 'io/write': {
51
+ readonly path: string;
52
+ };
53
+ 'io/exists': {
54
+ readonly path: string;
55
+ };
56
+ 'io/failure': {
57
+ readonly reason: string;
58
+ };
59
+ 'object/not-found': {
60
+ readonly kind: string;
61
+ readonly id: string;
62
+ };
63
+ 'object/unsupported': {
64
+ readonly operation: string;
65
+ readonly name: string;
66
+ };
67
+ 'format/unsupported': {
68
+ readonly format: string;
69
+ };
70
+ 'format/invalid': {
71
+ readonly format: string;
72
+ readonly reason: string;
73
+ };
74
+ 'capability/not-implemented': {
75
+ readonly feature: string;
76
+ };
77
+ 'binding/failure': {
78
+ readonly reason: string;
79
+ readonly code?: string;
80
+ };
81
+ }
82
+ /** Union of every frozen payload. */
83
+ export type OpenWordErrorParams = ErrorParamsByCode[OpenWordErrorCode];
84
+ /**
85
+ * One failure as a discriminated union: narrowing on `code` narrows `params`.
86
+ *
87
+ * Callers branch on {@link OpenWordFailure.code} and read the payload without a
88
+ * cast, so no branch depends on the wording of a message.
89
+ */
90
+ export type OpenWordFailure = {
91
+ [Code in OpenWordErrorCode]: {
92
+ readonly code: Code;
93
+ readonly params: ErrorParamsByCode[Code];
94
+ };
95
+ }[OpenWordErrorCode];
96
+ /** Why a payload was refused. */
97
+ export interface ErrorParamsRejection {
98
+ /** `unknown-code`: the code is outside the contract; `malformed`: the payload does not match its shape. */
99
+ readonly kind: 'unknown-code' | 'malformed';
100
+ /** Machine-readable reason, e.g. `missing key `id``. */
101
+ readonly reason: string;
102
+ }
103
+ /** Outcome of validating one payload against its code's frozen shape. */
104
+ export type ErrorParamsResult = {
105
+ readonly ok: true;
106
+ readonly params: OpenWordErrorParams;
107
+ } | {
108
+ readonly ok: false;
109
+ readonly rejection: ErrorParamsRejection;
110
+ };
111
+ /**
112
+ * Validates one payload against its code's frozen shape.
113
+ *
114
+ * A payload must be a plain object carrying exactly the declared keys, each of
115
+ * the declared type. Unknown codes, prose, arrays, missing keys, extra keys and
116
+ * mistyped values are refused so nothing half-formed reaches a branch.
117
+ */
118
+ export declare function parseErrorParams(code: string, payload: unknown): ErrorParamsResult;
119
+ /** Whether a code belongs to the frozen contract. */
120
+ export declare function isContractedCode(code: string): code is OpenWordErrorCode;
121
+ /**
122
+ * Resolves one code and payload into a discriminated failure.
123
+ *
124
+ * Unknown codes and malformed payloads land on `binding/failure`, keeping the
125
+ * original code and text as payload instead of guessing at parameters. That
126
+ * fallback is itself structured, so every branch stays exhaustive.
127
+ */
128
+ export declare function failureFrom(code: string, message: string, payload: unknown): OpenWordFailure;
22
129
  /** Options accepted by {@link OpenWordError}. */
23
130
  export interface OpenWordErrorOptions {
24
131
  readonly recoverable?: boolean;
25
132
  readonly details?: OpenWordErrorDetails;
133
+ readonly params?: unknown;
26
134
  readonly cause?: unknown;
27
135
  }
28
136
  /** Every failure thrown or rejected by this package. */
29
137
  export declare class OpenWordError extends Error {
30
- /** Stable, comparable code. */
31
- readonly code: OpenWordErrorCode;
138
+ /** The code and its frozen payload, as a discriminated union. */
139
+ readonly failure: OpenWordFailure;
32
140
  /** Whether retrying with different input or state can succeed. */
33
141
  readonly recoverable: boolean;
34
142
  /** Optional locators (`revision`, `documentId`, `objectId`, `format`, `feature`). */
35
143
  readonly details: OpenWordErrorDetails;
36
- constructor(code: OpenWordErrorCode, message: string, options?: OpenWordErrorOptions);
144
+ constructor(code: string, message: string, options?: OpenWordErrorOptions);
145
+ /** Stable, comparable code. */
146
+ get code(): OpenWordErrorCode;
147
+ /** Frozen parameters of {@link code}. */
148
+ get params(): OpenWordErrorParams;
37
149
  }
38
150
  /**
39
151
  * Reported by declared methods whose backing capability is not wired yet.
@@ -47,3 +159,14 @@ export declare class NotImplementedError extends OpenWordError {
47
159
  }
48
160
  /** Narrows an unknown thrown value to {@link OpenWordError}. */
49
161
  export declare function isOpenWordError(value: unknown): value is OpenWordError;
162
+ /** Selects the locale used to render error copy; `zh*` maps to `zh-CN`. */
163
+ export declare function setErrorLocale(tag: string): void;
164
+ /**
165
+ * Renders the product copy for a code and its params.
166
+ *
167
+ * Unknown codes and missing translations fall back to the binding's own text,
168
+ * so a replaced or removed native message never changes which branch a caller
169
+ * takes: that branch is decided by `code` and `params`.
170
+ */
171
+ export declare function renderErrorCopy(code: string, params: OpenWordErrorParams, fallback: string): string;
172
+ export {};
package/dist/errors.js CHANGED
@@ -5,23 +5,130 @@
5
5
  * never parse the message. A failure therefore keeps its code even when the
6
6
  * text is translated.
7
7
  */
8
- /** Every stable code the authoring surface may report. */
8
+ /** Every stable code the document surface may report. */
9
9
  export const errorCodes = [
10
10
  'session/disposed',
11
11
  'session/argument-invalid',
12
12
  'session/budget-exceeded',
13
13
  'document/not-found',
14
14
  'document/revision-conflict',
15
+ 'io/read',
16
+ 'io/write',
17
+ 'io/exists',
18
+ 'io/failure',
15
19
  'object/not-found',
16
20
  'object/unsupported',
17
21
  'format/unsupported',
18
22
  'format/invalid',
19
23
  'capability/not-implemented',
24
+ 'binding/failure',
20
25
  ];
26
+ const paramSpecs = {
27
+ 'session/disposed': {},
28
+ 'session/argument-invalid': { reason: 'string' },
29
+ 'session/budget-exceeded': {},
30
+ 'document/not-found': { handle: 'number?' },
31
+ 'document/revision-conflict': { actual: 'number', expected: 'number?' },
32
+ 'io/read': { path: 'string', kind: 'string' },
33
+ 'io/write': { path: 'string' },
34
+ 'io/exists': { path: 'string' },
35
+ 'io/failure': { reason: 'string' },
36
+ 'object/not-found': { kind: 'string', id: 'string' },
37
+ 'object/unsupported': { operation: 'string', name: 'string' },
38
+ 'format/unsupported': { format: 'string' },
39
+ 'format/invalid': { format: 'string', reason: 'string' },
40
+ 'capability/not-implemented': { feature: 'string' },
41
+ 'binding/failure': { reason: 'string', code: 'string?' },
42
+ };
43
+ /**
44
+ * Validates one payload against its code's frozen shape.
45
+ *
46
+ * A payload must be a plain object carrying exactly the declared keys, each of
47
+ * the declared type. Unknown codes, prose, arrays, missing keys, extra keys and
48
+ * mistyped values are refused so nothing half-formed reaches a branch.
49
+ */
50
+ export function parseErrorParams(code, payload) {
51
+ if (!isContractedCode(code)) {
52
+ return { ok: false, rejection: { kind: 'unknown-code', reason: 'unknown code ' + code } };
53
+ }
54
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
55
+ return { ok: false, rejection: { kind: 'malformed', reason: `${code} needs an object payload` } };
56
+ }
57
+ const spec = paramSpecs[code];
58
+ const record = payload;
59
+ for (const key of Object.keys(record)) {
60
+ if (!(key in spec)) {
61
+ return { ok: false, rejection: { kind: 'malformed', reason: 'unknown key ' + key + ' for ' + code } };
62
+ }
63
+ }
64
+ for (const [key, kind] of Object.entries(spec)) {
65
+ const optional = kind.endsWith('?');
66
+ const value = record[key];
67
+ if (value === undefined || (optional && value === null)) {
68
+ if (optional) {
69
+ continue;
70
+ }
71
+ return { ok: false, rejection: { kind: 'malformed', reason: 'missing key ' + key + ' for ' + code } };
72
+ }
73
+ const expected = kind.startsWith('number') ? 'number' : 'string';
74
+ if (typeof value !== expected || (expected === 'number' && !Number.isFinite(value))) {
75
+ return { ok: false, rejection: { kind: 'malformed', reason: 'key ' + key + ' must be a ' + expected + ' for ' + code } };
76
+ }
77
+ }
78
+ return { ok: true, params: record };
79
+ }
80
+ /** Whether a code belongs to the frozen contract. */
81
+ export function isContractedCode(code) {
82
+ return Object.prototype.hasOwnProperty.call(paramSpecs, code);
83
+ }
84
+ /**
85
+ * Resolves one code and payload into a discriminated failure.
86
+ *
87
+ * Unknown codes and malformed payloads land on `binding/failure`, keeping the
88
+ * original code and text as payload instead of guessing at parameters. That
89
+ * fallback is itself structured, so every branch stays exhaustive.
90
+ */
91
+ export function failureFrom(code, message, payload) {
92
+ const parsed = parseErrorParams(code, payload);
93
+ if (parsed.ok) {
94
+ return { code: code, params: parsed.params };
95
+ }
96
+ return { code: 'binding/failure', params: { reason: message, code } };
97
+ }
98
+ /**
99
+ * Payload the class derives when a caller omits one.
100
+ *
101
+ * Codes whose shape is only a `reason` take the message; codes whose shape is a
102
+ * locator take it from `details`. Codes that address an object by `kind`/`id`
103
+ * (or by `handle`, `path`, `operation`) must supply `params` explicitly, and an
104
+ * omission stays unstructured so the failure surfaces as `binding/failure`
105
+ * instead of a half-filled payload.
106
+ */
107
+ function defaultParams(code, message, details) {
108
+ switch (code) {
109
+ case 'session/argument-invalid':
110
+ case 'format/invalid':
111
+ case 'io/failure':
112
+ case 'binding/failure':
113
+ return { reason: message };
114
+ case 'capability/not-implemented':
115
+ return details.feature === undefined ? undefined : { feature: details.feature };
116
+ case 'format/unsupported':
117
+ return details.format === undefined ? undefined : { format: details.format };
118
+ case 'document/revision-conflict':
119
+ return details.revision === undefined ? undefined : { actual: details.revision };
120
+ case 'session/disposed':
121
+ case 'session/budget-exceeded':
122
+ case 'document/not-found':
123
+ return {};
124
+ default:
125
+ return undefined;
126
+ }
127
+ }
21
128
  /** Every failure thrown or rejected by this package. */
22
129
  export class OpenWordError extends Error {
23
- /** Stable, comparable code. */
24
- code;
130
+ /** The code and its frozen payload, as a discriminated union. */
131
+ failure;
25
132
  /** Whether retrying with different input or state can succeed. */
26
133
  recoverable;
27
134
  /** Optional locators (`revision`, `documentId`, `objectId`, `format`, `feature`). */
@@ -29,10 +136,19 @@ export class OpenWordError extends Error {
29
136
  constructor(code, message, options = {}) {
30
137
  super(message, options.cause === undefined ? undefined : { cause: options.cause });
31
138
  this.name = 'OpenWordError';
32
- this.code = code;
139
+ const params = options.params ?? defaultParams(code, message, options.details ?? {});
140
+ this.failure = failureFrom(code, message, params);
33
141
  this.recoverable = options.recoverable ?? false;
34
142
  this.details = Object.freeze({ ...options.details });
35
143
  }
144
+ /** Stable, comparable code. */
145
+ get code() {
146
+ return this.failure.code;
147
+ }
148
+ /** Frozen parameters of {@link code}. */
149
+ get params() {
150
+ return this.failure.params;
151
+ }
36
152
  }
37
153
  /**
38
154
  * Reported by declared methods whose backing capability is not wired yet.
@@ -43,7 +159,7 @@ export class OpenWordError extends Error {
43
159
  */
44
160
  export class NotImplementedError extends OpenWordError {
45
161
  constructor(feature, message = `\`${feature}\` is not implemented yet`) {
46
- super('capability/not-implemented', message, { recoverable: false, details: { feature } });
162
+ super('capability/not-implemented', message, { recoverable: false, details: { feature }, params: { feature } });
47
163
  this.name = 'NotImplementedError';
48
164
  }
49
165
  }
@@ -51,3 +167,73 @@ export class NotImplementedError extends OpenWordError {
51
167
  export function isOpenWordError(value) {
52
168
  return value instanceof OpenWordError;
53
169
  }
170
+ /**
171
+ * Product copy for each stable code, rendered from its typed `params`.
172
+ *
173
+ * The binding's own text is only a fallback for codes this catalog does not
174
+ * carry yet; the machine-readable `code` and `params` never depend on locale.
175
+ */
176
+ const messageCatalog = {
177
+ en: {
178
+ 'session/disposed': 'the OpenWord session has been disposed; create a new instance',
179
+ 'session/argument-invalid': 'the request was rejected: {reason}',
180
+ 'session/budget-exceeded': 'the operation exceeded the session budget',
181
+ 'document/not-found': 'no live document has handle {handle}',
182
+ 'document/revision-conflict': 'the document changed at revision {actual}; the edit expected {expected}',
183
+ 'io/read': 'could not read `{path}` ({kind})',
184
+ 'io/write': 'could not publish `{path}`',
185
+ 'io/exists': '`{path}` already exists; pass overwrite to replace it',
186
+ 'io/failure': 'the file operation failed: {reason}',
187
+ 'object/not-found': 'the `{kind}` `{id}` was not found',
188
+ 'object/unsupported': 'the `{operation}` `{name}` is not supported by this build',
189
+ 'format/unsupported': '`{format}` has no route in this build',
190
+ 'format/invalid': 'the `{format}` input is invalid: {reason}',
191
+ 'capability/not-implemented': 'the `{feature}` capability is not implemented yet',
192
+ 'binding/failure': 'the native binding reported a failure: {reason}',
193
+ },
194
+ 'zh-CN': {
195
+ 'session/disposed': 'OpenWord 会话已释放;请创建新实例',
196
+ 'session/argument-invalid': '请求被拒绝:{reason}',
197
+ 'session/budget-exceeded': '操作超出会话预算',
198
+ 'document/not-found': '没有句柄 {handle} 对应的活动文档',
199
+ 'document/revision-conflict': '文档已变更到修订 {actual};本次编辑期望 {expected}',
200
+ 'io/read': '无法读取 `{path}`({kind})',
201
+ 'io/write': '无法发布 `{path}`',
202
+ 'io/exists': '`{path}` 已存在;传入 overwrite 以替换',
203
+ 'io/failure': '文件操作失败:{reason}',
204
+ 'object/not-found': '未找到 `{kind}` `{id}`',
205
+ 'object/unsupported': '此构建不支持 `{operation}` `{name}`',
206
+ 'format/unsupported': '`{format}` 在此构建中没有可用路径',
207
+ 'format/invalid': '`{format}` 输入无效:{reason}',
208
+ 'capability/not-implemented': '`{feature}` 能力尚未实现',
209
+ 'binding/failure': '原生绑定返回了失败:{reason}',
210
+ },
211
+ };
212
+ let currentLocale = 'en';
213
+ /** Selects the locale used to render error copy; `zh*` maps to `zh-CN`. */
214
+ export function setErrorLocale(tag) {
215
+ currentLocale = tag.toLowerCase().startsWith('zh') ? 'zh-CN' : 'en';
216
+ }
217
+ /**
218
+ * Renders the product copy for a code and its params.
219
+ *
220
+ * Unknown codes and missing translations fall back to the binding's own text,
221
+ * so a replaced or removed native message never changes which branch a caller
222
+ * takes: that branch is decided by `code` and `params`.
223
+ */
224
+ export function renderErrorCopy(code, params, fallback) {
225
+ const template = messageCatalog[currentLocale]?.[code];
226
+ if (template === undefined) {
227
+ return fallback;
228
+ }
229
+ const payload = params;
230
+ let complete = true;
231
+ const rendered = template.replace(/\{(\w+)\}/g, (match, key) => {
232
+ if (payload[key] === undefined) {
233
+ complete = false;
234
+ return match;
235
+ }
236
+ return String(payload[key]);
237
+ });
238
+ return complete ? rendered : fallback;
239
+ }
package/dist/index.d.ts CHANGED
@@ -9,8 +9,8 @@
9
9
  export { OpenWord } from './open-word.js';
10
10
  export { GuiError, closeGui, defaultGuiContentDir, isGuiOpen, openGui, pumpEvents, runGui } from './gui.js';
11
11
  export type { GuiCloseResult, GuiOpenResult, GuiStatus, OpenGuiOptions } from './gui.js';
12
- export { NotImplementedError, OpenWordError, errorCodes, isOpenWordError } from './errors.js';
13
- export type { OpenWordErrorCode, OpenWordErrorDetails, OpenWordErrorOptions } from './errors.js';
12
+ export { NotImplementedError, OpenWordError, errorCodes, isOpenWordError, renderErrorCopy, setErrorLocale } from './errors.js';
13
+ export type { OpenWordErrorCode, OpenWordErrorDetails, OpenWordErrorOptions, OpenWordErrorParams } from './errors.js';
14
14
  export { defaultIntentFor, documentFormats, formatFromPath, formatInfo, formatRegistry } from './formats.js';
15
15
  export type { DocumentFormat, DocumentFormatInfo, DocumentIntent, FormatFamily, FormatMarkup, FormatOpenKind, } from './formats.js';
16
16
  export type * from './types.js';
package/dist/index.js CHANGED
@@ -8,5 +8,5 @@
8
8
  */
9
9
  export { OpenWord } from './open-word.js';
10
10
  export { GuiError, closeGui, defaultGuiContentDir, isGuiOpen, openGui, pumpEvents, runGui } from './gui.js';
11
- export { NotImplementedError, OpenWordError, errorCodes, isOpenWordError } from './errors.js';
11
+ export { NotImplementedError, OpenWordError, errorCodes, isOpenWordError, renderErrorCopy, setErrorLocale } from './errors.js';
12
12
  export { defaultIntentFor, documentFormats, formatFromPath, formatInfo, formatRegistry } from './formats.js';
package/dist/native.d.ts CHANGED
@@ -34,5 +34,31 @@ export interface NativeBinding {
34
34
  closeGui(): string;
35
35
  isGuiOpen(): boolean;
36
36
  }
37
+ /**
38
+ * One failure as the addon reports it.
39
+ *
40
+ * `code` and `detail.params` are the machine contract; `message` is display
41
+ * text only. `detail` also carries the optional locators beside the payload.
42
+ */
43
+ export interface NativeFailure {
44
+ readonly code: string;
45
+ readonly message: string;
46
+ readonly detail: {
47
+ readonly params?: unknown;
48
+ readonly revision?: number;
49
+ readonly documentId?: string;
50
+ readonly objectId?: string;
51
+ readonly format?: string;
52
+ readonly feature?: string;
53
+ readonly recoverable?: boolean;
54
+ };
55
+ }
56
+ /**
57
+ * Reads one thrown native value into {@link NativeFailure}, or `undefined` when
58
+ * it carries no stable code.
59
+ *
60
+ * This only reads fields: no branch compares message text.
61
+ */
62
+ export declare function readNativeFailure(error: unknown): NativeFailure | undefined;
37
63
  /** Loads the addon once, or returns `undefined` when it is not installed. */
38
64
  export declare function nativeBinding(): NativeBinding | undefined;
package/dist/native.js CHANGED
@@ -8,6 +8,24 @@
8
8
  import { createRequire } from 'node:module';
9
9
  const requireNative = createRequire(import.meta.url);
10
10
  let cached;
11
+ /**
12
+ * Reads one thrown native value into {@link NativeFailure}, or `undefined` when
13
+ * it carries no stable code.
14
+ *
15
+ * This only reads fields: no branch compares message text.
16
+ */
17
+ export function readNativeFailure(error) {
18
+ if (typeof error !== 'object' || error === null) {
19
+ return undefined;
20
+ }
21
+ const candidate = error;
22
+ if (typeof candidate.code !== 'string' || candidate.code.length === 0) {
23
+ return undefined;
24
+ }
25
+ const detail = typeof candidate.detail === 'object' && candidate.detail !== null ? candidate.detail : {};
26
+ const message = typeof candidate.message === 'string' ? candidate.message : String(error);
27
+ return { code: candidate.code, message, detail };
28
+ }
11
29
  /** Loads the addon once, or returns `undefined` when it is not installed. */
12
30
  export function nativeBinding() {
13
31
  if (cached === undefined) {
package/dist/open-word.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * no window, no file. Native initialisation and imports happen inside the async
6
6
  * methods, so a failure is always awaited and always carries a stable code.
7
7
  */
8
- import { OpenWordError } from './errors.js';
8
+ import { OpenWordError, setErrorLocale } from './errors.js';
9
9
  import * as service from './service.js';
10
10
  /** Authoring session. One instance manages one declared document surface. */
11
11
  export class OpenWord {
@@ -16,6 +16,7 @@ export class OpenWord {
16
16
  handles = new Set();
17
17
  constructor(options = {}) {
18
18
  this.locale = options.locale ?? 'en';
19
+ setErrorLocale(this.locale);
19
20
  }
20
21
  /** Whether {@link dispose} has run. */
21
22
  get disposed() {
@@ -47,7 +48,7 @@ export class OpenWord {
47
48
  assertPath(path);
48
49
  const intent = input?.intent ?? 'edit';
49
50
  if (intent !== 'edit') {
50
- throw new OpenWordError('format/unsupported', `native documents open for editing; \`${intent}\` needs the projection pipeline`, { details: { feature: `open.intent.${intent}` } });
51
+ throw new OpenWordError('capability/not-implemented', `native documents open for editing; \`${intent}\` needs the projection pipeline`, { details: { feature: `open.intent.${intent}` } });
51
52
  }
52
53
  const opened = service.open(path);
53
54
  this.handles.add(opened.handle);
package/dist/service.js CHANGED
@@ -5,9 +5,8 @@
5
5
  * text and exit codes belong to `cli.ts` and to the authoring surface. Nothing
6
6
  * here knows about a command line.
7
7
  */
8
- import { NotImplementedError, OpenWordError, errorCodes } from './errors.js';
9
- import { nativeBinding } from './native.js';
10
- const knownCodes = new Set(errorCodes);
8
+ import { NotImplementedError, OpenWordError, failureFrom, renderErrorCopy } from './errors.js';
9
+ import { nativeBinding, readNativeFailure } from './native.js';
11
10
  function binding(feature) {
12
11
  const native = nativeBinding();
13
12
  if (!native) {
@@ -27,13 +26,29 @@ function translate(error) {
27
26
  if (error instanceof OpenWordError) {
28
27
  return error;
29
28
  }
30
- const message = error instanceof Error ? error.message : String(error);
31
- const separator = message.indexOf(': ');
32
- const code = separator > 0 ? message.slice(0, separator) : '';
33
- if (knownCodes.has(code)) {
34
- return new OpenWordError(code, message.slice(separator + 2), { details: { feature: code } });
29
+ const native = readNativeFailure(error);
30
+ if (native === undefined) {
31
+ const message = error instanceof Error ? error.message : String(error);
32
+ const params = { reason: message };
33
+ return new OpenWordError('binding/failure', renderErrorCopy('binding/failure', params, message), {
34
+ params,
35
+ cause: error,
36
+ });
35
37
  }
36
- return new OpenWordError('format/invalid', message, { cause: error });
38
+ // Branch on the code and its frozen payload; the native text is display only.
39
+ const failure = failureFrom(native.code, native.message, native.detail.params);
40
+ return new OpenWordError(failure.code, renderErrorCopy(failure.code, failure.params, native.message), {
41
+ params: failure.params,
42
+ details: {
43
+ revision: native.detail.revision,
44
+ documentId: native.detail.documentId,
45
+ objectId: native.detail.objectId,
46
+ format: native.detail.format,
47
+ feature: native.detail.feature,
48
+ },
49
+ recoverable: native.detail.recoverable,
50
+ cause: error,
51
+ });
37
52
  }
38
53
  /** Reads the capability matrix of the installed addon. */
39
54
  export function capabilities() {
package/dist/types.d.ts CHANGED
@@ -216,6 +216,15 @@ export type EditOperation = {
216
216
  readonly type: 'heading.append';
217
217
  readonly level: number;
218
218
  readonly text: string;
219
+ } | {
220
+ /** Inserts a heading before the block at flat index `index`, mirroring `paragraph.insert`. */
221
+ readonly type: 'heading.insert';
222
+ /** Zero-based flat block index the new heading lands in front of; equal to the block count to append. */
223
+ readonly index: number;
224
+ /** Heading level, `1..6`. */
225
+ readonly level: number;
226
+ /** Heading text, stored as one plain text run. */
227
+ readonly text: string;
219
228
  } | {
220
229
  /** Changes the level of an existing heading without moving or retitling it. */
221
230
  readonly type: 'heading.setLevel';
@@ -250,6 +259,104 @@ export type EditOperation = {
250
259
  readonly id: string;
251
260
  /** New first number; must be a positive integer. */
252
261
  readonly start: number;
262
+ } | {
263
+ /** Replaces one item's text, keeping its number, nesting and check state. */
264
+ readonly type: 'list.setItem';
265
+ /** List address such as `node-4`. */
266
+ readonly id: string;
267
+ /** Zero-based item index inside the list. */
268
+ readonly item: number;
269
+ /** New item text; must not be blank. */
270
+ readonly text: string;
271
+ } | {
272
+ /** Sets the check state of one task item, keeping its text and nesting. */
273
+ readonly type: 'list.setItemChecked';
274
+ /** Task list address such as `node-4`. */
275
+ readonly id: string;
276
+ /** Zero-based item index inside the list. */
277
+ readonly item: number;
278
+ /** New check state. */
279
+ readonly checked: boolean;
280
+ } | {
281
+ /** Marks one item as a task, or clears the task marker, keeping its text and nesting. */
282
+ readonly type: 'list.setItemTask';
283
+ /** List address such as `node-4`. */
284
+ readonly id: string;
285
+ /** Zero-based item index inside the list. */
286
+ readonly item: number;
287
+ /** `true` makes the item a task; `false` turns it back into a plain item. */
288
+ readonly task: boolean;
289
+ /** Initial check state when `task` is `true`; defaults to unchecked. */
290
+ readonly checked?: boolean;
291
+ } | {
292
+ /** Moves one item to a new position inside its list, keeping its content. */
293
+ readonly type: 'list.moveItem';
294
+ /** List address such as `node-4`. */
295
+ readonly id: string;
296
+ /** Zero-based item index to move. */
297
+ readonly item: number;
298
+ /** Zero-based target position inside the list. */
299
+ readonly index: number;
300
+ } | {
301
+ /** Moves one item, with everything nested under it, into another list. */
302
+ readonly type: 'list.moveItemTo';
303
+ /** Source list address such as `node-4`. */
304
+ readonly id: string;
305
+ /** Zero-based item index to move. */
306
+ readonly item: number;
307
+ /** Destination list address. */
308
+ readonly target: string;
309
+ /** Zero-based insertion point in the destination list, up to its item count. */
310
+ readonly index: number;
311
+ } | {
312
+ /** Sorts the list's top-level items by their text, keeping nested children attached. */
313
+ readonly type: 'list.sortItems';
314
+ /** List address such as `node-4`. */
315
+ readonly id: string;
316
+ /** Sorts ascending when true (the default); descending when false. */
317
+ readonly ascending?: boolean;
318
+ }
319
+ /** Flips the list's top-level items, keeping nested children attached; ordered lists renumber consecutively. */
320
+ | {
321
+ readonly type: 'list.reverseItems';
322
+ readonly id: string;
323
+ } | {
324
+ /** Nests one item under the item before it as a child list. */
325
+ readonly type: 'list.indentItem';
326
+ /** List address such as `node-4`. */
327
+ readonly id: string;
328
+ /** Zero-based item index; `0` is refused because the first item has no previous sibling. */
329
+ readonly item: number;
330
+ } | {
331
+ /** Lifts an item's nested list back into its parent run. */
332
+ readonly type: 'list.unindentItem';
333
+ /** List address such as `node-4`. */
334
+ readonly id: string;
335
+ /** Zero-based item index whose nested list is lifted; an item without one is refused. */
336
+ readonly item: number;
337
+ } | {
338
+ /** Inserts a new plain item before position `item` of an existing list. */
339
+ readonly type: 'list.insertItem';
340
+ /** List address such as `node-4`. */
341
+ readonly id: string;
342
+ /** Zero-based insertion point; equal to the item count to append at the end. */
343
+ readonly item: number;
344
+ /** New item text; must not be blank. */
345
+ readonly text: string;
346
+ } | {
347
+ /** Copies one item, with everything nested under it, directly after itself. */
348
+ readonly type: 'list.duplicateItem';
349
+ /** List address such as `node-4`. */
350
+ readonly id: string;
351
+ /** Zero-based item index; must exist in the run. */
352
+ readonly item: number;
353
+ } | {
354
+ /** Removes one item, with everything nested under it, from an existing list. */
355
+ readonly type: 'list.removeItem';
356
+ /** List address such as `node-4`. */
357
+ readonly id: string;
358
+ /** Zero-based item index; the last item cannot be removed. */
359
+ readonly item: number;
253
360
  } | {
254
361
  readonly type: 'taskList.append';
255
362
  /** A string item is unchecked; an object may set `checked`. */
@@ -260,6 +367,13 @@ export type EditOperation = {
260
367
  } | {
261
368
  readonly type: 'quote.append';
262
369
  readonly text: string;
370
+ } | {
371
+ /** Replaces a quote's content with one paragraph, keeping its id and position. */
372
+ readonly type: 'quote.setText';
373
+ /** Quote address such as `node-2`. */
374
+ readonly id: string;
375
+ /** New quote text; must be non-empty. */
376
+ readonly text: string;
263
377
  } | {
264
378
  readonly type: 'code.append';
265
379
  readonly text: string;
@@ -271,6 +385,13 @@ export type EditOperation = {
271
385
  readonly id: string;
272
386
  /** New tag; omit or use an empty string to clear it. */
273
387
  readonly language?: string;
388
+ } | {
389
+ /** Replaces the source text of an existing code block, keeping its language tag. */
390
+ readonly type: 'code.setText';
391
+ /** Code block address such as `node-5`. */
392
+ readonly id: string;
393
+ /** New source text; must be non-empty. */
394
+ readonly text: string;
274
395
  } | {
275
396
  readonly type: 'table.append';
276
397
  readonly rows: readonly (readonly string[])[];
@@ -280,6 +401,22 @@ export type EditOperation = {
280
401
  /** Zero-based table index in document order. */
281
402
  readonly table: number;
282
403
  readonly cells: readonly string[];
404
+ } | {
405
+ /** Replaces the table footer row; an empty array removes the footer. */
406
+ readonly type: 'table.setFooter';
407
+ /** Zero-based table index in document order. */
408
+ readonly table: number;
409
+ readonly cells: readonly string[];
410
+ } | {
411
+ /** Replaces the whole header band; every row needs the same cell count, an empty array clears it. */
412
+ readonly type: 'table.setHeaderRows';
413
+ readonly table: number;
414
+ readonly rows: readonly (readonly string[])[];
415
+ } | {
416
+ /** Replaces the whole footer band; every row needs the same cell count, an empty array clears it. */
417
+ readonly type: 'table.setFooterRows';
418
+ readonly table: number;
419
+ readonly rows: readonly (readonly string[])[];
283
420
  } | {
284
421
  readonly type: 'table.setCaption';
285
422
  /** Zero-based table index in document order. */
@@ -287,9 +424,14 @@ export type EditOperation = {
287
424
  /** New caption. Omit or `null` to clear the caption. */
288
425
  readonly caption?: string | null;
289
426
  } | {
427
+ /** Replaces document properties; at least one field is required. */
290
428
  readonly type: 'metadata.set';
291
429
  readonly title?: string;
292
430
  readonly author?: string;
431
+ /** Primary language tag such as `en` or `zh-CN`. */
432
+ readonly language?: string;
433
+ /** Free-form tags; an empty array clears them. */
434
+ readonly tags?: readonly string[];
293
435
  } | {
294
436
  readonly type: 'document.replaceText';
295
437
  readonly find: string;
@@ -308,6 +450,33 @@ export type EditOperation = {
308
450
  readonly type: 'paragraph.insert';
309
451
  readonly index: number;
310
452
  readonly text: string;
453
+ } | {
454
+ /** Sets how many grid columns and rows one cell covers; `1x1` unmerges it. */
455
+ readonly type: 'table.setCellSpan';
456
+ /** Zero-based table index in document order. */
457
+ readonly table: number;
458
+ /** Row index across head, body and foot rows. */
459
+ readonly row: number;
460
+ /** Grid column of the cell's top-left corner. */
461
+ readonly column: number;
462
+ /** Grid columns covered, at least 1. */
463
+ readonly colspan: number;
464
+ /** Rows covered, at least 1. */
465
+ readonly rowspan: number;
466
+ } | {
467
+ /** Sorts the body rows by one cell column; header and footer bands stay put. */
468
+ readonly type: 'table.sortRows';
469
+ /** Zero-based table index in document order. */
470
+ readonly table: number;
471
+ /** Zero-based cell index inside each body row. */
472
+ readonly column: number;
473
+ /** Ascending when true, which is the default. */
474
+ readonly ascending?: boolean;
475
+ }
476
+ /** Flips a rectangular table's rows and columns; head and footer rows fold into the body. */
477
+ | {
478
+ readonly type: 'table.transpose';
479
+ readonly table: number;
311
480
  } | {
312
481
  readonly type: 'table.setCell';
313
482
  readonly table: number;
@@ -323,6 +492,22 @@ export type EditOperation = {
323
492
  readonly type: 'table.deleteRow';
324
493
  readonly table: number;
325
494
  readonly row: number;
495
+ } | {
496
+ /** Moves a row to another grid position, across the head, body and footer bands. */
497
+ readonly type: 'table.moveRow';
498
+ /** Zero-based table index. */
499
+ readonly table: number;
500
+ /** Zero-based index of the row to move. */
501
+ readonly row: number;
502
+ /** Zero-based target grid position; equal to the row count to move the row to the end. */
503
+ readonly index: number;
504
+ } | {
505
+ /** Deep-copies a row directly after the source row. */
506
+ readonly type: 'table.duplicateRow';
507
+ /** Zero-based table index. */
508
+ readonly table: number;
509
+ /** Zero-based index of the row to copy. */
510
+ readonly row: number;
326
511
  } | {
327
512
  readonly type: 'table.insertColumn';
328
513
  readonly table: number;
@@ -332,6 +517,22 @@ export type EditOperation = {
332
517
  readonly type: 'table.deleteColumn';
333
518
  readonly table: number;
334
519
  readonly column: number;
520
+ } | {
521
+ /** Moves one grid column to another position in every row. */
522
+ readonly type: 'table.moveColumn';
523
+ /** Zero-based table index. */
524
+ readonly table: number;
525
+ /** Zero-based grid column to move. */
526
+ readonly column: number;
527
+ /** Zero-based target grid position inside the same column count. */
528
+ readonly index: number;
529
+ } | {
530
+ /** Deep-copies one grid column directly after itself. */
531
+ readonly type: 'table.duplicateColumn';
532
+ /** Zero-based table index. */
533
+ readonly table: number;
534
+ /** Zero-based grid column to copy. */
535
+ readonly column: number;
335
536
  } | {
336
537
  readonly type: 'paragraph.update';
337
538
  readonly id?: string;
@@ -341,6 +542,29 @@ export type EditOperation = {
341
542
  readonly type: 'block.move';
342
543
  readonly id: string;
343
544
  readonly index: number;
545
+ }
546
+ /** Convert a block to another kind in place; `level` is required for a
547
+ * heading target, `language` optional for code, `ordered` optional for a list. */
548
+ | {
549
+ readonly type: 'block.convert';
550
+ readonly id: string;
551
+ readonly to: 'paragraph' | 'heading' | 'quote' | 'code' | 'list';
552
+ readonly level?: number;
553
+ readonly language?: string | null;
554
+ readonly ordered?: boolean;
555
+ }
556
+ /** Exchange the document positions of two top-level blocks; subtrees travel. */
557
+ | {
558
+ readonly type: 'block.swap';
559
+ readonly id: string;
560
+ readonly target: string;
561
+ } | {
562
+ /** Rewrites the block's own text with a casing rule; nested blocks keep theirs. */
563
+ readonly type: 'block.setTextCase';
564
+ /** Block address: `section-N` or `node-N`. */
565
+ readonly id: string;
566
+ /** Casing rule applied to paragraph, heading, list item and code text. */
567
+ readonly case: 'upper' | 'lower' | 'title';
344
568
  } | BlockDuplicateOperation | {
345
569
  readonly type: 'template.fill';
346
570
  readonly values: Readonly<Record<string, string | number | boolean>>;
@@ -366,28 +590,56 @@ export interface EditOperationResult {
366
590
  readonly id?: string;
367
591
  /** Address of the fresh block `block.duplicate` created. */
368
592
  readonly newId?: string;
593
+ /** Destination list echoed by `list.moveItemTo`, or the other block echoed by `block.swap`. */
594
+ readonly target?: string;
369
595
  /** Depth-first position the block an operation created now holds. */
370
596
  readonly index?: number;
371
- /** List items created by `list.append` or `taskList.append`. */
597
+ /** Kind the block had before `block.convert`. */
598
+ readonly from?: string;
599
+ /** Kind `block.convert` switched the block to. */
600
+ readonly to?: string;
601
+ /** Casing rule applied by `block.setTextCase`. */
602
+ readonly case?: 'upper' | 'lower' | 'title';
603
+ /** Text runs rewritten by `block.setTextCase`. */
604
+ readonly changed?: number;
605
+ /** List items created by `list.append` or `taskList.append`, or the top-level count sorted by `list.sortItems` or reversed by `list.reverseItems`. */
372
606
  readonly items?: number;
373
- /** Checked items created by `taskList.append`. */
374
- readonly checked?: number;
607
+ /** Checked items created by `taskList.append`, or the state applied by `list.setItemTask`. */
608
+ readonly checked?: number | boolean | null;
609
+ /** Task flag applied by `list.setItemTask`. */
610
+ readonly task?: boolean;
611
+ /** Tags applied by `metadata.set`, or `null` when it was not part of the request. */
612
+ readonly tags?: readonly string[] | null;
375
613
  /** Whether the list appended by `list.append` is ordered. */
376
614
  readonly ordered?: boolean;
615
+ /** Sort direction applied by `list.sortItems`. */
616
+ readonly ascending?: boolean;
377
617
  /** First number requested by `list.append` or applied by `list.setStart`; `null` when none was given or the list is unordered. */
378
618
  readonly start?: number | null;
379
- /** Language tag of the code block appended by `code.append`; `null` when none was given. */
619
+ /** Item index addressed by `list.setItem`, `list.indentItem`, `list.unindentItem`, `list.insertItem`, `list.duplicateItem` or `list.removeItem`. */
620
+ readonly item?: number;
621
+ /** Language tag of a code block or the language applied by `metadata.set`; `null` when none was given. */
380
622
  readonly language?: string | null;
381
623
  /** Table index addressed by a table operation. */
382
624
  readonly table?: number;
383
625
  /** Row index addressed by a row operation. */
384
626
  readonly row?: number;
627
+ /** Grid position of the copy created by `table.duplicateRow`. */
628
+ readonly newRow?: number;
385
629
  /** Grid column index addressed by a column operation. */
386
630
  readonly column?: number;
387
631
  /** Caption set or cleared by `table.setCaption`; `null` when cleared. */
388
632
  readonly caption?: string | null;
389
- /** Header cells applied by `table.setHeader`. */
633
+ /** Header or footer cells applied by `table.setHeader` or `table.setFooter`. */
390
634
  readonly cells?: readonly string[];
635
+ /** Header or footer row count written by `table.setHeaderRows` or `table.setFooterRows`. */
636
+ readonly rows?: number;
637
+ /** Grid columns reported by `table.transpose`. */
638
+ readonly columns?: number;
639
+ /** Head rows folded into the body by `table.transpose`. */
640
+ readonly headRows?: number;
641
+ /** Footer rows folded into the body by `table.transpose`. */
642
+ readonly footRows?: number;
391
643
  /** Level applied by `heading.setLevel`. */
392
644
  readonly level?: number;
393
645
  /** Title applied by `heading.setText`. */
package/package.json CHANGED
@@ -34,11 +34,11 @@
34
34
  "main": "./dist/index.js",
35
35
  "name": "@wae/open-word",
36
36
  "optionalDependencies": {
37
- "@wae/open-word-darwin-arm64": "0.0.1",
38
- "@wae/open-word-darwin-x64": "0.0.1",
39
- "@wae/open-word-linux-arm64": "0.0.1",
40
- "@wae/open-word-linux-x64": "0.0.1",
41
- "@wae/open-word-win32-x64": "0.0.1"
37
+ "@wae/open-word-darwin-arm64": "0.0.2",
38
+ "@wae/open-word-darwin-x64": "0.0.2",
39
+ "@wae/open-word-linux-arm64": "0.0.2",
40
+ "@wae/open-word-linux-x64": "0.0.2",
41
+ "@wae/open-word-win32-x64": "0.0.2"
42
42
  },
43
43
  "publishConfig": {
44
44
  "access": "public"
@@ -50,10 +50,12 @@
50
50
  },
51
51
  "scripts": {
52
52
  "build": "tsc -p tsconfig.json",
53
- "test": "tsc -p tsconfig.test.json && node --test dist-test/tests/smoke.test.js",
53
+ "build:test": "tsc -p tsconfig.test.json",
54
+ "example": "tsc -p tsconfig.test.json && node dist-test/examples/offer-workflow.js",
55
+ "test": "tsc -p tsconfig.test.json && node --test dist-test/tests/smoke.test.js dist-test/tests/error-contract.test.js dist-test/tests/transaction.test.js",
54
56
  "typecheck": "tsc -p tsconfig.json --noEmit"
55
57
  },
56
58
  "type": "module",
57
59
  "types": "./dist/index.d.ts",
58
- "version": "0.0.1"
60
+ "version": "0.0.2"
59
61
  }