@restatedev/restate-sdk-cloudflare-workers 1.17.2 → 1.17.3

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.
@@ -66,7 +66,7 @@ var EndpointBuilder = class {
66
66
  function computeDiscovery(components) {
67
67
  return {
68
68
  minProtocolVersion: 5,
69
- maxProtocolVersion: 7,
69
+ maxProtocolVersion: 8,
70
70
  services: [...components.values()].map((c) => c.discovery())
71
71
  };
72
72
  }
@@ -66,7 +66,7 @@ var EndpointBuilder = class {
66
66
  function computeDiscovery(components) {
67
67
  return {
68
68
  minProtocolVersion: 5,
69
- maxProtocolVersion: 7,
69
+ maxProtocolVersion: 8,
70
70
  services: [...components.values()].map((c) => c.discovery())
71
71
  };
72
72
  }
@@ -1 +1 @@
1
- {"version":3,"file":"endpoint.js","names":["name"],"sources":["../../src/endpoint/endpoint.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type {\n JournalValueCodec,\n ServiceDefinition,\n VirtualObjectDefinition,\n WorkflowDefinition,\n} from \"@restatedev/restate-sdk-core\";\n\nimport type {\n ObjectOptions,\n ServiceOptions,\n WorkflowOptions,\n} from \"../types/rpc.js\";\nimport { HandlerWrapper } from \"../types/rpc.js\";\nimport type { Component } from \"./components.js\";\nimport {\n ServiceComponent,\n VirtualObjectComponent,\n WorkflowComponent,\n} from \"./components.js\";\nimport type * as discovery from \"./discovery.js\";\nimport { defaultLoggerTransport } from \"../logging/console_logger_transport.js\";\nimport {\n type LoggerTransport,\n LogSource,\n} from \"../logging/logger_transport.js\";\nimport type { Logger } from \"../logging/logger.js\";\nimport { createLogger } from \"../logging/logger.js\";\nimport type { DefaultServiceOptions } from \"../endpoint.js\";\n\nfunction isServiceDefinition<P extends string, M>(\n m: Record<string, any>\n): m is ServiceDefinition<P, M> & { service: M } {\n return m && m.service !== undefined;\n}\n\nfunction isObjectDefinition<P extends string, M>(\n m: Record<string, any>\n): m is VirtualObjectDefinition<P, M> & { object: M } {\n return m && m.object !== undefined;\n}\n\nfunction isWorkflowDefinition<P extends string, M>(\n m: Record<string, any>\n): m is WorkflowDefinition<P, M> & { workflow: M } {\n return m && m.workflow !== undefined;\n}\n\n/**\n * Services can have additional information that is not part of the definition.\n * For example a description or metadata.\n */\ntype ServiceAuxInfo = {\n description?: string;\n metadata?: Record<string, any>;\n options?: ServiceOptions | ObjectOptions | WorkflowOptions;\n};\n\nexport type Endpoint = {\n loggerTransport: LoggerTransport;\n components: Map<string, Component>;\n keySet: string[];\n /**\n * This is a simple console without contextual info.\n *\n * This should be used only in cases where no contextual info is available.\n */\n rlog: Logger;\n /**\n * All discovery metadata, except protocol mode provided by the node/fetch/lambda endpoint implementations\n */\n discoveryMetadata: Omit<discovery.Endpoint, \"protocolMode\">;\n\n /**\n * Codec provider to use for journal values.\n */\n journalValueCodec?: Promise<JournalValueCodec>;\n};\n\nexport class EndpointBuilder {\n private readonly serviceDefinitions: Map<\n string,\n | ServiceDefinition<string, any>\n | VirtualObjectDefinition<string, any>\n | WorkflowDefinition<string, any>\n > = new Map();\n private loggerTransport: LoggerTransport = defaultLoggerTransport;\n private keySet: string[] = [];\n private defaultServiceOptions: DefaultServiceOptions = {};\n private journalValueCodecProvider?: () => Promise<JournalValueCodec>;\n\n public bind<P extends string, M>(\n definition:\n | ServiceDefinition<P, M>\n | VirtualObjectDefinition<P, M>\n | WorkflowDefinition<P, M>\n ) {\n // Validate service name\n if (definition.name.indexOf(\"/\") !== -1) {\n throw new Error(\"service name must not contain any slash '/'\");\n }\n\n this.serviceDefinitions.set(definition.name, definition);\n }\n\n public addIdentityKeys(...keys: string[]) {\n this.keySet.push(...keys);\n }\n\n public setDefaultServiceOptions(options: DefaultServiceOptions) {\n this.defaultServiceOptions = options;\n }\n\n public setLogger(newLogger: LoggerTransport) {\n this.loggerTransport = newLogger;\n }\n\n public setJournalValueCodecProvider(\n codecProvider: () => Promise<JournalValueCodec>\n ) {\n this.journalValueCodecProvider = codecProvider;\n }\n\n public build(): Endpoint {\n const rlog = createLogger(this.loggerTransport, LogSource.SYSTEM);\n\n // Build the components\n const components = new Map<string, Component>();\n for (const [name, definition] of this.serviceDefinitions) {\n if (isServiceDefinition(definition)) {\n const { name, service } = definition;\n if (!service) {\n throw new TypeError(`no service implementation found.`);\n }\n components.set(\n name,\n buildServiceComponent(\n name,\n service,\n definition as ServiceAuxInfo,\n this.defaultServiceOptions\n )\n );\n } else if (isObjectDefinition(definition)) {\n const { name, object } = definition;\n if (!object) {\n throw new TypeError(`no object implementation found.`);\n }\n components.set(\n name,\n buildVirtualObjectComponent(\n name,\n object,\n definition as ServiceAuxInfo,\n this.defaultServiceOptions\n )\n );\n } else if (isWorkflowDefinition(definition)) {\n const { name, workflow } = definition;\n if (!workflow) {\n throw new TypeError(`no workflow implementation found.`);\n }\n components.set(\n name,\n buildWorkflowComponent(\n name,\n workflow,\n definition as ServiceAuxInfo,\n this.defaultServiceOptions\n )\n );\n } else {\n throw new TypeError(\n `cannot bind ${name}, can only bind a service or a virtual object or a workflow definition`\n );\n }\n }\n\n // Compute discovery metadata\n const discoveryMetadata = computeDiscovery(components);\n\n return {\n keySet: this.keySet,\n loggerTransport: this.loggerTransport,\n rlog,\n components,\n discoveryMetadata,\n journalValueCodec: this.journalValueCodecProvider\n ? this.journalValueCodecProvider()\n : undefined,\n };\n }\n}\n\nfunction computeDiscovery(\n components: Map<string, Component>\n): discovery.Endpoint {\n return {\n minProtocolVersion: 5,\n maxProtocolVersion: 7,\n services: [...components.values()].map((c) => c.discovery()),\n };\n}\n\nfunction buildServiceComponent(\n name: string,\n router: any,\n definition: ServiceAuxInfo,\n defaultServiceOptions: DefaultServiceOptions\n): ServiceComponent {\n if (name.indexOf(\"/\") !== -1) {\n throw new Error(\"service name must not contain any slash '/'\");\n }\n const component = new ServiceComponent(\n name,\n definition.description,\n definition.metadata,\n {\n ...defaultServiceOptions,\n ...(definition?.options as ServiceOptions | undefined),\n }\n );\n\n for (const [route, handler] of Object.entries(\n router as { [s: string]: any }\n )) {\n const wrapper = HandlerWrapper.fromHandler(handler);\n if (!wrapper) {\n throw new TypeError(`${route} is not a restate handler.`);\n }\n wrapper.bindInstance(router);\n component.add(route, wrapper);\n }\n\n return component;\n}\n\nfunction buildVirtualObjectComponent(\n name: string,\n router: any,\n definition: ServiceAuxInfo,\n defaultServiceOptions: DefaultServiceOptions\n): VirtualObjectComponent {\n if (name.indexOf(\"/\") !== -1) {\n throw new Error(\"service name must not contain any slash '/'\");\n }\n const component = new VirtualObjectComponent(\n name,\n definition.description,\n definition.metadata,\n {\n ...defaultServiceOptions,\n ...(definition?.options as ObjectOptions | undefined),\n }\n );\n\n for (const [route, handler] of Object.entries(\n router as { [s: string]: any }\n )) {\n const wrapper = HandlerWrapper.fromHandler(handler);\n if (!wrapper) {\n throw new TypeError(`${route} is not a restate handler.`);\n }\n wrapper.bindInstance(router);\n component.add(route, wrapper);\n }\n return component;\n}\n\nfunction buildWorkflowComponent(\n name: string,\n workflow: any,\n definition: ServiceAuxInfo,\n defaultServiceOptions: DefaultServiceOptions\n): WorkflowComponent {\n if (name.indexOf(\"/\") !== -1) {\n throw new Error(\"service name must not contain any slash '/'\");\n }\n const component = new WorkflowComponent(\n name,\n definition.description,\n definition.metadata,\n {\n ...defaultServiceOptions,\n ...(definition?.options as WorkflowOptions | undefined),\n }\n );\n\n for (const [route, handler] of Object.entries(\n workflow as { [s: string]: any }\n )) {\n const wrapper = HandlerWrapper.fromHandler(handler);\n if (!wrapper) {\n throw new TypeError(`${route} is not a restate handler.`);\n }\n wrapper.bindInstance(workflow);\n component.add(route, wrapper);\n }\n return component;\n}\n"],"mappings":";;;;;;;AA0CA,S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AU,GAAG,MAAM,4BAA4B;AAE3D,UAAQ,aAAa,OAAO;AAC5B,YAAU,IAAI,OAAO,QAAQ;;AAE/B,QAAO;;AAGT,SAAS,uBACP,MACA,UACA,YACA,uBACmB;AACnB,KAAI,KAAK,QAAQ,IAAI,KAAK,GACxB,OAAM,IAAI,MAAM,8CAA8C;CAEhE,MAAM,YAAY,IAAI,kBACpB,MACA,WAAW,aACX,WAAW,UACX;EACE,GAAG;EACH,GAAI,YAAY;EACjB,CACF;AAED,MAAK,MAAM,CAAC,OAAO,YAAY,OAAO,QACpC,SACD,EAAE;EACD,MAAM,UAAU,eAAe,YAAY,QAAQ;AACnD,MAAI,CAAC,QACH,OAAM,IAAI,UAAU,GAAG,MAAM,4BAA4B;AAE3D,UAAQ,aAAa,SAAS;AAC9B,YAAU,IAAI,OAAO,QAAQ;;AAE/B,QAAO"}
1
+ {"version":3,"file":"endpoint.js","names":["name"],"sources":["../../src/endpoint/endpoint.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type {\n JournalValueCodec,\n ServiceDefinition,\n VirtualObjectDefinition,\n WorkflowDefinition,\n} from \"@restatedev/restate-sdk-core\";\n\nimport type {\n ObjectOptions,\n ServiceOptions,\n WorkflowOptions,\n} from \"../types/rpc.js\";\nimport { HandlerWrapper } from \"../types/rpc.js\";\nimport type { Component } from \"./components.js\";\nimport {\n ServiceComponent,\n VirtualObjectComponent,\n WorkflowComponent,\n} from \"./components.js\";\nimport type * as discovery from \"./discovery.js\";\nimport { defaultLoggerTransport } from \"../logging/console_logger_transport.js\";\nimport {\n type LoggerTransport,\n LogSource,\n} from \"../logging/logger_transport.js\";\nimport type { Logger } from \"../logging/logger.js\";\nimport { createLogger } from \"../logging/logger.js\";\nimport type { DefaultServiceOptions } from \"../endpoint.js\";\n\nfunction isServiceDefinition<P extends string, M>(\n m: Record<string, any>\n): m is ServiceDefinition<P, M> & { service: M } {\n return m && m.service !== undefined;\n}\n\nfunction isObjectDefinition<P extends string, M>(\n m: Record<string, any>\n): m is VirtualObjectDefinition<P, M> & { object: M } {\n return m && m.object !== undefined;\n}\n\nfunction isWorkflowDefinition<P extends string, M>(\n m: Record<string, any>\n): m is WorkflowDefinition<P, M> & { workflow: M } {\n return m && m.workflow !== undefined;\n}\n\n/**\n * Services can have additional information that is not part of the definition.\n * For example a description or metadata.\n */\ntype ServiceAuxInfo = {\n description?: string;\n metadata?: Record<string, any>;\n options?: ServiceOptions | ObjectOptions | WorkflowOptions;\n};\n\nexport type Endpoint = {\n loggerTransport: LoggerTransport;\n components: Map<string, Component>;\n keySet: string[];\n /**\n * This is a simple console without contextual info.\n *\n * This should be used only in cases where no contextual info is available.\n */\n rlog: Logger;\n /**\n * All discovery metadata, except protocol mode provided by the node/fetch/lambda endpoint implementations\n */\n discoveryMetadata: Omit<discovery.Endpoint, \"protocolMode\">;\n\n /**\n * Codec provider to use for journal values.\n */\n journalValueCodec?: Promise<JournalValueCodec>;\n};\n\nexport class EndpointBuilder {\n private readonly serviceDefinitions: Map<\n string,\n | ServiceDefinition<string, any>\n | VirtualObjectDefinition<string, any>\n | WorkflowDefinition<string, any>\n > = new Map();\n private loggerTransport: LoggerTransport = defaultLoggerTransport;\n private keySet: string[] = [];\n private defaultServiceOptions: DefaultServiceOptions = {};\n private journalValueCodecProvider?: () => Promise<JournalValueCodec>;\n\n public bind<P extends string, M>(\n definition:\n | ServiceDefinition<P, M>\n | VirtualObjectDefinition<P, M>\n | WorkflowDefinition<P, M>\n ) {\n // Validate service name\n if (definition.name.indexOf(\"/\") !== -1) {\n throw new Error(\"service name must not contain any slash '/'\");\n }\n\n this.serviceDefinitions.set(definition.name, definition);\n }\n\n public addIdentityKeys(...keys: string[]) {\n this.keySet.push(...keys);\n }\n\n public setDefaultServiceOptions(options: DefaultServiceOptions) {\n this.defaultServiceOptions = options;\n }\n\n public setLogger(newLogger: LoggerTransport) {\n this.loggerTransport = newLogger;\n }\n\n public setJournalValueCodecProvider(\n codecProvider: () => Promise<JournalValueCodec>\n ) {\n this.journalValueCodecProvider = codecProvider;\n }\n\n public build(): Endpoint {\n const rlog = createLogger(this.loggerTransport, LogSource.SYSTEM);\n\n // Build the components\n const components = new Map<string, Component>();\n for (const [name, definition] of this.serviceDefinitions) {\n if (isServiceDefinition(definition)) {\n const { name, service } = definition;\n if (!service) {\n throw new TypeError(`no service implementation found.`);\n }\n components.set(\n name,\n buildServiceComponent(\n name,\n service,\n definition as ServiceAuxInfo,\n this.defaultServiceOptions\n )\n );\n } else if (isObjectDefinition(definition)) {\n const { name, object } = definition;\n if (!object) {\n throw new TypeError(`no object implementation found.`);\n }\n components.set(\n name,\n buildVirtualObjectComponent(\n name,\n object,\n definition as ServiceAuxInfo,\n this.defaultServiceOptions\n )\n );\n } else if (isWorkflowDefinition(definition)) {\n const { name, workflow } = definition;\n if (!workflow) {\n throw new TypeError(`no workflow implementation found.`);\n }\n components.set(\n name,\n buildWorkflowComponent(\n name,\n workflow,\n definition as ServiceAuxInfo,\n this.defaultServiceOptions\n )\n );\n } else {\n throw new TypeError(\n `cannot bind ${name}, can only bind a service or a virtual object or a workflow definition`\n );\n }\n }\n\n // Compute discovery metadata\n const discoveryMetadata = computeDiscovery(components);\n\n return {\n keySet: this.keySet,\n loggerTransport: this.loggerTransport,\n rlog,\n components,\n discoveryMetadata,\n journalValueCodec: this.journalValueCodecProvider\n ? this.journalValueCodecProvider()\n : undefined,\n };\n }\n}\n\nfunction computeDiscovery(\n components: Map<string, Component>\n): discovery.Endpoint {\n return {\n minProtocolVersion: 5,\n maxProtocolVersion: 8,\n services: [...components.values()].map((c) => c.discovery()),\n };\n}\n\nfunction buildServiceComponent(\n name: string,\n router: any,\n definition: ServiceAuxInfo,\n defaultServiceOptions: DefaultServiceOptions\n): ServiceComponent {\n if (name.indexOf(\"/\") !== -1) {\n throw new Error(\"service name must not contain any slash '/'\");\n }\n const component = new ServiceComponent(\n name,\n definition.description,\n definition.metadata,\n {\n ...defaultServiceOptions,\n ...(definition?.options as ServiceOptions | undefined),\n }\n );\n\n for (const [route, handler] of Object.entries(\n router as { [s: string]: any }\n )) {\n const wrapper = HandlerWrapper.fromHandler(handler);\n if (!wrapper) {\n throw new TypeError(`${route} is not a restate handler.`);\n }\n wrapper.bindInstance(router);\n component.add(route, wrapper);\n }\n\n return component;\n}\n\nfunction buildVirtualObjectComponent(\n name: string,\n router: any,\n definition: ServiceAuxInfo,\n defaultServiceOptions: DefaultServiceOptions\n): VirtualObjectComponent {\n if (name.indexOf(\"/\") !== -1) {\n throw new Error(\"service name must not contain any slash '/'\");\n }\n const component = new VirtualObjectComponent(\n name,\n definition.description,\n definition.metadata,\n {\n ...defaultServiceOptions,\n ...(definition?.options as ObjectOptions | undefined),\n }\n );\n\n for (const [route, handler] of Object.entries(\n router as { [s: string]: any }\n )) {\n const wrapper = HandlerWrapper.fromHandler(handler);\n if (!wrapper) {\n throw new TypeError(`${route} is not a restate handler.`);\n }\n wrapper.bindInstance(router);\n component.add(route, wrapper);\n }\n return component;\n}\n\nfunction buildWorkflowComponent(\n name: string,\n workflow: any,\n definition: ServiceAuxInfo,\n defaultServiceOptions: DefaultServiceOptions\n): WorkflowComponent {\n if (name.indexOf(\"/\") !== -1) {\n throw new Error(\"service name must not contain any slash '/'\");\n }\n const component = new WorkflowComponent(\n name,\n definition.description,\n definition.metadata,\n {\n ...defaultServiceOptions,\n ...(definition?.options as WorkflowOptions | undefined),\n }\n );\n\n for (const [route, handler] of Object.entries(\n workflow as { [s: string]: any }\n )) {\n const wrapper = HandlerWrapper.fromHandler(handler);\n if (!wrapper) {\n throw new TypeError(`${route} is not a restate handler.`);\n }\n wrapper.bindInstance(workflow);\n component.add(route, wrapper);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Q;AACnD,MAAI,CAAC,QACH,OAAM,IAAI,UAAU,GAAG,MAAM,4BAA4B;AAE3D,UAAQ,aAAa,OAAO;AAC5B,YAAU,IAAI,OAAO,QAAQ;;AAE/B,QAAO;;AAGT,SAAS,uBACP,MACA,UACA,YACA,uBACmB;AACnB,KAAI,KAAK,QAAQ,IAAI,KAAK,GACxB,OAAM,IAAI,MAAM,8CAA8C;CAEhE,MAAM,YAAY,IAAI,kBACpB,MACA,WAAW,aACX,WAAW,UACX;EACE,GAAG;EACH,GAAI,YAAY;EACjB,CACF;AAED,MAAK,MAAM,CAAC,OAAO,YAAY,OAAO,QACpC,SACD,EAAE;EACD,MAAM,UAAU,eAAe,YAAY,QAAQ;AACnD,MAAI,CAAC,QACH,OAAM,IAAI,UAAU,GAAG,MAAM,4BAA4B;AAE3D,UAAQ,aAAa,SAAS;AAC9B,YAAU,IAAI,OAAO,QAAQ;;AAE/B,QAAO"}
@@ -40,7 +40,7 @@ export interface WasmSendHandle {
40
40
 
41
41
  export type WasmAsyncResultValue = "NotReady" | "Empty" | { Success: Uint8Array } | { Failure: WasmFailure } | { StateKeys: string[] } | { InvocationId: string };
42
42
 
43
- export type WasmDoProgressResult = "AnyCompleted" | "WaitExternalProgress" | { ExecuteRun: number } | "CancelSignalReceived";
43
+ export type WasmDoProgressResult = "AnyCompleted" | "WaitExternalProgress" | { ExecuteRun: number } | "CancelSignalReceived" | { EphemeralNotificationReady: number };
44
44
 
45
45
  export type WasmUnresolvedFuture = { Single: number } | { FirstCompleted: WasmUnresolvedFuture[] } | { AllCompleted: WasmUnresolvedFuture[] } | { FirstSucceededOrAllFailed: WasmUnresolvedFuture[] } | { AllSucceededOrFirstFailed: WasmUnresolvedFuture[] } | { Unknown: WasmUnresolvedFuture[] };
46
46
 
@@ -134,6 +134,7 @@ export class WasmVM {
134
134
  free(): void;
135
135
  [Symbol.dispose](): void;
136
136
  do_progress(future: WasmUnresolvedFuture): WasmDoProgressResult;
137
+ ephemeral_state_get(key: string): number;
137
138
  get_response_head(): WasmResponseHead;
138
139
  is_completed(handle: number): boolean;
139
140
  is_processing(): boolean;
@@ -177,6 +178,7 @@ export class WasmVM {
177
178
  sys_sleep(millis: bigint, name?: string | null): number;
178
179
  sys_write_output_failure(value: WasmFailure): void;
179
180
  sys_write_output_success(buffer: Uint8Array): void;
181
+ take_ephemeral_notification(ephemeral_notification_handle: number): WasmAsyncResultValue;
180
182
  take_notification(handle: number): WasmAsyncResultValue;
181
183
  take_output(): Uint8Array;
182
184
  }
@@ -335,6 +335,19 @@ export class WasmVM {
335
335
  }
336
336
  return takeFromExternrefTable0(ret[0]);
337
337
  }
338
+ /**
339
+ * @param {string} key
340
+ * @returns {number}
341
+ */
342
+ ephemeral_state_get(key) {
343
+ const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
344
+ const len0 = WASM_VECTOR_LEN;
345
+ const ret = wasm.wasmvm_ephemeral_state_get(this.__wbg_ptr, ptr0, len0);
346
+ if (ret[2]) {
347
+ throw takeFromExternrefTable0(ret[1]);
348
+ }
349
+ return ret[0] >>> 0;
350
+ }
338
351
  /**
339
352
  * @returns {WasmResponseHead}
340
353
  */
@@ -895,6 +908,17 @@ export class WasmVM {
895
908
  throw takeFromExternrefTable0(ret[0]);
896
909
  }
897
910
  }
911
+ /**
912
+ * @param {number} ephemeral_notification_handle
913
+ * @returns {WasmAsyncResultValue}
914
+ */
915
+ take_ephemeral_notification(ephemeral_notification_handle) {
916
+ const ret = wasm.wasmvm_take_ephemeral_notification(this.__wbg_ptr, ephemeral_notification_handle);
917
+ if (ret[2]) {
918
+ throw takeFromExternrefTable0(ret[1]);
919
+ }
920
+ return takeFromExternrefTable0(ret[0]);
921
+ }
898
922
  /**
899
923
  * @param {number} handle
900
924
  * @returns {WasmAsyncResultValue}
@@ -23,6 +23,7 @@ export const wasmheader_new: (a: number, b: number, c: number, d: number) => num
23
23
  export const wasmidentityverifier_new: (a: number, b: number) => [number, number, number];
24
24
  export const wasmidentityverifier_verify_identity: (a: number, b: number, c: number, d: number, e: number) => [number, number];
25
25
  export const wasmvm_do_progress: (a: number, b: any) => [number, number, number];
26
+ export const wasmvm_ephemeral_state_get: (a: number, b: number, c: number) => [number, number, number];
26
27
  export const wasmvm_get_response_head: (a: number) => number;
27
28
  export const wasmvm_is_completed: (a: number, b: number) => number;
28
29
  export const wasmvm_is_processing: (a: number) => number;
@@ -66,10 +67,11 @@ export const wasmvm_sys_signal: (a: number, b: number, c: number) => [number, nu
66
67
  export const wasmvm_sys_sleep: (a: number, b: bigint, c: number, d: number) => [number, number, number];
67
68
  export const wasmvm_sys_write_output_failure: (a: number, b: any) => [number, number];
68
69
  export const wasmvm_sys_write_output_success: (a: number, b: number, c: number) => [number, number];
70
+ export const wasmvm_take_ephemeral_notification: (a: number, b: number) => [number, number, number];
69
71
  export const wasmvm_take_notification: (a: number, b: number) => [number, number, number];
70
72
  export const wasmvm_take_output: (a: number) => any;
71
- export const __wbg_get_wasminput_invocation_id: (a: number) => [number, number];
72
73
  export const start: () => void;
74
+ export const __wbg_get_wasminput_invocation_id: (a: number) => [number, number];
73
75
  export const __wbindgen_malloc: (a: number, b: number) => number;
74
76
  export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
75
77
  export const __wbindgen_exn_store: (a: number) => void;
package/dist/internal.cjs CHANGED
@@ -2,7 +2,25 @@ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
2
  const require_errors = require('./types/errors.cjs');
3
3
 
4
4
  //#region src/internal.ts
5
- var internal_exports = /* @__PURE__ */ require_rolldown_runtime.__export({ isSuspendedError: () => require_errors.isSuspendedError });
5
+ var internal_exports = /* @__PURE__ */ require_rolldown_runtime.__export({
6
+ asInternal: () => asInternal,
7
+ isSuspendedError: () => require_errors.isSuspendedError
8
+ });
9
+ /**
10
+ * Downcast the given context to {@link ContextInternal}, to access the internal APIs.
11
+ *
12
+ * Works with every context type passed to handlers, e.g. `Context`, `ObjectContext`, `ObjectSharedContext`, `WorkflowContext`.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * const ctxInternal = restate.internal.asInternal(ctx);
17
+ * ```
18
+ *
19
+ * @experimental
20
+ */
21
+ function asInternal(ctx) {
22
+ return ctx;
23
+ }
6
24
 
7
25
  //#endregion
8
26
  Object.defineProperty(exports, 'internal_exports', {
@@ -1,10 +1,24 @@
1
1
  import { isSuspendedError } from "./types/errors.cjs";
2
2
  import { Context, InvocationId, RestatePromise } from "./context.cjs";
3
+ import { Serde } from "@restatedev/restate-sdk-core";
3
4
 
4
5
  //#region src/internal.d.ts
5
6
  declare namespace internal_d_exports {
6
- export { ContextInternal, isSuspendedError };
7
+ export { ContextInternal, GetProjectOptions, asInternal, isSuspendedError };
7
8
  }
9
+ /**
10
+ * Downcast the given context to {@link ContextInternal}, to access the internal APIs.
11
+ *
12
+ * Works with every context type passed to handlers, e.g. `Context`, `ObjectContext`, `ObjectSharedContext`, `WorkflowContext`.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * const ctxInternal = restate.internal.asInternal(ctx);
17
+ * ```
18
+ *
19
+ * @experimental
20
+ */
21
+ declare function asInternal(ctx: Context): ContextInternal;
8
22
  /**
9
23
  * Internal {@link Context} interface exposing additional features.
10
24
  *
@@ -40,7 +54,7 @@ interface ContextInternal extends Context {
40
54
  * name: "greeter",
41
55
  * handlers: {
42
56
  * greet: async (ctx: restate.Context, name: string) => {
43
- * ctxInternal = ctx as restate.internal.ContextInternal;
57
+ * const ctxInternal = restate.internal.asInternal(ctx);
44
58
  * const result = await RestatePromise.race([
45
59
  * ctx.run(() => longRunningTask(name)),
46
60
  * ctxInternal.cancellation().map(() => { throw new restate.TerminalError("Cancelled") }),
@@ -58,7 +72,7 @@ interface ContextInternal extends Context {
58
72
  * name: "greeter",
59
73
  * handlers: {
60
74
  * greet: async (ctx: restate.Context, name: string) => {
61
- * const ctxInternal = ctx as restate.internal.ContextInternal;
75
+ * const ctxInternal = restate.internal.asInternal(ctx);
62
76
  * const controller = new AbortController();
63
77
  * const cancellation = ctxInternal.cancellation()
64
78
  * .map(() => {
@@ -82,7 +96,7 @@ interface ContextInternal extends Context {
82
96
  * name: "greeter",
83
97
  * handlers: {
84
98
  * greet: async (ctx: restate.Context, name: string) => {
85
- * const ctxInternal = ctx as restate.internal.ContextInternal;
99
+ * const ctxInternal = restate.internal.asInternal(ctx);
86
100
  * try {
87
101
  * return await RestatePromise.race([
88
102
  * ctx.run(() => longRunningTask(name)),
@@ -118,7 +132,56 @@ interface ContextInternal extends Context {
118
132
  * @experimental
119
133
  */
120
134
  cancelPreviousCalls(): RestatePromise<InvocationId[]>;
135
+ /**
136
+ * Get state from the Restate runtime, apply the given `projection` to it,
137
+ * and record in the journal only the result of the projection.
138
+ *
139
+ * Use this to read big state values when you need only a small part of them:
140
+ * unlike `ctx.get`, the complete state value is not recorded in the journal,
141
+ * only its projection.
142
+ *
143
+ * It will appear in the UI as run(project:state_key).
144
+ *
145
+ * This method **MUST** only be used within Virtual Object and Workflow handlers.
146
+ *
147
+ * **NOTE:** Requires Restate >= 1.8 with service protocol V8 enabled, and **does not** work with request/response protocol mode (e.g. with AWS Lambda).
148
+ *
149
+ * @param name key of the state to retrieve
150
+ * @param projection function receiving the state value, or `null` if the state is empty.
151
+ * @param options serde for the state value, and serde for the projection result.
152
+ * @returns a {@link RestatePromise} resolved with the result of the projection.
153
+ *
154
+ * @example
155
+ * ```ts
156
+ * const ctxInternal = restate.internal.asInternal(ctx);
157
+ * const itemsCount = await ctxInternal.getProject<Item[], number>(
158
+ * "items",
159
+ * (items) => items?.length ?? 0
160
+ * );
161
+ * ```
162
+ *
163
+ * @experimental
164
+ */
165
+ getProject<TValue, TResult>(name: string, projection: (value: TValue | null) => TResult | Promise<TResult>, options?: GetProjectOptions<TValue, TResult>): RestatePromise<TResult>;
121
166
  }
167
+ /**
168
+ * Options for {@link ContextInternal.getProject}.
169
+ *
170
+ * @experimental
171
+ */
172
+ type GetProjectOptions<TValue, TResult> = {
173
+ /**
174
+ * Serde used to deserialize the state value.
175
+ */
176
+ serde?: Serde<TValue>;
177
+ /**
178
+ * Serde used to serialize the projection result, recorded in the journal.
179
+ *
180
+ * If not set, defaults to {@link GetProjectOptions.serde} when that is set,
181
+ * otherwise to the default serde.
182
+ */
183
+ resultSerde?: Serde<TResult>;
184
+ };
122
185
  //#endregion
123
186
  export { internal_d_exports };
124
187
  //# sourceMappingURL=internal.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"internal.d.cts","names":[],"sources":["../src/internal.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;AAWiB,UAAA,eAAA,SAAwB,OAAR,CAAA;EAgGf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAAA;;;;;;;;;;yBAWO,eAAe"}
1
+ {"version":3,"file":"internal.d.cts","names":[],"sources":["../src/internal.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;AAiBA;AAWA;;AA2GwC,iBAtHxB,UAAA,CAsHwB,GAAA,EAtHR,OAsHQ,CAAA,EAtHE,eAsHF;;;;;;;;AAmC1B,UA9IG,eAAA,SAAwB,OA8I3B,CAAA;EACM;;;;AAQpB;;;;EAYgB,YAAA,EAAA,EAAA,OAAA;EAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAnEH;;;;;;;;;;yBAWO,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gEAkChB,kBAAkB,UAAU,QAAQ,oBAC9C,kBAAkB,QAAQ,WACnC,eAAe;;;;;;;KAQR;;;;UAIF,MAAM;;;;;;;gBAQA,MAAM"}
@@ -1,10 +1,24 @@
1
1
  import { isSuspendedError } from "./types/errors.js";
2
2
  import { Context, InvocationId, RestatePromise } from "./context.js";
3
+ import { Serde } from "@restatedev/restate-sdk-core";
3
4
 
4
5
  //#region src/internal.d.ts
5
6
  declare namespace internal_d_exports {
6
- export { ContextInternal, isSuspendedError };
7
+ export { ContextInternal, GetProjectOptions, asInternal, isSuspendedError };
7
8
  }
9
+ /**
10
+ * Downcast the given context to {@link ContextInternal}, to access the internal APIs.
11
+ *
12
+ * Works with every context type passed to handlers, e.g. `Context`, `ObjectContext`, `ObjectSharedContext`, `WorkflowContext`.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * const ctxInternal = restate.internal.asInternal(ctx);
17
+ * ```
18
+ *
19
+ * @experimental
20
+ */
21
+ declare function asInternal(ctx: Context): ContextInternal;
8
22
  /**
9
23
  * Internal {@link Context} interface exposing additional features.
10
24
  *
@@ -40,7 +54,7 @@ interface ContextInternal extends Context {
40
54
  * name: "greeter",
41
55
  * handlers: {
42
56
  * greet: async (ctx: restate.Context, name: string) => {
43
- * ctxInternal = ctx as restate.internal.ContextInternal;
57
+ * const ctxInternal = restate.internal.asInternal(ctx);
44
58
  * const result = await RestatePromise.race([
45
59
  * ctx.run(() => longRunningTask(name)),
46
60
  * ctxInternal.cancellation().map(() => { throw new restate.TerminalError("Cancelled") }),
@@ -58,7 +72,7 @@ interface ContextInternal extends Context {
58
72
  * name: "greeter",
59
73
  * handlers: {
60
74
  * greet: async (ctx: restate.Context, name: string) => {
61
- * const ctxInternal = ctx as restate.internal.ContextInternal;
75
+ * const ctxInternal = restate.internal.asInternal(ctx);
62
76
  * const controller = new AbortController();
63
77
  * const cancellation = ctxInternal.cancellation()
64
78
  * .map(() => {
@@ -82,7 +96,7 @@ interface ContextInternal extends Context {
82
96
  * name: "greeter",
83
97
  * handlers: {
84
98
  * greet: async (ctx: restate.Context, name: string) => {
85
- * const ctxInternal = ctx as restate.internal.ContextInternal;
99
+ * const ctxInternal = restate.internal.asInternal(ctx);
86
100
  * try {
87
101
  * return await RestatePromise.race([
88
102
  * ctx.run(() => longRunningTask(name)),
@@ -118,7 +132,56 @@ interface ContextInternal extends Context {
118
132
  * @experimental
119
133
  */
120
134
  cancelPreviousCalls(): RestatePromise<InvocationId[]>;
135
+ /**
136
+ * Get state from the Restate runtime, apply the given `projection` to it,
137
+ * and record in the journal only the result of the projection.
138
+ *
139
+ * Use this to read big state values when you need only a small part of them:
140
+ * unlike `ctx.get`, the complete state value is not recorded in the journal,
141
+ * only its projection.
142
+ *
143
+ * It will appear in the UI as run(project:state_key).
144
+ *
145
+ * This method **MUST** only be used within Virtual Object and Workflow handlers.
146
+ *
147
+ * **NOTE:** Requires Restate >= 1.8 with service protocol V8 enabled, and **does not** work with request/response protocol mode (e.g. with AWS Lambda).
148
+ *
149
+ * @param name key of the state to retrieve
150
+ * @param projection function receiving the state value, or `null` if the state is empty.
151
+ * @param options serde for the state value, and serde for the projection result.
152
+ * @returns a {@link RestatePromise} resolved with the result of the projection.
153
+ *
154
+ * @example
155
+ * ```ts
156
+ * const ctxInternal = restate.internal.asInternal(ctx);
157
+ * const itemsCount = await ctxInternal.getProject<Item[], number>(
158
+ * "items",
159
+ * (items) => items?.length ?? 0
160
+ * );
161
+ * ```
162
+ *
163
+ * @experimental
164
+ */
165
+ getProject<TValue, TResult>(name: string, projection: (value: TValue | null) => TResult | Promise<TResult>, options?: GetProjectOptions<TValue, TResult>): RestatePromise<TResult>;
121
166
  }
167
+ /**
168
+ * Options for {@link ContextInternal.getProject}.
169
+ *
170
+ * @experimental
171
+ */
172
+ type GetProjectOptions<TValue, TResult> = {
173
+ /**
174
+ * Serde used to deserialize the state value.
175
+ */
176
+ serde?: Serde<TValue>;
177
+ /**
178
+ * Serde used to serialize the projection result, recorded in the journal.
179
+ *
180
+ * If not set, defaults to {@link GetProjectOptions.serde} when that is set,
181
+ * otherwise to the default serde.
182
+ */
183
+ resultSerde?: Serde<TResult>;
184
+ };
122
185
  //#endregion
123
186
  export { internal_d_exports };
124
187
  //# sourceMappingURL=internal.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"internal.d.ts","names":[],"sources":["../src/internal.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;AAWiB,UAAA,eAAA,SAAwB,OAAR,CAAA;EAgGf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAAA;;;;;;;;;;yBAWO,eAAe"}
1
+ {"version":3,"file":"internal.d.ts","names":[],"sources":["../src/internal.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;AAiBA;AAWA;;AA2GwC,iBAtHxB,UAAA,CAsHwB,GAAA,EAtHR,OAsHQ,CAAA,EAtHE,eAsHF;;;;;;;;AAmC1B,UA9IG,eAAA,SAAwB,OA8I3B,CAAA;EACM;;;;AAQpB;;;;EAYgB,YAAA,EAAA,EAAA,OAAA;EAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAnEH;;;;;;;;;;yBAWO,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gEAkChB,kBAAkB,UAAU,QAAQ,oBAC9C,kBAAkB,QAAQ,WACnC,eAAe;;;;;;;KAQR;;;;UAIF,MAAM;;;;;;;gBAQA,MAAM"}
package/dist/internal.js CHANGED
@@ -2,7 +2,25 @@ import { __export } from "./_virtual/rolldown_runtime.js";
2
2
  import { isSuspendedError } from "./types/errors.js";
3
3
 
4
4
  //#region src/internal.ts
5
- var internal_exports = /* @__PURE__ */ __export({ isSuspendedError: () => isSuspendedError });
5
+ var internal_exports = /* @__PURE__ */ __export({
6
+ asInternal: () => asInternal,
7
+ isSuspendedError: () => isSuspendedError
8
+ });
9
+ /**
10
+ * Downcast the given context to {@link ContextInternal}, to access the internal APIs.
11
+ *
12
+ * Works with every context type passed to handlers, e.g. `Context`, `ObjectContext`, `ObjectSharedContext`, `WorkflowContext`.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * const ctxInternal = restate.internal.asInternal(ctx);
17
+ * ```
18
+ *
19
+ * @experimental
20
+ */
21
+ function asInternal(ctx) {
22
+ return ctx;
23
+ }
6
24
 
7
25
  //#endregion
8
26
  export { internal_exports };
@@ -1 +1 @@
1
- {"version":3,"file":"internal.js","names":[],"sources":["../src/internal.ts"],"sourcesContent":["import { Context, InvocationId, RestatePromise } from \"./context.js\";\n\nexport { isSuspendedError } from \"./types/errors.js\";\n\n/**\n * Internal {@link Context} interface exposing additional features.\n *\n * Please note that this API is to be considered experimental and might change without notice.\n *\n * @experimental\n */\nexport interface ContextInternal extends Context {\n /**\n * Returns true if the handler is in the processing phase.\n * This is the mechanism used by `ctx.console` to distinguish whether we should log or not in replaying/processing.\n *\n * **WARNING**: This method should not be used to influence control flow, as it will **surely** lead to non-determinism errors!\n *\n * @experimental\n */\n isProcessing(): boolean;\n\n /**\n * Returns a {@link RestatePromise} that resolves with `undefined` when Restate signals cancellation\n * of the current invocation.\n *\n * This method **MUST** only be used when the handler (or its parent service/endpoint) is configured\n * with `explicitCancellation: true`. Without configuring this option, cancellations are propagated automatically,\n * and this promise will **NEVER** resolve.\n *\n * **Promise reuse:** calling this method multiple times returns the **same** promise instance as long as\n * the current cancellation signal has not yet arrived. Once the promise resolves (cancellation received),\n * later calls return a **new** promise that will resolve on the next cancellation signal.\n *\n * @example Race a long-running side effect against cancellation\n * ```ts\n * const greeter = restate.service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: restate.Context, name: string) => {\n * ctxInternal = ctx as restate.internal.ContextInternal;\n * const result = await RestatePromise.race([\n * ctx.run(() => longRunningTask(name)),\n * ctxInternal.cancellation().map(() => { throw new restate.TerminalError(\"Cancelled\") }),\n * ]);\n * return result;\n * },\n * },\n * options: { explicitCancellation: true },\n * });\n * ```\n *\n * @example Use the cancellation promise to create an AbortSignal for ctx.run\n * ```ts\n * const greeter = restate.service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: restate.Context, name: string) => {\n * const ctxInternal = ctx as restate.internal.ContextInternal;\n * const controller = new AbortController();\n * const cancellation = ctxInternal.cancellation()\n * .map(() => {\n * controller.abort();\n * throw new restate.TerminalError(\"Cancelled\");\n * });\n *\n * return RestatePromise.race([\n * ctx.run(() => fetch(`https://api.example.com/greet/${name}`, { signal: controller.signal })),\n * cancellation,\n * ]);\n * },\n * },\n * options: { explicitCancellation: true },\n * });\n * ```\n *\n * @example Handle cancellation, perform cleanup, then listen for the next cancellation\n * ```ts\n * const greeter = restate.service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: restate.Context, name: string) => {\n * const ctxInternal = ctx as restate.internal.ContextInternal;\n * try {\n * return await RestatePromise.race([\n * ctx.run(() => longRunningTask(name)),\n * ctxInternal.cancellation().map(() => { throw new restate.TerminalError(\"Cancelled\") }),\n * ]);\n * } catch (e) {\n * // Perform cleanup\n * await ctx.run(() => cleanupResources(name));\n *\n * // After cancellation is resolved, ctx.cancellation() returns a fresh promise.\n * // Race cleanup confirmation against the next cancellation signal.\n * await RestatePromise.race([\n * ctx.run(() => confirmCleanup(name)),\n * ctxInternal.cancellation().map(() => { throw new restate.TerminalError(\"Canceled during cleanup\") }),\n * ]);\n * }\n * },\n * },\n * options: { explicitCancellation: true },\n * });\n * ```\n *\n * @experimental\n */\n cancellation(): RestatePromise<void>;\n\n /**\n * Cancel all previous calls made from this handler.\n *\n * This method **MUST** only be used when the handler (or its parent service/endpoint) is configured\n * with `explicitCancellation: true`. Without configuring this option, this operation will always be a no-op.\n *\n * @return the invocation id of the canceled calls.\n * @experimental\n */\n cancelPreviousCalls(): RestatePromise<InvocationId[]>;\n}\n"],"mappings":""}
1
+ {"version":3,"file":"internal.js","names":[],"sources":["../src/internal.ts"],"sourcesContent":["import { Context, InvocationId, RestatePromise } from \"./context.js\";\nimport type { Serde } from \"@restatedev/restate-sdk-core\";\n\nexport { isSuspendedError } from \"./types/errors.js\";\n\n/**\n * Downcast the given context to {@link ContextInternal}, to access the internal APIs.\n *\n * Works with every context type passed to handlers, e.g. `Context`, `ObjectContext`, `ObjectSharedContext`, `WorkflowContext`.\n *\n * @example\n * ```ts\n * const ctxInternal = restate.internal.asInternal(ctx);\n * ```\n *\n * @experimental\n */\nexport function asInternal(ctx: Context): ContextInternal {\n return ctx as ContextInternal;\n}\n\n/**\n * Internal {@link Context} interface exposing additional features.\n *\n * Please note that this API is to be considered experimental and might change without notice.\n *\n * @experimental\n */\nexport interface ContextInternal extends Context {\n /**\n * Returns true if the handler is in the processing phase.\n * This is the mechanism used by `ctx.console` to distinguish whether we should log or not in replaying/processing.\n *\n * **WARNING**: This method should not be used to influence control flow, as it will **surely** lead to non-determinism errors!\n *\n * @experimental\n */\n isProcessing(): boolean;\n\n /**\n * Returns a {@link RestatePromise} that resolves with `undefined` when Restate signals cancellation\n * of the current invocation.\n *\n * This method **MUST** only be used when the handler (or its parent service/endpoint) is configured\n * with `explicitCancellation: true`. Without configuring this option, cancellations are propagated automatically,\n * and this promise will **NEVER** resolve.\n *\n * **Promise reuse:** calling this method multiple times returns the **same** promise instance as long as\n * the current cancellation signal has not yet arrived. Once the promise resolves (cancellation received),\n * later calls return a **new** promise that will resolve on the next cancellation signal.\n *\n * @example Race a long-running side effect against cancellation\n * ```ts\n * const greeter = restate.service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: restate.Context, name: string) => {\n * const ctxInternal = restate.internal.asInternal(ctx);\n * const result = await RestatePromise.race([\n * ctx.run(() => longRunningTask(name)),\n * ctxInternal.cancellation().map(() => { throw new restate.TerminalError(\"Cancelled\") }),\n * ]);\n * return result;\n * },\n * },\n * options: { explicitCancellation: true },\n * });\n * ```\n *\n * @example Use the cancellation promise to create an AbortSignal for ctx.run\n * ```ts\n * const greeter = restate.service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: restate.Context, name: string) => {\n * const ctxInternal = restate.internal.asInternal(ctx);\n * const controller = new AbortController();\n * const cancellation = ctxInternal.cancellation()\n * .map(() => {\n * controller.abort();\n * throw new restate.TerminalError(\"Cancelled\");\n * });\n *\n * return RestatePromise.race([\n * ctx.run(() => fetch(`https://api.example.com/greet/${name}`, { signal: controller.signal })),\n * cancellation,\n * ]);\n * },\n * },\n * options: { explicitCancellation: true },\n * });\n * ```\n *\n * @example Handle cancellation, perform cleanup, then listen for the next cancellation\n * ```ts\n * const greeter = restate.service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: restate.Context, name: string) => {\n * const ctxInternal = restate.internal.asInternal(ctx);\n * try {\n * return await RestatePromise.race([\n * ctx.run(() => longRunningTask(name)),\n * ctxInternal.cancellation().map(() => { throw new restate.TerminalError(\"Cancelled\") }),\n * ]);\n * } catch (e) {\n * // Perform cleanup\n * await ctx.run(() => cleanupResources(name));\n *\n * // After cancellation is resolved, ctx.cancellation() returns a fresh promise.\n * // Race cleanup confirmation against the next cancellation signal.\n * await RestatePromise.race([\n * ctx.run(() => confirmCleanup(name)),\n * ctxInternal.cancellation().map(() => { throw new restate.TerminalError(\"Canceled during cleanup\") }),\n * ]);\n * }\n * },\n * },\n * options: { explicitCancellation: true },\n * });\n * ```\n *\n * @experimental\n */\n cancellation(): RestatePromise<void>;\n\n /**\n * Cancel all previous calls made from this handler.\n *\n * This method **MUST** only be used when the handler (or its parent service/endpoint) is configured\n * with `explicitCancellation: true`. Without configuring this option, this operation will always be a no-op.\n *\n * @return the invocation id of the canceled calls.\n * @experimental\n */\n cancelPreviousCalls(): RestatePromise<InvocationId[]>;\n\n /**\n * Get state from the Restate runtime, apply the given `projection` to it,\n * and record in the journal only the result of the projection.\n *\n * Use this to read big state values when you need only a small part of them:\n * unlike `ctx.get`, the complete state value is not recorded in the journal,\n * only its projection.\n *\n * It will appear in the UI as run(project:state_key).\n *\n * This method **MUST** only be used within Virtual Object and Workflow handlers.\n *\n * **NOTE:** Requires Restate >= 1.8 with service protocol V8 enabled, and **does not** work with request/response protocol mode (e.g. with AWS Lambda).\n *\n * @param name key of the state to retrieve\n * @param projection function receiving the state value, or `null` if the state is empty.\n * @param options serde for the state value, and serde for the projection result.\n * @returns a {@link RestatePromise} resolved with the result of the projection.\n *\n * @example\n * ```ts\n * const ctxInternal = restate.internal.asInternal(ctx);\n * const itemsCount = await ctxInternal.getProject<Item[], number>(\n * \"items\",\n * (items) => items?.length ?? 0\n * );\n * ```\n *\n * @experimental\n */\n getProject<TValue, TResult>(\n name: string,\n projection: (value: TValue | null) => TResult | Promise<TResult>,\n options?: GetProjectOptions<TValue, TResult>\n ): RestatePromise<TResult>;\n}\n\n/**\n * Options for {@link ContextInternal.getProject}.\n *\n * @experimental\n */\nexport type GetProjectOptions<TValue, TResult> = {\n /**\n * Serde used to deserialize the state value.\n */\n serde?: Serde<TValue>;\n\n /**\n * Serde used to serialize the projection result, recorded in the journal.\n *\n * If not set, defaults to {@link GetProjectOptions.serde} when that is set,\n * otherwise to the default serde.\n */\n resultSerde?: Serde<TResult>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiBA,SAAgB,WAAW,KAA+B;AACxD,QAAO"}
package/dist/package.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
2
  //#region package.json
3
- var version = "1.17.2";
3
+ var version = "1.17.3";
4
4
 
5
5
  //#endregion
6
6
  Object.defineProperty(exports, 'version', {
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "1.17.2";
2
+ var version = "1.17.3";
3
3
 
4
4
  //#endregion
5
5
  export { version };
@@ -1 +1 @@
1
- {"version":3,"file":"package.js","names":[],"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"@restatedev/restate-sdk\",\n \"version\": \"1.17.2\",\n \"description\": \"Typescript SDK for Restate\",\n \"author\": \"Restate Developers\",\n \"email\": \"code@restate.dev\",\n \"license\": \"MIT\",\n \"homepage\": \"https://github.com/restatedev/sdk-typescript#readme\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/restatedev/sdk-typescript.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/restatedev/sdk-typescript/issues\"\n },\n \"type\": \"module\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.cts\",\n \"exports\": {\n \".\": {\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./fetch\": {\n \"import\": \"./dist/fetch.js\",\n \"require\": \"./dist/fetch.cjs\"\n },\n \"./lambda\": {\n \"import\": \"./dist/lambda.js\",\n \"require\": \"./dist/lambda.cjs\"\n },\n \"./node\": {\n \"import\": \"./dist/node.js\",\n \"require\": \"./dist/node.cjs\"\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"test\": \"turbo run _test --filter={.}...\",\n \"_test\": \"vitest run\",\n \"build\": \"turbo run _build --filter={.}...\",\n \"_build\": \"tsc --noEmit && tsdown\",\n \"dev\": \"tsc --noEmit --watch\",\n \"clean\": \"rm -rf dist *.tsbuildinfo .turbo\",\n \"check:types\": \"turbo run _check:types --filter={.}...\",\n \"_check:types\": \"tsc --noEmit --project tsconfig.build.json\",\n \"lint\": \"eslint .\",\n \"check:exports\": \"turbo run _check:exports --filter={.}...\",\n \"_check:exports\": \"attw --pack .\",\n \"check:api\": \"turbo run _check:api --filter={.}...\",\n \"_check:api\": \"api-extractor run --local && api-extractor run --local --config api-extractor.fetch.json && api-extractor run --local --config api-extractor.lambda.json && api-extractor run --local --config api-extractor.node.json\",\n \"prepublishOnly\": \"pnpm -w verify\"\n },\n \"dependencies\": {\n \"@restatedev/restate-sdk-core\": \"workspace:*\"\n },\n \"devDependencies\": {\n \"@types/aws-lambda\": \"^8.10.115\"\n },\n \"typesVersions\": {\n \"*\": {\n \"fetch\": [\n \"./dist/fetch.d.ts\"\n ],\n \"lambda\": [\n \"./dist/lambda.d.ts\"\n ],\n \"node\": [\n \"./dist/node.d.ts\"\n ]\n }\n }\n}\n"],"mappings":";cAEa"}
1
+ {"version":3,"file":"package.js","names":[],"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"@restatedev/restate-sdk\",\n \"version\": \"1.17.3\",\n \"description\": \"Typescript SDK for Restate\",\n \"author\": \"Restate Developers\",\n \"email\": \"code@restate.dev\",\n \"license\": \"MIT\",\n \"homepage\": \"https://github.com/restatedev/sdk-typescript#readme\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/restatedev/sdk-typescript.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/restatedev/sdk-typescript/issues\"\n },\n \"type\": \"module\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.cts\",\n \"exports\": {\n \".\": {\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./fetch\": {\n \"import\": \"./dist/fetch.js\",\n \"require\": \"./dist/fetch.cjs\"\n },\n \"./lambda\": {\n \"import\": \"./dist/lambda.js\",\n \"require\": \"./dist/lambda.cjs\"\n },\n \"./node\": {\n \"import\": \"./dist/node.js\",\n \"require\": \"./dist/node.cjs\"\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"test\": \"turbo run _test --filter={.}...\",\n \"_test\": \"vitest run\",\n \"build\": \"turbo run _build --filter={.}...\",\n \"_build\": \"tsc --noEmit && tsdown\",\n \"dev\": \"tsc --noEmit --watch\",\n \"clean\": \"rm -rf dist *.tsbuildinfo .turbo\",\n \"check:types\": \"turbo run _check:types --filter={.}...\",\n \"_check:types\": \"tsc --noEmit --project tsconfig.build.json\",\n \"lint\": \"eslint .\",\n \"check:exports\": \"turbo run _check:exports --filter={.}...\",\n \"_check:exports\": \"attw --pack .\",\n \"check:api\": \"turbo run _check:api --filter={.}...\",\n \"_check:api\": \"api-extractor run --local && api-extractor run --local --config api-extractor.fetch.json && api-extractor run --local --config api-extractor.lambda.json && api-extractor run --local --config api-extractor.node.json\",\n \"prepublishOnly\": \"pnpm -w verify\"\n },\n \"dependencies\": {\n \"@restatedev/restate-sdk-core\": \"workspace:*\"\n },\n \"devDependencies\": {\n \"@types/aws-lambda\": \"^8.10.115\"\n },\n \"typesVersions\": {\n \"*\": {\n \"fetch\": [\n \"./dist/fetch.d.ts\"\n ],\n \"lambda\": [\n \"./dist/lambda.d.ts\"\n ],\n \"node\": [\n \"./dist/node.d.ts\"\n ]\n }\n }\n}\n"],"mappings":";cAEa"}
package/dist/promises.cjs CHANGED
@@ -234,10 +234,11 @@ var ConstRestatePromise = class ConstRestatePromise extends InternalRestatePromi
234
234
  * Promises executor, gluing VM with I/O and Promises given to user space.
235
235
  */
236
236
  var PromisesExecutor = class {
237
- constructor(coreVm, outputPump, runClosuresTracker, externalProgressChannel, errorCallback) {
237
+ constructor(coreVm, outputPump, runClosuresTracker, ephemeralRequestTracker, externalProgressChannel, errorCallback) {
238
238
  this.coreVm = coreVm;
239
239
  this.outputPump = outputPump;
240
240
  this.runClosuresTracker = runClosuresTracker;
241
+ this.ephemeralRequestTracker = ephemeralRequestTracker;
241
242
  this.externalProgressChannel = externalProgressChannel;
242
243
  this.errorCallback = errorCallback;
243
244
  }
@@ -263,6 +264,9 @@ var PromisesExecutor = class {
263
264
  } else if (doProgressResult === "CancelSignalReceived") {
264
265
  restatePromise.tryCancel();
265
266
  return;
267
+ } else if ("EphemeralNotificationReady" in doProgressResult) {
268
+ const completionId = doProgressResult.EphemeralNotificationReady;
269
+ await this.ephemeralRequestTracker.complete(completionId, this.coreVm.take_ephemeral_notification(completionId));
266
270
  } else {
267
271
  this.runClosuresTracker.executeRun(doProgressResult.ExecuteRun);
268
272
  await (0, node_timers_promises.setImmediate)();
@@ -1 +1 @@
1
- {"version":3,"file":"promises.d.cts","names":[],"sources":["../src/promises.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;iBA8CgB,uBAAuB,QAAQ,UAAU,eAAe"}
1
+ {"version":3,"file":"promises.d.cts","names":[],"sources":["../src/promises.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;iBAkDgB,uBAAuB,QAAQ,UAAU,eAAe"}
@@ -1 +1 @@
1
- {"version":3,"file":"promises.d.ts","names":[],"sources":["../src/promises.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;iBA8CgB,uBAAuB,QAAQ,UAAU,eAAe"}
1
+ {"version":3,"file":"promises.d.ts","names":[],"sources":["../src/promises.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;iBAkDgB,uBAAuB,QAAQ,UAAU,eAAe"}
package/dist/promises.js CHANGED
@@ -232,10 +232,11 @@ var ConstRestatePromise = class ConstRestatePromise extends InternalRestatePromi
232
232
  * Promises executor, gluing VM with I/O and Promises given to user space.
233
233
  */
234
234
  var PromisesExecutor = class {
235
- constructor(coreVm, outputPump, runClosuresTracker, externalProgressChannel, errorCallback) {
235
+ constructor(coreVm, outputPump, runClosuresTracker, ephemeralRequestTracker, externalProgressChannel, errorCallback) {
236
236
  this.coreVm = coreVm;
237
237
  this.outputPump = outputPump;
238
238
  this.runClosuresTracker = runClosuresTracker;
239
+ this.ephemeralRequestTracker = ephemeralRequestTracker;
239
240
  this.externalProgressChannel = externalProgressChannel;
240
241
  this.errorCallback = errorCallback;
241
242
  }
@@ -261,6 +262,9 @@ var PromisesExecutor = class {
261
262
  } else if (doProgressResult === "CancelSignalReceived") {
262
263
  restatePromise.tryCancel();
263
264
  return;
265
+ } else if ("EphemeralNotificationReady" in doProgressResult) {
266
+ const completionId = doProgressResult.EphemeralNotificationReady;
267
+ await this.ephemeralRequestTracker.complete(completionId, this.coreVm.take_ephemeral_notification(completionId));
264
268
  } else {
265
269
  this.runClosuresTracker.executeRun(doProgressResult.ExecuteRun);
266
270
  await setImmediate();