@astrale-os/sdk 0.6.0-beta.54 → 0.6.0-beta.55

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.
@@ -2,4 +2,6 @@ export { defineAction } from './define.js';
2
2
  export type { Action, ActionDefinition } from './action.js';
3
3
  export type { ActionContext, ActionBinaryInput, ActionExecution, Caller, DomainGraphExecutor, DomainGraphExecutors, DomainKernelSessions, DomainMutate, DomainQuery, } from './context.js';
4
4
  export type { ActionBinary, ActionOutputOf } from './output.js';
5
+ export { FILE_MEMORY_LIMIT, FileReadError } from '../file/index.js';
6
+ export type { FileReadErrorCode, ReceivedFile, WithFiles } from '../file/index.js';
5
7
  export type { DeclaredErrorDefinition, DeclaredErrorFactory, DeclaredErrorFamily, DeclaredErrorOptions, DeclaredErrors, } from '../error/index.js';
@@ -1 +1,2 @@
1
1
  export { defineAction } from './define.js';
2
+ export { FILE_MEMORY_LIMIT, FileReadError } from '../file/index.js';
@@ -5,6 +5,7 @@ import type { NodeId } from '../../platform/graph/node/index.js';
5
5
  import type { CallableInputOf, CallableInputModeOf, Domain, ResolvedFunction, ResolvedMethod } from '../../platform/schema/index.js';
6
6
  import type { HandlerDependencies } from '../dependency/index.js';
7
7
  import type { DeclaredErrorFactory, DeclaredErrors, NoDeclaredErrors } from '../error/index.js';
8
+ import type { WithFiles } from '../file/index.js';
8
9
  import type { IntegrationClients, Integrations } from '../integration/index.js';
9
10
  import type { Mutation, MutationExecutor, MutationInputOf, MutationOutputOf, DefinedMutation } from '../mutation/index.js';
10
11
  import type { InputOf, OutputOf, Page, QueryDefinition, QueryExecutor, DefinedQuery, QueryOptions } from '../query/index.js';
@@ -134,7 +135,11 @@ type SelfOf<Callable> = Callable extends ResolvedMethod<unknown, unknown, false>
134
135
  export type ActionContext<Callable extends ResolvedCallable, DomainValue extends Domain = Domain, Definitions extends Integrations = Readonly<Record<never, never>>, Errors extends DeclaredErrors = NoDeclaredErrors> = {
135
136
  /** Exact admitted Domain retained by the Build being executed. */
136
137
  readonly domain: DomainValue;
137
- readonly input: CallableInputOf<Callable>;
138
+ /**
139
+ * The admitted input, with a file object in place of the receipt at each `file()` field. A file
140
+ * object reads the file with the caller's authority, and a blob Property accepts it as it is.
141
+ */
142
+ readonly input: WithFiles<CallableInputOf<Callable>>;
138
143
  readonly integrations: IntegrationClients<Definitions>;
139
144
  readonly execution: ActionExecution;
140
145
  /** Construct one implementation-declared safe business error for `throw error(...)`. */
@@ -2,4 +2,6 @@ export { defineAction, isAction } from './define.js';
2
2
  export type { Action, ActionAddress, ActionAddressOf, ActionDefinition, CallableAtAddress, LocalCallable, ResolvedDomainOf, } from './action.js';
3
3
  export type { ActionContext, ActionBinaryInput, ActionExecution, AnonymousCaller, AuthenticatedCaller, AuthorityMode, AuthorityName, AuthoritySelection, Caller, DomainCapabilities, DomainGraphExecutor, DomainGraphExecutors, DomainKernelSessions, DomainMutate, DomainQuery, ResolvedCallable, } from './context.js';
4
4
  export type { ActionBinary, ActionOutputOf } from './output.js';
5
+ export { FILE_MEMORY_LIMIT, FileReadError } from '../file/index.js';
6
+ export type { FileReadErrorCode, ReceivedFile, WithFiles } from '../file/index.js';
5
7
  export type { DeclaredErrorDefinition, DeclaredErrorFactory, DeclaredErrorFamily, DeclaredErrorOptions, DeclaredErrors, } from '../error/index.js';
@@ -1 +1,2 @@
1
1
  export { defineAction, isAction } from './define.js';
2
+ export { FILE_MEMORY_LIMIT, FileReadError } from '../file/index.js';
@@ -0,0 +1,11 @@
1
+ import type { Binary } from '../../platform/client/index.js';
2
+ /** The chunks of one downloaded body, and how to give it up unread. */
3
+ export declare function chunksOf(body: Binary['body']): {
4
+ readonly iterable: AsyncIterable<Uint8Array>;
5
+ cancel(): Promise<void>;
6
+ };
7
+ /**
8
+ * A pull-driven web stream over chunks opened on its first read: nothing is downloaded until the
9
+ * consumer reads, and cancelling the stream cancels the download.
10
+ */
11
+ export declare function readableOf(open: () => Promise<AsyncIterable<Uint8Array>>): ReadableStream<Uint8Array>;
@@ -0,0 +1,45 @@
1
+ /** The chunks of one downloaded body, and how to give it up unread. */
2
+ export function chunksOf(body) {
3
+ if (body instanceof Uint8Array) {
4
+ return {
5
+ iterable: (async function* () {
6
+ if (body.byteLength > 0)
7
+ yield body;
8
+ })(),
9
+ cancel: async () => { },
10
+ };
11
+ }
12
+ return {
13
+ iterable: body,
14
+ cancel: async () => {
15
+ // An unread body is given up by asking its iterator to return, as the Client does: the
16
+ // response it reads is then cancelled. The refusal that gave it up is what the reader sees.
17
+ try {
18
+ await body[Symbol.asyncIterator]().return?.();
19
+ }
20
+ catch {
21
+ // Already closed.
22
+ }
23
+ },
24
+ };
25
+ }
26
+ /**
27
+ * A pull-driven web stream over chunks opened on its first read: nothing is downloaded until the
28
+ * consumer reads, and cancelling the stream cancels the download.
29
+ */
30
+ export function readableOf(open) {
31
+ let iterator;
32
+ return new ReadableStream({
33
+ async pull(controller) {
34
+ iterator ??= (await open())[Symbol.asyncIterator]();
35
+ const next = await iterator.next();
36
+ if (next.done === true)
37
+ controller.close();
38
+ else
39
+ controller.enqueue(next.value);
40
+ },
41
+ async cancel() {
42
+ await iterator?.return?.();
43
+ },
44
+ }, { highWaterMark: 0 });
45
+ }
@@ -0,0 +1,72 @@
1
+ import type { Binary } from '../../platform/client/index.js';
2
+ import type { schema } from '../../platform/schema/index.js';
3
+ /**
4
+ * The most `text()` and `bytes()` hold in memory: 10 MiB (10,485,760 bytes). A larger file is read
5
+ * with `stream()`.
6
+ */
7
+ export declare const FILE_MEMORY_LIMIT: number;
8
+ /**
9
+ * A file the caller sent in a `file()` input field: the upload receipt it named, and the file's
10
+ * bytes, read on demand from the Kernel with the caller's authority. Each read downloads the file
11
+ * again; nothing is kept between reads.
12
+ */
13
+ export interface ReceivedFile {
14
+ /**
15
+ * The upload receipt the caller sent. It is bound to the user who uploaded the file and expires
16
+ * 15 minutes after the upload. Only that user, or a Domain acting for them, can read or attach it.
17
+ */
18
+ readonly receipt: schema.values.BlobReceipt;
19
+ /**
20
+ * The file's bytes as they arrive, for a file of any size. The Kernel verifies the file's digest
21
+ * when the last chunk arrives, so the stream fails at its end if the bytes differ from what was
22
+ * uploaded: write nothing derived from it anywhere lasting before it ends.
23
+ */
24
+ stream(): ReadableStream<Uint8Array>;
25
+ /** The file decoded as UTF-8, once all of it arrived and was verified. At most `FILE_MEMORY_LIMIT`. */
26
+ text(): Promise<string>;
27
+ /** The file's bytes, once all of them arrived and were verified. At most `FILE_MEMORY_LIMIT`. */
28
+ bytes(): Promise<Uint8Array>;
29
+ }
30
+ /**
31
+ * A callable input as its handler receives it: a file object in place of the receipt at each
32
+ * `file()` field.
33
+ */
34
+ export type WithFiles<Input> = 0 extends 1 & Input ? Input : Input extends schema.values.BlobReceipt ? ReceivedFile : Input extends object ? {
35
+ [Key in keyof Input]: WithFiles<Input[Key]>;
36
+ } : Input;
37
+ /** What a `file()` field admits, checked when the handler reads the file. */
38
+ export interface FileConstraints {
39
+ readonly maxBytes?: number;
40
+ readonly mediaTypes?: readonly string[];
41
+ }
42
+ /** Why the SDK refused to read a received file. */
43
+ export type FileReadErrorCode =
44
+ /** The file is larger than `FILE_MEMORY_LIMIT`, the most `text()` and `bytes()` hold. */
45
+ 'FILE_MEMORY_LIMIT'
46
+ /** The file is larger than its `file()` field's `maxBytes`. */
47
+ | 'FILE_TOO_LARGE'
48
+ /** The file's media type is not one of its `file()` field's `mediaTypes`. */
49
+ | 'FILE_MEDIA_TYPE';
50
+ /**
51
+ * A received file the SDK refused to read. Uncaught by the handler, it reaches the caller as
52
+ * `LIMIT_EXCEEDED` (size) or `VALIDATION_ERROR` (media type), with this code as its reason.
53
+ */
54
+ export declare class FileReadError extends Error {
55
+ readonly code: FileReadErrorCode;
56
+ /** The JSON Pointer of the field in the callable input, when the file came from one. */
57
+ readonly pointer?: string | undefined;
58
+ readonly name = "FileReadError";
59
+ constructor(code: FileReadErrorCode, message: string,
60
+ /** The JSON Pointer of the field in the callable input, when the file came from one. */
61
+ pointer?: string | undefined);
62
+ }
63
+ /** Where a received file's bytes come from: one download per read. */
64
+ export type FileSource = () => Promise<Binary>;
65
+ export interface ReceivedFileOptions {
66
+ readonly constraints?: FileConstraints;
67
+ readonly pointer?: string;
68
+ }
69
+ /** One file object over a receipt; `source` downloads its bytes, once per read. */
70
+ export declare function receivedFile(receipt: schema.values.BlobReceipt, source: FileSource, options?: ReceivedFileOptions): ReceivedFile;
71
+ /** Whether `value` is a file object the SDK made. */
72
+ export declare function isReceivedFile(value: unknown): value is ReceivedFile;
@@ -0,0 +1,111 @@
1
+ import { chunksOf, readableOf } from './binary.js';
2
+ /**
3
+ * The most `text()` and `bytes()` hold in memory: 10 MiB (10,485,760 bytes). A larger file is read
4
+ * with `stream()`.
5
+ */
6
+ export const FILE_MEMORY_LIMIT = 10 * 1024 * 1024;
7
+ /**
8
+ * A received file the SDK refused to read. Uncaught by the handler, it reaches the caller as
9
+ * `LIMIT_EXCEEDED` (size) or `VALIDATION_ERROR` (media type), with this code as its reason.
10
+ */
11
+ export class FileReadError extends Error {
12
+ code;
13
+ pointer;
14
+ name = 'FileReadError';
15
+ constructor(code, message,
16
+ /** The JSON Pointer of the field in the callable input, when the file came from one. */
17
+ pointer) {
18
+ super(message);
19
+ this.code = code;
20
+ this.pointer = pointer;
21
+ }
22
+ }
23
+ const files = new WeakSet();
24
+ /** One file object over a receipt; `source` downloads its bytes, once per read. */
25
+ export function receivedFile(receipt, source, options = {}) {
26
+ if (typeof receipt !== 'string' || receipt.length === 0) {
27
+ throw new TypeError('A received file requires its upload receipt.');
28
+ }
29
+ const { constraints, pointer } = options;
30
+ const open = async (memory) => {
31
+ const binary = await source();
32
+ const opened = openedOf(binary);
33
+ try {
34
+ admitMediaType(binary.mediaType, constraints, pointer);
35
+ if (opened.length !== undefined)
36
+ admitLength(opened.length, constraints, memory, pointer);
37
+ }
38
+ catch (cause) {
39
+ await opened.cancel();
40
+ throw cause;
41
+ }
42
+ return opened;
43
+ };
44
+ const bytes = async () => {
45
+ const opened = await open(FILE_MEMORY_LIMIT);
46
+ const parts = [];
47
+ let total = 0;
48
+ for await (const chunk of bounded(opened.chunks, constraints, FILE_MEMORY_LIMIT, pointer)) {
49
+ parts.push(chunk);
50
+ total += chunk.byteLength;
51
+ }
52
+ if (parts.length === 1)
53
+ return parts[0];
54
+ const joined = new Uint8Array(total);
55
+ let offset = 0;
56
+ for (const part of parts) {
57
+ joined.set(part, offset);
58
+ offset += part.byteLength;
59
+ }
60
+ return joined;
61
+ };
62
+ const value = Object.freeze({
63
+ receipt,
64
+ stream: () => readableOf(async () => {
65
+ const opened = await open();
66
+ return bounded(opened.chunks, constraints, undefined, pointer);
67
+ }),
68
+ bytes,
69
+ text: async () => new TextDecoder().decode(await bytes()),
70
+ });
71
+ files.add(value);
72
+ return value;
73
+ }
74
+ /** Whether `value` is a file object the SDK made. */
75
+ export function isReceivedFile(value) {
76
+ return typeof value === 'object' && value !== null && files.has(value);
77
+ }
78
+ function openedOf(binary) {
79
+ const length = binary.body instanceof Uint8Array ? binary.body.byteLength : streamedLength(binary);
80
+ const chunks = chunksOf(binary.body);
81
+ return {
82
+ ...(length === undefined ? {} : { length }),
83
+ chunks: chunks.iterable,
84
+ cancel: chunks.cancel,
85
+ };
86
+ }
87
+ function streamedLength(binary) {
88
+ return 'length' in binary ? binary.length : undefined;
89
+ }
90
+ function admitMediaType(mediaType, constraints, pointer) {
91
+ if (constraints?.mediaTypes === undefined || constraints.mediaTypes.includes(mediaType))
92
+ return;
93
+ throw new FileReadError('FILE_MEDIA_TYPE', `The file's media type ${mediaType} is not one its field admits (${constraints.mediaTypes.join(', ')}).`, pointer);
94
+ }
95
+ function admitLength(length, constraints, memory, pointer) {
96
+ if (constraints?.maxBytes !== undefined && length > constraints.maxBytes) {
97
+ throw new FileReadError('FILE_TOO_LARGE', `The file is larger than the ${constraints.maxBytes} bytes its field admits.`, pointer);
98
+ }
99
+ if (memory !== undefined && length > memory) {
100
+ throw new FileReadError('FILE_MEMORY_LIMIT', `The file is larger than the ${memory} bytes text() and bytes() hold in memory: read it with stream().`, pointer);
101
+ }
102
+ }
103
+ /** The chunks of `source`, refused as soon as they run past a bound whatever length was declared. */
104
+ async function* bounded(source, constraints, memory, pointer) {
105
+ let total = 0;
106
+ for await (const chunk of source) {
107
+ total += chunk.byteLength;
108
+ admitLength(total, constraints, memory, pointer);
109
+ yield chunk;
110
+ }
111
+ }
@@ -0,0 +1,4 @@
1
+ export { FILE_MEMORY_LIMIT, FileReadError, isReceivedFile, receivedFile } from './file.js';
2
+ export type { FileConstraints, FileReadErrorCode, FileSource, ReceivedFile, ReceivedFileOptions, WithFiles, } from './file.js';
3
+ export { filePositionsOf, withFiles } from './input.js';
4
+ export type { FilePosition } from './input.js';
@@ -0,0 +1,2 @@
1
+ export { FILE_MEMORY_LIMIT, FileReadError, isReceivedFile, receivedFile } from './file.js';
2
+ export { filePositionsOf, withFiles } from './input.js';
@@ -0,0 +1,13 @@
1
+ import * as values from '@astrale-os/kernel-dsl/v1/schema/values';
2
+ import type { schema } from '../../platform/schema/index.js';
3
+ import type { ResolvedCallable } from '../action/context.js';
4
+ import type { ReceivedFile } from './file.js';
5
+ /** Where a callable's input holds a `file()` field, and what the field states about its file. */
6
+ export type FilePosition = values.FilePosition;
7
+ /** Every position of a `file()` field in the input of `callable`, binary metadata included. */
8
+ export declare function filePositionsOf(callable: ResolvedCallable): readonly FilePosition[];
9
+ /**
10
+ * `input` with a file object, made by `fileOf`, in place of the receipt at each `file()` field.
11
+ * Nothing else is copied: only the objects and arrays on the way to a file are new.
12
+ */
13
+ export declare function withFiles(positions: readonly FilePosition[], input: unknown, fileOf: (receipt: schema.values.BlobReceipt, located: values.LocatedFile) => ReceivedFile): unknown;
@@ -0,0 +1,57 @@
1
+ import { isBinaryInput } from '@astrale-os/kernel-dsl/v1/language';
2
+ import * as values from '@astrale-os/kernel-dsl/v1/schema/values';
3
+ const positionsByCallable = new WeakMap();
4
+ /** Every position of a `file()` field in the input of `callable`, binary metadata included. */
5
+ export function filePositionsOf(callable) {
6
+ const known = positionsByCallable.get(callable);
7
+ if (known !== undefined)
8
+ return known;
9
+ const contract = isBinaryInput(callable.input) ? callable.input.metadata : callable.input;
10
+ const positions = values.filePositions(contract);
11
+ positionsByCallable.set(callable, positions);
12
+ return positions;
13
+ }
14
+ /**
15
+ * `input` with a file object, made by `fileOf`, in place of the receipt at each `file()` field.
16
+ * Nothing else is copied: only the objects and arrays on the way to a file are new.
17
+ */
18
+ export function withFiles(positions, input, fileOf) {
19
+ if (positions.length === 0)
20
+ return input;
21
+ let result = input;
22
+ for (const located of values.locateFiles(positions, input)) {
23
+ if (typeof located.value !== 'string')
24
+ continue;
25
+ const file = fileOf(located.value, located);
26
+ result = replaceAt(result, input, tokensOf(located.pointer), file);
27
+ }
28
+ return result;
29
+ }
30
+ /**
31
+ * `target` with `value` at `tokens`. A container still shared with `original` is copied before it
32
+ * changes, so the admitted input is never written.
33
+ */
34
+ function replaceAt(target, original, tokens, value) {
35
+ if (tokens.length === 0)
36
+ return value;
37
+ const [token, ...rest] = tokens;
38
+ if (Array.isArray(target)) {
39
+ const index = Number(token);
40
+ const copy = target === original ? [...target] : target;
41
+ copy[index] = replaceAt(target[index], original[index], rest, value);
42
+ return copy;
43
+ }
44
+ const source = target;
45
+ const copy = target === original ? { ...source } : source;
46
+ copy[token] = replaceAt(source[token], original?.[token], rest, value);
47
+ return copy;
48
+ }
49
+ /** The reference tokens of an RFC 6901 JSON Pointer. */
50
+ function tokensOf(pointer) {
51
+ if (pointer === '')
52
+ return [];
53
+ return pointer
54
+ .slice(1)
55
+ .split('/')
56
+ .map((token) => token.replaceAll('~1', '/').replaceAll('~0', '~'));
57
+ }
@@ -1,8 +1,18 @@
1
1
  import type { MutationPropsInput } from '@astrale-os/kernel-core/graph/mutate';
2
2
  import type { PropertyInputOf, ResolvedClass, ResolvedProperty } from '@astrale-os/kernel-dsl/v1';
3
3
  import { PropertyValues } from '@astrale-os/kernel-dsl/v1/language';
4
+ import type { schema } from '../../../platform/schema/index.js';
4
5
  import type { StoredPropertyInputOf } from '../../../platform/schema/property-input.js';
5
- export type RichPropertyInput<Class> = PropertyInputOf<Class>;
6
+ import type { ReceivedFile } from '../../file/index.js';
7
+ /**
8
+ * The values a Mutation writes. A blob Property takes an upload receipt, or a file object a
9
+ * handler received, which writes its receipt.
10
+ */
11
+ export type RichPropertyInput<Class> = {
12
+ [Name in keyof PropertyInputOf<Class>]: AttachableBlob<PropertyInputOf<Class>[Name]>;
13
+ };
14
+ /** A blob write also takes a received file object, as its receipt. */
15
+ type AttachableBlob<Value> = [Extract<Value, schema.values.BlobReceipt>] extends [never] ? Value : Value | ReceivedFile;
6
16
  export type RichPropertyName<Class> = Extract<keyof PropertyInputOf<Class>, string>;
7
17
  export interface RichPropertyConditions<Class> {
8
18
  readonly equals?: StoredPropertyInputOf<Class>;
@@ -22,3 +32,4 @@ export declare function delta<Class extends ResolvedClass>(selected: Class, inpu
22
32
  unset: readonly `${string}:class.${string}.property.${string}`[];
23
33
  }>;
24
34
  export declare function resolvedProperty<Class extends ResolvedClass>(selected: Class, name: RichPropertyName<Class>): ResolvedProperty;
35
+ export {};
@@ -1,5 +1,6 @@
1
1
  import { PropertyKey } from '@astrale-os/kernel-dsl/v1/addressing';
2
2
  import { PropertyValues } from '@astrale-os/kernel-dsl/v1/language';
3
+ import { isReceivedFile } from '../../file/index.js';
3
4
  export function properties(selected, input) {
4
5
  const ordinary = Object.create(null);
5
6
  const receipts = [];
@@ -12,10 +13,12 @@ export function properties(selected, input) {
12
13
  }
13
14
  sources.set(property.key, name);
14
15
  if (isBlobProperty(property)) {
15
- if (typeof value !== 'string') {
16
- throw new TypeError(`Blob Property ${property.key} requires an upload receipt.`);
16
+ // A received file attaches as the receipt its caller uploaded it under.
17
+ const receipt = isReceivedFile(value) ? value.receipt : value;
18
+ if (typeof receipt !== 'string') {
19
+ throw new TypeError(`Blob Property ${property.key} requires an upload receipt or a received file.`);
17
20
  }
18
- receipts.push([property.key, value]);
21
+ receipts.push([property.key, receipt]);
19
22
  }
20
23
  else {
21
24
  ordinary[name] = value;
@@ -1,4 +1,5 @@
1
1
  import { isAction } from '../action/index.js';
2
+ import { filePositionsOf } from '../file/index.js';
2
3
  import { isWorkflow } from '../workflow/index.js';
3
4
  import { admitActions } from './actions.js';
4
5
  import { runtimeCallables } from './callables.js';
@@ -6,6 +7,8 @@ import { admitWorkflows } from './workflows.js';
6
7
  /** Prove unique and exhaustive Action/Workflow coverage of the root executable set. */
7
8
  export function admitRuntimeRegistry(domain, input) {
8
9
  const callables = runtimeCallables(domain);
10
+ for (const { address, callable } of callables)
11
+ refuseAnonymousFile(address, callable);
9
12
  if (!Array.isArray(input.functions)) {
10
13
  throw new TypeError('Runtime functions must be an array.');
11
14
  }
@@ -35,3 +38,12 @@ export function admitRuntimeRegistry(domain, input) {
35
38
  workflows,
36
39
  });
37
40
  }
41
+ /**
42
+ * A file is read and attached as the caller, with the receipt they uploaded. A call to an
43
+ * `anonymous` callable may carry no credential, and then has no caller to do it as.
44
+ */
45
+ function refuseAnonymousFile(address, callable) {
46
+ if (callable.auth !== 'anonymous' || filePositionsOf(callable).length === 0)
47
+ return;
48
+ throw new TypeError(`Callable ${address} is anonymous and declares a file() input: a file is read as the caller, and an anonymous call may have none. Declare it 'authenticated' or 'authorized'.`);
49
+ }
@@ -1,5 +1,5 @@
1
1
  import type { HandlerRequest } from '@astrale-os/kernel-server';
2
- import type { ActionExecution, ActionBinaryInput, Caller, DomainGraphExecutors, DomainKernelSessions } from '../../../application/action/index.js';
2
+ import type { ActionExecution, ActionBinaryInput, Caller, DomainGraphExecutors, DomainKernelSessions, ResolvedCallable } from '../../../application/action/index.js';
3
3
  import type { HandlerDependencies } from '../../../application/dependency/index.js';
4
4
  import type { MutationExecutor } from '../../../application/mutation/index.js';
5
5
  import type { QueryExecutor } from '../../../application/query/index.js';
@@ -21,4 +21,4 @@ export interface DispatchContext {
21
21
  readonly execution: ActionExecution;
22
22
  readonly self?: NodeId;
23
23
  }
24
- export declare function context(request: HandlerRequest, runtime: InitializedRuntime, authentication: InvocationAuthentication, self: NodeId | undefined): DispatchContext;
24
+ export declare function context(request: HandlerRequest, runtime: InitializedRuntime, callable: ResolvedCallable, authentication: InvocationAuthentication, self: NodeId | undefined): DispatchContext;
@@ -1,6 +1,7 @@
1
+ import { filePositionsOf, receivedFile, withFiles } from '../../../application/file/index.js';
1
2
  import { bindCapabilities } from '../capabilities/index.js';
2
3
  import { clients } from '../integration/index.js';
3
- export function context(request, runtime, authentication, self) {
4
+ export function context(request, runtime, callable, authentication, self) {
4
5
  const sessions = authentication.graph;
5
6
  const execution = Object.freeze({
6
7
  signal: request.context.execution.signal,
@@ -14,7 +15,7 @@ export function context(request, runtime, authentication, self) {
14
15
  });
15
16
  return Object.freeze({
16
17
  domain: runtime.loaded.domain,
17
- input: request.call.input,
18
+ input: filesOf(callable, request.call.input, authentication),
18
19
  ...(request.context.binary === undefined ? {} : { body: request.context.binary }),
19
20
  caller: authentication.caller,
20
21
  ...bindCapabilities(runtime.loaded.domain, sessions, runtime.loaded.release.build.requirements.capabilities.classes ?? []),
@@ -29,3 +30,22 @@ export function context(request, runtime, authentication, self) {
29
30
  ...(self === undefined ? {} : { self }),
30
31
  });
31
32
  }
33
+ /**
34
+ * The input with a file object at each `file()` field, which reads the file as the caller: the
35
+ * receipt is bound to the user who uploaded it, never to this Domain.
36
+ */
37
+ function filesOf(callable, input, authentication) {
38
+ const positions = filePositionsOf(callable);
39
+ if (positions.length === 0)
40
+ return input;
41
+ const caller = 'caller' in authentication.graph ? authentication.graph.caller : undefined;
42
+ return withFiles(positions, input, (receipt, located) => receivedFile(receipt, async () => {
43
+ // The runtime registry refuses a file() field on an anonymous callable: its call may have
44
+ // no caller to read the file as.
45
+ if (caller === undefined)
46
+ throw new TypeError('A file is read as the caller; this call has none.');
47
+ return caller.content.download({ receipt });
48
+ },
49
+ // The field's maxBytes and mediaTypes, checked on each read.
50
+ { pointer: located.pointer, constraints: located.position }));
51
+ }
@@ -112,7 +112,7 @@ async function dispatchAdmitted(request, inputConfig, admitted, established) {
112
112
  admittedAuthentication ??= await authentication(selected.implementation.callable, request, inputConfig.runtime.loaded.domain, inputConfig.authority);
113
113
  close ??= once(admittedAuthentication.close);
114
114
  active(request.context.execution);
115
- const dispatchContext = context(request, inputConfig.runtime, admittedAuthentication, selected.self);
115
+ const dispatchContext = context(request, inputConfig.runtime, selected.implementation.callable, admittedAuthentication, selected.self);
116
116
  const output = selected.implementation.kind === 'action'
117
117
  ? await action(selected.implementation, dispatchContext)
118
118
  : await workflow(selected.implementation, dispatchContext, inputConfig.workflows);
@@ -1,4 +1,5 @@
1
1
  import * as errors from '@astrale-os/kernel-protocol/errors';
2
+ import { FileReadError } from '../../../application/file/index.js';
2
3
  import { QueryError } from '../../../application/query/execution/error.js';
3
4
  import { ClientError, MissError, ProtocolError as ClientProtocolError, ResponseError, SessionError, StaleRouteError, TransportError, } from '../../../platform/client/index.js';
4
5
  const PUBLIC_DIAGNOSTICS = new Set(['VALUE_SCHEMA_INSTANCE_INVALID', 'VS_NUMBER_DOMAIN']);
@@ -53,6 +54,13 @@ export function projectError(input) {
53
54
  if (input instanceof QueryError && input.cause instanceof ResponseError) {
54
55
  return projectError(input.cause);
55
56
  }
57
+ // A received file the handler could not read: the caller sent a file its field or its handler
58
+ // does not take.
59
+ if (input instanceof FileReadError) {
60
+ const details = input.pointer === undefined ? {} : Object.freeze({ pointer: input.pointer });
61
+ const reason = Object.freeze({ code: input.code, details });
62
+ return protocolError(input.code === 'FILE_MEDIA_TYPE' ? 'VALIDATION_ERROR' : 'LIMIT_EXCEEDED', input.message, reason);
63
+ }
56
64
  if (input instanceof ResponseError) {
57
65
  if (!PUBLIC_ERROR_CODES.has(input.code)) {
58
66
  return protocolError('BACKEND_UNAVAILABLE', 'Dependency Kernel returned invalid error evidence.');
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /** Curated SDK authoring journey. Semantic values remain available from focused subpaths. */
2
2
  export { defineAction } from './application/action/index.js';
3
- export type { Action, ActionContext, ActionOutputOf, Caller, DeclaredErrorDefinition, DeclaredErrorFactory, DeclaredErrorFamily, DeclaredErrorOptions, DeclaredErrors, } from './application/action/index.js';
3
+ export type { Action, ActionContext, ActionOutputOf, Caller, DeclaredErrorDefinition, DeclaredErrorFactory, DeclaredErrorFamily, DeclaredErrorOptions, DeclaredErrors, ReceivedFile, } from './application/action/index.js';
4
4
  export { defineDomain, defineFrontend, external, requirements, route, routes, vite, } from './application/index.js';
5
5
  export type { DomainDefinition, Frontend, Requirements, Route, Routes, } from './application/index.js';
6
6
  export { defineIntegration, defineProvider } from './application/integration/index.js';
@@ -1,2 +1,2 @@
1
- /** Generated from the Kernel Schema of @astrale-os/kernel-core 1.0.0-beta.34, reduced to its Classes. Regenerate with pnpm sync:kernel-schema. */
1
+ /** Generated from the Kernel Schema of @astrale-os/kernel-core 1.0.0-beta.35, reduced to its Classes. Regenerate with pnpm sync:kernel-schema. */
2
2
  export declare const kernelCompiledSchema: string;