@dxos/functions 0.8.2-main.fbd8ed0 → 0.8.2-staging.42af850

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 (55) hide show
  1. package/dist/lib/browser/bundler/index.mjs.map +3 -3
  2. package/dist/lib/browser/index.mjs +175 -32
  3. package/dist/lib/browser/index.mjs.map +4 -4
  4. package/dist/lib/browser/meta.json +1 -1
  5. package/dist/lib/node/bundler/index.cjs.map +3 -3
  6. package/dist/lib/node/index.cjs +167 -30
  7. package/dist/lib/node/index.cjs.map +4 -4
  8. package/dist/lib/node/meta.json +1 -1
  9. package/dist/lib/node-esm/bundler/index.mjs.map +3 -3
  10. package/dist/lib/node-esm/index.mjs +175 -32
  11. package/dist/lib/node-esm/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/meta.json +1 -1
  13. package/dist/types/src/bundler/bundler.d.ts.map +1 -1
  14. package/dist/types/src/executor/executor.d.ts +8 -0
  15. package/dist/types/src/executor/executor.d.ts.map +1 -0
  16. package/dist/types/src/executor/index.d.ts +2 -0
  17. package/dist/types/src/executor/index.d.ts.map +1 -0
  18. package/dist/types/src/handler.d.ts +7 -3
  19. package/dist/types/src/handler.d.ts.map +1 -1
  20. package/dist/types/src/index.d.ts +2 -0
  21. package/dist/types/src/index.d.ts.map +1 -1
  22. package/dist/types/src/schema.d.ts.map +1 -1
  23. package/dist/types/src/services/ai.d.ts +9 -0
  24. package/dist/types/src/services/ai.d.ts.map +1 -0
  25. package/dist/types/src/services/credentials.d.ts +30 -0
  26. package/dist/types/src/services/credentials.d.ts.map +1 -0
  27. package/dist/types/src/services/database.d.ts +9 -0
  28. package/dist/types/src/services/database.d.ts.map +1 -0
  29. package/dist/types/src/services/index.d.ts +7 -0
  30. package/dist/types/src/services/index.d.ts.map +1 -0
  31. package/dist/types/src/services/queues.d.ts +10 -0
  32. package/dist/types/src/services/queues.d.ts.map +1 -0
  33. package/dist/types/src/services/service-container.d.ts +25 -0
  34. package/dist/types/src/services/service-container.d.ts.map +1 -0
  35. package/dist/types/src/services/tracing.d.ts +15 -0
  36. package/dist/types/src/services/tracing.d.ts.map +1 -0
  37. package/dist/types/src/trace.d.ts +9 -8
  38. package/dist/types/src/trace.d.ts.map +1 -1
  39. package/dist/types/src/types.d.ts.map +1 -1
  40. package/package.json +20 -20
  41. package/src/bundler/bundler.ts +7 -1
  42. package/src/executor/executor.ts +47 -0
  43. package/src/executor/index.ts +5 -0
  44. package/src/handler.ts +8 -3
  45. package/src/index.ts +4 -0
  46. package/src/schema.ts +8 -9
  47. package/src/services/ai.ts +15 -0
  48. package/src/services/credentials.ts +55 -0
  49. package/src/services/database.ts +14 -0
  50. package/src/services/index.ts +10 -0
  51. package/src/services/queues.ts +16 -0
  52. package/src/services/service-container.ts +58 -0
  53. package/src/services/tracing.ts +27 -0
  54. package/src/trace.ts +4 -4
  55. package/src/types.ts +17 -16
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/bundler/bundler.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { type BuildOptions } from 'esbuild';\nimport { build, initialize, type BuildResult, type Plugin } from 'esbuild-wasm';\n\nimport { subtleCrypto } from '@dxos/crypto';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nexport type Import = {\n moduleUrl: string;\n defaultImport: boolean;\n namedImports: string[];\n};\n\nexport type BundleOptions = {\n /**\n * Path to the source file on the local file system.\n * If provided, the path will be used instead of the `source` code.\n */\n path?: string;\n\n /**\n * Source code to bundle.\n * Required if `path` is not provided.\n */\n source?: string;\n};\n\nexport type BundleResult = {\n timestamp: number;\n sourceHash?: Buffer;\n imports?: Import[];\n bundle?: string;\n error?: any;\n};\n\nexport type BundlerOptions = {\n platform: BuildOptions['platform'];\n sandboxedModules: string[];\n remoteModules: Record<string, string>;\n};\n\nlet initialized: Promise<void>;\nexport const initializeBundler = async (options: { wasmUrl: string }) => {\n await (initialized ??= initialize({\n wasmURL: options.wasmUrl,\n }));\n};\n\n/**\n * ESBuild bundler.\n */\nexport class Bundler {\n constructor(private readonly _options: BundlerOptions) {}\n\n async bundle({ path, source }: BundleOptions): Promise<BundleResult> {\n const { sandboxedModules: providedModules, ...options } = this._options;\n\n const createResult = async (result?: Partial<BundleResult>) => {\n return {\n timestamp: Date.now(),\n sourceHash: source ? Buffer.from(await subtleCrypto.digest('SHA-256', Buffer.from(source))) : undefined,\n ...result,\n };\n };\n\n if (this._options.platform === 'browser') {\n invariant(initialized, 'Compiler not initialized.');\n await initialized;\n }\n\n const imports = source ? analyzeSourceFileImports(source) : [];\n\n // https://esbuild.github.io/api/#build\n try {\n const result = await build({\n platform: options.platform,\n conditions: ['workerd', 'browser'],\n metafile: true,\n write: false,\n entryPoints: [path ?? 'memory:main.tsx'],\n bundle: true,\n format: 'esm',\n plugins: [\n {\n name: 'memory',\n setup: (build) => {\n build.onResolve({ filter: /^\\.\\/runtime\\.js$/ }, ({ path }) => {\n return { path, external: true };\n });\n\n build.onResolve({ filter: /^dxos:functions$/ }, ({ path }) => {\n return { path: './runtime.js', external: true };\n });\n\n build.onResolve({ filter: /^memory:/ }, ({ path }) => {\n return { path: path.split(':')[1], namespace: 'memory' };\n });\n\n build.onLoad({ filter: /.*/, namespace: 'memory' }, ({ path }) => {\n if (path === 'main.tsx') {\n return {\n contents: source,\n loader: 'tsx',\n };\n }\n });\n\n for (const module of providedModules) {\n build.onResolve({ filter: new RegExp(`^${module}$`) }, ({ path }) => {\n return { path, namespace: 'injected-module' };\n });\n }\n\n build.onLoad({ filter: /.*/, namespace: 'injected-module' }, ({ path }) => {\n const namedImports = imports.find((entry) => entry.moduleIdentifier === path)?.namedImports ?? [];\n return {\n contents: `\n const { ${namedImports.join(',')} } = window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}];\n export { ${namedImports.join(',')} };\n export default window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}].default;\n `,\n loader: 'tsx',\n };\n });\n },\n },\n httpPlugin,\n ],\n });\n\n log('compile complete', result.metafile);\n\n return await createResult({\n imports: this.analyzeImports(result),\n bundle: result.outputFiles![0].text,\n });\n } catch (err) {\n return await createResult({ error: err });\n }\n }\n\n // TODO(dmaretskyi): In the future we can replace the compiler with SWC with plugins running in WASM.\n analyzeImports(result: BuildResult): Import[] {\n invariant(result.outputFiles);\n\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, result.outputFiles[0].text);\n return Object.values(result.metafile!.outputs)[0].imports.map((entry): Import => {\n const namedImports: string[] = [];\n\n const parsedImport = parsedImports.find((capture) => capture?.[4] === entry.path);\n if (parsedImport?.[2]) {\n NAMED_IMPORTS_REGEX.lastIndex = 0;\n const namedImportsMatch = NAMED_IMPORTS_REGEX.exec(parsedImport[2]);\n if (namedImportsMatch) {\n namedImportsMatch[1].split(',').forEach((importName) => {\n namedImports.push(importName.trim());\n });\n }\n }\n\n return {\n moduleUrl: entry.path,\n defaultImport: !!parsedImport?.[1],\n namedImports,\n };\n });\n }\n\n analyzeSourceFileImports(code: string) {\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, code);\n return parsedImports.map((capture) => {\n return {\n defaultImportName: capture[1],\n namedImports: capture[2]?.split(',').map((importName) => importName.trim()),\n wildcardImportName: capture[3],\n moduleIdentifier: capture[4],\n quotes: capture[5],\n };\n });\n }\n}\n\n// https://regex101.com/r/FEN5ks/1\n// https://stackoverflow.com/a/73265022\n// $1 = default import name (can be non-existent)\n// $2 = destructured exports (can be non-existent)\n// $3 = wildcard import name (can be non-existent)\n// $4 = module identifier\n// $5 = quotes used (either ' or \")\nconst IMPORT_REGEX =\n /import(?:(?:(?:[ \\n\\t]+([^ *\\n\\t{},]+)[ \\n\\t]*(?:,|[ \\n\\t]+))?([ \\n\\t]*{(?:[ \\n\\t]*[^ \\n\\t\"'{}]+[ \\n\\t]*,?)+})?[ \\n\\t]*)|[ \\n\\t]*\\*[ \\n\\t]*as[ \\n\\t]+([^ \\n\\t{}]+)[ \\n\\t]+)from[ \\n\\t]*(?:['\"])([^'\"\\n]+)(['\"])/gm;\n\nconst NAMED_IMPORTS_REGEX = /[ \\n\\t]*{((?:[ \\n\\t]*[^ \\n\\t\"'{}]+[ \\n\\t]*,?)+)}[ \\n\\t]*/gm;\n\nconst allMatches = (regex: RegExp, str: string) => {\n regex.lastIndex = 0;\n\n let match;\n const matches = [];\n while ((match = regex.exec(str))) {\n matches.push(match);\n }\n\n return matches;\n};\n\ntype ParsedImport = {\n defaultImportName?: string;\n namedImports: string[];\n wildcardImportName?: string;\n moduleIdentifier: string;\n quotes: string;\n};\n\nconst analyzeSourceFileImports = (code: string): ParsedImport[] => {\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, code);\n return parsedImports.map((capture) => {\n return {\n defaultImportName: capture[1],\n namedImports: capture[2]\n ?.trim()\n .slice(1, -1)\n .split(',')\n .map((importName) => importName.trim()),\n wildcardImportName: capture[3],\n moduleIdentifier: capture[4],\n quotes: capture[5],\n };\n });\n};\n\nconst httpPlugin: Plugin = {\n name: 'http',\n setup: (build) => {\n // Intercept import paths starting with \"http:\" and \"https:\" so esbuild doesn't attempt to map them to a file system location.\n // Tag them with the \"http-url\" namespace to associate them with this plugin.\n build.onResolve({ filter: /^https?:\\/\\// }, (args) => ({\n path: args.path,\n namespace: 'http-url',\n }));\n\n // We also want to intercept all import paths inside downloaded files and resolve them against the original URL.\n // All of these files will be in the \"http-url\" namespace.\n // Make sure to keep the newly resolved URL in the \"http-url\" namespace so imports inside it will also be resolved as URLs recursively.\n build.onResolve({ filter: /.*/, namespace: 'http-url' }, (args) => ({\n path: new URL(args.path, args.importer).toString(),\n namespace: 'http-url',\n }));\n\n // When a URL is loaded, we want to actually download the content from the internet.\n // This has just enough logic to be able to handle the example import from unpkg.com but in reality this would probably need to be more complex.\n build.onLoad({ filter: /.*/, namespace: 'http-url' }, async (args) => {\n const response = await fetch(args.path);\n return { contents: await response.text(), loader: 'jsx' };\n });\n },\n};\n"],
5
- "mappings": ";;;AAKA,SAASA,OAAOC,kBAAiD;AAEjE,SAASC,oBAAoB;AAC7B,SAASC,iBAAiB;AAC1B,SAASC,WAAW;;AAoCpB,IAAIC;AACG,IAAMC,oBAAoB,OAAOC,YAAAA;AACtC,SAAOF,gBAAgBJ,WAAW;IAChCO,SAASD,QAAQE;EACnB,CAAA;AACF;AAKO,IAAMC,UAAN,MAAMA;EACXC,YAA6BC,UAA0B;SAA1BA,WAAAA;EAA2B;EAExD,MAAMC,OAAO,EAAEC,MAAMC,OAAM,GAA0C;AACnE,UAAM,EAAEC,kBAAkBC,iBAAiB,GAAGV,QAAAA,IAAY,KAAKK;AAE/D,UAAMM,eAAe,OAAOC,WAAAA;AAC1B,aAAO;QACLC,WAAWC,KAAKC,IAAG;QACnBC,YAAYR,SAASS,OAAOC,KAAK,MAAMvB,aAAawB,OAAO,WAAWF,OAAOC,KAAKV,MAAAA,CAAAA,CAAAA,IAAYY;QAC9F,GAAGR;MACL;IACF;AAEA,QAAI,KAAKP,SAASgB,aAAa,WAAW;AACxCzB,gBAAUE,aAAa,6BAAA;;;;;;;;;AACvB,YAAMA;IACR;AAEA,UAAMwB,UAAUd,SAASe,yBAAyBf,MAAAA,IAAU,CAAA;AAG5D,QAAI;AACF,YAAMI,SAAS,MAAMnB,MAAM;QACzB4B,UAAUrB,QAAQqB;QAClBG,YAAY;UAAC;UAAW;;QACxBC,UAAU;QACVC,OAAO;QACPC,aAAa;UAACpB,QAAQ;;QACtBD,QAAQ;QACRsB,QAAQ;QACRC,SAAS;UACP;YACEC,MAAM;YACNC,OAAO,CAACtC,WAAAA;AACNA,cAAAA,OAAMuC,UAAU;gBAAEC,QAAQ;cAAoB,GAAG,CAAC,EAAE1B,MAAAA,MAAI,MAAE;AACxD,uBAAO;kBAAEA,MAAAA;kBAAM2B,UAAU;gBA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C,SAAAA;AAC3D,YAAMI,WAAW,MAAMC,MAAML,KAAK5E,IAAI;AACtC,aAAO;QAAE+B,UAAU,MAAMiD,SAASnC,KAAI;QAAIb,QAAQ;MAAM;IAC1D,CAAA;EACF;AACF;",
6
- "names": ["build", "initialize", "subtleCrypto", "invariant", "log", "initialized", "initializeBundler", "options", "wasmURL", "wasmUrl", "Bundler", "constructor", "_options", "bundle", "path", "source", "sandboxedModules", "providedModules", "createResult", "result", "timestamp", "Date", "now", "sourceHash", "Buffer", "from", "digest", "undefined", "platform", "imports", "analyzeSourceFileImports", "conditions", "metafile", "write", "entryPoints", "format", "plugins", "name", "setup", "onResolve", "filter", "external", "split", "namespace", "onLoad", "contents", "loader", "module", "RegExp", "namedImports", "find", "entry", "moduleIdentifier", "join", "JSON", "stringify", "httpPlugin", "analyzeImports", "outputFiles", "text", "err", "error", "parsedImports", "allMatches", "IMPORT_REGEX", "Object", "values", "outputs", "map", "parsedImport", "capture", "NAMED_IMPORTS_REGEX", "lastIndex", "namedImportsMatch", "exec", "forEach", "importName", "push", "trim", "moduleUrl", "defaultImport", "code", "defaultImportName", "wildcardImportName", "quotes", "regex", "str", "match", "matches", "slice", "args", "URL", "importer", "toString", "response", "fetch"]
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { type BuildOptions } from 'esbuild';\nimport { build, initialize, type BuildResult, type Plugin } from 'esbuild-wasm';\n\nimport { subtleCrypto } from '@dxos/crypto';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nexport type Import = {\n moduleUrl: string;\n defaultImport: boolean;\n namedImports: string[];\n};\n\nexport type BundleOptions = {\n /**\n * Path to the source file on the local file system.\n * If provided, the path will be used instead of the `source` code.\n */\n path?: string;\n\n /**\n * Source code to bundle.\n * Required if `path` is not provided.\n */\n source?: string;\n};\n\nexport type BundleResult = {\n timestamp: number;\n sourceHash?: Buffer;\n imports?: Import[];\n bundle?: string;\n error?: any;\n};\n\nexport type BundlerOptions = {\n platform: BuildOptions['platform'];\n sandboxedModules: string[];\n remoteModules: Record<string, string>;\n};\n\nlet initialized: Promise<void>;\nexport const initializeBundler = async (options: { wasmUrl: string }) => {\n await (initialized ??= initialize({\n wasmURL: options.wasmUrl,\n }));\n};\n\n/**\n * ESBuild bundler.\n */\nexport class Bundler {\n constructor(private readonly _options: BundlerOptions) {}\n\n async bundle({ path, source }: BundleOptions): Promise<BundleResult> {\n const { sandboxedModules: providedModules, ...options } = this._options;\n\n const createResult = async (result?: Partial<BundleResult>) => {\n return {\n timestamp: Date.now(),\n sourceHash: source ? Buffer.from(await subtleCrypto.digest('SHA-256', Buffer.from(source))) : undefined,\n ...result,\n };\n };\n\n if (this._options.platform === 'browser') {\n invariant(initialized, 'Compiler not initialized.');\n await initialized;\n }\n\n const imports = source ? analyzeSourceFileImports(source) : [];\n\n // https://esbuild.github.io/api/#build\n try {\n const result = await build({\n platform: options.platform,\n conditions: ['workerd', 'browser'],\n metafile: true,\n write: false,\n entryPoints: [path ?? 'memory:main.tsx'],\n bundle: true,\n format: 'esm',\n plugins: [\n {\n name: 'memory',\n setup: (build) => {\n build.onResolve({ filter: /^\\.\\/runtime\\.js$/ }, ({ path }) => {\n return { path, external: true };\n });\n\n build.onResolve({ filter: /^dxos:functions$/ }, ({ path }) => {\n return { path: './runtime.js', external: true };\n });\n\n build.onResolve({ filter: /^memory:/ }, ({ path }) => {\n return { path: path.split(':')[1], namespace: 'memory' };\n });\n\n build.onLoad({ filter: /.*/, namespace: 'memory' }, ({ path }) => {\n if (path === 'main.tsx') {\n return {\n contents: source,\n loader: 'tsx',\n };\n }\n });\n\n for (const module of providedModules) {\n build.onResolve({ filter: new RegExp(`^${module}$`) }, ({ path }) => {\n return { path, namespace: 'injected-module' };\n });\n }\n\n build.onLoad({ filter: /.*/, namespace: 'injected-module' }, ({ path }) => {\n const namedImports = imports.find((entry) => entry.moduleIdentifier === path)?.namedImports ?? [];\n return {\n contents: `\n const { ${namedImports.join(',')} } = window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}];\n export { ${namedImports.join(',')} };\n export default window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}].default;\n `,\n loader: 'tsx',\n };\n });\n },\n },\n httpPlugin,\n ],\n });\n\n log('compile complete', result.metafile);\n\n return await createResult({\n imports: this.analyzeImports(result),\n bundle: result.outputFiles![0].text,\n });\n } catch (err) {\n return await createResult({ error: err });\n }\n }\n\n // TODO(dmaretskyi): In the future we can replace the compiler with SWC with plugins running in WASM.\n analyzeImports(result: BuildResult): Import[] {\n invariant(result.outputFiles);\n\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, result.outputFiles[0].text);\n return Object.values(result.metafile!.outputs)[0].imports.map((entry): Import => {\n const namedImports: string[] = [];\n\n const parsedImport = parsedImports.find((capture) => capture?.[4] === entry.path);\n if (parsedImport?.[2]) {\n NAMED_IMPORTS_REGEX.lastIndex = 0;\n const namedImportsMatch = NAMED_IMPORTS_REGEX.exec(parsedImport[2]);\n if (namedImportsMatch) {\n namedImportsMatch[1].split(',').forEach((importName) => {\n namedImports.push(importName.trim());\n });\n }\n }\n\n return {\n moduleUrl: entry.path,\n defaultImport: !!parsedImport?.[1],\n namedImports,\n };\n });\n }\n\n analyzeSourceFileImports(code: string): {\n defaultImportName: string;\n namedImports: string[];\n wildcardImportName: string;\n moduleIdentifier: string;\n quotes: string;\n }[] {\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, code);\n return parsedImports.map((capture) => {\n return {\n defaultImportName: capture[1],\n namedImports: capture[2]?.split(',').map((importName) => importName.trim()),\n wildcardImportName: capture[3],\n moduleIdentifier: capture[4],\n quotes: capture[5],\n };\n });\n }\n}\n\n// https://regex101.com/r/FEN5ks/1\n// https://stackoverflow.com/a/73265022\n// $1 = default import name (can be non-existent)\n// $2 = destructured exports (can be non-existent)\n// $3 = wildcard import name (can be non-existent)\n// $4 = module identifier\n// $5 = quotes used (either ' or \")\nconst IMPORT_REGEX =\n /import(?:(?:(?:[ \\n\\t]+([^ *\\n\\t{},]+)[ \\n\\t]*(?:,|[ \\n\\t]+))?([ \\n\\t]*{(?:[ \\n\\t]*[^ \\n\\t\"'{}]+[ \\n\\t]*,?)+})?[ \\n\\t]*)|[ \\n\\t]*\\*[ \\n\\t]*as[ \\n\\t]+([^ \\n\\t{}]+)[ \\n\\t]+)from[ \\n\\t]*(?:['\"])([^'\"\\n]+)(['\"])/gm;\n\nconst NAMED_IMPORTS_REGEX = /[ \\n\\t]*{((?:[ \\n\\t]*[^ \\n\\t\"'{}]+[ \\n\\t]*,?)+)}[ \\n\\t]*/gm;\n\nconst allMatches = (regex: RegExp, str: string) => {\n regex.lastIndex = 0;\n\n let match;\n const matches = [];\n while ((match = regex.exec(str))) {\n matches.push(match);\n }\n\n return matches;\n};\n\ntype ParsedImport = {\n defaultImportName?: string;\n namedImports: string[];\n wildcardImportName?: string;\n moduleIdentifier: string;\n quotes: string;\n};\n\nconst analyzeSourceFileImports = (code: string): ParsedImport[] => {\n // TODO(dmaretskyi): Support import aliases and wildcard imports.\n const parsedImports = allMatches(IMPORT_REGEX, code);\n return parsedImports.map((capture) => {\n return {\n defaultImportName: capture[1],\n namedImports: capture[2]\n ?.trim()\n .slice(1, -1)\n .split(',')\n .map((importName) => importName.trim()),\n wildcardImportName: capture[3],\n moduleIdentifier: capture[4],\n quotes: capture[5],\n };\n });\n};\n\nconst httpPlugin: Plugin = {\n name: 'http',\n setup: (build) => {\n // Intercept import paths starting with \"http:\" and \"https:\" so esbuild doesn't attempt to map them to a file system location.\n // Tag them with the \"http-url\" namespace to associate them with this plugin.\n build.onResolve({ filter: /^https?:\\/\\// }, (args) => ({\n path: args.path,\n namespace: 'http-url',\n }));\n\n // We also want to intercept all import paths inside downloaded files and resolve them against the original URL.\n // All of these files will be in the \"http-url\" namespace.\n // Make sure to keep the newly resolved URL in the \"http-url\" namespace so imports inside it will also be resolved as URLs recursively.\n build.onResolve({ filter: /.*/, namespace: 'http-url' }, (args) => ({\n path: new URL(args.path, args.importer).toString(),\n namespace: 'http-url',\n }));\n\n // When a URL is loaded, we want to actually download the content from the internet.\n // This has just enough logic to be able to handle the example import from unpkg.com but in reality this would probably need to be more complex.\n build.onLoad({ filter: /.*/, namespace: 'http-url' }, async (args) => {\n const response = await fetch(args.path);\n return { contents: await response.text(), loader: 'jsx' };\n });\n },\n};\n"],
5
+ "mappings": ";;;AAKA,SAASA,OAAOC,kBAAiD;AAEjE,SAASC,oBAAoB;AAC7B,SAASC,iBAAiB;AAC1B,SAASC,WAAW;;AAoCpB,IAAIC;AACG,IAAMC,oBAAoB,OAAOC,YAAAA;AACtC,SAAOF,gBAAgBJ,WAAW;IAChCO,SAASD,QAAQE;EACnB,CAAA;AACF;AAKO,IAAMC,UAAN,MAAMA;EACX,YAA6BC,UAA0B;SAA1BA,WAAAA;EAA2B;EAExD,MAAMC,OAAO,EAAEC,MAAMC,OAAM,GAA0C;AACnE,UAAM,EAAEC,kBAAkBC,iBAAiB,GAAGT,QAAAA,IAAY,KAAKI;AAE/D,UAAMM,eAAe,OAAOC,WAAAA;AAC1B,aAAO;QACLC,WAAWC,KAAKC,IAAG;QACnBC,YAAYR,SAASS,OAAOC,KAAK,MAAMtB,aAAauB,OAAO,WAAWF,OAAOC,KAAKV,MAAAA,CAAAA,CAAAA,IAAYY;QAC9F,GAAGR;MACL;IACF;AAEA,QAAI,KAAKP,SAASgB,aAAa,WAAW;AACxCxB,gBAAUE,aAAa,6BAAA;;;;;;;;;AACvB,YAAMA;IACR;AAEA,UAAMuB,UAAUd,SAASe,yBAAyBf,MAAAA,IAAU,CAAA;AAG5D,QAAI;AACF,YAAMI,SAAS,MAAMlB,MAAM;QACzB2B,UAAUpB,QAAQoB;QAClBG,YAAY;UAAC;UAAW;;QACxBC,UAAU;QACVC,OAAO;QACPC,aAAa;UAACpB,QAAQ;;QACtBD,QAAQ;QACRsB,QAAQ;QACRC,S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+C,UAAU;MAClE5E,MAAM,IAAI6E,IAAID,KAAK5E,MAAM4E,KAAKE,QAAQ,EAAEC,SAAQ;MAChDlD,WAAW;IACb,EAAA;AAIA1C,IAAAA,OAAM2C,OAAO;MAAEJ,QAAQ;MAAMG,WAAW;IAAW,GAAG,OAAO+C,SAAAA;AAC3D,YAAMI,WAAW,MAAMC,MAAML,KAAK5E,IAAI;AACtC,aAAO;QAAE+B,UAAU,MAAMiD,SAASnC,KAAI;QAAIb,QAAQ;MAAM;IAC1D,CAAA;EACF;AACF;",
6
+ "names": ["build", "initialize", "subtleCrypto", "invariant", "log", "initialized", "initializeBundler", "options", "wasmURL", "wasmUrl", "Bundler", "_options", "bundle", "path", "source", "sandboxedModules", "providedModules", "createResult", "result", "timestamp", "Date", "now", "sourceHash", "Buffer", "from", "digest", "undefined", "platform", "imports", "analyzeSourceFileImports", "conditions", "metafile", "write", "entryPoints", "format", "plugins", "name", "setup", "onResolve", "filter", "external", "split", "namespace", "onLoad", "contents", "loader", "module", "RegExp", "namedImports", "find", "entry", "moduleIdentifier", "join", "JSON", "stringify", "httpPlugin", "analyzeImports", "outputFiles", "text", "err", "error", "parsedImports", "allMatches", "IMPORT_REGEX", "Object", "values", "outputs", "map", "parsedImport", "capture", "NAMED_IMPORTS_REGEX", "lastIndex", "namedImportsMatch", "exec", "forEach", "importName", "push", "trim", "moduleUrl", "defaultImport", "code", "defaultImportName", "wildcardImportName", "quotes", "regex", "str", "match", "matches", "slice", "args", "URL", "importer", "toString", "response", "fetch"]
7
7
  }
@@ -19,7 +19,7 @@ var defineFunction = (params) => {
19
19
 
20
20
  // packages/core/functions/src/schema.ts
21
21
  import { Schema as Schema2 } from "effect";
22
- import { EchoObject, JsonSchemaType, LabelAnnotationId, Ref, TypedObject } from "@dxos/echo-schema";
22
+ import { EchoObject, JsonSchemaType, LabelAnnotation, Ref, TypedObject } from "@dxos/echo-schema";
23
23
  import { DataType } from "@dxos/schema";
24
24
  var ScriptType = Schema2.Struct({
25
25
  name: Schema2.optional(Schema2.String),
@@ -28,12 +28,12 @@ var ScriptType = Schema2.Struct({
28
28
  // Whether source has changed since last deploy.
29
29
  changed: Schema2.optional(Schema2.Boolean),
30
30
  source: Ref(DataType.Text)
31
- }).annotations({
32
- [LabelAnnotationId]: "name"
33
31
  }).pipe(EchoObject({
34
32
  typename: "dxos.org/type/Script",
35
33
  version: "0.1.0"
36
- }));
34
+ }), LabelAnnotation.set([
35
+ "name"
36
+ ]));
37
37
  var FunctionType = class extends TypedObject({
38
38
  typename: "dxos.org/type/Function",
39
39
  version: "0.1.0"
@@ -54,27 +54,29 @@ var FunctionType = class extends TypedObject({
54
54
 
55
55
  // packages/core/functions/src/trace.ts
56
56
  import { Schema as Schema4 } from "effect";
57
+ import { Queue } from "@dxos/echo-db";
57
58
  import { EchoObject as EchoObject2, Expando as Expando2, ObjectId, Ref as Ref3 } from "@dxos/echo-schema";
58
59
  import { log } from "@dxos/log";
59
60
 
60
61
  // packages/core/functions/src/types.ts
61
62
  import { Schema as Schema3, SchemaAST } from "effect";
62
- import { Expando, OptionsAnnotationId, TypedObject as TypedObject2, DXN, Ref as Ref2, RawObject } from "@dxos/echo-schema";
63
- var TriggerKind;
64
- (function(TriggerKind2) {
63
+ import { Expando, OptionsAnnotationId, TypedObject as TypedObject2, Ref as Ref2, RawObject } from "@dxos/echo-schema";
64
+ import { DXN } from "@dxos/keys";
65
+ var TriggerKind = /* @__PURE__ */ function(TriggerKind2) {
65
66
  TriggerKind2["Timer"] = "timer";
66
67
  TriggerKind2["Webhook"] = "webhook";
67
68
  TriggerKind2["Subscription"] = "subscription";
68
69
  TriggerKind2["Email"] = "email";
69
70
  TriggerKind2["Queue"] = "queue";
70
- })(TriggerKind || (TriggerKind = {}));
71
+ return TriggerKind2;
72
+ }({});
71
73
  var kindLiteralAnnotations = {
72
- [SchemaAST.TitleAnnotationId]: "Kind"
74
+ title: "Kind"
73
75
  };
74
76
  var TimerTriggerSchema = Schema3.Struct({
75
77
  kind: Schema3.Literal("timer").annotations(kindLiteralAnnotations),
76
78
  cron: Schema3.String.annotations({
77
- [SchemaAST.TitleAnnotationId]: "Cron",
79
+ title: "Cron",
78
80
  [SchemaAST.ExamplesAnnotationId]: [
79
81
  "0 0 * * *"
80
82
  ]
@@ -85,31 +87,31 @@ var EmailTriggerSchema = Schema3.Struct({
85
87
  }).pipe(Schema3.mutable);
86
88
  var QueueTriggerSchema = Schema3.Struct({
87
89
  kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
88
- queue: DXN
90
+ queue: DXN.Schema
89
91
  }).pipe(Schema3.mutable);
90
92
  var WebhookTriggerSchema = Schema3.Struct({
91
93
  kind: Schema3.Literal("webhook").annotations(kindLiteralAnnotations),
92
94
  method: Schema3.optional(Schema3.String.annotations({
93
- [SchemaAST.TitleAnnotationId]: "Method",
95
+ title: "Method",
94
96
  [OptionsAnnotationId]: [
95
97
  "GET",
96
98
  "POST"
97
99
  ]
98
100
  })),
99
101
  port: Schema3.optional(Schema3.Number.annotations({
100
- [SchemaAST.TitleAnnotationId]: "Port"
102
+ title: "Port"
101
103
  }))
102
104
  }).pipe(Schema3.mutable);
103
105
  var QuerySchema = Schema3.Struct({
104
106
  type: Schema3.optional(Schema3.String.annotations({
105
- [SchemaAST.TitleAnnotationId]: "Type"
107
+ title: "Type"
106
108
  })),
107
109
  props: Schema3.optional(Schema3.Record({
108
110
  key: Schema3.String,
109
111
  value: Schema3.Any
110
112
  }))
111
113
  }).annotations({
112
- [SchemaAST.TitleAnnotationId]: "Query"
114
+ title: "Query"
113
115
  });
114
116
  var SubscriptionTriggerSchema = Schema3.Struct({
115
117
  kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
@@ -118,18 +120,18 @@ var SubscriptionTriggerSchema = Schema3.Struct({
118
120
  options: Schema3.optional(Schema3.Struct({
119
121
  // Watch changes to object (not just creation).
120
122
  deep: Schema3.optional(Schema3.Boolean.annotations({
121
- [SchemaAST.TitleAnnotationId]: "Nested"
123
+ title: "Nested"
122
124
  })),
123
125
  // Debounce changes (delay in ms).
124
126
  delay: Schema3.optional(Schema3.Number.annotations({
125
- [SchemaAST.TitleAnnotationId]: "Delay"
127
+ title: "Delay"
126
128
  }))
127
129
  }).annotations({
128
- [SchemaAST.TitleAnnotationId]: "Options"
130
+ title: "Options"
129
131
  }))
130
132
  }).pipe(Schema3.mutable);
131
133
  var TriggerSchema = Schema3.Union(TimerTriggerSchema, WebhookTriggerSchema, SubscriptionTriggerSchema, EmailTriggerSchema, QueueTriggerSchema).annotations({
132
- [SchemaAST.TitleAnnotationId]: "Trigger"
134
+ title: "Trigger"
133
135
  });
134
136
  var EmailTriggerOutput = Schema3.mutable(Schema3.Struct({
135
137
  from: Schema3.String,
@@ -148,7 +150,7 @@ var WebhookTriggerOutput = Schema3.mutable(Schema3.Struct({
148
150
  bodyText: Schema3.String
149
151
  }));
150
152
  var QueueTriggerOutput = Schema3.mutable(Schema3.Struct({
151
- queue: DXN,
153
+ queue: DXN.Schema,
152
154
  item: Schema3.Any,
153
155
  cursor: Schema3.String
154
156
  }));
@@ -165,7 +167,7 @@ var FunctionTriggerSchema = Schema3.Struct({
165
167
  */
166
168
  // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
167
169
  function: Schema3.optional(Ref2(Expando).annotations({
168
- [SchemaAST.TitleAnnotationId]: "Function"
170
+ title: "Function"
169
171
  })),
170
172
  /**
171
173
  * Only used for workflowSchema.
@@ -173,10 +175,10 @@ var FunctionTriggerSchema = Schema3.Struct({
173
175
  * @deprecated Remove and enforce a single input node in all compute graphSchema.
174
176
  */
175
177
  inputNodeId: Schema3.optional(Schema3.String.annotations({
176
- [SchemaAST.TitleAnnotationId]: "Input Node ID"
178
+ title: "Input Node ID"
177
179
  })),
178
180
  enabled: Schema3.optional(Schema3.Boolean.annotations({
179
- [SchemaAST.TitleAnnotationId]: "Enabled"
181
+ title: "Enabled"
180
182
  })),
181
183
  spec: Schema3.optional(TriggerSchema),
182
184
  /**
@@ -211,17 +213,17 @@ var FUNCTION_TYPES = [
211
213
 
212
214
  // packages/core/functions/src/trace.ts
213
215
  var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/trace.ts";
214
- var InvocationOutcome;
215
- (function(InvocationOutcome2) {
216
+ var InvocationOutcome = /* @__PURE__ */ function(InvocationOutcome2) {
216
217
  InvocationOutcome2["SUCCESS"] = "success";
217
218
  InvocationOutcome2["FAILURE"] = "failure";
218
219
  InvocationOutcome2["PENDING"] = "pending";
219
- })(InvocationOutcome || (InvocationOutcome = {}));
220
- var InvocationTraceEventType;
221
- (function(InvocationTraceEventType2) {
220
+ return InvocationOutcome2;
221
+ }({});
222
+ var InvocationTraceEventType = /* @__PURE__ */ function(InvocationTraceEventType2) {
222
223
  InvocationTraceEventType2["START"] = "start";
223
224
  InvocationTraceEventType2["END"] = "end";
224
- })(InvocationTraceEventType || (InvocationTraceEventType = {}));
225
+ return InvocationTraceEventType2;
226
+ }({});
225
227
  var TraceEventException = Schema4.Struct({
226
228
  timestampMs: Schema4.Number,
227
229
  message: Schema4.String,
@@ -248,10 +250,9 @@ var InvocationTraceStartEvent = Schema4.Struct({
248
250
  // TODO(burdon): Input schema?
249
251
  input: Schema4.Object,
250
252
  /**
251
- * Queue DXN for function/workflow invocation events.
253
+ * Queue for function/workflow invocation events.
252
254
  */
253
- // TODO(burdon): Need reference type for queue. vs. string?
254
- invocationTraceQueue: Ref3(Expando2),
255
+ invocationTraceQueue: Ref3(Queue),
255
256
  /**
256
257
  * DXN of the invoked function/workflow.
257
258
  */
@@ -389,10 +390,149 @@ var getInvocationUrl = (functionUrl, edgeUrl, options = {}) => {
389
390
  url.protocol = isSecure(url.protocol) ? "https" : "http";
390
391
  return url.toString();
391
392
  };
393
+
394
+ // packages/core/functions/src/services/ai.ts
395
+ import { Context } from "effect";
396
+ var AiService = class extends Context.Tag("AiService")() {
397
+ };
398
+
399
+ // packages/core/functions/src/services/database.ts
400
+ import { Context as Context2 } from "effect";
401
+ var DatabaseService = class extends Context2.Tag("DatabaseService")() {
402
+ };
403
+
404
+ // packages/core/functions/src/services/queues.ts
405
+ import { Context as Context3 } from "effect";
406
+ var QueuesService = class extends Context3.Tag("QueuesService")() {
407
+ };
408
+
409
+ // packages/core/functions/src/services/credentials.ts
410
+ import { Context as Context4 } from "effect";
411
+ var CredentialsService = class extends Context4.Tag("CredentialsService")() {
412
+ };
413
+ var ConfiguredCredentialsService = class {
414
+ constructor(credentials = []) {
415
+ this.credentials = credentials;
416
+ }
417
+ addCredentials(credentials) {
418
+ this.credentials.push(...credentials);
419
+ return this;
420
+ }
421
+ async queryCredentials(query) {
422
+ return this.credentials.filter((credential) => credential.service === query.service);
423
+ }
424
+ async getCredential(query) {
425
+ const credential = this.credentials.find((credential2) => credential2.service === query.service);
426
+ if (!credential) {
427
+ throw new Error(`Credential not found for service: ${query.service}`);
428
+ }
429
+ return credential;
430
+ }
431
+ };
432
+
433
+ // packages/core/functions/src/services/tracing.ts
434
+ import { Context as Context5 } from "effect";
435
+ var TracingService = class extends Context5.Tag("TracingService")() {
436
+ static {
437
+ this.noop = {
438
+ write: () => {
439
+ }
440
+ };
441
+ }
442
+ static {
443
+ this.console = {
444
+ write: (event) => {
445
+ console.log(event);
446
+ }
447
+ };
448
+ }
449
+ };
450
+
451
+ // packages/core/functions/src/services/service-container.ts
452
+ var SERVICE_MAPPING = {
453
+ [DatabaseService.key]: "database",
454
+ [AiService.key]: "ai",
455
+ [QueuesService.key]: "queues",
456
+ [CredentialsService.key]: "credentials",
457
+ [TracingService.key]: "tracing"
458
+ };
459
+ var DEFAULT_SERVICES = {
460
+ tracing: TracingService.noop
461
+ };
462
+ var ServiceContainer = class _ServiceContainer {
463
+ constructor() {
464
+ this._services = {
465
+ ...DEFAULT_SERVICES
466
+ };
467
+ }
468
+ /**
469
+ * Set services.
470
+ * @param services - Services to set.
471
+ * @returns The container instance.
472
+ */
473
+ setServices(services) {
474
+ this._services = {
475
+ ...this._services,
476
+ ...services
477
+ };
478
+ return this;
479
+ }
480
+ getService(tag) {
481
+ const serviceKey = SERVICE_MAPPING[tag.key];
482
+ const service = serviceKey != null ? this._services[serviceKey] : void 0;
483
+ if (!service) {
484
+ throw new Error(`Service not available: ${tag.key}`);
485
+ }
486
+ return service;
487
+ }
488
+ clone() {
489
+ return new _ServiceContainer().setServices({
490
+ ...this._services
491
+ });
492
+ }
493
+ };
494
+
495
+ // packages/core/functions/src/executor/executor.ts
496
+ import { Effect, Schema as Schema5 } from "effect";
497
+ var FunctionExecutor = class {
498
+ constructor(_services) {
499
+ this._services = _services;
500
+ }
501
+ // TODO(dmaretskyi): Invocation context: queue, space, etc...
502
+ async invoke(fnDef, input) {
503
+ const assertInput = fnDef.inputSchema.pipe(Schema5.asserts);
504
+ assertInput(input);
505
+ const context = {
506
+ getService: this._services.getService.bind(this._services),
507
+ getSpace: async (_spaceId) => {
508
+ throw new Error("Not available. Use the database service instead.");
509
+ },
510
+ space: void 0,
511
+ get ai() {
512
+ throw new Error("Not available. Use the ai service instead.");
513
+ }
514
+ };
515
+ const result = await fnDef.handler({
516
+ context,
517
+ data: input
518
+ });
519
+ const assertOutput = fnDef.outputSchema?.pipe(Schema5.asserts);
520
+ assertOutput(result);
521
+ if (Effect.isEffect(result)) {
522
+ return Effect.runPromise(result);
523
+ }
524
+ return result;
525
+ }
526
+ };
392
527
  export {
528
+ AiService,
529
+ ConfiguredCredentialsService,
530
+ CredentialsService,
531
+ DatabaseService,
393
532
  EmailTriggerOutput,
394
533
  FUNCTIONS_PRESET_META_KEY,
395
534
  FUNCTION_TYPES,
535
+ FunctionExecutor,
396
536
  FunctionManifestSchema,
397
537
  FunctionTrigger,
398
538
  FunctionTriggerSchema,
@@ -402,12 +542,15 @@ export {
402
542
  InvocationTraceEventType,
403
543
  InvocationTraceStartEvent,
404
544
  QueueTriggerOutput,
545
+ QueuesService,
405
546
  ScriptType,
547
+ ServiceContainer,
406
548
  SubscriptionTriggerOutput,
407
549
  TimerTriggerOutput,
408
550
  TraceEvent,
409
551
  TraceEventException,
410
552
  TraceEventLog,
553
+ TracingService,
411
554
  TriggerKind,
412
555
  TriggerSchema,
413
556
  WebhookTriggerOutput,