@simpleplatform/sdk 4.1.0 → 4.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
@@ -17,6 +17,13 @@ Version 4.1 removes the `temperature` and `reasoningBudget` options from
17
17
  the result. Where your code sets or reads either one, remove it; results stay
18
18
  the same.
19
19
 
20
+ **A test that builds the client by hand** adds what the client gained, or it
21
+ stops type checking: `navigation`, `ui`, and `open` beside `current` under
22
+ `records` (for example `records: { current: vi.fn(), open: vi.fn() }`). Its
23
+ `navigation.open` must accept both `NavigationOpenOptions` and
24
+ `NavigationOpenUrlOptions`; one typed for only `NavigationOpenOptions` no
25
+ longer type checks.
26
+
20
27
  ## Upgrading from 2.x to 3
21
28
 
22
29
  Version 3 is the first release that carries the Space calls added after 2.5.0.
@@ -32,10 +39,6 @@ One of those changes renamed how a Space connects, which is why this is a major.
32
39
  | `ConnectSpaceOptions` | `ConnectOptions` |
33
40
  | `SpaceWindowLike`, `SpaceMessageEvent` | No longer exported. A test declares its own. |
34
41
 
35
- **A test that builds the client by hand** adds what the client gained, or it
36
- stops type checking: `navigation`, `ui`, and `open` beside `current` under
37
- `records` (for example `records: { current: vi.fn(), open: vi.fn() }`).
38
-
39
42
  **Two behaviours change with no change in your code:**
40
43
 
41
44
  - `connect()` sets `overscroll-behavior-y: none` on the Space's root element,
@@ -317,6 +320,28 @@ for platform targets a browser has no name for.
317
320
  `open()` returns `void` as soon as the request is posted. The host gives no
318
321
  confirmation, and a host without the navigation handler ignores the message.
319
322
 
323
+ To open an address outside the platform, pass an absolute HTTPS `url` in place
324
+ of the `path`. It opens only in a new tab, so `target: 'new-tab'` is required.
325
+ `open()` takes `NavigationOpenOptions` (`{ path, target? }`) or
326
+ `NavigationOpenUrlOptions` (`{ url, target: 'new-tab' }`):
327
+
328
+ ```ts
329
+ simple.navigation.open({ target: 'new-tab', url: 'https://example.com/help' })
330
+ ```
331
+
332
+ The platform opens it with `noopener` and `noreferrer`, so the new tab has no
333
+ handle back to the platform tab. `open()` first answers `'unavailable'` when
334
+ the host is not HTTPS or has no navigation bridge. Only then does it check the
335
+ `url`, and throw `SpaceProtocolError` with code `'invalid_request'` for a `url` with
336
+ `'same-tab'` or with no target, a `url` that is not HTTPS, a `url` that
337
+ carries a username or a password, and options that hold both a `path` and a
338
+ `url`, or neither. The SDK sends the address as the browser parses it. A
339
+ platform that opens only its own pages does not open it, and sends no reply.
340
+
341
+ The platform opens an outside address only when the Space lists its origin
342
+ under `permissions.links` in its manifest, for example `https://*.example.com`.
343
+ An unlisted address does not open.
344
+
320
345
  ### Space context
321
346
 
322
347
  `simple.context` is explicit host-provided page context. It is never inferred
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @file Base64 for the JSON boundary, worked out by hand.
3
+ *
4
+ * A server action's runtime has neither `btoa` nor `Buffer`, so nothing here
5
+ * reaches for a global. It is arithmetic over the bytes, and it answers the same
6
+ * in every runtime the SDK runs in.
7
+ */
8
+ /**
9
+ * Encodes bytes as base64, in the standard alphabet with the standard padding
10
+ * and no line breaks, which is the form the platform accepts.
11
+ *
12
+ * The bytes are read in a loop, three at a time, and never spread into a call.
13
+ * A spread makes every byte an argument, and a call takes at most 65,535 of
14
+ * those in a server action and a stack's worth in a browser.
15
+ *
16
+ * @param bytes The bytes to encode.
17
+ * @returns The encoded text, which is empty when there are no bytes.
18
+ */
19
+ export declare function encodeBase64(bytes: Uint8Array): string;
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @file Base64 for the JSON boundary, worked out by hand.
3
+ *
4
+ * A server action's runtime has neither `btoa` nor `Buffer`, so nothing here
5
+ * reaches for a global. It is arithmetic over the bytes, and it answers the same
6
+ * in every runtime the SDK runs in.
7
+ */
8
+ /** The standard alphabet of RFC 4648, which is the one the platform decodes. */
9
+ const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
10
+ /** What takes the place of a symbol when the last group of bytes runs short. */
11
+ const PAD = '=';
12
+ /**
13
+ * Encodes bytes as base64, in the standard alphabet with the standard padding
14
+ * and no line breaks, which is the form the platform accepts.
15
+ *
16
+ * The bytes are read in a loop, three at a time, and never spread into a call.
17
+ * A spread makes every byte an argument, and a call takes at most 65,535 of
18
+ * those in a server action and a stack's worth in a browser.
19
+ *
20
+ * @param bytes The bytes to encode.
21
+ * @returns The encoded text, which is empty when there are no bytes.
22
+ */
23
+ export function encodeBase64(bytes) {
24
+ let encoded = '';
25
+ for (let start = 0; start < bytes.length; start += 3) {
26
+ const left = bytes.length - start;
27
+ // Left to right: the first byte takes the top eight of twenty-four bits. A
28
+ // read past the end answers nothing, so a group of one or two leaves the
29
+ // rest zero.
30
+ const group = ((bytes[start] ?? 0) << 16) | ((bytes[start + 1] ?? 0) << 8) | (bytes[start + 2] ?? 0);
31
+ encoded += ALPHABET.charAt(group >>> 18)
32
+ + ALPHABET.charAt((group >>> 12) & 0x3F)
33
+ + (left > 1 ? ALPHABET.charAt((group >>> 6) & 0x3F) : PAD)
34
+ + (left > 2 ? ALPHABET.charAt(group & 0x3F) : PAD);
35
+ }
36
+ return encoded;
37
+ }
@@ -10,7 +10,7 @@ import type { SimpleTasksClient } from './tasks.js';
10
10
  import type { SimpleHeaderClient, SimpleTabsClient, SimpleToastClient, SpaceHeaderTransport, SpaceTabsTransport, SpaceToastTransport } from './ui.js';
11
11
  export type { ActionFailedDetails, ActionRunOptions, SimpleActionsClient, } from './actions.js';
12
12
  export type { DocumentStageInput, DocumentStageResult, SimpleDocumentsClient, StagedDocumentHandle, } from './documents.js';
13
- export type { NavigationOpenOptions, NavigationTarget, SimpleNavigationClient, SpaceNavigationTransport, } from './navigation.js';
13
+ export type { NavigationOpenOptions, NavigationOpenUrlOptions, NavigationTarget, SimpleNavigationClient, SpaceNavigationTransport, } from './navigation.js';
14
14
  export { PROTOCOL_VERSION, SpaceDataError, SpaceProtocolError } from './protocol.js';
15
15
  export type { ProtocolErrorResponse, ProtocolRequest, ProtocolResponse, ProtocolSuccessResponse, SpaceDataErrorPayload, SpaceProtocolErrorPayload, SpaceTransport, } from './protocol.js';
16
16
  export { MANAGED_RECORD_FORM_PROTOCOL_VERSION } from './record-form.js';
@@ -1,6 +1,6 @@
1
1
  import type { SimpleClient } from './core.js';
2
2
  import { HEADER_ACTIONS_PROTOCOL_VERSION, PROTOCOL_VERSION, RECORDS_PROTOCOL_VERSION, SpaceDataError, SpaceProtocolError, TABS_PROTOCOL_VERSION, TOAST_PROTOCOL_VERSION } from './core.js';
3
- export type { ActionFailedDetails, ActionRunOptions, DocumentStageInput, DocumentStageResult, GraphQLVariables, HeaderAction, HeaderActionType, JsonObject, JsonValue, NavigationOpenOptions, NavigationTarget, OpenRecordOptions, RecordErrorSnapshot, RecordFieldSnapshot, RecordFormError, RecordHandle, RecordOpenRequest, RecordOpenResult, RecordReference, RecordSnapshot, RecordSubmitResult, RecordUpdateResult, SetTabsOptions, SimpleActionsClient, SimpleClient, SimpleDataClient, SimpleDocumentsClient, SimpleHeaderActionsClient, SimpleHeaderClient, SimpleNavigationClient, SimpleRecordsClient, SimpleTabsClient, SimpleTasksClient, SimpleToastClient, SpaceContext, SpaceDataErrorPayload, SpaceNavigationTransport, SpaceProtocolErrorPayload, SpaceTab, SpaceTabsSelectionEvent, SpaceTabsTransport, SpaceToastOptions, SpaceToastVariant, StagedDocumentHandle, TaskCreateInput, TaskCreateResult, TaskReplyInput, TaskReplyResult, TaskStatus, } from './core.js';
3
+ export type { ActionFailedDetails, ActionRunOptions, DocumentStageInput, DocumentStageResult, GraphQLVariables, HeaderAction, HeaderActionType, JsonObject, JsonValue, NavigationOpenOptions, NavigationOpenUrlOptions, NavigationTarget, OpenRecordOptions, RecordErrorSnapshot, RecordFieldSnapshot, RecordFormError, RecordHandle, RecordOpenRequest, RecordOpenResult, RecordReference, RecordSnapshot, RecordSubmitResult, RecordUpdateResult, SetTabsOptions, SimpleActionsClient, SimpleClient, SimpleDataClient, SimpleDocumentsClient, SimpleHeaderActionsClient, SimpleHeaderClient, SimpleNavigationClient, SimpleRecordsClient, SimpleTabsClient, SimpleTasksClient, SimpleToastClient, SpaceContext, SpaceDataErrorPayload, SpaceNavigationTransport, SpaceProtocolErrorPayload, SpaceTab, SpaceTabsSelectionEvent, SpaceTabsTransport, SpaceToastOptions, SpaceToastVariant, StagedDocumentHandle, TaskCreateInput, TaskCreateResult, TaskReplyInput, TaskReplyResult, TaskStatus, } from './core.js';
4
4
  export { HOST_UI_PROTOCOL_VERSION } from './host-ui.js';
5
5
  export { HEADER_ACTIONS_PROTOCOL_VERSION, PROTOCOL_VERSION, RECORDS_PROTOCOL_VERSION, SpaceDataError, SpaceProtocolError, TABS_PROTOCOL_VERSION, TOAST_PROTOCOL_VERSION };
6
6
  export type { CreateRecordOptions, NewRecordOptions, PanelContent, SimpleCreateRecordClient, SimpleNewRecordClient, SimplePanelClient } from './host-ui.js';
@@ -15,9 +15,20 @@ export type NavigationTarget = 'same-tab' | 'new-tab';
15
15
  export interface NavigationOpenOptions {
16
16
  path: string;
17
17
  target?: NavigationTarget;
18
+ url?: never;
19
+ }
20
+ /**
21
+ * Opens an absolute HTTPS `url` outside the platform. It opens only in a new
22
+ * tab, so `target` must be `new-tab`, and it may not carry a username or a
23
+ * password. Options hold a `path` or a `url`, never both.
24
+ */
25
+ export interface NavigationOpenUrlOptions {
26
+ url: string;
27
+ target: 'new-tab';
28
+ path?: never;
18
29
  }
19
30
  export interface SimpleNavigationClient {
20
- open: (options: NavigationOpenOptions) => void;
31
+ open: (options: NavigationOpenOptions | NavigationOpenUrlOptions) => void;
21
32
  }
22
33
  export interface SpaceNavigationTransport {
23
34
  navigate: (url: string, target: NavigationTarget) => void;
@@ -4,12 +4,16 @@ export function createNavigationClient(hostOrigin, transport) {
4
4
  open(options) {
5
5
  if (!isObjectRecord(options))
6
6
  throw invalidRequest('Navigation options must be an object.');
7
- const { path, target } = options;
8
- if (typeof path !== 'string' || path.length === 0 || !path.startsWith('/') || path.startsWith('//') || path.includes('\\'))
7
+ const { path, target, url: address } = options;
8
+ if ((path === undefined) === (address === undefined))
9
+ throw invalidRequest('Navigation options must hold either a path or a url, not both.');
10
+ if (address === undefined && (typeof path !== 'string' || path.length === 0 || !path.startsWith('/') || path.startsWith('//') || path.includes('\\')))
9
11
  throw invalidRequest('Navigation path must be a host-relative path starting with one slash, with no backslash.');
10
12
  const resolvedTarget = target === undefined ? 'same-tab' : target;
11
13
  if (resolvedTarget !== 'same-tab' && resolvedTarget !== 'new-tab')
12
14
  throw invalidRequest('Navigation target must be "same-tab" or "new-tab".');
15
+ if (address !== undefined && resolvedTarget !== 'new-tab')
16
+ throw invalidRequest('A navigation url opens only in a new tab: set target to "new-tab".');
13
17
  if (!hostOrigin || new URL(hostOrigin).protocol !== 'https:') {
14
18
  throw new SpaceProtocolError({
15
19
  code: 'unavailable',
@@ -22,6 +26,10 @@ export function createNavigationClient(hostOrigin, transport) {
22
26
  message: 'The platform-navigation bridge is unavailable for this Space.',
23
27
  });
24
28
  }
29
+ if (address !== undefined) {
30
+ transport.navigate(outsideAddress(address), resolvedTarget);
31
+ return;
32
+ }
25
33
  // URL parsing drops a tab or a newline, which can turn a path into another host's address.
26
34
  const url = new URL(path, hostOrigin);
27
35
  if (url.origin !== new URL(hostOrigin).origin)
@@ -30,3 +38,22 @@ export function createNavigationClient(hostOrigin, transport) {
30
38
  },
31
39
  };
32
40
  }
41
+ /**
42
+ * Checks an address outside the platform and returns it as the browser parses
43
+ * it, so the address sent is the one checked. The platform opens such an
44
+ * address only over HTTPS and never with a username or a password in it.
45
+ */
46
+ function outsideAddress(address) {
47
+ let url;
48
+ try {
49
+ url = typeof address === 'string' ? new URL(address) : undefined;
50
+ }
51
+ catch {
52
+ url = undefined;
53
+ }
54
+ if (url?.protocol !== 'https:')
55
+ throw invalidRequest('Navigation url must be an absolute HTTPS address.');
56
+ if (url.username !== '' || url.password !== '')
57
+ throw invalidRequest('Navigation url must not carry a username or a password.');
58
+ return url.href;
59
+ }
package/dist/storage.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { execute as hostExecute, executeBytes as hostExecuteBytes } from './host';
2
+ import { encodeBase64 } from './internal/base64';
2
3
  /** The host action that answers a stored file's size. */
3
4
  const STAT = 'action:storage/stat';
4
5
  /** The host action that answers one range of a stored file as its bytes. */
@@ -47,9 +48,20 @@ export async function uploadBuffer(buffer, filename, mimeType, target, context)
47
48
  throw new Error('Target table_name is required and cannot be empty');
48
49
  if (!target.field_name || target.field_name.trim() === '')
49
50
  throw new Error('Target field_name is required and cannot be empty');
50
- const bytes = buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : buffer;
51
+ // JavaScript callers are not held to the type, and `new Uint8Array` would
52
+ // read a number as a length and an array as values, wrapped into bytes. So
53
+ // anything but a buffer or a view is refused, from whichever realm it came.
54
+ if (!ArrayBuffer.isView(buffer) && !isArrayBuffer(buffer))
55
+ throw new Error('buffer must be an ArrayBuffer or a Uint8Array');
56
+ // A plain view over exactly the caller's bytes. A view that starts partway
57
+ // into a larger buffer sends only its own part.
58
+ const bytes = ArrayBuffer.isView(buffer)
59
+ ? new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)
60
+ : new Uint8Array(buffer);
61
+ if (bytes.length === 0)
62
+ throw new Error('An upload needs at least one byte, and this buffer is empty.');
51
63
  // Base64-encode at the JSON boundary (JSON.stringify cannot carry raw binary)
52
- const base64 = btoa(String.fromCharCode(...bytes));
64
+ const base64 = encodeBase64(bytes);
53
65
  const source = { bytes: base64, filename, mime_type: mimeType };
54
66
  const response = await hostExecute('action:storage/upload-external', { source, target }, context);
55
67
  if (!response.ok)
@@ -243,6 +255,10 @@ async function readExactly(handle, offset, length, context) {
243
255
  throw new Error(`The file answered ${part.length} bytes for the ${length} at offset ${offset}, so it is not the size it was when the read began. Read it again.`);
244
256
  return part;
245
257
  }
258
+ /** Whether a value is an ArrayBuffer, from this realm or another. */
259
+ function isArrayBuffer(value) {
260
+ return Object.prototype.toString.call(value) === '[object ArrayBuffer]';
261
+ }
246
262
  /** The error for a call the host refused in its envelope, naming the call. */
247
263
  function refused(actionName, message) {
248
264
  if (message === undefined || message.trim() === '')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simpleplatform/sdk",
3
- "version": "4.1.0",
3
+ "version": "4.2.1",
4
4
  "description": "Simple Platform Typescript SDK",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://docs.simple.dev",
@@ -82,6 +82,6 @@
82
82
  "scripts": {
83
83
  "build": "rm -rf dist && tsc && cp src/worker-override.js dist/ && cp cli/build.js dist/ && cp src/space/package.json dist/space/",
84
84
  "test": "pnpm run build && node --test test/*.test.mjs",
85
- "typecheck": "tsc --noEmit"
85
+ "typecheck": "tsc --noEmit && tsc -p tsconfig.types.json"
86
86
  }
87
87
  }