@intuned/runtime-dev 1.0.4-stuck.1 → 1.0.6-cli-auth.0.0.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.
Files changed (95) hide show
  1. package/InterfaceTemplate/utils.ts +53 -31
  2. package/bin/cli-build +3 -0
  3. package/bin/create-auth-session +3 -0
  4. package/bin/deploy +3 -0
  5. package/bin/init +3 -0
  6. package/bin/run-api +3 -0
  7. package/dist/commands/api/run.js +2 -2
  8. package/dist/commands/auth-sessions/load.js +1 -1
  9. package/dist/commands/auth-sessions/run-check.js +2 -2
  10. package/dist/commands/auth-sessions/run-create.js +2 -2
  11. package/dist/commands/browser/save-state.js +1 -1
  12. package/dist/commands/browser/start-browser.js +1 -1
  13. package/dist/commands/build.js +4 -4
  14. package/dist/commands/cli-auth-sessions/check.d.ts +0 -0
  15. package/dist/commands/cli-auth-sessions/check.js +1 -0
  16. package/dist/commands/cli-auth-sessions/create.d.ts +2 -0
  17. package/dist/commands/cli-auth-sessions/create.js +28 -0
  18. package/dist/commands/cli-auth-sessions/utils.d.ts +4 -0
  19. package/dist/commands/cli-auth-sessions/utils.js +55 -0
  20. package/dist/commands/cli-build/cli-build.d.ts +2 -0
  21. package/dist/commands/cli-build/cli-build.js +20 -0
  22. package/dist/commands/common/browserUtils.d.ts +1 -1
  23. package/dist/commands/common/browserUtils.js +3 -3
  24. package/dist/commands/common/getFirstLineNumber.test.js +2 -2
  25. package/dist/commands/common/projectExclusions.d.ts +2 -0
  26. package/dist/commands/common/projectExclusions.js +8 -0
  27. package/dist/commands/common/tsNodeImport.d.ts +2 -1
  28. package/dist/commands/common/tsNodeImport.js +20 -6
  29. package/dist/commands/common/utils/fileUtils.js +2 -2
  30. package/dist/commands/common/utils/settings.js +1 -1
  31. package/dist/commands/common/utils/template.d.ts +1 -1
  32. package/dist/commands/common/utils/template.js +1 -1
  33. package/dist/commands/deploy/deploy.d.ts +2 -0
  34. package/dist/commands/deploy/deploy.js +47 -0
  35. package/dist/commands/deploy/utils.d.ts +16 -0
  36. package/dist/commands/deploy/utils.js +350 -0
  37. package/dist/commands/init/init.d.ts +2 -0
  38. package/dist/commands/init/init.js +22 -0
  39. package/dist/commands/init/utils.d.ts +9 -0
  40. package/dist/commands/init/utils.js +179 -0
  41. package/dist/commands/interface/run.js +141 -94
  42. package/dist/commands/run-api-cli/run-api.d.ts +2 -0
  43. package/dist/commands/run-api-cli/run-api.js +48 -0
  44. package/dist/commands/run-api-cli/utils.d.ts +10 -0
  45. package/dist/commands/run-api-cli/utils.js +98 -0
  46. package/dist/commands/ts-check.js +2 -2
  47. package/dist/common/Logger/Logger/index.js +1 -1
  48. package/dist/common/Logger/index.js +1 -1
  49. package/dist/common/asyncLocalStorage/index.d.ts +1 -1
  50. package/dist/common/asyncLocalStorage/index.js +2 -2
  51. package/dist/common/cli/cliReadme.d.ts +1 -0
  52. package/dist/common/cli/cliReadme.js +69 -0
  53. package/dist/common/cli/constants.d.ts +24 -0
  54. package/dist/common/cli/constants.js +30 -0
  55. package/dist/common/cli/types.d.ts +52 -0
  56. package/dist/common/cli/types.js +7 -0
  57. package/dist/common/cli/utils.d.ts +6 -0
  58. package/dist/common/cli/utils.js +35 -0
  59. package/dist/common/contextStorageStateHelpers.d.ts +20 -13
  60. package/dist/common/contextStorageStateHelpers.js +69 -42
  61. package/dist/common/getPlaywrightConstructs.d.ts +1 -1
  62. package/dist/common/getPlaywrightConstructs.js +5 -5
  63. package/dist/common/jwtTokenManager.js +2 -2
  64. package/dist/common/runApi/errors.d.ts +0 -11
  65. package/dist/common/runApi/errors.js +2 -41
  66. package/dist/common/runApi/index.d.ts +2 -1
  67. package/dist/common/runApi/index.js +11 -4
  68. package/dist/common/runApi/types.d.ts +82 -76
  69. package/dist/common/runApi/types.js +1 -1
  70. package/dist/common/settingsSchema.js +1 -1
  71. package/dist/common/telemetry.js +1 -1
  72. package/package.json +14 -6
  73. package/WebTemplate/accessKeyHelpers.ts +0 -28
  74. package/WebTemplate/api.ts +0 -139
  75. package/WebTemplate/app.ts +0 -18
  76. package/WebTemplate/controllers/async.ts +0 -142
  77. package/WebTemplate/controllers/authSessions/check.ts +0 -61
  78. package/WebTemplate/controllers/authSessions/create.ts +0 -101
  79. package/WebTemplate/controllers/authSessions/index.ts +0 -41
  80. package/WebTemplate/controllers/authSessions/killOperation.ts +0 -35
  81. package/WebTemplate/controllers/authSessions/resumeOperation.ts +0 -56
  82. package/WebTemplate/controllers/authSessions/store.ts +0 -19
  83. package/WebTemplate/controllers/controllers.ts +0 -73
  84. package/WebTemplate/controllers/runApi/helpers.ts +0 -128
  85. package/WebTemplate/controllers/runApi/index.ts +0 -68
  86. package/WebTemplate/controllers/runApi/types.ts +0 -13
  87. package/WebTemplate/controllers/traces.ts +0 -151
  88. package/WebTemplate/features.ts +0 -8
  89. package/WebTemplate/headers.ts +0 -6
  90. package/WebTemplate/index.playwright.ts +0 -47
  91. package/WebTemplate/index.vanilla.ts +0 -26
  92. package/WebTemplate/jobs.ts +0 -356
  93. package/WebTemplate/shutdown.ts +0 -64
  94. package/WebTemplate/utils.ts +0 -257
  95. package/WebTemplate.zip +0 -0
@@ -1,356 +0,0 @@
1
- import { runApi, RunBody } from "./controllers/runApi";
2
- import {
3
- ATTEMPT_NUMBER_HEADER,
4
- JOB_ID_HEADER,
5
- JOB_RUN_ID_HEADER,
6
- RUN_ID_HEADER,
7
- SHOULD_SHUTDOWN_HEADER,
8
- } from "./headers";
9
- import {
10
- getErrorResponse,
11
- isHeadless,
12
- isJobRunMachine,
13
- ProxyConfig,
14
- proxyToUrl,
15
- } from "./utils";
16
- import {
17
- callBackendFunctionWithToken,
18
- backendFunctionsTokenManager,
19
- } from "@intuned/runtime/dist/common/jwtTokenManager";
20
- import retry from "async-retry";
21
- import { runWithContext } from "@intuned/runtime";
22
- import { setTimeout } from "timers/promises";
23
- import { deleteTrace, uploadTrace } from "./controllers/traces";
24
-
25
- type JobPayload = {
26
- headers: Record<string, string>;
27
- originalPayload: any;
28
- payload: RunBody;
29
- startTime: number;
30
- functionName: string;
31
- receiptHandle: string;
32
- traceSignedUrl?: string;
33
- };
34
-
35
- if (isJobRunMachine()) {
36
- console.log("Running in job v3 mode");
37
- void jobsV3();
38
- }
39
-
40
- async function runApiInContext(
41
- jobPayload: JobPayload
42
- ): Promise<Awaited<ReturnType<typeof runApi>>> {
43
- const runId = jobPayload.headers[RUN_ID_HEADER] as string;
44
- const jobId = process.env.JOB_ID as string;
45
- const jobRunId = process.env.JOB_RUN_ID as string;
46
- const proxy = jobPayload.payload.proxy
47
- ? (proxyToUrl(jobPayload.payload.proxy as ProxyConfig) as string)
48
- : undefined;
49
- const contextData = {
50
- runId: runId ?? "",
51
- jobId,
52
- jobRunId,
53
- queueId: undefined,
54
- proxy,
55
- timeoutInfo: {
56
- extendTimeoutCallback: async () => {
57
- try {
58
- await extendTimeout(jobPayload);
59
- } catch (error: any) {
60
- console.error("Error extending timeout", error);
61
- }
62
- },
63
- },
64
- ...(jobPayload.payload.executionContext ?? {}),
65
- };
66
-
67
- const backendFunctionsToken = jobPayload.payload.functionsToken;
68
- if (backendFunctionsToken) {
69
- backendFunctionsTokenManager.token = backendFunctionsToken;
70
- }
71
-
72
- try {
73
- return await runWithContext(contextData, runApi, {
74
- functionName: jobPayload.functionName,
75
- ...jobPayload.payload,
76
- runId: jobPayload.headers[RUN_ID_HEADER],
77
- attemptNumber: jobPayload.headers[ATTEMPT_NUMBER_HEADER],
78
- shouldSaveTrace: true,
79
- headless: isHeadless(),
80
- });
81
- } catch (error: any) {
82
- return getErrorResponse(error);
83
- }
84
- }
85
-
86
- async function jobsV3() {
87
- await reportReady();
88
- const initialDelay = 1000;
89
- let delay = initialDelay;
90
- while (true as boolean) {
91
- await setTimeout(delay);
92
- try {
93
- const { payload, shouldShutdown } = await requestPayload();
94
- if (!payload) {
95
- if (shouldShutdown) {
96
- console.log("Received shutdown signal from job");
97
- process.exit(0);
98
- }
99
- delay = Math.min(delay * 2, 60000);
100
- continue;
101
- }
102
- delay = initialDelay;
103
- console.log("Running payload", payload.functionName);
104
- const { body, status } = await runApiInContext(payload);
105
-
106
- await reportResultsAndUploadTraces(payload, status, body);
107
-
108
- if (shouldShutdown) {
109
- process.exit(0);
110
- }
111
- } catch (error: any) {
112
- console.error("Error in payload", error);
113
- }
114
- }
115
- }
116
-
117
- async function reportReady() {
118
- console.log("Ready");
119
- }
120
-
121
- async function requestPayload(): Promise<{
122
- payload: JobPayload | null;
123
- shouldShutdown: boolean;
124
- }> {
125
- console.log("Requesting payload");
126
- const result = await callBackendFunctionWithToken("jobs/requestPayload", {
127
- headers: {
128
- "fly-instance-id": process.env.FLY_ALLOC_ID ?? "",
129
- [JOB_ID_HEADER]: process.env.JOB_ID ?? "",
130
- [JOB_RUN_ID_HEADER]: process.env.JOB_RUN_ID ?? "",
131
- },
132
- });
133
- const shouldShutdown = result.headers.get(SHOULD_SHUTDOWN_HEADER) === "true";
134
- if (result.status === 200) {
135
- const payload = (await result.json()) as JobPayload;
136
- console.log("Received payload", payload);
137
- return {
138
- payload: {
139
- ...payload,
140
- headers: {
141
- ...payload.headers,
142
- [JOB_ID_HEADER]: process.env.JOB_ID ?? "",
143
- [JOB_RUN_ID_HEADER]: process.env.JOB_RUN_ID ?? "",
144
- },
145
- },
146
- shouldShutdown,
147
- };
148
- }
149
- if (result.status === 204) {
150
- console.log("No payload available");
151
- return {
152
- payload: null,
153
- shouldShutdown,
154
- };
155
- }
156
- console.log("Failed to obtain payload", result.status, await result.text());
157
- return {
158
- payload: null,
159
- shouldShutdown,
160
- };
161
- }
162
-
163
- async function reportResultsAndUploadTraces(
164
- payload: JobPayload,
165
- statusCode: number,
166
- body: any
167
- ) {
168
- await reportJobRunResult({
169
- runId: payload.headers[RUN_ID_HEADER] as string,
170
- result: {
171
- statusCode,
172
- body,
173
- receiptHandle: payload.receiptHandle,
174
- },
175
- originalPayload: payload.originalPayload,
176
- startTime: payload.startTime,
177
- functionsToken: backendFunctionsTokenManager.token,
178
- });
179
- await uploadJobRunTrace(payload);
180
- }
181
-
182
- async function reportJobRunResult({
183
- runId,
184
- result,
185
- originalPayload,
186
- startTime,
187
- functionsToken,
188
- }: {
189
- runId: string;
190
- result: {
191
- statusCode: number;
192
- body: any;
193
- receiptHandle: string;
194
- };
195
- originalPayload: any;
196
- startTime: number;
197
- functionsToken?: string;
198
- }) {
199
- console.log("Reporting payload result");
200
- const reqResult = await retry(
201
- async (bail) => {
202
- const response = await callBackendFunctionWithToken("jobs/reportResult", {
203
- method: "POST",
204
- headers: {
205
- "Content-Type": "application/json",
206
- "fly-instance-id": process.env.FLY_ALLOC_ID ?? "",
207
- [JOB_ID_HEADER]: process.env.JOB_ID ?? "",
208
- [JOB_RUN_ID_HEADER]: process.env.JOB_RUN_ID ?? "",
209
- },
210
- body: JSON.stringify({
211
- runId,
212
- result,
213
- originalPayload,
214
- startTime,
215
- }),
216
- });
217
-
218
- if (!response.ok) {
219
- if ([401, 403, 404, 413].includes(response.status)) {
220
- bail(
221
- new Error(
222
- `Reporting result failed (non-retryable), status ${response.status}`
223
- )
224
- );
225
- }
226
- throw new Error(`Reporting result failed, status ${response.status}`);
227
- }
228
-
229
- return response;
230
- },
231
- {
232
- retries: 5,
233
- factor: 2,
234
- maxTimeout: 1000 * 60, // 1 minute
235
- minTimeout: 1000 * 5, // 5 seconds
236
- }
237
- );
238
- console.log("Reported payload result", reqResult.ok, await reqResult.text());
239
- }
240
-
241
- async function uploadJobRunTrace(
242
- payload: NonNullable<
243
- NonNullable<Awaited<ReturnType<typeof requestPayload>>>["payload"]
244
- >
245
- ) {
246
- if (!payload.traceSignedUrl) {
247
- return;
248
- }
249
- const runId = payload.headers[RUN_ID_HEADER] as string;
250
- const attemptNumber = payload.headers[ATTEMPT_NUMBER_HEADER] as
251
- | string
252
- | undefined;
253
- console.log("Uploading trace", runId, attemptNumber);
254
- const uploadTraceResult = await uploadTrace({
255
- runId,
256
- attemptNumber,
257
- signedUrl: payload.traceSignedUrl,
258
- });
259
- if (uploadTraceResult.isErr()) {
260
- console.error("Error uploading trace", uploadTraceResult.error, {
261
- runId,
262
- attemptNumber,
263
- });
264
- } else {
265
- console.log(
266
- "Trace uploaded successfully, reporting trace",
267
- runId,
268
- attemptNumber
269
- );
270
- await retry(
271
- async (bail) => {
272
- const response = await callBackendFunctionWithToken(
273
- "jobs/reportTrace",
274
- {
275
- method: "POST",
276
- headers: {
277
- "Content-Type": "application/json",
278
- "fly-instance-id": process.env.FLY_ALLOC_ID ?? "",
279
- [JOB_ID_HEADER]: process.env.JOB_ID ?? "",
280
- [JOB_RUN_ID_HEADER]: process.env.JOB_RUN_ID ?? "",
281
- },
282
- body: JSON.stringify({
283
- runId,
284
- attemptNumber,
285
- traceSignedUrl: payload.traceSignedUrl,
286
- }),
287
- }
288
- );
289
-
290
- if (!response.ok) {
291
- if ([401, 403, 404].includes(response.status)) {
292
- bail(
293
- new Error(
294
- `Reporting trace failed (non-retryable), status ${response.status}`
295
- )
296
- );
297
- }
298
- throw new Error(`Reporting trace failed, status ${response.status}`);
299
- }
300
-
301
- console.log("Trace reported successfully", runId, attemptNumber);
302
- return response;
303
- },
304
- {
305
- retries: 2,
306
- minTimeout: 1000 * 5,
307
- }
308
- ).catch(() => undefined);
309
- }
310
- console.log("Deleting trace", runId, attemptNumber);
311
- const deleteTraceResult = await deleteTrace({
312
- runId,
313
- attemptNumber,
314
- });
315
- if (deleteTraceResult.isErr()) {
316
- console.error("Error deleting trace", deleteTraceResult.error, {
317
- runId,
318
- attemptNumber,
319
- });
320
- }
321
- }
322
-
323
- async function extendTimeout(payload: JobPayload) {
324
- console.log("Requesting timeout extension for", payload.functionName);
325
- const extendTimeoutRes = await callBackendFunctionWithToken(
326
- "jobs/extendTimeout",
327
- {
328
- method: "POST",
329
- headers: {
330
- "Content-Type": "application/json",
331
- "fly-instance-id": process.env.FLY_ALLOC_ID ?? "",
332
- [JOB_ID_HEADER]: process.env.JOB_ID ?? "",
333
- [JOB_RUN_ID_HEADER]: process.env.JOB_RUN_ID ?? "",
334
- },
335
- body: JSON.stringify({
336
- receiptHandle: payload.receiptHandle,
337
- }),
338
- }
339
- );
340
- if (!extendTimeoutRes.ok) {
341
- console.error(
342
- "Requesting timeout extension failed",
343
- extendTimeoutRes.status,
344
- await extendTimeoutRes.text()
345
- );
346
- return false;
347
- }
348
- console.log("Request timeout extension success", extendTimeoutRes.ok);
349
- const response = await extendTimeoutRes.json();
350
- const newFunctionsToken = response.functionsToken;
351
- if (newFunctionsToken) {
352
- backendFunctionsTokenManager.token = newFunctionsToken;
353
- console.log("Backend functions token renewed");
354
- }
355
- return true;
356
- }
@@ -1,64 +0,0 @@
1
- import { isJobRunMachine } from "./utils";
2
- import { promisify } from "util";
3
- import { AsyncRunEndpointController } from "./utils";
4
- import { Server } from "http";
5
-
6
- export class ShutdownController {
7
- private static _instance?: ShutdownController;
8
-
9
- static initialize(server: Server) {
10
- if (this._instance) {
11
- throw new Error("ShutdownController is already initialized");
12
- }
13
- this._instance = new ShutdownController(server);
14
- }
15
-
16
- public static get instance() {
17
- if (!this._instance) {
18
- throw new Error("ShutdownController is not initialized");
19
- }
20
- return this._instance;
21
- }
22
-
23
- private server: Server;
24
- private timer: NodeJS.Timeout | null = null;
25
- private constructor(server: Server) {
26
- this.server = server;
27
- }
28
-
29
- async checkForShutdown() {
30
- if (await this.serverShouldShutdown()) {
31
- if (this.timer) clearTimeout(this.timer);
32
- this.timer = setTimeout(async () => {
33
- if (await this.serverShouldShutdown()) {
34
- console.log("No active requests, shutting down the server.");
35
- process.exit(0);
36
- }
37
- // TIME_TO_SHUTDOWN in seconds to match tired-proxy
38
- }, this.calculateShutdownDelay());
39
- }
40
- }
41
-
42
- private async getActiveRequests() {
43
- const activeConnections = await promisify(
44
- (...params: Parameters<typeof this.server.getConnections>) =>
45
- this.server.getConnections(...params)
46
- )();
47
- return activeConnections + AsyncRunEndpointController.activeRequestsCount;
48
- }
49
-
50
- private async serverShouldShutdown() {
51
- if (isJobRunMachine()) {
52
- return false;
53
- }
54
- return (await this.getActiveRequests()) === 0;
55
- }
56
-
57
- private calculateShutdownDelay(): number | undefined {
58
- const shutdownTime = +process.env.TIME_TO_SHUTDOWN;
59
- if (isNaN(shutdownTime) || shutdownTime <= 0) {
60
- return 60 * 1000;
61
- }
62
- return shutdownTime * 1000;
63
- }
64
- }
@@ -1,257 +0,0 @@
1
- import * as playwright from "@intuned/playwright-core";
2
- import { Handler, Response } from "@tinyhttp/app";
3
- import * as path from "path";
4
- import { getExecutionContext } from "@intuned/runtime";
5
- import { setTimeout } from "timers/promises";
6
-
7
- export class FunctionNotFoundError extends Error {
8
- functionName: string;
9
- path: string;
10
- constructor(functionName: string, path: string) {
11
- const message = `function ${functionName} not found in ${path}`;
12
- super(message);
13
- this.functionName = functionName;
14
- this.path = path;
15
- this.name = "FunctionNotFound";
16
- Object.setPrototypeOf(this, FunctionNotFoundError.prototype);
17
- }
18
- }
19
-
20
- export function getIsRetryableError(error: any) {
21
- if (error?.message) {
22
- return error.message.includes("ERR_NETWORK_CHANGED");
23
- }
24
- return false;
25
- }
26
-
27
- export function getErrorResponse(error: any): {
28
- status: number;
29
- body: any;
30
- } {
31
- if (error instanceof FunctionNotFoundError) {
32
- return {
33
- status: 404,
34
- body: {
35
- message: error.message,
36
- error: error.name,
37
- },
38
- };
39
- }
40
- if (error instanceof playwright.errors.TimeoutError) {
41
- return {
42
- status: 500,
43
- body: { message: error.message, error: error.name },
44
- };
45
- }
46
- /**
47
- * here we use error.constructor.name instead of error instanceof RunError
48
- * this is because the error is thrown by importing the runner from the api code on intuned app
49
- * the definition of class RunError which is imported from here is different than the class RunError
50
- * imported from the user.
51
- */
52
- if (error.constructor.name === "RunError") {
53
- return {
54
- status: 200,
55
- body: {
56
- status: error.options.status_code ?? 500,
57
- message: error.message,
58
- error: error.options.error_code ?? error.name,
59
- intunedOptions: error.options,
60
- },
61
- };
62
- }
63
- return {
64
- status: 500,
65
- body: { error: error?.name ?? error, message: error?.message },
66
- };
67
- }
68
-
69
- export function handlePlaywrightExecutionError(error: any, res: Response) {
70
- const { status, body } = getErrorResponse(error);
71
- return res.status(status).json(body);
72
- }
73
-
74
- type EventTraceEvent = {
75
- type: "event";
76
- time: number;
77
- class: string;
78
- method: string;
79
- params: any;
80
- pageId?: string;
81
- };
82
-
83
- type AppHandlerParams = Parameters<Handler>;
84
-
85
- export function errorRetryMiddleware(handler: Handler) {
86
- return async (...args: AppHandlerParams) => {
87
- let attempts = 1;
88
- const [req, res, next] = args;
89
- // eslint-disable-next-line no-constant-condition
90
- while (true) {
91
- try {
92
- await handler(req, res, next);
93
- break;
94
- } catch (error) {
95
- console.log(error?.name, error?.message);
96
- if (!getIsRetryableError(error) || attempts >= 3) {
97
- return handlePlaywrightExecutionError(error, res);
98
- }
99
- attempts++;
100
- }
101
- }
102
- };
103
- }
104
-
105
- export function getTraceFilePath(runId: string, attemptNumber?: string) {
106
- const fileName = `${runId}${attemptNumber ? `_${attemptNumber}` : ""}`;
107
- return path.join(process.env.TRACES_DIRECTORY ?? "", `${fileName}.zip`);
108
- }
109
-
110
- export interface ProxyConfig {
111
- username: string;
112
- server: string;
113
- password: string;
114
- }
115
-
116
- export function proxyToUrl(proxy: ProxyConfig) {
117
- const url = new URL(proxy.server);
118
- url.username = proxy.username;
119
- url.password = proxy.password;
120
- return url.toString();
121
- }
122
-
123
- export function isJobRunMachine() {
124
- return process.env.JOB_ID && process.env.JOB_RUN_ID;
125
- }
126
-
127
- export function isHeadless() {
128
- return process.env.INTUNED_PLAYWRIGHT_HEADLESS !== "0";
129
- }
130
-
131
- export abstract class AsyncRunEndpointController {
132
- private static activeRequests: Set<string> = new Set();
133
-
134
- static isRunning(taskToken: string) {
135
- return this.activeRequests.has(taskToken);
136
- }
137
-
138
- static addRequest(taskToken: string) {
139
- this.activeRequests.add(taskToken);
140
- }
141
-
142
- static removeRequest(taskToken: string) {
143
- this.activeRequests.delete(taskToken);
144
- }
145
-
146
- static get activeRequestsCount() {
147
- return this.activeRequests.size;
148
- }
149
- }
150
-
151
- export async function waitWithExtendableTimeout<T>({
152
- initialTimeout,
153
- promise,
154
- abortController,
155
- }: {
156
- initialTimeout: number;
157
- promise: Promise<T>;
158
- abortController?: AbortController;
159
- }): Promise<
160
- | {
161
- timedOut: true;
162
- }
163
- | {
164
- timedOut: false;
165
- result: T;
166
- }
167
- > {
168
- const context = getExecutionContext()!;
169
- if (context.timeoutInfo) {
170
- context.timeoutInfo.timeoutTimestamp = Date.now() + initialTimeout;
171
- }
172
- const timerSymbol = Symbol("timer");
173
- if (!context) {
174
- const result = await Promise.race([
175
- promise,
176
- setTimeout(initialTimeout, timerSymbol),
177
- ]);
178
- if (result === timerSymbol) {
179
- abortController?.abort("Timed out");
180
- return { timedOut: true };
181
- }
182
- return { timedOut: false, result };
183
- }
184
-
185
- let taskTimeout = initialTimeout;
186
- while (true as boolean) {
187
- const result = await Promise.race([
188
- promise,
189
- setTimeout(taskTimeout, timerSymbol),
190
- ]);
191
-
192
- if (result !== timerSymbol) {
193
- break;
194
- }
195
-
196
- const remainingTime =
197
- (context.timeoutInfo?.timeoutTimestamp ?? 0) - Date.now();
198
- if (remainingTime < 0) {
199
- abortController?.abort("Timed out");
200
- return { timedOut: true };
201
- }
202
-
203
- taskTimeout = remainingTime;
204
- }
205
-
206
- return {
207
- timedOut: false,
208
- result: await promise,
209
- };
210
- }
211
-
212
- export async function importModule(path: string) {
213
- const [folderName, ...functionNameParts] = path.split("/");
214
- const functionNameDepth = functionNameParts.length;
215
-
216
- // string literals should be inline
217
- // currently we support only 5 levels of depth
218
- // rollup dynamic import does not support multiple levels of dynamic imports so we need to specify the possible paths explicitly
219
- try {
220
- let imported: any = undefined;
221
- switch (functionNameDepth) {
222
- case 1:
223
- imported = await import(`./${folderName}/${functionNameParts[0]}.ts`);
224
- break;
225
- case 2:
226
- imported = await import(
227
- `./${folderName}/${functionNameParts[0]}/${functionNameParts[1]}.ts`
228
- );
229
- break;
230
- case 3:
231
- imported = await import(
232
- `./${folderName}/${functionNameParts[0]}/${functionNameParts[1]}/${functionNameParts[2]}.ts`
233
- );
234
- break;
235
- case 4:
236
- imported = await import(
237
- `./${folderName}/${functionNameParts[0]}/${functionNameParts[1]}/${functionNameParts[2]}/${functionNameParts[3]}.ts`
238
- );
239
- break;
240
- case 5:
241
- imported = await import(
242
- `./${folderName}/${functionNameParts[0]}/${functionNameParts[1]}/${functionNameParts[2]}/${functionNameParts[3]}/${functionNameParts[4]}.ts`
243
- );
244
- break;
245
- default:
246
- throw new Error(
247
- "intuned supports maximum 5 levels of depth in the api folder"
248
- );
249
- }
250
- return imported;
251
- } catch (error: any) {
252
- if (error.message.includes("Unknown variable dynamic import")) {
253
- throw new FunctionNotFoundError("", path);
254
- }
255
- throw error;
256
- }
257
- }
package/WebTemplate.zip DELETED
Binary file